Wiremock Stubbing not working - stubbing

I've just started using Wiremock and I have a question about stubbing.
From the docs, it seems to be that you can use either a JSON file under mappings OR the code stubFor(get(urlEqualTo(... in your Java code. However, I'm finding that using stubFor(get(urlEqualTo( results in 'Request was not matched' messages appearing in the Wiremock console.
Is this correct behaviour? Does stubbing need both the code and the json file?
Thanks.

No, wiremock can work only with .json Files or only with java code.
You can combine it if you want.
When the request is not matched, then the url is not correctly stubbed.
If you are using the standalone process you can start it with --verbose to find detailed information why the request was not matched.

WireMock can work with just JSON payloads in mappings. Sounds like there's something else going on with your configuration, but I'd need more details to diagnose.

Not necessary. I have tried below code and it worked for me:
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import com.github.tomakehurst.wiremock.WireMockServer;
public class WireMockTest {
public static void main(String[] args) throws InterruptedException {
WireMockServer wireMockServer1 = new WireMockServer();
wireMockServer1.start();
wireMockServer1.stubFor(get(urlEqualTo("/testWireMock"))
.willReturn(aResponse().withHeader("Content-Type", "text/plain")
.withStatus(200).withBody("Welcome to WireMock!")));
System.out.println("Server started");
Thread.sleep(1000);
wireMockServer1.stop();
}
}

Related

Issue with Spring Security, Spring Webflow, file uploads and UTF-8

I have a problem very similar to the one described here: File Upload using Spring WebFlow 2.4.0, parameter not binded, but that one didn't mention anything about UTF-8 issues. I'm using Spring Framework 4.1.6, Spring Security 4.0.2 and Spring Webflow 2.4.2.
It revolves around StandardServletMultipartResolver vs. CommonsMultipartResolver as far as I can tell, but I'm not sure. If I use CommonsMultipartResolver I can upload files on any page except for Webflow pages fine and UTF-8 encoding works as well on all pages. However on the Webflow pages an exception is thrown trying to access the file . If I use StandardServletMultipartResolver then all of the file uploads work, including Webflow, but on any page that has a UTF-8 character, e.g., caractère, I get garbage.
The wierd thing is I can see in FireBug that the file is being posted when I use the commons resolver. Also, if I debug the RequestContext coming from Webflow I can also see the file buried 4 levels deep in requests. The code for the common resolver (see end of post for the standard resolver code):
public FileResult uploadFile(Recipe recipe, RequestContext requestContext) {
ServletExternalContext context = (ServletExternalContext) requestContext.getExternalContext();
MultipartHttpServletRequest multipartRequest = new DefaultMultipartHttpServletRequest((HttpServletRequest)context.getNativeRequest());
MultipartFile file = multipartRequest.getFile("file");
So, is this a Spring Security issue or a Spring Webflow problem? I suspect the commons resolver would work if I could cast the RequestContext above correctly, but I've tried numerous combinations with no luck. Any guidance on this would be greatly appreciated.
Here are some relevant configurations and code:
WebMvcConfig
#Bean
public CommonsMultipartResolver filterMultipartResolver() {
CommonsMultipartResolver resolver = new CommonsMultipartResolver();
resolver.setDefaultEncoding("UTF-8");
return resolver;
}
SecurityConfig
#Override
protected void configure(HttpSecurity http) throws Exception {
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
characterEncodingFilter.setForceEncoding(true);
http
//.csrf().disable()
.addFilterBefore(characterEncodingFilter, CsrfFilter.class)
...more settings...
SecurityInitializer
#Override
protected void beforeSpringSecurityFilterChain(ServletContext servletContext) {
insertFilters(servletContext, new MultipartFilter());
}
Webflow Action
<action-state id="uploadFile">
<evaluate expression="fileActions.uploadFile(recipe, flowRequestContext)"/>
<transition to="review"/>
</action-state>
Upload file method
public FileResult uploadFile(Recipe recipe, RequestContext requestContext) {
ServletExternalContext context = (ServletExternalContext) requestContext.getExternalContext();
MultipartHttpServletRequest multipartRequest = new StandardMultipartHttpServletRequest((HttpServletRequest)context.getNativeRequest());
MultipartFile file = multipartRequest.getFile("file");
...rest of code to save the file...
Turns out you can cast the RequestContext to get at the underlying MultipartHttpServletRequest but it's not pretty. Here's what I ended up with:
Upload file method
public FileResult uploadFile(Recipe recipe, RequestContext requestContext) {
logger.debug("uploadFile");
ServletExternalContext context = (ServletExternalContext) requestContext.getExternalContext();
SecurityContextHolderAwareRequestWrapper wrapper1 = (SecurityContextHolderAwareRequestWrapper)context.getNativeRequest();
HttpServletRequestWrapper wrapper2 = (HttpServletRequestWrapper)wrapper1.getRequest();
FirewalledRequest firewall = (FirewalledRequest)wrapper2.getRequest();
MultipartHttpServletRequest multipartRequest = (DefaultMultipartHttpServletRequest)firewall.getRequest();
MultipartFile file = multipartRequest.getFile("file");
...rest of code to save the file...
Using this I get to keep the CommonsMultipartResolver, all file uploads in the app work whether Webflow or not, and I have no issues with UTF-8 and character mangling.
I'm not particularly happy with this solution (even though it works) since it's dependent upon a specific nesting of requests that could change in the future(?). I'm be interested if anyone else has run into the same UTF-8 issue and how they solved it, but for now I'm going to test the heck out of this and move on.

Swagger api listing is empty

Recently I have configure swagger with one of my project. Its using jersey2 and JAX-WS on tomcat for restful API. I have used following manual to configure
https://github.com/swagger-api/swagger-core/wiki/Swagger-Core-Jersey-2.X-Project-Setup-1.5
${basepath}/swagger.json response with following
{"swagger":"2.0","info":{"version":"1.0.0","title":""},"host":"localhost:8080","basePath":"/myapi","schemes":["http"]}
Unfortounately it does not contain any api which is under my resource package.
I have tried with the answer of following question
swagger - empty listing with no API
But it didn't help either.
The above answer using com.wordnik.swagger.* package(s)
But with the manual I got io.swagger.* package(s), which doesn't have
JaxrsApiReader class
My assumption is swagger couldn't scan my api list from Resource package.
But could not figure out which configuration or which code snippet I have missed.
Any help?....
It looks like you forgot to mark the rest endpoints with #Api
I had the same issue, I used a different approach that worked for me, by adding information only in my Application class. In case you have one, that might help you:
public class MyApi extends Application {
public MyApi() {
super();
BeanConfig beanConfig = new BeanConfig();
beanConfig.setTitle("MyApi");
beanConfig.setVersion("0.0.1");
beanConfig.setSchemes(new String[]{"http", "https"});
beanConfig.setHost("localhost:8080");
beanConfig.setBasePath("/mypath");
//putting only the path to my api unblocked me, I removed "io.swagger.resources"
beanConfig.setResourcePackage("system.organization.api");
beanConfig.setScan(true);
beanConfig.setPrettyPrint(true);
}
#Override
public Set<Class<?>> getClasses() {
Set<Class<?>> s = new HashSet<>();
s.add(MyApis);
//for swagger
s.add(ApiListingResource.class);
s.add(SwaggerSerializers.class);
return s;
}
}
Then, the links of classes with #API annotation appeared in swagger.json
Mostly done with the same manual you used: https://github.com/swagger-api/swagger-core/wiki/Swagger-Core-Jersey-1.X-Project-Setup-1.5

JAX-RS Client API async request

I am trying to use the JAX-RS Client API to request a resource through HTTP GET, by using the following code: (I used jersey-client v2.12 and also resteasy-client v3.0.8.Final to test the implementation)
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.InvocationCallback;
public class StackOverflowExample {
public static void main(String[] args) {
Client client = ClientBuilder.newClient();
client.target("http://example.com/").request().async().get(new InvocationCallback<String>() {
#Override
public void completed(String s) {
System.out.println("Async got: " + s);
}
#Override
public void failed(Throwable throwable) {
System.out.println("Async failure...");
}
});
}
}
As I expected the String is printed almost immediately. But the process keeps running about one minute, although there isn't any code that should be executed.
The JAX-RS spec just says that we should use the InvocationCallback and nothing else that matters to my issue. But even if I use a Future the same effect happens. I also tested, if this has something to do with a timeout, which was very unlikely and wrong. The debugger shows that there are some threads running namely DestroyJavaVM and jersey-client-async-executor-0 or pool-1-thread-1 in the case of resteasy.
Do you have any idea what is going wrong here?
It is allways helpful to consult the JavaDoc. Concerning my issue it says:
Clients are heavy-weight objects that manage the client-side communication infrastructure. Initialization as well as disposal of a Client instance may be a rather expensive operation. It is therefore advised to construct only a small number of Client instances in the application. Client instances must be properly closed before being disposed to avoid leaking resources.
If I close the client properly everything is working as expected.
public class StackOverflowExample {
public static void main(String[] args) {
Client client = ClientBuilder.newClient();
// request here
client.close();
}
}

Camel aws-s3 not working

I am trying to create a camel route to transfer a file from an FTP server to an AWS S3 storage.
I have written the following route
private static class MyRouteBuilder extends RouteBuilder {
#Override
public void configure() throws Exception
{
from("sftp://<<ftp_server_name>>&noop=true&include=<<file_name>>...")
.process(new Processor(){
#Override
public void process(Exchange ex)
{
System.out.println("Hello");
}
})
.to("aws-s3://my-dev-bucket ?
accessKey=ABC***********&secretKey=12abc********+**********");
}
The issue is, this gives me the following exception:
Exception in thread "main" org.apache.camel.FailedToCreateRouteException: Failed to create route route1 at: >>> To[aws-s3://my-dev-bucket?accessKey=ABC*******************&secretKey=123abc******************** <<< in route: Route(route1)[[From[sftp://<<ftp-server>>... because of Failed to resolve endpoint: aws-s3://my-dev-bucket?accessKey=ABC***************&secretKey=123abc************** due to: The request signature we calculated does not match the signature you provided. Check your key and signing method.
I then tried to do this the other way. i.e.writing a method like this:
public void boot() throws Exception {
// create a Main instance
main = new Main();
// enable hangup support so you can press ctrl + c to terminate the JVM
main.enableHangupSupport();
// bind MyBean into the registery
main.bind("foo", new MyBean());
// add routes
AWSCredentials awsCredentials = new BasicAWSCredentials("ABC*****************", "123abc*************************");
AmazonS3 client = new AmazonS3Client(awsCredentials);
//main.bind("client", client);
main.addRouteBuilder(new MyRouteBuilder());
main.run();
}
and invoking using the bound variable #client. This approach does not give any exceptions, but the file transfer does not work.
To make sure that there's nothing wrong with my approach, I tried aws-sqs instead of aws-s3 and that works fine (file succesfully transfers to the SQS queue)
Any idea why this is happening? Is there some basic issue with "aws-s3" connector for camel?
Have you tried of using RAW() function to wrap as like RAW(secretkey or accesskey).
It will help you to pass your keys as it is without encoding.
Any plus signs in you secret key need to be url encoded as %2B, in your case **********+*********** becomes **********%2B***********
When you configure Camel endpoints using URIs then the parameter values gets url encoded by default.
This can be a problem when you want to configure passwords as is.
To do that you can tell Camel to use the raw value, by enclosing the value with RAW(value). See more details at How do I configure endpoints which has an example also.
See Camel Documentation
Your url should looks like:
aws-s3:bucketName?accessKey=RAW(XXXX)&secretKey=RAW(XXXX)

spring-boot property placeholder

I'm not able to figure out why I am not able to inject values into my application.properties file in spring-boot. external property into the logging.file variable. I have an application.properties file which looks like this
logging.file=${mylogfile}
server.port=${myport}
with corresponding Spring-boot Application class
#PropertySources({
#PropertySource("file:///c:/myfolder/externalprops.properties"),
})
#Configuration
#EnableAutoConfiguration
#ComponentScan
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
and external property file
mylogfile=myoutput.log
myport=8060
When I run my spring-boot 1.0.2.REL application I get the following exception every time I try to inject mylogfile into the logging.file property in application.properties
Exception in thread "main" java.lang.IllegalArgumentException: Could not resolve placeholder 'mylogfile' in string value "${mylogfile}"
at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:174)
Note that I am not having any problems injecting and starting up the application if I inject the server port number on its own.
I am going around in circles on this issue and cannot figure out what I am doing wrong.
I don't think you can use #PropertySource to inject values into "application.properties" - the latter has to be parsed and ready to use before any #Configuration is read, or even known about. Your external properties could go in "${user.dir}/application.properties" and I think that would achieve what you are trying to do.