Search in sources :

Example 1 with MockMultipartHttpServletRequest

use of org.springframework.mock.web.MockMultipartHttpServletRequest in project iaf by ibissource.

the class StreamPipeTest method doPipeHttpRequestCheckAntiVirusPassedTest.

@Test
public void doPipeHttpRequestCheckAntiVirusPassedTest() throws Exception {
    StreamPipe streamPipe = new StreamPipe();
    streamPipe.setCheckAntiVirus(true);
    streamPipe.registerForward(createPipeSuccessForward());
    MockMultipartHttpServletRequest request = createMultipartHttpRequest(streamPipe, true);
    streamPipe.addParameter(createHttpRequestParameter(request, session));
    streamPipe.configure();
    PipeRunResult pipeRunResult = streamPipe.doPipe("", session);
    assertEquals("success", pipeRunResult.getPipeForward().getName());
    String expectedResult = "<parts>" + "<part type=\"string\" name=\"string1\" sessionKey=\"part_string\" size=\"19\"/>" + "<part type=\"file\" name=\"doc001.pdf\" sessionKey=\"part_file\" size=\"26358\" mimeType=\"application/octet-stream; charset=ISO-8859-1\"/>" + "<part type=\"file\" name=\"doc002.pdf\" sessionKey=\"part_file2\" size=\"25879\" mimeType=\"application/octet-stream; charset=ISO-8859-1\"/>" + "</parts>";
    assertEquals(expectedResult, pipeRunResult.getResult());
}
Also used : PipeRunResult(nl.nn.adapterframework.core.PipeRunResult) MockMultipartHttpServletRequest(org.springframework.mock.web.MockMultipartHttpServletRequest) Test(org.junit.Test)

Example 2 with MockMultipartHttpServletRequest

use of org.springframework.mock.web.MockMultipartHttpServletRequest in project iaf by ibissource.

the class StreamPipeTest method doPipeHttpRequestCheckAntiVirusFailedTest.

@Test
public void doPipeHttpRequestCheckAntiVirusFailedTest() throws Exception {
    StreamPipe streamPipe = new StreamPipe();
    streamPipe.setCheckAntiVirus(true);
    PipeForward pipeAntiVirusFailedForward = new PipeForward();
    pipeAntiVirusFailedForward.setName(StreamPipe.ANTIVIRUS_FAILED_FORWARD);
    streamPipe.registerForward(pipeAntiVirusFailedForward);
    streamPipe.registerForward(createPipeSuccessForward());
    MockMultipartHttpServletRequest request = createMultipartHttpRequest(streamPipe, true, true);
    streamPipe.addParameter(createHttpRequestParameter(request, session));
    streamPipe.configure();
    PipeRunResult pipeRunResult = streamPipe.doPipe("", session);
    assertEquals("antiVirusFailed", pipeRunResult.getPipeForward().getName());
    String expectedResult = "multipart contains file [doc002.pdf] with antivirus status [Fail] and message []";
    assertEquals(expectedResult, pipeRunResult.getResult());
}
Also used : PipeRunResult(nl.nn.adapterframework.core.PipeRunResult) MockMultipartHttpServletRequest(org.springframework.mock.web.MockMultipartHttpServletRequest) PipeForward(nl.nn.adapterframework.core.PipeForward) Test(org.junit.Test)

Example 3 with MockMultipartHttpServletRequest

use of org.springframework.mock.web.MockMultipartHttpServletRequest in project iaf by ibissource.

the class TestTool method createParametersMapFromParamProperties.

/**
 * Create a Map for a specific property based on other properties that are
 * the same except for a .param1.name, .param1.value or .param1.valuefile
 * suffix.  The property with the .name suffix specifies the key for the
 * Map, the property with the value suffix specifies the value for the Map.
 * A property with a the .valuefile suffix can be used as an alternative
 * for a property with a .value suffix to specify the file to read the
 * value for the Map from. More than one param can be specified by using
 * param2, param3 etc.
 *
 * @param propertiesDirectory suffix for filenames specified by properties
 *                            with a .valuefile suffix. Can be left empty.
 * @param properties
 * @param property
 * @param writers
 * @return
 */
private static Map createParametersMapFromParamProperties(Properties properties, String property, Map writers, boolean createParameterObjects, ParameterResolutionContext parameterResolutionContext) {
    debugMessage("Search parameters for property '" + property + "'", writers);
    Map result = new HashMap();
    boolean processed = false;
    int i = 1;
    while (!processed) {
        String name = properties.getProperty(property + ".param" + i + ".name");
        if (name != null) {
            Object value;
            String type = properties.getProperty(property + ".param" + i + ".type");
            if ("httpResponse".equals(type)) {
                String outputFile;
                String filename = properties.getProperty(property + ".param" + i + ".filename");
                if (filename != null) {
                    outputFile = properties.getProperty(property + ".param" + i + ".filename.absolutepath");
                } else {
                    outputFile = properties.getProperty(property + ".param" + i + ".outputfile");
                }
                HttpServletResponseMock httpServletResponseMock = new HttpServletResponseMock();
                httpServletResponseMock.setOutputFile(outputFile);
                value = httpServletResponseMock;
            } else if ("httpRequest".equals(type)) {
                value = properties.getProperty(property + ".param" + i + ".value");
                if ("multipart".equals(value)) {
                    MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest();
                    // following line is required to avoid
                    // "(FileUploadException) the request was rejected because
                    // no multipart boundary was found"
                    request.setContentType("multipart/mixed;boundary=gc0p4Jq0M2Yt08jU534c0p");
                    List<Part> parts = new ArrayList<Part>();
                    boolean partsProcessed = false;
                    int j = 1;
                    while (!partsProcessed) {
                        String filename = properties.getProperty(property + ".param" + i + ".part" + j + ".filename");
                        if (filename == null) {
                            partsProcessed = true;
                        } else {
                            String partFile = properties.getProperty(property + ".param" + i + ".part" + j + ".filename.absolutepath");
                            String partType = properties.getProperty(property + ".param" + i + ".part" + j + ".type");
                            String partName = properties.getProperty(property + ".param" + i + ".part" + j + ".name");
                            if ("file".equalsIgnoreCase(partType)) {
                                File file = new File(partFile);
                                try {
                                    FilePart filePart = new FilePart("file" + j, (partName == null ? file.getName() : partName), file);
                                    parts.add(filePart);
                                } catch (FileNotFoundException e) {
                                    errorMessage("Could not read file '" + partFile + "': " + e.getMessage(), e, writers);
                                }
                            } else {
                                String string = readFile(partFile, writers);
                                StringPart stringPart = new StringPart((partName == null ? "string" + j : partName), string);
                                parts.add(stringPart);
                            }
                            j++;
                        }
                    }
                    Part[] allParts = new Part[parts.size()];
                    allParts = parts.toArray(allParts);
                    MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(allParts, new PostMethod().getParams());
                    ByteArrayOutputStream requestContent = new ByteArrayOutputStream();
                    try {
                        multipartRequestEntity.writeRequest(requestContent);
                    } catch (IOException e) {
                        errorMessage("Could not create multipart: " + e.getMessage(), e, writers);
                    }
                    request.setContent(requestContent.toByteArray());
                    request.setContentType(multipartRequestEntity.getContentType());
                    value = request;
                } else {
                    MockHttpServletRequest request = new MockHttpServletRequest();
                    value = request;
                }
            } else {
                value = properties.getProperty(property + ".param" + i + ".value");
                if (value == null) {
                    String filename = properties.getProperty(property + ".param" + i + ".valuefile.absolutepath");
                    if (filename != null) {
                        value = readFile(filename, writers);
                    } else {
                        String inputStreamFilename = properties.getProperty(property + ".param" + i + ".valuefileinputstream.absolutepath");
                        if (inputStreamFilename != null) {
                            try {
                                value = new FileInputStream(inputStreamFilename);
                            } catch (FileNotFoundException e) {
                                errorMessage("Could not read file '" + inputStreamFilename + "': " + e.getMessage(), e, writers);
                            }
                        }
                    }
                }
            }
            if (value != null && value instanceof String) {
                if ("node".equals(properties.getProperty(property + ".param" + i + ".type"))) {
                    try {
                        value = XmlUtils.buildNode((String) value, true);
                    } catch (DomBuilderException e) {
                        errorMessage("Could not build node for parameter '" + name + "' with value: " + value, e, writers);
                    }
                } else if ("domdoc".equals(properties.getProperty(property + ".param" + i + ".type"))) {
                    try {
                        value = XmlUtils.buildDomDocument((String) value, true);
                    } catch (DomBuilderException e) {
                        errorMessage("Could not build node for parameter '" + name + "' with value: " + value, e, writers);
                    }
                } else if ("list".equals(properties.getProperty(property + ".param" + i + ".type"))) {
                    List<String> parts = new ArrayList<String>(Arrays.asList(((String) value).split("\\s*(,\\s*)+")));
                    List list = new LinkedList<String>();
                    for (String part : parts) {
                        list.add(part);
                    }
                    value = list;
                } else if ("map".equals(properties.getProperty(property + ".param" + i + ".type"))) {
                    List<String> parts = new ArrayList<String>(Arrays.asList(((String) value).split("\\s*(,\\s*)+")));
                    Map map = new LinkedHashMap<String, String>();
                    for (String part : parts) {
                        String[] splitted = part.split("\\s*(=\\s*)+", 2);
                        if (splitted.length == 2) {
                            map.put(splitted[0], splitted[1]);
                        } else {
                            map.put(splitted[0], "");
                        }
                    }
                    value = map;
                }
            }
            if (createParameterObjects) {
                String pattern = properties.getProperty(property + ".param" + i + ".pattern");
                if (value == null && pattern == null) {
                    errorMessage("Property '" + property + ".param" + i + " doesn't have a value or pattern", writers);
                } else {
                    try {
                        Parameter parameter = new Parameter();
                        parameter.setName(name);
                        if (value != null && !(value instanceof String)) {
                            parameter.setSessionKey(name);
                            parameterResolutionContext.getSession().put(name, value);
                        } else {
                            parameter.setValue((String) value);
                            parameter.setPattern(pattern);
                        }
                        parameter.configure();
                        result.put(name, parameter);
                        debugMessage("Add param with name '" + name + "', value '" + value + "' and pattern '" + pattern + "' for property '" + property + "'", writers);
                    } catch (ConfigurationException e) {
                        errorMessage("Parameter '" + name + "' could not be configured", writers);
                    }
                }
            } else {
                if (value == null) {
                    errorMessage("Property '" + property + ".param" + i + ".value' or '" + property + ".param" + i + ".valuefile' or '" + property + ".param" + i + ".valuefileinputstream' not found while property '" + property + ".param" + i + ".name' exist", writers);
                } else {
                    result.put(name, value);
                    debugMessage("Add param with name '" + name + "' and value '" + value + "' for property '" + property + "'", writers);
                }
            }
            i++;
        } else {
            processed = true;
        }
    }
    return result;
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) PostMethod(org.apache.commons.httpclient.methods.PostMethod) FileNotFoundException(java.io.FileNotFoundException) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) ArrayList(java.util.ArrayList) ConfigurationException(nl.nn.adapterframework.configuration.ConfigurationException) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) FileInputStream(java.io.FileInputStream) LinkedList(java.util.LinkedList) MockMultipartHttpServletRequest(org.springframework.mock.web.MockMultipartHttpServletRequest) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Part(org.apache.commons.httpclient.methods.multipart.Part) Parameter(nl.nn.adapterframework.parameters.Parameter) DomBuilderException(nl.nn.adapterframework.util.DomBuilderException) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) File(java.io.File)

Example 4 with MockMultipartHttpServletRequest

use of org.springframework.mock.web.MockMultipartHttpServletRequest in project Gemma by PavlidisLab.

the class FileUploadUtilTest method testCopyUploadedFileStreamClosed.

@Test
public void testCopyUploadedFileStreamClosed() throws FileNotFoundException, IOException {
    MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest();
    request.setMethod("POST");
    String text_contents = "test";
    String key = "file1";
    String filename = "test_upload.txt";
    MockMultipartFile sourceFile = new MockMultipartFile(key, filename, "text/plain", text_contents.getBytes());
    long expectedSize = sourceFile.getSize();
    request.setContent(text_contents.getBytes());
    request.addFile(sourceFile);
    File copiedFile = FileUploadUtil.copyUploadedFile(request, key);
    assert (copiedFile.exists());
    assertEquals(expectedSize, copiedFile.length());
    copiedFile.delete();
}
Also used : MockMultipartFile(org.springframework.mock.web.MockMultipartFile) MockMultipartHttpServletRequest(org.springframework.mock.web.MockMultipartHttpServletRequest) MockMultipartFile(org.springframework.mock.web.MockMultipartFile) File(java.io.File) Test(org.junit.Test)

Example 5 with MockMultipartHttpServletRequest

use of org.springframework.mock.web.MockMultipartHttpServletRequest in project spring-framework by spring-projects.

the class MockMultipartHttpServletRequestBuilderTests method addFileWithoutFilename.

// gh-26261, gh-26400
@Test
void addFileWithoutFilename() throws Exception {
    MockPart jsonPart = new MockPart("data", "{\"node\":\"node\"}".getBytes(UTF_8));
    jsonPart.getHeaders().setContentType(MediaType.APPLICATION_JSON);
    MockMultipartHttpServletRequest mockRequest = (MockMultipartHttpServletRequest) new MockMultipartHttpServletRequestBuilder("/upload").file(new MockMultipartFile("file", "Test".getBytes(UTF_8))).part(jsonPart).buildRequest(new MockServletContext());
    assertThat(mockRequest.getFileMap()).containsOnlyKeys("file");
    assertThat(mockRequest.getParameterMap()).hasSize(1);
    assertThat(mockRequest.getParameter("data")).isEqualTo("{\"node\":\"node\"}");
    assertThat(mockRequest.getParts()).extracting(Part::getName).containsExactly("data");
}
Also used : MockMultipartFile(org.springframework.mock.web.MockMultipartFile) MockMultipartHttpServletRequest(org.springframework.mock.web.MockMultipartHttpServletRequest) MockPart(org.springframework.mock.web.MockPart) MockServletContext(org.springframework.mock.web.MockServletContext) Test(org.junit.jupiter.api.Test)

Aggregations

MockMultipartHttpServletRequest (org.springframework.mock.web.MockMultipartHttpServletRequest)12 Test (org.junit.Test)5 File (java.io.File)4 PipeRunResult (nl.nn.adapterframework.core.PipeRunResult)4 Test (org.junit.jupiter.api.Test)4 MockMultipartFile (org.springframework.mock.web.MockMultipartFile)4 ResponseCodeView (com.thoughtworks.go.server.web.ResponseCodeView)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 ArrayList (java.util.ArrayList)2 PostMethod (org.apache.commons.httpclient.methods.PostMethod)2 FilePart (org.apache.commons.httpclient.methods.multipart.FilePart)2 MultipartRequestEntity (org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity)2 Part (org.apache.commons.httpclient.methods.multipart.Part)2 StringPart (org.apache.commons.httpclient.methods.multipart.StringPart)2 MockPart (org.springframework.mock.web.MockPart)2 MockServletContext (org.springframework.mock.web.MockServletContext)2 ModelAndView (org.springframework.web.servlet.ModelAndView)2 JobIdentifier (com.thoughtworks.go.domain.JobIdentifier)1 FileInputStream (java.io.FileInputStream)1 FileNotFoundException (java.io.FileNotFoundException)1