本文的目的是介绍salesforce零基础学习的详细情况,特别关注九十八Type浅谈的相关信息。我们将通过专业的研究、有关数据的分析等多种方式,为您呈现一个全面的了解salesforce零基础学习的机
本文的目的是介绍salesforce零基础学习的详细情况,特别关注九十八Type浅谈的相关信息。我们将通过专业的研究、有关数据的分析等多种方式,为您呈现一个全面的了解salesforce零基础学习的机会,同时也不会遗漏关于12. Salesforce Apex异常处理、Java开发笔记(九十八)利用Callable启动线程、OpenSSL学习(十八):基础-指令rsa、org.apache.camel.component.salesforce.api.SalesforceException的实例源码的知识。
本文目录一览:- salesforce零基础学习(九十八)Type浅谈(sales type)
- 12. Salesforce Apex异常处理
- Java开发笔记(九十八)利用Callable启动线程
- OpenSSL学习(十八):基础-指令rsa
- org.apache.camel.component.salesforce.api.SalesforceException的实例源码
salesforce零基础学习(九十八)Type浅谈(sales type)
在Salesforce的世界,凡事皆Metadata。
先通过一句经常使用的代码带入一下:
Account accountItem = (Account)JSON.deserialize(accountString,Account.class);
这种代码相信大部分开发都会写过,前台将数据序列化,通过字符串的形参传递给后台,后台将数据进行反序列化,从而获取到这个表或者这个自定义类的实例。所以问题来了,为啥第二个参数是 Account.class?我们通过官方的API描述可能更好的进行了解。
这里我们引出了 Type的概念,他是apex 预定的类型,包括 基础数据类型(Integer等) , 集合, sObject类型以及 用户定义的类。基础数据类型等等都是 object类型,所以当我们理解salesforce里面的类型时,可以简单的分成两个大类:Object & sObject。所以Type概念引入完了,它用来干嘛?怎么声明?什么时候用呢?
Type t1 = Integer.class;
Type t2 = Type.forName(''Integer'');
system.debug(t1.equals(t2));
上面的简单的demo中提供了两种声明Type的方式,一种是根据 object | sObject使用 .class声明,另外一种是使用 Type的方法forName来实例化变量。既然变量可以声明出来,我们就可以看看他的方法考虑如何搞事情了。
Type的方法非常少,所以我们想要查看其对应的方法描述以及使用很容易就看完。这里针对几个重要的方法进行描述:
- forName(fullyQualifiedName):返回与指定的完全限定的类名相对应的类型。这里的类名包括salesforce系统预制的类,自定义的类以及sObject名称;
- isAssignableFrom(sourceType):如果object指定类型的引用可以从子类型分配,则返回true,否则返回false。这个方法我们可能首先会先想到 instanceof,因为都是来判断类型是否相兼容匹配,但是 instanceof必须是初始化这个类或者对象的变量,才能使用 instanceof 来进行判断,使用 此方法可以省去了静态编译时的依赖,所以如果想判断依赖性,可以优先考虑此方法。
- newInstance():此方法用来实例化一个指定Type的对象,返回类型是一个object对象,我们可以强制转换成我们需要的对象类型。因为apex也是面向对象的语言,封装,继承,多态三大特性,我们可以通过 newInstance实现父子类型的轻松转换调用相关的方法从而实现动态配置。
基础信息介绍完毕,此篇浅入浅出,介绍两种可能用到的场景。
1. JSON序列化与反序列化
这个我们经常使用,一笔带过:通过字符串以及指定的 Type类型可以转换成指定的数据类型。
Account accountItem = (Account)JSON.deserialize(accountString,Account.class);
2. 针对Custom Setting等根据配置的动态的类调用动态方法的使用
ParentClass是一个父类,有两个变量以及一个虚拟的方法,继承的子类可以进行实现
public abstract class ParentClass {
public String param1 { get; set; }
public String param2 { get; set; }
public ParentClass() {
this.param1 = ''value1'';
this.param2 = ''value2'';
}
public virtual String joinParam() {
return param1 + param2;
}
}
SonClass1继承了它并实现了它相关的方法
public class SonClass1 extends ParentClass {
public SonClass1() {
super();
this.param1 = ''son value1'';
this.param2 = ''son value2'';
}
public override String joinParam() {
return super.joinParam();
}
}
还有其他的SonClassn继承了它并实现了它的相关的方法,我们在custom setting中配置了不同的场景应该调用的不同的子类,公共方法中,我们只需要使用以下的代码来判断和调用即可。
public String executeJoin(String className) {
Type t = Type.forName(className);
Type t2 = Type.forName(''ParentClass'');
if(!t2.isAssignableFrom(t)) {
throw new CustomException(''should be son class of ParentClass'');
}
ParentClass newObj = (ParentClass)t.newInstance();
return newObj.joinParam();
}
总结:篇中简单的介绍了salesforce中的 Type的使用,抛砖引玉,想要深入了解还要自行查看官方文档。篇中有错误的地方欢迎指出,有不懂的欢迎留言。
12. Salesforce Apex异常处理
一些常用的异常:
// Math Exception
//Double result = 10/0;
//System.debug(''Result: ''+result);
// DML Exception
//Account accRec = new Account();
//insert accRec;
// Null Pointer Exception
//String str;
//System.debug(str.toLowerCase());
// throw an exception Programmatically
throw new NullPointerException();
需要记住的一点是, 一旦代码或程序抛出异常, 整个事务将回滚, 包括DML事务。 因此我们需要了解如何处理这些异常,下面我们将学习如何妥善处理这些异常, 然后从中恢复。因此, 这意味着, 当抛出异常时, 您可以处理它, 在处理了这个异常之后, 程序的代码执行并没有停止, 它还继续执行。
所以, 你需要了解try - catch - finally。 如果你认为你的程序可以在特定的一行或者特定的一段代码中抛出某种类型的异常, 那么你应该把这段代码放在try块中。
因此, 您需要识别可能在稍后阶段抛出异常的代码, 然后需要将其放入try块中。 在try块之后, 可以有两种不同类型的块。第一个是catch块, 第二个是finally块, 这两个块都在try块之后执行。 catch块的工作是捕获try块引发的特定异常。
- 一个try块可以有多个catch块, 每个catch块都捕获不同类型的异常。
- 无论异常是否从try块中抛出, finally都将始终执行, 而catch块仅在抛出异常并被catch块捕获时执行。
System.debug(''Before Exception'');
try{
// Math Exception
//Double result = 10/0;
//System.debug(''Result: ''+result);
//DML Exception
Account accRec = new Account();
insert accRec;
System.debug(''Empty try block '');
} catch(MathException e){
System.debug(''Cought Math exception '');
} catch(DMLException e){
System.debug(''Cought DML Exception'');
}finally {
System.debug(''finally called '');
}
System.debug(''After Exception'');
Exception类是其他异常类(MathException,DMLException...)的父类
System.debug(''Before Exception'');
try{
// Math Exception
Double result = 10/0;
System.debug(''Result: ''+result);
// DML Exception
// Account accRec = new Account();
// insert accRec;
System.debug(''Empty try block '');
} catch(Exception e){
System.debug(''Caught generic exception '');
} finally {
System.debug(''finally called '');
}
System.debug(''After Exception'');
System.debug(''Before Exception'');
try{
// Math Exception
Double result = 10/0;
System.debug(''Result: ''+result);
// DML Exception
// Account accRec = new Account();
// insert accRec;
System.debug(''Empty try block '');
} catch(Exception e){
system.debug(''Cause ''+e.getCause());
system.debug(''Message ''+e.getMessage());
system.debug(''Line Number ''+e.getLineNumber());
system.debug(''Stack Trace ''+e.getStackTraceString ());
} finally {
System.debug(''finally called '');
}
System.debug(''After Exception'');
现在, 让我们转到Apex文档, 在这里, 我们可以看到常见的异常方法。
- 第一个方法是getCause方法, 它返回异常的原因。
- 第二个是getLineNumber, 它返回异常从哪一行抛出, 例如, 在这段代码中, 异常将从第四行抛出。 因此, 您可以使用getLineNumber方法获取该行。
- 第三个方法是getMessage, 它将显示完整的异常消息。
- 第四个是getStackTraceString, 它会返回代码的完整堆栈跟踪, 比如异常从哪里抛出的, 哪个方法调用了那一行, 以及该方法存在于哪个类中.
- 您还可以使用getTypeName获取异常类型, 这在处理类似的泛型异常时非常有用。
定义义异常类
如果想要构建自己的异常框架, 那么在这种情况下, 除了Apex提供的内置异常之外, 您可能还需要创建自己的异常, 以便可以创建自己的自定义异常。
因此, 您需要创建一个新的Apex类, 并需要继承Exception类。 我将创建一个新的自定义异常, 并将其命名为ProcessException, 此Apex类必须继承Exception类。
// a custom exception class
public class ProcessException extends Exception {
}
System.debug(''Before Exception'');
try{
throw new ProcessException(''My custom exception'');
} catch(Exception e){
system.debug(''Cause ''+e.getCause());
system.debug(''Message ''+e.getMessage());
system.debug(''Line Number ''+e.getLineNumber());
system.debug(''Stack Trace ''+e.getStackTraceString ());
} finally {
System.debug(''finally called '');
}
System.debug(''After Exception'');
Java开发笔记(九十八)利用Callable启动线程
前面介绍了如何利用Runnable接口构建线程任务,该方式确实方便了线程代码的复用与共享,然而Runnable不像公共方法那样有返回值,也就无法将线程代码的处理结果传给外部,造成外部既不知晓该线程是否已经执行完毕,也不了解该线程的运算结果是什么,总之无法跟踪分线程的行动踪迹。这里显然是不完美的,调用方法都有返回值,为何通过Runnable启动线程就无法获得返回值呢?为此Java又提供了另一种开启线程的方式,即利用Callable接口构建任务代码,实现该接口需要重写call方法,call方法类似run方法,同样存放着开发者定义的任务代码。不同的是,run方法没有返回值,而call方法支持定义输出参数,从而在设计上保留了分线程在运行结束时返回结果的可能性。
Callable是个泛型接口,它的返回值类型在外部调用时指定,要想创建一个Callable实例,既能通过定义完整的新类来实现,也能通过普通的匿名内部类实现。举个简单的应用例子,比如希望开启分线程生成某个随机数,并将随机数返回给主线程,则采取匿名内部类方式书写的Callable定义代码如下所示:
// 定义一个Callable代码段,返回100以内的随机整数
// 第一种方式:采取匿名内部类方式书写
Callable<Integer> callable = new Callable<Integer>() {
@Override
public Integer call() { // 返回值为Integer类型
int random = new Random().nextInt(100); // 获取100以内的随机整数
// 以下打印随机数日志,包括当前时间、当前线程、随机数值等信息
PrintUtils.print(Thread.currentThread().getName(), "任务生成的随机数="+random);
return random;
}
};
由于Callable又是个函数式接口,因此能够利用Lambda表达式来简化匿名内部类,于是掐头去尾后的Lambda表达式代码示例如下:
// 第二种方式:采取Lambda表达式书写
Callable<Integer> callable = () -> {
int random = new Random().nextInt(100);
PrintUtils.print(Thread.currentThread().getName(), "任务生成的随机数="+random);
return random;
};
因为获取随机数的关键代码仅有一行,所以完全可以进一步精简Lambda表达式的代码,压缩冗余后只有下面短小精悍的一行代码:
// 第三种方式:进一步精简后的Lambda表达式
Callable<Integer> callable = () -> new Random().nextInt(100);
有了Callable实例之后,还需要引入未来任务FutureTask把它包装一下,因为只有FutureTask才能真正跟踪任务的执行状态。以下是FutureTask的主要方法说明:
run:启动未来任务。
get:获取未来任务的执行结果。
isDone:判断未来任务是否执行完毕。
cancel:取消未来任务。
isCancelled:判断未来任务是否取消。
现在结合Callable与FutureTask,串起来运行一下拥有返回值的未来任务,首先把Callable实例填进FutureTask的构造方法,由此得到一个未来任务的实例;接着调用未来任务的run方法启动该任务,最后调用未来任务的get方法获取任务的执行结果。根据以上步骤编写的未来任务代码如下所示:
// 根据代码段实例创建一个未来任务
FutureTask<Integer> future = new FutureTask<Integer>(callable);
future.run(); // 运行未来任务
try {
Integer result = future.get(); // 获取未来任务的执行结果
PrintUtils.print(Thread.currentThread().getName(), "主线程的执行结果="+result);
} catch (InterruptedException | ExecutionException e) {
// get方法会一直等到未来任务的执行完成,由于等待期间可能收到中断信号,因此这里得捕捉中断异常
e.printStackTrace();
}
运行上述的任务调用代码,观察到的任务日志如下:
16:48:53.363 main 任务生成的随机数=11
16:48:53.422 main 主线程的执行结果=11
有没有发现什么不对劲的地方?第一行日志是在Callable实例的call方法中打印的,第二行日志是在主线程获得返回值后打印的,可是从日志看,两行日志都由main线程也就是主线程输出的,说明未来任务仍然由主线程执行,而非由分线程执行。
那么如何才能开启分线程来执行未来任务呢?当然还得让Thread类亲自出马了,就像使用分线程执行Runnable任务那样,同样要把Callable实例放入Thread的构造方法当中,然后再调用线程实例的start方法方可启动线程任务。于是添加线程类之后的未来任务代码变成了下面这样:
// 根据代码段实例创建一个未来任务
FutureTask<Integer> future = new FutureTask<Integer>(callable);
// 把未来任务放入新创建的线程中,并启动分线程处理
new Thread(future).start();
try {
Integer result = future.get(); // 获取未来任务的执行结果
PrintUtils.print(Thread.currentThread().getName(), "主线程的执行结果="+result);
} catch (InterruptedException | ExecutionException e) {
// get方法会一直等到未来任务的执行完成,由于等待期间可能收到中断信号,因此这里得捕捉中断异常
e.printStackTrace();
}
运行上面的未来任务代码,观察到以下的程序日志:
16:49:49.816 Thread-0 任务生成的随机数=38
16:49:49.820 main 主线程的执行结果=38
从日志中的Thread-0名称可知,此时的未来任务总算交由分线程执行了。
更多Java技术文章参见《Java开发笔记(序)章节目录》
OpenSSL学习(十八):基础-指令rsa
用法openssl rsa [-inform PEM|NET|DER] [-outform PEM|NET|DER] [-in filename]
[-passin arg] [-out filename] [-passout arg] [-sgckey] [-des] [-des3]
[-idea] [-text] [-noout] [-modulus] [-check] [-pubin] [-pubout]
说明:
rsa指令专门处理RSA密钥.其实其用法和dsa的差不多.
OPTIONS
-inform DER|PEM|NET
指定输入的格式是DEM还是DER还是NET.注意, 这里多了一种格式,就是NET,DER格式采用ASN1的DER标准格式。一般用的多的都是PEM格式,就是base64编码格式.你去看看你做出来的那些.key, .crt文件一般都是PEM格式的,第一行和最后一行指明内容,中间就是经过编码的东西。NET格式在本章后面会详细解释.
-outform DER|PEM|NET
和上一个差不多,不同的是指定输出格式
-in filename
要分析的文件名称。如果文件有密码保护,会要你输入的.
-passin arg
去看看CA那一章关于这个option的解释吧。
-out filename
要输出的文件名。
-passout arg
没什么用的一个选项,用来把保护key文件的密码输出的,意义和passin差不多。
-sgckey
配合NET格式的私有密钥文件的一个option, 没有必要去深入知道了。
-des|-des3|-idea
指明用什么加密算法把我们的私有密钥加密。加密的时候会需要我们输入密码来保护该文件的。如果这仨一个都没有选,那么你的私有密钥就以明文写进你的key文件。该选项只能输出PEM格式的文件。
-text
打印出私有密钥的各个组成部分.
-noout
不打印出key的编码版本信息。
-modulus
把其公共密钥的值也打印出来
-pubin
缺省的来说是从输入文件里读到私有密钥,这个就可以从输入文件里去读公共密钥.
-pubout
缺省的来说是打印出私有密钥,这个就可以打印公共密钥.如果上面那个选项有set那么这个选项也自动被set.
-check
检查RSA的私有密钥是否被破坏了这个指令实在和dsa太相似了。copy的我手软。
现在解释一下NET是一种什么格式。它是为了和老的netscape server以及IIS兼容才弄出来的。他使用没有被salt过的RC4做加密算法,加密强度很底,如果不是一定要用就别用。
举例时间:
把RSA私有密钥文件的保护密码去掉(最好别这么做)
openssl rsa -in key.pem -out keyout.pem
用DES3算法加密我们的私有密码文件:
openssl rsa -in key.pem -des3 -out keyout.pem
把一个私有密钥文件从PEM格式转化成DER格式:
openssl rsa -in key.pem -outform DER -out keyout.der
把私有密钥的所有内容详细的打印出来:
openssl rsa -in key.pem -text -noout
只打印出公共密钥部分:
openssl rsa -in key.pem -pubout -out pubkey.pem
org.apache.camel.component.salesforce.api.SalesforceException的实例源码
public SalesforceUpdateSObjectComponent() { super("salesforce-update-sobject",SalesforceUpdateSObjectComponent.class.getName()); // set sObjectId header setBeforeProducer(exchange -> { // parse input json and extract Id field final ObjectMapper mapper = JsonUtils.createObjectMapper(); final JsonNode node = mapper.readTree(exchange.getIn().getBody(String.class)); final JsonNode sObjectId = node.get("Id"); if (sObjectId == null) { exchange.setException(new SalesforceException("Missing field Id",404)); } else { exchange.getIn().setHeader(SalesforceEndpointConfig.soBJECT_ID,sObjectId.asText()); } clearBaseFields((ObjectNode) node); // update input json exchange.getIn().setBody(mapper.writeValueAsstring(node)); }); }
public SalesforceProducer(SalesforceEndpoint endpoint) throws SalesforceException { super(endpoint); final SalesforceEndpointConfig endpointConfig = endpoint.getConfiguration(); final PayloadFormat payloadFormat = endpointConfig.getFormat(); // check if its a Bulk Operation final OperationName operationName = endpoint.getoperationName(); if (isBulkOperation(operationName)) { processor = new BulkApiProcessor(endpoint); } else if (isAnalyticsOperation(operationName)) { processor = new AnalyticsApiProcessor(endpoint); } else { // create an appropriate processor if (payloadFormat == PayloadFormat.JSON) { // create a JSON exchange processor processor = new JsonRestProcessor(endpoint); } else { processor = new XmlRestProcessor(endpoint); } } }
private void processGetJob(final Exchange exchange,final AsyncCallback callback) throws SalesforceException { JobInfo jobBody; jobBody = exchange.getIn().getBody(JobInfo.class); String jobId; if (jobBody != null) { jobId = jobBody.getId(); } else { jobId = getParameter(JOB_ID,exchange,USE_BODY,NOT_OPTIONAL); } bulkClient.getJob(jobId,new Bulkapiclient.JobInfoResponseCallback() { @Override public void onResponse(JobInfo jobInfo,SalesforceException ex) { processResponse(exchange,jobInfo,ex,callback); } }); }
private void processCloseJob(final Exchange exchange,final AsyncCallback callback) throws SalesforceException { JobInfo jobBody; String jobId; jobBody = exchange.getIn().getBody(JobInfo.class); if (jobBody != null) { jobId = jobBody.getId(); } else { jobId = getParameter(JOB_ID,NOT_OPTIONAL); } bulkClient.closeJob(jobId,callback); } }); }
private void processAbortJob(final Exchange exchange,NOT_OPTIONAL); } bulkClient.abortJob(jobId,callback); } }); }
private void processCreateBatch(final Exchange exchange,final AsyncCallback callback) throws SalesforceException { String jobId; // since request is in the body,use headers or endpoint params ContentType contentType = ContentType.fromValue( getParameter(CONTENT_TYPE,IGnorE_BODY,NOT_OPTIONAL)); jobId = getParameter(JOB_ID,NOT_OPTIONAL); InputStream request; try { request = exchange.getIn().getMandatoryBody(InputStream.class); } catch (CamelException e) { String msg = "Error preparing batch request: " + e.getMessage(); throw new SalesforceException(msg,e); } bulkClient.createBatch(request,jobId,contentType,new Bulkapiclient.BatchInfoResponseCallback() { @Override public void onResponse(BatchInfo batchInfo,batchInfo,callback); } }); }
private void processGetBatch(final Exchange exchange,final AsyncCallback callback) throws SalesforceException { String jobId; BatchInfo batchBody = exchange.getIn().getBody(BatchInfo.class); String batchId; if (batchBody != null) { jobId = batchBody.getJobId(); batchId = batchBody.getId(); } else { jobId = getParameter(JOB_ID,NOT_OPTIONAL); batchId = getParameter(BATCH_ID,NOT_OPTIONAL); } bulkClient.getBatch(jobId,batchId,callback); } }); }
private void processGetAllBatches(final Exchange exchange,NOT_OPTIONAL); } bulkClient.getAllBatches(jobId,new Bulkapiclient.BatchInfoListResponseCallback() { @Override public void onResponse(List<BatchInfo> batchInfoList,batchInfoList,callback); } }); }
private void processCreateBatchQuery(final Exchange exchange,final AsyncCallback callback) throws SalesforceException { JobInfo jobBody; String jobId; ContentType contentType; jobBody = exchange.getIn().getBody(JobInfo.class); String soqlQuery; if (jobBody != null) { jobId = jobBody.getId(); contentType = jobBody.getContentType(); // use SOQL query from header or endpoint config soqlQuery = getParameter(SOBJECT_QUERY,NOT_OPTIONAL); } else { jobId = getParameter(JOB_ID,NOT_OPTIONAL); contentType = ContentType.fromValue( getParameter(CONTENT_TYPE,NOT_OPTIONAL)); // reuse SOBJECT_QUERY property soqlQuery = getParameter(SOBJECT_QUERY,NOT_OPTIONAL); } bulkClient.createBatchQuery(jobId,soqlQuery,new Bulkapiclient.BatchInfoResponseCallback() { @Override public void onResponse(BatchInfo batchInfo,SalesforceException ex) { processResponse(exchange,callback); } }); }
private void processGetQueryResultIds(final Exchange exchange,final AsyncCallback callback) throws SalesforceException { String jobId; BatchInfo batchBody; String batchId; batchBody = exchange.getIn().getBody(BatchInfo.class); if (batchBody != null) { jobId = batchBody.getJobId(); batchId = batchBody.getId(); } else { jobId = getParameter(JOB_ID,NOT_OPTIONAL); } bulkClient.getQueryResultIds(jobId,new Bulkapiclient.QueryResultIdsCallback() { @Override public void onResponse(List<String> ids,ids,callback); } }); }
private void processCreateSobject(final Exchange exchange,final AsyncCallback callback) throws SalesforceException { String sObjectName; // determine parameters from input AbstractSObject AbstractSObjectBase sObjectBase = exchange.getIn().getBody(AbstractSObjectBase.class); if (sObjectBase != null) { sObjectName = sObjectBase.getClass().getSimpleName(); } else { sObjectName = getParameter(SOBJECT_NAME,NOT_OPTIONAL); } restClient.createSObject(sObjectName,getRequestStream(exchange),new RestClient.ResponseCallback() { @Override public void onResponse(InputStream response,SalesforceException exception) { processResponse(exchange,response,exception,callback); } }); }
private void processUpdateSobject(final Exchange exchange,final AsyncCallback callback) throws SalesforceException { String sObjectName; // determine parameters from input AbstractSObject final AbstractSObjectBase sObjectBase = exchange.getIn().getBody(AbstractSObjectBase.class); String sObjectId; if (sObjectBase != null) { sObjectName = sObjectBase.getClass().getSimpleName(); // remember the sObject Id sObjectId = sObjectBase.getId(); // clear base object fields,which cannot be updated sObjectBase.clearBaseFields(); } else { sObjectName = getParameter(SOBJECT_NAME,NOT_OPTIONAL); sObjectId = getParameter(SOBJECT_ID,NOT_OPTIONAL); } final String finalsObjectId = sObjectId; restClient.updateSObject(sObjectName,sObjectId,callback); restoreFields(exchange,sObjectBase,finalsObjectId,null,null); } }); }
private void processDeleteSobject(final Exchange exchange,final AsyncCallback callback) throws SalesforceException { String sObjectName; // determine parameters from input AbstractSObject final AbstractSObjectBase sObjectBase = exchange.getIn().getBody(AbstractSObjectBase.class); String sObjectIdValue; if (sObjectBase != null) { sObjectName = sObjectBase.getClass().getSimpleName(); sObjectIdValue = sObjectBase.getId(); } else { sObjectName = getParameter(SOBJECT_NAME,NOT_OPTIONAL); sObjectIdValue = getParameter(SOBJECT_ID,NOT_OPTIONAL); } final String sObjectId = sObjectIdValue; restClient.deleteSObject(sObjectName,new RestClient.ResponseCallback() { @Override public void onResponse(InputStream response,SalesforceException exception) { processResponse(exchange,callback); restoreFields(exchange,null); } }); }
private void restoreFields(Exchange exchange,AbstractSObjectBase sObjectBase,String sObjectId,String sObjectExtIdName,Object oldValue) { // restore fields if (sObjectBase != null) { // restore the Id if it was cleared if (sObjectId != null) { sObjectBase.setId(sObjectId); } // restore the external id if it was cleared if (sObjectExtIdName != null && oldValue != null) { try { setPropertyValue(sObjectBase,sObjectExtIdName,oldValue); } catch (SalesforceException e) { // YES,the exchange may fail if the property cannot be reset!!! exchange.setException(e); } } } }
private void setResponseClass(Exchange exchange,String sObjectName) throws SalesforceException { Class<?> sObjectClass; if (sObjectName != null) { // lookup class from class map sObjectClass = classMap.get(sObjectName); if (null == sObjectClass) { throw new SalesforceException(String.format("No class found for SObject %s",sObjectName),null); } } else { // use custom response class property final String className = getParameter(SOBJECT_CLASS,NOT_OPTIONAL); try { sObjectClass = endpoint.getComponent().getCamelContext() .getClassResolver().resolveMandatoryClass(className); } catch (ClassNotFoundException e) { throw new SalesforceException( String.format("SObject class not found %s,%s",className,e.getMessage()),e); } } exchange.setProperty(RESPONSE_CLASS,sObjectClass); }
private void processExecuteSyncReport(final Exchange exchange,final AsyncCallback callback) throws SalesforceException { String reportId; final Boolean includeDetails = getParameter(INCLUDE_DETAILS,IS_OPTIONAL,Boolean.class); // try getting report Metadata from body first ReportMetadata reportMetadata = exchange.getIn().getBody(ReportMetadata.class); if (reportMetadata != null) { reportId = reportMetadata.getId(); if (reportId == null) { reportId = getParameter(REPORT_ID,NOT_OPTIONAL); } } else { reportId = getParameter(REPORT_ID,NOT_OPTIONAL); reportMetadata = getParameter(REPORT_MetaDATA,ReportMetadata.class); } analyticsClient.executeSyncReport(reportId,includeDetails,reportMetadata,new Analyticsapiclient.ReportResultsResponseCallback() { @Override public void onResponse(AbstractReportResultsBase reportResults,reportResults,callback); } }); }
private void processExecuteAsyncReport(final Exchange exchange,ReportMetadata.class); } analyticsClient.executeAsyncReport(reportId,new Analyticsapiclient.ReportInstanceResponseCallback() { @Override public void onResponse(ReportInstance reportInstance,reportInstance,callback); } }); }
@Override public void getJob(String jobId,final JobInfoResponseCallback callback) { final Request get = getRequest(HttpMethod.GET,jobUrl(jobId)); // make the call and parse the result doHttpRequest(get,new ClientResponseCallback() { @Override public void onResponse(InputStream response,SalesforceException ex) { JobInfo value = null; try { value = unmarshalResponse(response,get,JobInfo.class); } catch (SalesforceException e) { ex = e; } callback.onResponse(value,ex); } }); }
@Override public void createBatch(InputStream batchStream,String jobId,ContentType contentTypeEnum,final BatchInfoResponseCallback callback) { final Request post = getRequest(HttpMethod.POST,batchUrl(jobId,null)); post.content(new InputStreamContentProvider(batchStream)); post.header(HttpHeader.CONTENT_TYPE,getContentType(contentTypeEnum) + ";charset=" + StringUtil.__UTF8); // make the call and parse the result doHttpRequest(post,SalesforceException ex) { BatchInfo value = null; try { value = unmarshalResponse(response,post,BatchInfo.class); } catch (SalesforceException e) { ex = e; } callback.onResponse(value,ex); } }); }
@Override public void getBatch(String jobId,String batchId,final BatchInfoResponseCallback callback) { final Request get = getRequest(HttpMethod.GET,batchId)); // make the call and parse the result doHttpRequest(get,ex); } }); }
@Override public void getAllBatches(String jobId,final BatchInfoListResponseCallback callback) { final Request get = getRequest(HttpMethod.GET,null)); // make the call and parse the result doHttpRequest(get,SalesforceException ex) { BatchInfoList value = null; try { value = unmarshalResponse(response,BatchInfoList.class); } catch (SalesforceException e) { ex = e; } callback.onResponse(value != null ? value.getBatchInfo() : null,ex); } }); }
@Override public void getQueryResultIds(String jobId,final QueryResultIdsCallback callback) { final Request get = getRequest(HttpMethod.GET,batchResultUrl(jobId,SalesforceException ex) { QueryResultList value = null; try { value = unmarshalResponse(response,QueryResultList.class); } catch (SalesforceException e) { ex = e; } callback.onResponse(value != null ? Collections.unmodifiableList(value.getResult()) : null,ex); } }); }
@Override protected SalesforceException createRestException(Response response,InputStream responseContent) { // this must be of type Error try { final Error error = unmarshalResponse(responseContent,response.getRequest(),Error.class); final RestError restError = new RestError(); restError.setErrorCode(error.getExceptionCode()); restError.setMessage(error.getExceptionMessage()); return new SalesforceException(Arrays.asList(restError),response.getStatus()); } catch (SalesforceException e) { String msg = "Error un-marshaling Salesforce Error: " + e.getMessage(); return new SalesforceException(msg,e); } }
@Override public void query(String soqlQuery,ResponseCallback callback) { try { String encodedQuery = urlEncode(soqlQuery); final Request get = getRequest(HttpMethod.GET,versionUrl() + "query/?q=" + encodedQuery); // requires authorization token setAccesstoken(get); doHttpRequest(get,new DelegatingClientCallback(callback)); } catch (UnsupportedEncodingException e) { String msg = "Unexpected error: " + e.getMessage(); callback.onResponse(null,new SalesforceException(msg,e)); } }
@Override public void search(String soslQuery,ResponseCallback callback) { try { String encodedQuery = urlEncode(soslQuery); final Request get = getRequest(HttpMethod.GET,versionUrl() + "search/?q=" + encodedQuery); // requires authorization token setAccesstoken(get); doHttpRequest(get,e)); } }
@Override public void getRecentReports(final RecentReportsResponseCallback callback) { final Request request = getRequest(HttpMethod.GET,reportsUrl()); doHttpRequest(request,new ClientResponseCallback() { @Override @SuppressWarnings("unchecked") public void onResponse(InputStream response,SalesforceException ex) { List<RecentReport> recentReports = null; if (response != null) { try { recentReports = unmarshalResponse(response,request,new TypeReference<List<RecentReport>>() { } ); } catch (SalesforceException e) { ex = e; } } callback.onResponse(recentReports,ex); } }); }
@Override public void getReportDescription(String reportId,final ReportDescriptionResponseCallback callback) { final Request request = getRequest(HttpMethod.GET,reportsDescribeUrl(reportId)); doHttpRequest(request,SalesforceException ex) { ReportDescription reportDescription = null; try { reportDescription = unmarshalResponse(response,ReportDescription.class); } catch (SalesforceException e) { ex = e; } callback.onResponse(reportDescription,ex); } }); }
@Override public void getReportInstances(String reportId,final ReportInstanceListResponseCallback callback) { final Request request = getRequest(HttpMethod.GET,reportInstancesUrl(reportId)); doHttpRequest(request,SalesforceException ex) { List<ReportInstance> reportInstances = null; if (response != null) { try { reportInstances = unmarshalResponse(response,new TypeReference<List<ReportInstance>>() { } ); } catch (SalesforceException e) { ex = e; } } callback.onResponse(reportInstances,ex); } }); }
@Override public void getReportResults(String reportId,String instanceId,final ReportResultsResponseCallback callback) { final Request request = getRequest(HttpMethod.GET,reportInstancesUrl(reportId,instanceId)); doHttpRequest(request,SalesforceException ex) { AsyncReportResults reportResults = null; try { reportResults = unmarshalResponse(response,AsyncReportResults.class); } catch (SalesforceException e) { ex = e; } callback.onResponse(reportResults,ex); } }); }
private <T> T unmarshalResponse(InputStream response,Request request,Class<T> responseClass) throws SalesforceException { if (response == null) { return null; } try { return objectMapper.readValue(response,responseClass); } catch (IOException e) { throw new SalesforceException( String.format("Error unmarshaling response {%s:%s} : %s",request.getmethod(),request.getURI(),e); } }
@Test public void testApexCall() throws Exception { try { doTestApexCall(""); doTestApexCall("Xml"); } catch (CamelExecutionException e) { if (e.getCause() instanceof SalesforceException) { SalesforceException cause = (SalesforceException) e.getCause(); if (cause.getStatusCode() == HttpStatus.NOT_FOUND_404) { LOG.error("Make sure test REST resource MerchandiseRestResource.apxc has been loaded: " + e.getMessage()); } } throw e; } }
@Override public void process(final Exchange exchange) throws Exception { // parse input json and extract Id field final Message in = exchange.getIn(); final String body = in.getBody(String.class); if (body == null) { return; } final ObjectNode node = (ObjectNode) MAPPER.readTree(body); final String idPropertyName = determineIdProperty(exchange); final JsonNode idProperty = node.remove(idPropertyName); if (idProperty == null) { exchange.setException( new SalesforceException("Missing option value for Id or " + SalesforceEndpointConfig.soBJECT_EXT_ID_NAME,404)); return; } final String idValue = idProperty.textValue(); if ("Id".equals(idPropertyName)) { in.setHeader(SalesforceEndpointConfig.soBJECT_ID,idValue); } else { in.setHeader(SalesforceEndpointConfig.soBJECT_EXT_ID_VALUE,idValue); } // base fields are not allowed to be updated clearBaseFields(node); // update input json in.setBody(MAPPER.writeValueAsstring(node)); }
@Override protected void doStop() throws Exception { if (classMap != null) { classMap.clear(); } try { if (subscriptionHelper != null) { // shutdown all streaming connections // note that this is done in the component,and not in consumer ServiceHelper.stopService(subscriptionHelper); subscriptionHelper = null; } if (session != null && session.getAccesstoken() != null) { try { // logout of Salesforce ServiceHelper.stopService(session); } catch (SalesforceException ignored) { } } } finally { if (httpClient != null) { // shutdown http client connections httpClient.stop(); // destroy http client if it was created by the component if (config.getHttpClient() == null) { httpClient.destroy(); } httpClient = null; } } }
/** * Gets value for a parameter from header,endpoint config,or exchange body (optional). * * @param exchange exchange to inspect * @param convertInBody converts In body to parameterClass value if true * @param propName name of property * @param optional if {@code true} returns null,otherwise throws RestException * @param parameterClass parameter type * @return value of property,or {@code null} for optional parameters if not found. * @throws org.apache.camel.component.salesforce.api.SalesforceException * if the property can't be found or on conversion errors. */ protected final <T> T getParameter(String propName,Exchange exchange,boolean convertInBody,boolean optional,Class<T> parameterClass) throws SalesforceException { final Message in = exchange.getIn(); T propValue = in.getHeader(propName,parameterClass); if (propValue == null) { // check if type conversion Failed if (in.getHeader(propName) != null) { throw new IllegalArgumentException("Header " + propName + " Could not be converted to type " + parameterClass.getName()); } final Object value = endpointConfigMap.get(propName); if (value == null || parameterClass.isinstance(value)) { propValue = parameterClass.cast(value); } else { try { propValue = exchange.getContext().getTypeConverter().mandatoryConvertTo(parameterClass,value); } catch (NoTypeConversionAvailableException e) { throw new SalesforceException(e); } } } propValue = (propValue == null && convertInBody) ? in.getBody(parameterClass) : propValue; // error if property was not set if (propValue == null && !optional) { String msg = "Missing property " + propName + (convertInBody ? ",message body Could not be converted to type " + parameterClass.getName() : ""); throw new SalesforceException(msg,null); } return propValue; }
private void processCreateJob(final Exchange exchange,final AsyncCallback callback) throws InvalidPayloadException { JobInfo jobBody = exchange.getIn().getMandatoryBody(JobInfo.class); bulkClient.createJob(jobBody,callback); } }); }
private void processResponse(Exchange exchange,Object body,SalesforceException ex,AsyncCallback callback) { final Message out = exchange.getout(); if (ex != null) { exchange.setException(ex); } else { out.setBody(body); } // copy headers and attachments out.getHeaders().putAll(exchange.getIn().getHeaders()); out.getAttachments().putAll(exchange.getIn().getAttachments()); // signal exchange completion callback.done(false); }
private void processGetVersions(final Exchange exchange,final AsyncCallback callback) { restClient.getVersions(new RestClient.ResponseCallback() { @Override public void onResponse(InputStream response,SalesforceException exception) { // process response entity and create out message processResponse(exchange,callback); } }); }
private void processGetResources(final Exchange exchange,final AsyncCallback callback) { restClient.getResources(new RestClient.ResponseCallback() { @Override public void onResponse(InputStream response,callback); } }); }
private void processGetGlobalObjects(final Exchange exchange,final AsyncCallback callback) { restClient.getGlobalObjects(new RestClient.ResponseCallback() { @Override public void onResponse(InputStream response,callback); } }); }
private void processGetBasicInfo(final Exchange exchange,final AsyncCallback callback) throws SalesforceException { String sObjectName = getParameter(SOBJECT_NAME,NOT_OPTIONAL); restClient.getBasicInfo(sObjectName,callback); } }); }
关于salesforce零基础学习和九十八Type浅谈的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于12. Salesforce Apex异常处理、Java开发笔记(九十八)利用Callable启动线程、OpenSSL学习(十八):基础-指令rsa、org.apache.camel.component.salesforce.api.SalesforceException的实例源码等相关内容,可以在本站寻找。
本文标签: