com.github.tomakehurst.wiremock.common.FileSource Java Examples

The following examples show how to use com.github.tomakehurst.wiremock.common.FileSource. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RedirectTest.java    From gradle-download-task with Apache License 2.0 6 votes vote down vote up
@Override
public Response transform(Request request, Response response,
        FileSource files, Parameters parameters) {
    if (redirects == null) {
        redirects = parameters.getInt("redirects");
    }
    String nl;
    if (redirects > 1) {
        redirects--;
        nl = "/" + REDIRECT + "?r=" + redirects;
    } else {
        nl = "/" + TEST_FILE_NAME;
    }
    return Response.Builder.like(response)
            .but().headers(response.getHeaders()
                    .plus(new HttpHeader("Location", nl)))
            .build();
}
 
Example #2
Source File: AbstractGitHubWireMockTest.java    From github-branch-source-plugin with MIT License 6 votes vote down vote up
@Override
public Response transform(Request request, Response response, FileSource files,
                          Parameters parameters) {
    if ("application/json"
        .equals(response.getHeaders().getContentTypeHeader().mimeTypePart())) {
        return Response.Builder.like(response)
            .but()
            .body(response.getBodyAsString()
                .replace("https://api.github.com/",
                    "http://localhost:" + githubApi.port() + "/")
                .replace("https://raw.githubusercontent.com/",
                    "http://localhost:" + githubRaw.port() + "/")
            )
            .build();
    }
    return response;
}
 
Example #3
Source File: ResourcesFileSource.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
@Override
public FileSource child(String subDirectoryName) {
	List<FileSource> childSources = new ArrayList<>();
	for (FileSource resource : this.sources) {
		try {
			UrlResource uri = new UrlResource(
					resource.child(subDirectoryName).getUri());
			if (uri.createRelative(subDirectoryName).exists()) {
				childSources.add(resource.child(subDirectoryName));
			}
		}
		catch (IOException e) {
			// Ignore
		}
	}
	if (!childSources.isEmpty()) {
		return new ResourcesFileSource(childSources.toArray(new FileSource[0]));
	}
	return this.sources[0].child(subDirectoryName);
}
 
Example #4
Source File: ResourcesFileSource.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
private static FileSource[] toSources(Resource[] resources) {
	FileSource[] sources = new FileSource[resources.length];
	for (int i = 0; i < resources.length; i++) {
		Resource resource = resources[i];
		if (resource instanceof ClassPathResource) {
			ClassPathResource classes = (ClassPathResource) resource;
			sources[i] = new ClasspathFileSource(classes.getPath());
		}
		else if (resource instanceof FileSystemResource) {
			FileSystemResource files = (FileSystemResource) resource;
			sources[i] = new SingleRootFileSource(files.getFile());
		}
		else if (resource instanceof UrlResource) {
			sources[i] = fileOrFallbackToClasspath(resource);
		}
		else {
			throw new IllegalArgumentException(
					"Unsupported resource type for file source: "
							+ resource.getClass());
		}
	}
	return sources;
}
 
Example #5
Source File: IntegrationTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Override
public com.github.tomakehurst.wiremock.http.Response transform(
        Request request, com.github.tomakehurst.wiremock.http.Response response, FileSource files,
        Parameters parameters) {

    final String newResponse;
    try {
        newResponse = cacheResponseFromRequestJson(request.getBodyAsString(),
                parameters.getString("matcherName"));
    } catch (IOException e) {
        return com.github.tomakehurst.wiremock.http.Response.response()
                .body(e.getMessage())
                .status(500)
                .build();
    }
    return com.github.tomakehurst.wiremock.http.Response.response().body(newResponse).status(200).build();
}
 
Example #6
Source File: WireMockBase.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Override
public Response transform(Request request, Response response, FileSource files, Parameters parameters) {
    // if gzipped, ungzip they body and discard the Content-Encoding header
    if (response.getHeaders().getHeader("Content-Encoding").containsValue("gzip")) {
        Iterable<HttpHeader> headers = Iterables.filter(
            response.getHeaders().all(),
            (HttpHeader header) -> header != null && !header.keyEquals("Content-Encoding") && !header.containsValue("gzip")
        );
        return Response.Builder.like(response)
            .but()
            .body(Gzip.unGzip(response.getBody()))
            .headers(new HttpHeaders(headers))
            .build();
    }
    return response;
}
 
Example #7
Source File: WireMockBase.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Override
public Response transform(Request request, Response response, FileSource files, Parameters parameters) {
    if ("application/json"
        .equals(response.getHeaders().getContentTypeHeader().mimeTypePart())) {
        return Response.Builder.like(response)
            .but()
            .body(response.getBodyAsString().replace(sourceUrl, getServerUrl(rule)))
            .build();
    }
    return response;
}
 
Example #8
Source File: BodyTransformer.java    From wiremock-body-transformer with Apache License 2.0 5 votes vote down vote up
private String getResponseBody(ResponseDefinition responseDefinition, FileSource fileSource) {
    String body;
    if (responseDefinition.getBody() != null) {
        body = responseDefinition.getBody();
    } else {
        BinaryFile binaryFile = fileSource.getBinaryFileNamed(responseDefinition.getBodyFileName());
        body = new String(binaryFile.readContents(), StandardCharsets.UTF_8);
    }
    return body;
}
 
Example #9
Source File: ResourcesFileSource.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Override
public boolean exists() {
	for (FileSource resource : this.sources) {
		if (resource.exists()) {
			return true;
		}
	}
	return false;
}
 
Example #10
Source File: ResourcesFileSource.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Override
public List<TextFile> listFilesRecursively() {
	List<TextFile> files = new ArrayList<>();
	for (FileSource resource : this.sources) {
		files.addAll(resource.listFilesRecursively());
	}
	return files;
}
 
Example #11
Source File: ResourcesFileSource.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Override
public URI getUri() {
	for (FileSource resource : this.sources) {
		try {
			UrlResource uri = new UrlResource(resource.getUri());
			if (uri.exists()) {
				return resource.getUri();
			}
		}
		catch (IOException e) {
			// Ignore
		}
	}
	return this.sources[0].getUri();
}
 
Example #12
Source File: ResourcesFileSource.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Override
public String getPath() {
	for (FileSource resource : this.sources) {
		try {
			UrlResource uri = new UrlResource(resource.getUri());
			if (uri.exists()) {
				return resource.getPath();
			}
		}
		catch (IOException e) {
			// Ignore
		}
	}
	return this.sources[0].getPath();
}
 
Example #13
Source File: ResourcesFileSource.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Override
public TextFile getTextFileNamed(String name) {
	for (FileSource resource : this.sources) {
		TextFile file = resource.getTextFileNamed(name);
		try {
			file.readContentsAsString();
			return file;
		}
		catch (RuntimeException e) {
			// Ignore
		}
	}
	return null;
}
 
Example #14
Source File: ResourcesFileSource.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Override
public BinaryFile getBinaryFileNamed(String name) {
	for (FileSource resource : this.sources) {
		try {
			UrlResource uri = new UrlResource(resource.getUri());
			if (uri.exists()) {
				return resource.getBinaryFileNamed(name);
			}
		}
		catch (IOException e) {
			// Ignore
		}
	}
	throw new IllegalStateException("Cannot create file for " + name);
}
 
Example #15
Source File: ResourcesFileSource.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
private static FileSource fileOrFallbackToClasspath(Resource resource) {
	UrlResource file = (UrlResource) resource;
	try {
		URI uri = file.getURI();
		if (compressedResource(uri)) {
			return new ClasspathFileSource(pathFromCompressed(uri));
		}
		return new SingleRootFileSource(getFile(file));
	}
	catch (IOException e) {
		throw new IllegalStateException(e);
	}
}
 
Example #16
Source File: SchemaRegistryMock.java    From fluent-kafka-streams-tests with MIT License 5 votes vote down vote up
@Override
public ResponseDefinition transform(final Request request, final ResponseDefinition responseDefinition,
        final FileSource files, final Parameters parameters) {
    final String subject = Iterables.get(this.urlSplitter.split(request.getUrl()), 1);
    try {
        final int id = SchemaRegistryMock.this.register(subject,
                new Schema.Parser()
                        .parse(RegisterSchemaRequest.fromJson(request.getBodyAsString()).getSchema()));
        final RegisterSchemaResponse registerSchemaResponse = new RegisterSchemaResponse();
        registerSchemaResponse.setId(id);
        return ResponseDefinitionBuilder.jsonResponse(registerSchemaResponse);
    } catch (final IOException e) {
        throw new IllegalArgumentException("Cannot parse schema registration request", e);
    }
}
 
Example #17
Source File: GithubMockBase.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Override
public Response transform(Request request, Response response, FileSource files,
                          Parameters parameters) {
    if ("application/json"
            .equals(response.getHeaders().getContentTypeHeader().mimeTypePart())) {
        return Response.Builder.like(response)
                .but()
                .body(response.getBodyAsString()
                        .replace("https://api.github.com/",
                                "http://localhost:" + githubApi.port() + "/")
                )
                .build();
    }
    return response;
}
 
Example #18
Source File: AbstractInstancesProxyControllerIntegrationTest.java    From Moss with Apache License 2.0 5 votes vote down vote up
@Override
public Response transform(Request request, Response response, FileSource files, Parameters parameters) {
    return Response.Builder.like(response)
                           .headers(HttpHeaders.copyOf(response.getHeaders())
                                               .plus(new HttpHeader("Connection", "Close")))
                           .build();
}
 
Example #19
Source File: SchemaRegistryMock.java    From schema-registry-transfer-smt with Apache License 2.0 5 votes vote down vote up
@Override
public ResponseDefinition transform(final Request request, final ResponseDefinition responseDefinition,
                                    final FileSource files, final Parameters parameters) {
    String versionStr = Iterables.get(this.urlSplitter.split(request.getUrl()), 3);
    SchemaMetadata metadata;
    if (versionStr.equals("latest")) {
        metadata = SchemaRegistryMock.this.getSubjectVersion(getSubject(request), versionStr);
    } else {
        int version = Integer.parseInt(versionStr);
        metadata = SchemaRegistryMock.this.getSubjectVersion(getSubject(request), version);
    }
    return ResponseDefinitionBuilder.jsonResponse(metadata);
}
 
Example #20
Source File: SchemaRegistryMock.java    From schema-registry-transfer-smt with Apache License 2.0 5 votes vote down vote up
@Override
public ResponseDefinition transform(final Request request, final ResponseDefinition responseDefinition,
                                    final FileSource files, final Parameters parameters) {
    final List<Integer> versions = SchemaRegistryMock.this.listVersions(getSubject(request));
    log.debug("Got versions {}", versions);
    return ResponseDefinitionBuilder.jsonResponse(versions);
}
 
Example #21
Source File: SchemaRegistryMock.java    From schema-registry-transfer-smt with Apache License 2.0 5 votes vote down vote up
@Override
public ResponseDefinition transform(final Request request, final ResponseDefinition responseDefinition,
                                    final FileSource files, final Parameters parameters) {
    try {
        final int id = SchemaRegistryMock.this.register(getSubject(request),
                new Schema.Parser()
                        .parse(RegisterSchemaRequest.fromJson(request.getBodyAsString()).getSchema()));
        final RegisterSchemaResponse registerSchemaResponse = new RegisterSchemaResponse();
        registerSchemaResponse.setId(id);
        return ResponseDefinitionBuilder.jsonResponse(registerSchemaResponse);
    } catch (final IOException e) {
        throw new IllegalArgumentException("Cannot parse schema registration request", e);
    }
}
 
Example #22
Source File: SchemaRegistryMock.java    From fluent-kafka-streams-tests with MIT License 5 votes vote down vote up
@Override
public ResponseDefinition transform(final Request request, final ResponseDefinition responseDefinition,
        final FileSource files, final Parameters parameters) {
    final String versionStr = Iterables.get(this.urlSplitter.split(request.getUrl()), 3);
    final SchemaMetadata metadata;
    if (versionStr.equals("latest")) {
        metadata = SchemaRegistryMock.this.getSubjectVersion(this.getSubject(request), versionStr);
    } else {
        final int version = Integer.parseInt(versionStr);
        metadata = SchemaRegistryMock.this.getSubjectVersion(this.getSubject(request), version);
    }
    return ResponseDefinitionBuilder.jsonResponse(metadata);
}
 
Example #23
Source File: SchemaRegistryMock.java    From fluent-kafka-streams-tests with MIT License 5 votes vote down vote up
@Override
public ResponseDefinition transform(final Request request, final ResponseDefinition responseDefinition,
        final FileSource files, final Parameters parameters) {
    final List<Integer> versions = SchemaRegistryMock.this.listVersions(this.getSubject(request));
    log.debug("Got versions {}", versions);
    return ResponseDefinitionBuilder.jsonResponse(versions);
}
 
Example #24
Source File: ResourcesFileSource.java    From spring-cloud-contract with Apache License 2.0 4 votes vote down vote up
private ResourcesFileSource(FileSource... sources) {
	this.sources = sources;
}
 
Example #25
Source File: ServletContextFileSource.java    From AuTe-Framework with Apache License 2.0 4 votes vote down vote up
@Override
public FileSource child(String subDirectoryName) {
    return new ServletContextFileSource(rootPath + '/' + subDirectoryName);
}
 
Example #26
Source File: CustomWarConfiguration.java    From AuTe-Framework with Apache License 2.0 4 votes vote down vote up
@Override
public FileSource filesRoot() {
    return new ServletContextFileSource(fileSourceRoot);
}
 
Example #27
Source File: CustomVelocityResponseTransformer.java    From AuTe-Framework with Apache License 2.0 4 votes vote down vote up
@Override
public ResponseDefinition transform(
    final Request request,
    final ResponseDefinition responseDefinition,
    final FileSource files,
    final Parameters parameters
) throws RuntimeException {
    final VelocityEngine velocityEngine = new VelocityEngine();
    velocityEngine.init();
    final ToolManager toolManager = new ToolManager();
    toolManager.setVelocityEngine(velocityEngine);

    context = toolManager.createContext();
    URL url = getRequestUrl(request);
    addBodyToContext(request.getBodyAsString());
    addHeadersToContext(request.getHeaders());
    context.put("requestAbsoluteUrl", request.getAbsoluteUrl());
    context.put("requestUrl", request.getUrl());
    context.put("requestMethod", request.getMethod());
    context.put("queryParams", urlExtractor.extractQueryParameters(url));
    context.put("pathSegments", urlExtractor.extractPathSegments(url));
    context.put("staticContext", staticContexts.computeIfAbsent(url.getPath(), k -> new HashMap<>()));
    context.put(ExtendedScript.MQ_PROPERTIES, properties);

    String body;
    if (responseDefinition.specifiesBodyFile() && templateDeclared(responseDefinition)) {
        body = getRenderedBody(responseDefinition);
    } else if (responseDefinition.specifiesBodyContent()) {
        try {
            body = getRenderedBodyFromFile(responseDefinition);
        } catch (ParseException e) {
            body = e.getMessage();
            e.printStackTrace();
        }
    } else {
        return responseDefinition;
    }
    if (isPresentConvertCommand(responseDefinition.getHeaders().getHeader(MultipartConstant.CONVERT_BASE64_IN_MULTIPART.getValue()))) {
        log.info(" >>> ");
        log.info(body);
        return buildResponse(parseConvertBody(body), body, responseDefinition, true);
    }
    return buildResponse(null, body, responseDefinition, false);
}
 
Example #28
Source File: SchemaRegistryMock.java    From schema-registry-transfer-smt with Apache License 2.0 4 votes vote down vote up
@Override
public ResponseDefinition transform(final Request request, final ResponseDefinition responseDefinition,
                                    final FileSource files, final Parameters parameters) {
    Config config = new Config(SchemaRegistryMock.this.getCompatibility(getSubject(request)));
    return ResponseDefinitionBuilder.jsonResponse(config);
}
 
Example #29
Source File: SchemaRegistryMock.java    From fluent-kafka-streams-tests with MIT License 4 votes vote down vote up
@Override
public ResponseDefinition transform(final Request request, final ResponseDefinition responseDefinition,
        final FileSource files, final Parameters parameters) {
    final Collection<String> body = SchemaRegistryMock.this.listAllSubjects();
    return ResponseDefinitionBuilder.jsonResponse(body);
}
 
Example #30
Source File: AndroidAssetsReadOnlyFileSource.java    From AndroidHttpMockingExamples with Apache License 2.0 4 votes vote down vote up
@Override
public FileSource child(String name) {
    return new AndroidAssetsReadOnlyFileSource(assetManager, name);
}