Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ClassPathContentHandler can survive tmp folder cleanup #2361

Merged
merged 5 commits into from
Sep 30, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -146,15 +146,16 @@ boolean doHandle(Http.RequestMethod method, String requestedPath, ServerRequest
return true;
}

private boolean sendJar(Http.RequestMethod method,
String requestedResource,
URL url,
ServerRequest request,
ServerResponse response) {
boolean sendJar(Http.RequestMethod method,
String requestedResource,
URL url,
ServerRequest request,
ServerResponse response) {

LOGGER.fine(() -> "Sending static content from classpath: " + url);

ExtractedJarEntry extrEntry = extracted.computeIfAbsent(requestedResource, thePath -> extractJarEntry(url));
ExtractedJarEntry extrEntry = extracted
.compute(requestedResource, (key, entry) -> existOrCreate(url, entry));
if (extrEntry.tempFile == null) {
return false;
}
Expand All @@ -179,6 +180,13 @@ private boolean sendJar(Http.RequestMethod method,
return true;
}

private ExtractedJarEntry existOrCreate(URL url, ExtractedJarEntry entry) {
if (entry == null) return extractJarEntry(url);
if (entry.tempFile == null) return entry;
if (Files.notExists(entry.tempFile)) return extractJarEntry(url);
return entry;
}

private void sendUrlStream(Http.RequestMethod method, URL url, ServerRequest request, ServerResponse response)
throws IOException {

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
/*
* Copyright (c) 2020 Oracle and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.helidon.webserver;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Flow;
import java.util.function.Function;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.logging.Logger;

import io.helidon.common.http.DataChunk;
import io.helidon.common.http.HashParameters;
import io.helidon.common.http.Http;
import io.helidon.common.reactive.Single;
import io.helidon.media.common.MessageBodyWriterContext;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import org.junit.jupiter.api.Test;
import org.mockito.Mockito;

public class UnstableTempTest {

private static final Logger LOGGER = Logger.getLogger(UnstableTempTest.class.getName());

private static final String JAR_NAME = "test.jar";
private static final String FILE_NAME = "test.js";
private static final String FILE_CONTENT = "alert(\"Hello, World!\");";

@Test
void cleanedTmpDuringRuntime() throws IOException {
List<String> contents = new ArrayList<>(2);

Path jar = createJar();
URL jarUrl = new URL("jar:file:" + jar.toUri().getPath() + "!/" + FILE_NAME);
LOGGER.info("Generated test jar url: " + jarUrl.toString());
ClassPathContentHandler classPathContentHandler =
new ClassPathContentHandler("index.html",
new ContentTypeSelector(null),
"/",
Thread.currentThread().getContextClassLoader());

// Empty headers
RequestHeaders headers = mock(RequestHeaders.class);
when(headers.isAccepted(any())).thenReturn(true);
when(headers.acceptedTypes()).thenReturn(Collections.emptyList());
ResponseHeaders responseHeaders = mock(ResponseHeaders.class);

ServerRequest request = Mockito.mock(ServerRequest.class);
Mockito.when(request.headers()).thenReturn(headers);
ServerResponse response = Mockito.mock(ServerResponse.class);
MessageBodyWriterContext ctx = MessageBodyWriterContext.create(HashParameters.create());
ctx.registerFilter(dataChunkPub -> {
String fileContent = new String(Single.create(dataChunkPub).await().bytes());
contents.add(fileContent);
return Single.just(DataChunk.create(ByteBuffer.wrap(fileContent.getBytes())));
});
Mockito.when(response.headers()).thenReturn(responseHeaders);
Mockito.when(response.send(Mockito.any(Function.class))).then(mock -> {
Function<MessageBodyWriterContext, Flow.Publisher<DataChunk>> argument = mock.getArgument(0);
return Single.create(argument.apply(ctx)).onError(throwable -> throwable.printStackTrace());
});

classPathContentHandler.sendJar(Http.Method.GET, FILE_NAME, jarUrl, request, response);
deleteTmpFiles();
classPathContentHandler.sendJar(Http.Method.GET, FILE_NAME, jarUrl, request, response);

assertThat(contents, containsInAnyOrder(FILE_CONTENT, FILE_CONTENT));
}

private void deleteTmpFiles() throws IOException {
File tempDir = File.createTempFile("tempLocator", "je").getParentFile();
danielkec marked this conversation as resolved.
Show resolved Hide resolved
LOGGER.info("Temp dir: " + tempDir.getAbsolutePath());
danielkec marked this conversation as resolved.
Show resolved Hide resolved
//Delete all temp files
for (File file : Objects.requireNonNull(tempDir.listFiles((dir, name) -> name.endsWith(".je")))) {
danielkec marked this conversation as resolved.
Show resolved Hide resolved
assertThat("Unable to delete " + file.getName(), file.delete(), equalTo(Boolean.TRUE));
LOGGER.info("File " + file.getName() + " deleted.");
}
}

private Path createJar() {
try {
Path testJar = Path.of(UnstableTempTest.class.getResource("").toURI()).resolve(JAR_NAME);
Manifest manifest = new Manifest();
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
JarOutputStream target = new JarOutputStream(new FileOutputStream(testJar.toFile()), manifest);
JarEntry entry = new JarEntry(FILE_NAME);
BufferedOutputStream bos = new BufferedOutputStream(target);
target.putNextEntry(entry);
bos.write(FILE_CONTENT.getBytes());
bos.close();
target.close();
return testJar;
} catch (IOException | URISyntaxException e) {
throw new RuntimeException(e);
}
}
}