I want to generate a client program using the service
I am unable to display the results, how can I do so?
import java.rmi.RemoteException;
public class searchtry {
public static void main(String[] args) throws RemoteException {
SearchRequest request=new SearchRequest();
SearchRequestType1 type1=new SearchRequestType1();
query.setAppId("*********************************"); //Windows Live gave this id for using that service
query.setSources(new SourceType[]{SourceType.Web});
query.setQuery("Java");
aratip.setParameters(request);
SearchResponseType0 answer= client.search(type1);
System.out.println(answer.toString());
}
For starters, calling
answer.toString();
May or may not result in anything (usually won't). You might just get a string that represents the instance, not the string you're expecting. You need to find a method on SearchResponseType0 that will give you the string representation of the response. Perhaps a method like getContent() or getResponse() or something like that but without understanding more about the web service it's difficult to give you more help. Bottom line, you're using the wrong method to attempt to get the string content of the result.
It looks like your are using the bing-search-java-sdk. They have a very nice example on their homepage you might want to look at:
BingSearchServiceClientFactory factory = BingSearchServiceClientFactory.newInstance();
BingSearchClient client = factory.createBingSearchClient();
SearchRequestBuilder builder = client.newSearchRequestBuilder();
builder.withAppId(applicationId);
builder.withQuery("msdn blogs");
builder.withSourceType(SourceType.WEB);
builder.withVersion("2.0");
builder.withMarket("en-us");
builder.withAdultOption(AdultOption.MODERATE);
builder.withSearchOption(SearchOption.ENABLE_HIGHLIGHTING);
builder.withWebRequestCount(10L);
builder.withWebRequestOffset(0L);
builder.withWebRequestSearchOption(WebSearchOption.DISABLE_HOST_COLLAPSING);
builder.withWebRequestSearchOption(WebSearchOption.DISABLE_QUERY_ALTERATIONS);
SearchResponse response = client.search(builder.getResult());
for (WebResult result : response.getWeb().getResults()) {
System.out.println(result.getTitle());
System.out.println(result.getDescription());
System.out.println(result.getUrl());
System.out.println(result.getDateTime());
}
Related
This is my utility class to mock the service
public class MockService {
public static void bootUpMockServices() throws IOException {
String orderServiceSpecification = readFile("mappings/orderServicesSpecifications.json", Charset.defaultCharset());
String singleOrder = readFile("mappings/singleOrder.json", Charset.defaultCharset());
WireMock.stubFor(WireMock.get(WireMock.urlEqualTo("/orders"))
.willReturn(WireMock.aResponse()
.withStatus(200)
.withBody(orderServiceSpecification)));
WireMock.stubFor(WireMock.get(WireMock.urlEqualTo("/orders/1"))
.willReturn(WireMock.aResponse()
.withStatus(200)
.withBody(singleOrder)));
}
public static String readFile(String path, Charset encoding)
throws IOException {
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
}
As you can see I'm mocking a GET call /orders (with all the orders) and responding with the body with all the orders kept in a json file.
I'm also calling a single order by GET call /orders/1. I'm responding it with an JSON object in a file. But I want it to be dynamic. Like when I hit it with orders/30 then, I should be dynamically fetch order with id=30 and render it.
Currently, if you want dynamic behaviour of the kind you described you'll need to write a ResponseDefinitionTransformer and register it with the WireMockServer or WireMockRule on construction.
This is documented here: http://wiremock.org/docs/extending-wiremock/#transforming-responses
Example of a transformer implementation here:
https://github.com/tomakehurst/wiremock/blob/master/src/test/java/com/github/tomakehurst/wiremock/ResponseDefinitionTransformerAcceptanceTest.java#L208-L222
What you're trying to do could be done pretty straightforwardly with a stub mapping matching on a URL regex something like /orders/(\d+) and a transformer that parses out the number part then modifies the bodyFileName on the ResponseDefinition.
I am new to building web applications using spark java.
I am trying to use 'Before' filter but getting the below error. please help. I have pasted my code below.Bootstrap is my class having the main method.
Error: "The method before is undefined for the type BootStrap"
public class BootStrap {
public static void main(String[] args) throws Exception {
ipAddress("localhost");
port(3003);
staticFileLocation("/public/html");
before((request, response) -> {
String user = request.queryParams("user");
String password = request.queryParams("password");
String dbPassword = usernamePasswords.get(user);
if (!(password != null && password.equals(dbPassword))) {
halt(401, "You are not welcome here!!!");
}
});
}
I think it's just lacking to statically import Spark.*;
Not sure this helps, but according to this "Access-Control-Request-Method" is a request header, not a response header. That said, a 404 always shows that the resource you want to find does not exist. Are you sure your url is correct?
I'm looking for some guidance on real unit testing for Restlet components, and specifically extractors. There is plenty of advice on running JUnit to rest entire endpoints, but being picky this is not unit testing, but integration testing. I really don't want to have set up an entire routing system and Spring just to check an extractor against a mock data repository.
The extractor looks like this:
public class CaseQueryExtractor extends Extractor {
protected int beforeHandle(Request request, Response response) {
extractFromQuery("offset", "offset", true);
extractFromQuery("limit", "limit", true);
// Stuff happens...
attributes.put("query", query);
return CONTINUE;
}
}
I'm thinking part of the virtue of Restlets is that its nice routing model ought to make unit testing easy, but I can't figure out what I need to do to actually exercise extractFromQuery and its friends, and all my logic that builds a query object, without mocking so much that I'm losing testing against a realistic web request.
And yes, I am using Spring, but I don't want to have to set the whole context for this -- I'm not integration testing as I haven't actually finished the app yet. I'm happy to inject manually, once I know what I need to make to get this method called.
Here's where I'm at now:
public class CaseQueryExtractorTest {
private class TraceRestlet extends Restlet {
// Does snothing, but prevents warning shouts
}
private CaseQueryExtractor extractor;
#Before
public void initialize() {
Restlet mock = new TraceRestlet();
extractor = new CaseQueryExtractor();
extractor.setNext(mock);
}
#Test
public void testBasicExtraction() {
Reference reference = new Reference();
reference.addQueryParameter("offset", "5");
reference.addQueryParameter("limit", "3");
Request request = new Request(Method.GET, reference);
Response response = extractor.handle(request);
extractor.handle(request, response);
CaseQuery query = (CaseQuery) request.getAttributes().get("query");
assertNotNull(query);
}
}
Which of course fails, as whatever set up I am doing isn't enough to make Restlets able to extract the query parameters.
Any thoughts or pointers?
There is a test module in Restlet that can provide you some hints about unit testing. See https://github.com/restlet/restlet-framework-java/tree/master/modules/org.restlet.test/src/org/restlet/test.
You can have a look at class HeaderTestCase (see https://github.com/restlet/restlet-framework-java/blob/master/modules/org.restlet.test/src/org/restlet/test/HeaderTestCase.java).
For information, if you use attributes from request, your unit test will pass ;-) See below:
public class CaseQueryExtractor extends Extractor {
protected int beforeHandle(Request request, Response response) {
extractFromQuery("offset", "offset", true);
extractFromQuery("limit", "limit", true);
// Stuff happens...
CaseQuery query = new CaseQuery();
Map<String,Object> attributes = request.getAttributes();
attributes.put("query", query);
return CONTINUE;
}
}
I don't know if you want to go further...
Hope it helps you,
Thierry
I'm developing a Flex application using RobotLegs, LiveCycle DS & Java.
I'm trying to implement an update function, using LCDS, but I'm running into some strange behaviour:
This is the ActionScript code within a RobotLegs' execute command,
used to perform the update:
var token:AsyncToken = services.requestService.commit(new Array(model.currentRequestDetail));
responder = new AsyncResponder(resultHandler, faultHandler, token);
if ( token ) token.addResponder(responder);
The model.currentRequestDetail I'm trying to update is a RequestDetail Object:
[Managed]
[RemoteClass(alias="be.fgov.mobilit.td.lcds.vo.RequestDetail")]
public class RequestDetail {
public var id:Number;
public var request:Request;
public var task:Task;
/**
* Constructor
*/
public function RequestDetail() {
}
}
The first time the Actionscript code is executed, everything works fine.
The AsyncToken is nicely returned by the services.requestService.commit() function,
the resultHandler is executed as expected, and my object is updated in the GUI.
However, the second time this code is executed, my services.requestService.commit() function returns a null value, and my resultHandler is never reached.
I suspect we're not even reaching the java assembler.
This is how I declared the DataService:
var requestDetailService:DataService = new DataService("requestDetail");
requestDetailService.autoCommit = false;
Both the resultHandler & the faultHandler have the right signature:
resultHandler(result:Object, token:Object = null)
faultHandler(result:Object, token:Object = null)
We're also using a custom java assembler, this is the code:
package be.fgov.mobilit.td.lcds.assemblers;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import be.fgov.mobilit.td.lcds.vo.RequestDetail;
import flex.data.ChangeObject;
import flex.data.assemblers.AbstractAssembler;
public class RequestAssembler extends AbstractAssembler {
public RequestAssembler() {
// TODO Auto-generated constructor stub
}
public RequestDetail getRequest(Map<String, Object> identity) {
return ServiceUtility.getLcdsService().getRequestDetail(identity);
}
public List<ChangeObject> syncRequest(List<ChangeObject> changes) {
Iterator<ChangeObject> iterator = changes.iterator();
ChangeObject co;
while (iterator.hasNext()) {
co = (ChangeObject) iterator.next();
if (co.isUpdate()) {
co = doUpdate(co);
}
}
return changes;
}
private ChangeObject doUpdate(ChangeObject co) {
RequestDetail requestDetail = (RequestDetail) co.getNewVersion();
co.setNewVersion(ServiceUtility.getLcdsService().updateRequestDetail(requestDetail));
return co;
}
}
This is the assembler's configuration:
<destination id="request">
<properties>
<source>be.fgov.mobilit.td.lcds.assemblers.RequestAssembler</source>
<scope>application</scope>
<metadata>
<identity property="id" />
<identity property="task" />
</metadata>
<server>
<get-method>
<name>getRequest</name>
</get-method>
<sync-method>
<name>syncRequest</name>
</sync-method>
</server>
</properties>
</destination>
Long story short:
Does anyone have a clue/experience, why the 2nd time I execute the services.requestService.commit(); function it returns a null Asynctoken?
Thx in advance!
As requested, I added the (stripped) code from my services class.
As you can see, nothing really special going on:
package be.fgov.mobilit.services {
import mx.data.DataService;
import mx.messaging.Consumer;
import mx.messaging.events.MessageEvent;
import mx.rpc.http.HTTPService;
public class LiveCycleServices {
public var requestService:DataService;
public function LiveCycleServices() {
requestService = new DataService("request");
requestService.autoCommit = false;
}
/**
* #param MessageEvent The event object that is dispatched by the Flex framework
* #return void
*
* This message captures the server push messages that need to trigger an update
* of the task list, since this is specific for every client and cannot be
* determined on the server side, coming from LiveCycle.
*/
private function messageHandler(event:MessageEvent):void {
taskListService.refresh();
}
}
}
This is the chode where my result- & faulthandlers are added:
var token:AsyncToken = services.requestService.commit(new Array(model.currentRequestDetail));
var responder:AsyncResponder = new AsyncResponder(resultHandler, faultHandler, token);
if ( token ) token.addResponder(responder);
The aysnctoken returns null when you have no changes to commit. Hope this helps.
WWW, This isn't really an answer as such, but I need more space than a comment will give me. However, I'm not seeing how all your code is connected well enough to give you a good answer.
In general, the result and fault signatures should not look like what you describe as the "right" signature. The AsyncToken is expecting an IResponder, which whose fault and result mentods have a single parameter that is an Object. In general, this will be called with the fault or result event (as appropriate).
Now I am going into territory that is, for me, purely theoretical. It looks like to me that the DataService Class might possibly create just a single AsyncToken, since the connection is kept open. If that is the case, it is possible that the erroneous method signature damages the AsyncToken to the extent that it can't be returned for use by the method. I didn't see anything in the code that you pasted that looks like it calls your result and fault methods in a custom way.
I strongly doubt that the problem is in the Java code. AFAIK, the AsyncToken is created and set up to call the functions in the responder before the call is even made (at least that is how it seems to work with HTTPService or amf). I would expect that there's some error that is being "helpfully" suppressed, so you might benefit from stepping through the code.
I would suggest that you step back a bit and look a bit harder at the "S" part of the MVCS architecture implied by Robotlegs, and create a separate service Class that manages the whole thing, and merely kick off the process from a Command, rather than trying to pass control back and forth between your commands and services. As a side benefit, you can then swap out instances of the real service for test services when you don't need to be connected to the actual data (such as for doing design work).
i need to mock a javax.mail.Session object in my unit tests.
The class javax.mail.Session is marked final so Mockito is not able to create a mock. Does anyone have an idea how to fix this?
Edit:
My test is an Arquillian test and has already an annotation #RunWith(Arquillian.class). Therefore powermock is not an option.
You may refactor your code a little bit. In the "Working with Legacy Code" book by Martin Fowler, he describes a technique of separating the external API (think Java Mail API) from your own application code. The technique is called "Wrap and Skin" and is pretty simple.
What you should do is simply:
Create an interface MySession (which is your own stuff) by extracting methods from the javax.mail.Session class.
Implement that interface by creating a concrete class (looking a bit like the original javax.mail.Session)
In each method DELEGATE the call to equivalent javax.mail.Session method
Create your mock class which implements MySession :-)
Update your production code to use MySession instead of javax.mail.Session
Happy testing!
EDIT: Also take a look at this blog post: http://www.mhaller.de/archives/18-How-to-mock-a-thirdparty-final-class.html
Use PowerMockito to mock it.
#RunWith(PowerMockRunner.class)
// We prepare PartialMockClass for test because it's final or we need to mock private or static methods
#PrepareForTest(javax.mail.Session.class)
public class YourTestCase {
#Test
public void test() throws Exception {
PowerMockito.doReturn(value).when(classUnderTest, "methodToMock", "parameter1");
}
}
You can use the Mock JavaMail project. I first found it from Kohsuke Kawaguchi. Alan Franzoni also has a primer for it on his blog.
When you put this jar file in your classpath, it substitutes any sending of mail to in memory mailboxes that can be checked immediately. It's super easy to use.
Adding this to your classpath is admittedly a pretty heavy handed way to mock something, but you rarely want to send real emails in your automated tests anyway.
If you want to mock a final classes you can use the JDave unfinalizer which can be found here : http://jdave.org/documentation.html#mocking
It uses CGLib to alter the bytecode dynamically when the JVM is loaded to transform the class as a non final class.
This library can then be used with JMock2 ( http://www.jmock.org/mocking-classes.html ) to make your tests because as far as I know, Mockito is not compatible with JDave.
Use Java 8 Functions!
public class SendEmailGood {
private final Supplier<Message> messageSupplier;
private final Consumer<Message> messageSender;
public SendEmailGood(Supplier<Message> messageSupplier,
Consumer<Message> messageSender) {
this.messageSupplier = messageSupplier;
this.messageSender = messageSender;
}
public void send(String[] addresses, String from,
String subject, String body)
throws MessagingException {
Message message = messageSupplier.get();
for (String address : addresses) {
message.addRecipient
(Message.RecipientType.TO, new InternetAddress(address));
}
message.addFrom(new InternetAddress[]{new InternetAddress(from)});
message.setSubject(subject);
message.setText(body);
messageSender.accept(message);
}
}
Then your test code will look something like the following:
#Test
public void sendBasicEmail() throws MessagingException {
final boolean[] messageCalled = {false};
Consumer<Message> consumer = message -> {
messageCalled[0] = true;
};
Message message = mock(Message.class);
Supplier<Message> supplier = () -> message;
SendEmailGood sendEmailGood = new SendEmailGood(supplier, consumer);
String[] addresses = new String[2];
addresses[0] = "foo#foo.com";
addresses[1] = "boo#boo.com";
String from = "baz#baz.com";
String subject = "Test Email";
String body = "This is a sample email from us!";
sendEmailGood.send(addresses, from, subject, body);
verify(message).addRecipient(Message.RecipientType.TO, new InternetAddress("foo#foo.com"));
verify(message).addRecipient(Message.RecipientType.TO, new InternetAddress("boo#boo.com"));
verify(message).addFrom(new InternetAddress[]{new InternetAddress("baz#baz.com")});
verify(message).setSubject(subject);
verify(message).setText(body);
assertThat(messageCalled[0]).isTrue();
}
To create an integration test, plugin the real Session, and Transport.
Consumer<Message> consumer = message -> {
try {
Transport.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
};
Supplier<Message> supplier = () -> {
Properties properties = new Properties();
return new MimeMessage(Session.getDefaultInstance(properties));
};
See the PowerMock docs for running under JUnit 3, since it did not have runners, or use a byte-code manipulation tool.
If you can introduce Spring into your project you can use the JavaMailSender and mock that. I don't know how complicated your requirements are.
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
#Test
public void createAndSendBookChangesMail() {
// Your custom service layer object to test
MailServiceImpl service = new MailServiceImpl();
// MOCK BEHAVIOUR
JavaMailSender mailSender = mock(JavaMailSender.class);
service.setMailSender(mailSender);
// PERFORM TEST
service.createAndSendMyMail("some mail message content");
// ASSERT
verify(mailSender).send(any(SimpleMailMessage.class));
}
This is a pretty old question, but you could always implement your own Transport using the JavaMail API. With your own transport, you could just configure it according to this documentation. One benefit of this approach is you could do anything you want with these messages. Perhaps you would store them in a hash/set that you could then ensure they actually got sent in your unit tests. This way, you don't have to mock the final object, you just implement your own.
I use the mock-javamail library. It just replace the origin javamail implementation in the classpath. You can send mails normally, it just sends to in-memory MailBox, not a real mailbox.
Finally, you can use the MailBox object to assert anything you want to check.