Example usage for java.util.concurrent Callable call

List of usage examples for java.util.concurrent Callable call

Introduction

In this page you can find the example usage for java.util.concurrent Callable call.

Prototype

V call() throws Exception;

Source Link

Document

Computes a result, or throws an exception if unable to do so.

Usage

From source file:plaid.compilerjava.CompilerCore.java

private void generateCode(List<CompilationUnit> cus, final PackageRep plaidpath) throws Exception {
    if (cc.isVerbose()) {
        System.out.println("Generating code.");
    }/* w  ww . jav a 2 s  .c  o  m*/

    final List<File> allFiles = new ArrayList<File>();
    ExecutorService taskPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    for (final CompilationUnit cu : cus) {
        if (!cc.forceRecompile()) {
            boolean rebuild = false;
            for (Decl d : cu.getDecls()) {
                //System.out.println(d);
                StringBuilder packageName = new StringBuilder();
                for (String s : cu.getPackageName()) {
                    packageName.append(s);
                    packageName.append(System.getProperty("file.separator"));
                }
                File targetFile = new File(cc.getTempDir() + System.getProperty("file.separator") + packageName
                        + d.getName() + ".java");
                if (!targetFile.exists() || targetFile.lastModified() < cu.getSourceFile().lastModified()) {
                    rebuild = true;
                    break;
                }
            }
            if (!rebuild) {
                if (cc.isVerbose()) {
                    System.out.println("file up-to-date : " + cu.getSourceFile());
                }
                continue;
            }
            if (cc.isVerbose()) {
                System.out.println("Rebuild: " + cu.getSourceFile());
            }
        }
        Callable<Object> task = new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                try {
                    if (cc.isVerbose())
                        System.out.println("Generating code for:\n" + cu);
                    List<File> fileList = cu.codegen(cc, plaidpath);

                    synchronized (allFiles) {
                        allFiles.addAll(fileList);
                    }
                } catch (PlaidException p) {
                    System.err.println("Error while compiling " + cu.getSourceFile().toString() + ":");
                    System.err.println("");
                    printExceptionInformation(p);
                }
                return null;
            }
        };
        taskPool.submit(task);
    }
    taskPool.shutdown();
    while (!taskPool.isTerminated()) {
        taskPool.awaitTermination(1, TimeUnit.MINUTES);
    }

    if (!cc.isKeepTemporaryFiles()) {
        for (File f : allFiles) {
            f.deleteOnExit();
        }
    }

    if (cc.isVerbose()) {
        System.out.println("invoke Java compiler");
    }
    if (cc.isInvokeCompiler() && allFiles.size() > 0) {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
        Iterable<? extends JavaFileObject> fileObjects = fileManager.getJavaFileObjectsFromFiles(allFiles);

        List<String> optionList = new ArrayList<String>();
        optionList.addAll(Arrays.asList("-target", "1.5"));
        // Set compiler's classpath to be same as the runtime's
        optionList.addAll(Arrays.asList("-classpath", System.getProperty("java.class.path")));
        // TODO: Add a separate compiler flag for this.
        optionList.addAll(Arrays.asList("-d", cc.getOutputDir()));
        //         optionList.add("-verbose");

        // Invoke the compiler
        CompilationTask task = compiler.getTask(null, null, null, optionList, null, fileObjects);
        Boolean resultCode = task.call();
        if (!resultCode.booleanValue())
            throw new RuntimeException("Error while compiling generated Java files.");
    }
}

From source file:org.dasein.cloud.aws.compute.EC2Instance.java

@Override
public @Nullable String getUserData(@Nonnull String instanceId) throws InternalException, CloudException {
    APITrace.begin(getProvider(), "getUserData");
    try {/*from  ww  w .j a  va 2 s.com*/
        Callable<String> callable = new GetUserDataCallable(instanceId, getProvider()
                .getStandardParameters(getProvider().getContext(), EC2Method.DESCRIBE_INSTANCE_ATTRIBUTE),
                getProvider(), getProvider().getEc2Url());
        return callable.call();
    } catch (EC2Exception e) {
        logger.error(e.getSummary());
        throw new CloudException(e);
    } catch (CloudException ce) {
        throw ce;
    } catch (Exception e) {
        throw new InternalException(e);
    } finally {
        APITrace.end();
    }
}

From source file:org.dasein.cloud.aws.compute.EC2Instance.java

private @Nonnull List<VirtualMachine> runInstances(@Nonnull VMLaunchOptions cfg, @Nonnegative int instanceCount)
        throws CloudException, InternalException {
    List<VirtualMachine> servers = new ArrayList<VirtualMachine>(); // instance cache
    List<String> instanceIds = new ArrayList<String>(); // instanceId cache

    ProviderContext ctx = getProvider().getContext();
    if (ctx == null) {
        throw new CloudException("No context was established for this request");
    }//  w  w w  . j  av a 2 s .  c  om
    MachineImage img = null;
    final ComputeServices computeServices = getProvider().getComputeServices();
    if (computeServices != null) {
        img = computeServices.getImageSupport().getImage(cfg.getMachineImageId());
    }

    if (img == null) {
        throw new AWSResourceNotFoundException("No such machine image: " + cfg.getMachineImageId());
    }
    Map<String, String> parameters = getProvider().getStandardParameters(getProvider().getContext(),
            EC2Method.RUN_INSTANCES);
    String ramdiskImage = (String) cfg.getMetaData().get("ramdiskImageId"),
            kernelImage = (String) cfg.getMetaData().get("kernelImageId");
    EC2Method method;
    NodeList blocks;
    Document doc;

    parameters.put("ImageId", cfg.getMachineImageId());
    parameters.put("MinCount", String.valueOf(instanceCount));
    parameters.put("MaxCount", String.valueOf(instanceCount));
    parameters.put("InstanceType", cfg.getStandardProductId());
    AWSCloud.addValueIfNotNull(parameters, "ramdiskId", ramdiskImage);
    AWSCloud.addValueIfNotNull(parameters, "kernelId", kernelImage);
    AWSCloud.addValueIfNotNull(parameters, "IamInstanceProfile.Arn", cfg.getRoleId());
    if (cfg.getUserData() != null) {
        try {
            parameters.put("UserData", Base64.encodeBase64String(cfg.getUserData().getBytes("utf-8")));
        } catch (UnsupportedEncodingException e) {
            throw new InternalException(e);
        }
    }
    if (cfg.isPreventApiTermination()) {
        parameters.put("DisableApiTermination", "true");
    }
    if (cfg.getDataCenterId() != null) {
        parameters.put("Placement.AvailabilityZone", cfg.getDataCenterId());
    } else if (cfg.getVolumes().length > 0) {
        for (VolumeAttachment a : cfg.getVolumes()) {
            if (a.volumeToCreate != null) {
                String dc = a.volumeToCreate.getDataCenterId();
                if (dc != null) {
                    cfg.inDataCenter(dc);
                    break;
                }
            }
        }
    }
    AWSCloud.addValueIfNotNull(parameters, "KeyName", cfg.getBootstrapKey());

    if (getProvider().getEC2Provider().isAWS()) {
        parameters.put("Monitoring.Enabled", String.valueOf(cfg.isExtendedAnalytics()));
    }
    if (cfg.isIoOptimized()) {
        parameters.put("EbsOptimized", "true");
    }
    AWSCloud.addValueIfNotNull(parameters, "Placement.GroupName", cfg.getAffinityGroupId());

    final ArrayList<VolumeAttachment> existingVolumes = new ArrayList<VolumeAttachment>();
    TreeSet<String> deviceIds = new TreeSet<String>();
    if (cfg.getVolumes().length > 0) {
        Iterable<String> possibles = getProvider().getComputeServices().getVolumeSupport()
                .listPossibleDeviceIds(img.getPlatform());
        int i = 1;

        for (VolumeAttachment a : cfg.getVolumes()) {
            if (a.deviceId != null) {
                deviceIds.add(a.deviceId);
            } else if (a.volumeToCreate != null && a.volumeToCreate.getDeviceId() != null) {
                deviceIds.add(a.volumeToCreate.getDeviceId());
                a.deviceId = a.volumeToCreate.getDeviceId();
            }
        }
        for (VolumeAttachment a : cfg.getVolumes()) {
            if (a.deviceId == null) {
                for (String id : possibles) {
                    if (!deviceIds.contains(id)) {
                        a.deviceId = id;
                        deviceIds.add(id);
                    }
                }
                if (a.deviceId == null) {
                    throw new InternalException("Unable to identify a device ID for volume");
                }
            }
            if (a.existingVolumeId == null) {
                parameters.put("BlockDeviceMapping." + i + ".DeviceName", a.deviceId);

                VolumeProduct prd = getProvider().getComputeServices().getVolumeSupport()
                        .getVolumeProduct(a.volumeToCreate.getVolumeProductId());
                parameters.put("BlockDeviceMapping." + i + ".Ebs.VolumeType", prd.getProviderProductId());

                if (a.volumeToCreate.getIops() > 0) {
                    parameters.put("BlockDeviceMapping." + i + ".Ebs.Iops",
                            String.valueOf(a.volumeToCreate.getIops()));
                }

                if (a.volumeToCreate.getSnapshotId() != null) {
                    parameters.put("BlockDeviceMapping." + i + ".Ebs.SnapshotId",
                            a.volumeToCreate.getSnapshotId());
                } else {
                    parameters.put("BlockDeviceMapping." + i + ".Ebs.VolumeSize",
                            String.valueOf(a.volumeToCreate.getVolumeSize().getQuantity().intValue()));
                }
                i++;
            } else {
                existingVolumes.add(a);
            }
        }
    }
    if (cfg.getSubnetId() == null) {
        AWSCloud.addIndexedParameters(parameters, "SecurityGroupId.", cfg.getFirewallIds());
    } else if (cfg.getNetworkInterfaces() != null && cfg.getNetworkInterfaces().length > 0) {
        VMLaunchOptions.NICConfig[] nics = cfg.getNetworkInterfaces();
        int i = 1;

        for (VMLaunchOptions.NICConfig c : nics) {
            parameters.put("NetworkInterface." + i + ".DeviceIndex", String.valueOf(i));
            // this only applies for the first NIC
            if (i == 1) {
                parameters.put("NetworkInterface.1.AssociatePublicIpAddress",
                        String.valueOf(cfg.isAssociatePublicIpAddress()));
            }
            if (c.nicId == null) {
                parameters.put("NetworkInterface." + i + ".SubnetId", c.nicToCreate.getSubnetId());
                parameters.put("NetworkInterface." + i + ".Description", c.nicToCreate.getDescription());
                AWSCloud.addValueIfNotNull(parameters, "NetworkInterface." + i + ".PrivateIpAddress",
                        c.nicToCreate.getIpAddress());
                AWSCloud.addIndexedParameters(parameters, "NetworkInterface." + i + ".SecurityGroupId.",
                        c.nicToCreate.getFirewallIds());
            } else {
                parameters.put("NetworkInterface." + i + ".NetworkInterfaceId", c.nicId);
            }
            i++;
        }
    } else {
        parameters.put("NetworkInterface.1.DeviceIndex", "0");
        parameters.put("NetworkInterface.1.SubnetId", cfg.getSubnetId());
        parameters.put("NetworkInterface.1.AssociatePublicIpAddress",
                String.valueOf(cfg.isAssociatePublicIpAddress()));
        AWSCloud.addValueIfNotNull(parameters, "NetworkInterface.1.PrivateIpAddress", cfg.getPrivateIp());
        AWSCloud.addIndexedParameters(parameters, "NetworkInterface.1.SecurityGroupId.", cfg.getFirewallIds());
    }

    // Send request to AWS
    method = new EC2Method(getProvider(), parameters);
    try {
        doc = method.invoke();
    } catch (EC2Exception e) {
        String code = e.getCode();

        if (code != null && code.equals("InsufficientInstanceCapacity")) {
            return servers;
        }
        logger.error(e.getSummary());
        throw new CloudException(e);
    }
    blocks = doc.getElementsByTagName("instancesSet");

    for (int i = 0; i < blocks.getLength(); i++) {
        NodeList instances = blocks.item(i).getChildNodes();

        for (int j = 0; j < instances.getLength(); j++) {
            Node instance = instances.item(j);

            if (instance.getNodeName().equals("item")) {
                VirtualMachine server = toVirtualMachine(ctx, instance,
                        new ArrayList<IpAddress>() /* can't be an elastic IP */);
                if (server != null) {
                    servers.add(server);
                    instanceIds.add(server.getProviderVirtualMachineId());
                }
            }
        }
    }

    // Wait for EC2 to figure out the server exists
    List<VirtualMachine> serversCopy = describeInstances(instanceIds.toArray(new String[instanceIds.size()]));
    long timeout = System.currentTimeMillis() + CalendarWrapper.MINUTE;
    while (timeout > System.currentTimeMillis() && serversCopy.size() < servers.size()) {
        try {
            Thread.sleep(5000L);
        } catch (InterruptedException ignore) {
        }
        try {
            serversCopy = describeInstances(instanceIds.toArray(new String[instanceIds.size()]));
        } catch (Throwable ignore) {
        }
    }

    // FIXME: not clear what is to be done if time is out but `serversCopy` is still less than `servers`

    // Set all instances their tags
    List<Tag> tags = new ArrayList<Tag>();
    Map<String, Object> meta = cfg.getMetaData();
    for (Map.Entry<String, Object> entry : meta.entrySet()) {
        if (entry.getKey().equalsIgnoreCase("name") || entry.getKey().equalsIgnoreCase("description")) {
            continue;
        }
        // Tag value can be null, make sure we are careful
        tags.add(new Tag(entry.getKey(), entry.getValue() == null ? "" : entry.getValue().toString()));
    }
    tags.add(new Tag("Name", cfg.getFriendlyName()));
    tags.add(new Tag("Description", cfg.getDescription()));
    if (cfg.getVirtualMachineGroup() != null) {
        tags.add(new Tag("dsnVMGroup", cfg.getVirtualMachineGroup()));
    }
    getProvider().createTags(instanceIds.toArray(new String[instanceIds.size()]),
            tags.toArray(new Tag[tags.size()]));

    // Set all instances their passwords and attach volumes
    for (VirtualMachine server : servers) {
        if (cfg.isIpForwardingAllowed()) {
            enableIpForwarding(server.getProviderVirtualMachineId());
        }
        if (cfg.isIpForwardingAllowed()) {
            enableIpForwarding(server.getProviderVirtualMachineId());
        }
        if (server != null && cfg.getBootstrapKey() != null) {
            try {
                final String sid = server.getProviderVirtualMachineId();
                try {
                    Callable<String> callable = new GetPassCallable(sid, getProvider());
                    String password = callable.call();

                    if (password == null) {
                        server.setRootPassword(null);
                        server.setPasswordCallback(callable);
                    } else {
                        server.setRootPassword(password);
                    }
                    server.setPlatform(Platform.WINDOWS);
                } catch (CloudException e) {
                    logger.warn(e.getMessage());
                }
            } catch (Throwable t) {
                logger.warn("Unable to retrieve password for " + server.getProviderVirtualMachineId()
                        + ", Let's hope it's Unix: " + t.getMessage());
            }
        }

        if (!existingVolumes.isEmpty()) {
            final VirtualMachine vm = server;

            getProvider().hold();
            Thread thread = new Thread() {
                public void run() {
                    try {
                        for (VolumeAttachment a : existingVolumes) {
                            try {
                                if (computeServices != null) {
                                    computeServices.getVolumeSupport().attach(a.existingVolumeId,
                                            vm.getProviderMachineImageId(), a.deviceId);
                                }
                            } catch (Throwable t) {
                                // ignore all errors
                            }
                        }
                    } finally {
                        getProvider().release();
                    }
                }
            };

            thread.setName("Volume Mounter for " + server);
            thread.start();
        }
    }
    return servers;
}

From source file:com.openatk.field_work.MainActivity.java

private void createOperation(final Callable<Void> myFunc) {
    // get prompts.xml view
    LayoutInflater li = LayoutInflater.from(this);
    View promptsView = li.inflate(R.layout.new_operation_dialog, null);

    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
    alertDialogBuilder.setView(promptsView);

    final EditText userInput = (EditText) promptsView.findViewById(R.id.new_operation_dialog_name);

    // set dialog message
    alertDialogBuilder.setCancelable(false).setPositiveButton("Add", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            // Create the operation
            String name = userInput.getText().toString();
            if (name.isEmpty() == false) {

                Operation newOp = new Operation(name);
                TableOperations.updateOperation(dbHelper, newOp); //Add operation to db
                currentOperation = newOp;

                Log.d("MainActivity - createOperation", currentOperation.getName());

                dbHelper.close();// w w w  .  ja  va  2  s .  co  m
                //Add to operations list
                operationsList.add(0, newOp);
                if (spinnerMenuAdapter != null)
                    spinnerMenuAdapter.notifyDataSetChanged();
                selectCurrentOperationInSpinner();

                // Save this choice in preferences for next open
                SharedPreferences prefs = getApplicationContext().getSharedPreferences("com.openatk.field_work",
                        Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = prefs.edit();
                editor.putInt("currentOperationId", currentOperation.getId());
                editor.commit();

                // Continue what we were doing with callback
                if (myFunc != null) {
                    try {
                        myFunc.call();
                    } catch (Exception e) {
                        Log.d("MainActivity - createOperation", "Failed to call return method");
                        e.printStackTrace();
                    }
                }
            }
        }
    }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            dialog.cancel();
        }
    });

    // create alert dialog
    AlertDialog alertDialog = alertDialogBuilder.create();

    // show it
    alertDialog.show();
}

From source file:com.openatk.planting.MainActivity.java

private void createOperation(final Callable<Void> myFunc) {
    // get prompts.xml view
    LayoutInflater li = LayoutInflater.from(this);
    View promptsView = li.inflate(R.layout.new_operation_dialog, null);

    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
    alertDialogBuilder.setView(promptsView);

    final EditText userInput = (EditText) promptsView.findViewById(R.id.new_operation_dialog_name);

    // set dialog message
    alertDialogBuilder.setCancelable(false).setPositiveButton("Add", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            // Create the operation
            String name = userInput.getText().toString();
            if (name.isEmpty() == false) {
                // Create new operation
                SQLiteDatabase database = dbHelper.getWritableDatabase();
                ContentValues values = new ContentValues();
                values.put(TableOperations.COL_HAS_CHANGED, 1);
                values.put(TableOperations.COL_NAME, name);
                currentOperationId = (int) database.insert(TableOperations.TABLE_NAME, null, values);

                Log.d("MainActivity - createOperation", Integer.toString(currentOperationId));

                dbHelper.close();//from  w  w  w .  ja v  a  2  s. c  o m
                loadOperations();
                // selectCurrentOperationInSpinner();

                // Save this choice in preferences for next
                // open
                SharedPreferences prefs = PreferenceManager
                        .getDefaultSharedPreferences(getApplicationContext());
                SharedPreferences.Editor editor = prefs.edit();
                editor.putInt("currentOperationId", currentOperationId);
                editor.commit();

                // Continue what we were doing with callback
                if (myFunc != null) {
                    try {
                        myFunc.call();
                    } catch (Exception e) {
                        Log.d("MainActivity - createOperation", "Failed to call return method");
                        e.printStackTrace();
                    }
                }
            }
        }
    }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            dialog.cancel();
        }
    });

    // create alert dialog
    AlertDialog alertDialog = alertDialogBuilder.create();

    // show it
    alertDialog.show();
}

From source file:org.pentaho.platform.scheduler3.quartz.ActionAdapterQuartzJob.java

protected void invokeAction(final IAction actionBean, final String actionUser,
        final JobExecutionContext context, final Map<String, Serializable> params) throws Exception {
    final Map<String, Serializable> jobParams = new HashMap<String, Serializable>(params); // shallow copy

    // remove the scheduling infrastructure properties
    params.remove(OSGiQuartzSchedulerV2.RESERVEDMAPKEY_ACTIONCLASS);
    params.remove(OSGiQuartzSchedulerV2.RESERVEDMAPKEY_ACTIONID);
    params.remove(OSGiQuartzSchedulerV2.RESERVEDMAPKEY_ACTIONUSER);
    final IBackgroundExecutionStreamProvider streamProvider = (IBackgroundExecutionStreamProvider) params
            .get(OSGiQuartzSchedulerV2.RESERVEDMAPKEY_STREAMPROVIDER);
    params.remove(OSGiQuartzSchedulerV2.RESERVEDMAPKEY_STREAMPROVIDER);
    params.remove(OSGiQuartzSchedulerV2.RESERVEDMAPKEY_UIPASSPARAM);
    // The scheduled_fire_time is useful only to the blockoutAction see
    // PDI-10171//from  www . j  av a 2s .co m
    if (actionBean instanceof BlockoutAction) {
        params.put(IBlockoutManager.SCHEDULED_FIRE_TIME, context.getScheduledFireTime());
    }

    log.log(LogService.LOG_DEBUG,
            MessageFormat.format("Scheduling system invoking action {0} as user {1} with params [ {2} ]", //$NON-NLS-1$
                    actionBean.getClass().getName(),
                    actionUser, OSGiQuartzSchedulerV2.prettyPrintMap(params)));

    Callable<Boolean> actionBeanRunner = new Callable<Boolean>() {
        public Boolean call() throws Exception {
            LocaleHelper.setLocaleOverride((Locale) params.get(LocaleHelper.USER_LOCALE_PARAM));
            // sync job params to the action bean
            ActionHarness actionHarness = new ActionHarness(actionBean);
            boolean updateJob = false;

            final Map<String, Object> actionParams = new HashMap<String, Object>();
            actionParams.putAll(params);
            if (streamProvider != null) {
                actionParams.put("inputStream", streamProvider.getInputStream());
            }
            actionHarness.setValues(actionParams, new ActionSequenceCompatibilityFormatter());

            if (actionBean instanceof IVarArgsAction) {
                actionParams.remove("inputStream");
                actionParams.remove("outputStream");
                ((IVarArgsAction) actionBean).setVarArgs(actionParams);
            }

            boolean waitForFileCreated = false;
            OutputStream stream = null;

            if (streamProvider != null) {
                /*
                 * actionParams.remove( "inputStream" ); if ( actionBean
                 * instanceof IStreamingAction ) {
                 * streamProvider.setStreamingAction( (IStreamingAction)
                 * actionBean ); }
                 * 
                 * // BISERVER-9414 - validate that output path still exist
                 * SchedulerOutputPathResolver resolver = new
                 * SchedulerOutputPathResolver(
                 * streamProvider.getOutputPath(), actionUser ); String
                 * outputPath = resolver.resolveOutputFilePath();
                 * actionParams.put( "useJcr", Boolean.TRUE );
                 * actionParams.put( "jcrOutputPath", outputPath.substring(
                 * 0, outputPath.lastIndexOf( "/" ) ) );
                 * 
                 * if ( !outputPath.equals( streamProvider.getOutputPath() )
                 * ) { streamProvider.setOutputFilePath( outputPath ); //
                 * set fallback path updateJob = true; // job needs to be
                 * deleted and recreated with the new output path }
                 * 
                 * stream = streamProvider.getOutputStream(); if ( stream
                 * instanceof ISourcesStreamEvents ) { (
                 * (ISourcesStreamEvents) stream ).addListener( new
                 * IStreamListener() { public void fileCreated( final String
                 * filePath ) { synchronized ( lock ) { outputFilePath =
                 * filePath; lock.notifyAll(); } } } ); waitForFileCreated =
                 * true; } actionParams.put( "outputStream", stream ); //
                 * The lineage_id is only useful for the metadata and not
                 * needed at this level see PDI-10171 actionParams.remove(
                 * OSGiQuartzScheduler.RESERVEDMAPKEY_LINEAGE_ID );
                 * actionHarness.setValues( actionParams );
                 */
            }

            actionBean.execute();

            if (stream != null) {
                IOUtils.closeQuietly(stream);
            }

            if (waitForFileCreated) {
                synchronized (lock) {
                    if (outputFilePath == null) {
                        lock.wait();
                    }
                }
                sendEmail(actionParams, params, outputFilePath);
            }

            return updateJob;
        }
    };
    actionBeanRunner.call();
    boolean requiresUpdate = false;
    /*
     * if ( ( actionUser == null ) || ( actionUser.equals( "system session"
     * ) ) ) { //$NON-NLS-1$ // For now, don't try to run quartz jobs as
     * authenticated if the user // that created the job is a system user.
     * See PPP-2350 requiresUpdate =
     * SecurityHelper.getInstance().runAsAnonymous( actionBeanRunner ); }
     * else { try { requiresUpdate = SecurityHelper.getInstance().runAsUser(
     * actionUser, actionBeanRunner ); } catch ( Throwable t ) { Object
     * restartFlag = jobParams.get(
     * OSGiQuartzScheduler.RESERVEDMAPKEY_RESTART_FLAG ); if ( restartFlag
     * == null ) { final SimpleJobTrigger trigger = new SimpleJobTrigger(
     * new Date(), null, 0, 0 ); final Class<IAction> iaction =
     * (Class<IAction>) actionBean.getClass(); // recreate the job in the
     * context of the original creator
     * SecurityHelper.getInstance().runAsUser( actionUser, new
     * Callable<Void>() {
     * 
     * @Override public Void call() throws Exception { if(streamProvider !=
     * null) { streamProvider.setStreamingAction( null ); // remove
     * generated content } QuartzJobKey jobKey = QuartzJobKey.parse(
     * context.getJobDetail().getName() ); String jobName =
     * jobKey.getJobName(); jobParams.put(
     * OSGiQuartzScheduler.RESERVEDMAPKEY_RESTART_FLAG, Boolean.TRUE );
     * scheduler.createJob( jobName, iaction, jobParams, trigger,
     * streamProvider ); log.log(LogService.LOG_WARNING,
     * "New RunOnce job created for " + jobName +
     * " -> possible startup synchronization error" ); return null; } } ); }
     * else { log.log(LogService.LOG_WARNING,
     * "RunOnce already created, skipping" ); throw new Exception( t ); } }
     * }
     */

    scheduler.fireJobCompleted(actionBean, actionUser, params, streamProvider);

    /*
     * if ( requiresUpdate ) { log.log(LogService.LOG_WARNING,
     * "Output path for job: " + context.getJobDetail().getName() +
     * " has changed. Job requires update" ); try { final IJobTrigger
     * trigger = scheduler.getJob( context.getJobDetail().getName()
     * ).getJobTrigger(); final Class<IAction> iaction = (Class<IAction>)
     * actionBean.getClass();
     * 
     * // remove job with outdated/invalid output path scheduler.removeJob(
     * context.getJobDetail().getName() );
     * 
     * // recreate the job in the context of the original creator
     * SecurityHelper.getInstance().runAsUser( actionUser, new
     * Callable<Void>() {
     * 
     * @Override public Void call() throws Exception {
     * streamProvider.setStreamingAction( null ); // remove generated
     * content QuartzJobKey jobKey = QuartzJobKey.parse(
     * context.getJobDetail().getName() ); String jobName =
     * jobKey.getJobName(); org.pentaho.platform.api.scheduler2.Job j =
     * scheduler.createJob( jobName, iaction, jobParams, trigger,
     * streamProvider ); log.log(LogService.LOG_WARNING, "New Job: " +
     * j.getJobId() + " created" ); return null; } } ); } catch ( Exception
     * e ) { log.log(LogService.LOG_ERROR, e.getMessage(), e ); } }
     */

    log.log(LogService.LOG_DEBUG,
            MessageFormat
                    .format("Scheduling system successfully invoked action {0} as user {1} with params [ {2} ]", //$NON-NLS-1$
                            actionBean.getClass().getName(),
                            actionUser, OSGiQuartzSchedulerV2.prettyPrintMap(params)));
}

From source file:com.vmware.identity.idm.client.TenantManagementTest.java

private <T> T ensureNoSuchTenantExceptionOccurred(Callable<T> operation) throws Exception {
    boolean noSuchTenantExceptionOccurred = false;
    T result = null;/*from www  . j  a  va 2 s . c  om*/
    try {
        result = operation.call();
    } catch (NoSuchTenantException nste) {
        noSuchTenantExceptionOccurred = true;
    } finally {
        Assert.assertEquals(true, noSuchTenantExceptionOccurred);
    }
    return result;
}

From source file:org.regenstrief.util.Util.java

public final static <T> T call(final Callable<T> c) {
    try {//from   w w w .  ja v a 2s  .c o m
        return c == null ? null : c.call();
    } catch (final Exception e) {
        throw toRuntimeException(e);
    }
}