/** * Test that the body consisting of a file part can be posted. */ public void testPostFilePart() throws Exception { this.server.setHttpService(new EchoService()); PostMethod method = new PostMethod(); byte[] content = "Hello".getBytes(); MultipartRequestEntity entity = new MultipartRequestEntity( new Part[] { new FilePart( "param1", new ByteArrayPartSource("filename.txt", content), "text/plain", "ISO-8859-1") }, method.getParams()); method.setRequestEntity(entity); client.executeMethod(method); assertEquals(200,method.getStatusCode()); String body = method.getResponseBodyAsString(); assertTrue(body.indexOf("Content-Disposition: form-data; name=\"param1\"; filename=\"filename.txt\"") >= 0); assertTrue(body.indexOf("Content-Type: text/plain; charset=ISO-8859-1") >= 0); assertTrue(body.indexOf("Content-Transfer-Encoding: binary") >= 0); assertTrue(body.indexOf("Hello") >= 0); }
private void addFormDataPart(List<Part> parts, RequestableHttpVariable httpVariable, Object httpVariableValue) throws FileNotFoundException { String stringValue = ParameterUtils.toString(httpVariableValue); if (httpVariable.getDoFileUploadMode() == DoFileUploadMode.multipartFormData) { String filepath = Engine.theApp.filePropertyManager.getFilepathFromProperty(stringValue, getProject().getName()); File file = new File(filepath); if (file.exists()) { String charset = httpVariable.getDoFileUploadCharset(); String type = httpVariable.getDoFileUploadContentType(); if (org.apache.commons.lang3.StringUtils.isBlank(type)) { type = Engine.getServletContext().getMimeType(file.getName()); } parts.add(new FilePart(httpVariable.getHttpName(), file.getName(), file, type, charset)); } else { throw new FileNotFoundException(filepath); } } else { parts.add(new StringPart(httpVariable.getHttpName(), stringValue)); } }
public PostRequest buildMultipartPostRequest(File file, String filename, String siteId, String containerId) throws IOException { Part[] parts = { new FilePart("filedata", file.getName(), file, "text/plain", null), new StringPart("filename", filename), new StringPart("description", "description"), new StringPart("siteid", siteId), new StringPart("containerid", containerId) }; MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts, new HttpMethodParams()); ByteArrayOutputStream os = new ByteArrayOutputStream(); multipartRequestEntity.writeRequest(os); PostRequest postReq = new PostRequest(UPLOAD_URL, os.toByteArray(), multipartRequestEntity.getContentType()); return postReq; }
public void testPostFilePartUnknownLength() throws Exception { this.server.setHttpService(new EchoService()); String enc = "ISO-8859-1"; PostMethod method = new PostMethod(); byte[] content = "Hello".getBytes(enc); MultipartRequestEntity entity = new MultipartRequestEntity( new Part[] { new FilePart( "param1", new TestPartSource("filename.txt", content), "text/plain", enc) }, method.getParams()); method.setRequestEntity(entity); client.executeMethod(method); assertEquals(200,method.getStatusCode()); String body = method.getResponseBodyAsString(); assertTrue(body.indexOf("Content-Disposition: form-data; name=\"param1\"; filename=\"filename.txt\"") >= 0); assertTrue(body.indexOf("Content-Type: text/plain; charset="+enc) >= 0); assertTrue(body.indexOf("Content-Transfer-Encoding: binary") >= 0); assertTrue(body.indexOf("Hello") >= 0); }
/** *Procedure parameters: Filename which is a string representing a file on the local system *Parameters to TeleplanBroker are *ExternalAction = "AputAscii" *This is a RFC1867 Multi-part post *Results from TeleplanBroker are: * "SUCCESS" * "FAILURE" */ public TeleplanResponse putAsciiFile(File f) throws FileNotFoundException{ Part[] parts = { new StringPart("ExternalAction", "AputAscii"), new FilePart("submitASCII", f) }; return processRequest(CONTACT_URL,parts); // my ($filename) = @_; // my $request = POST $WEBBASE, Content_type => 'form-data', // Content => ['submitASCII' => [ $filename ], // 'ExternalAction' => 'AputAscii' // ]; // my $retVal = processRequest($request); // if ($retVal == $SUCCESS) // {#valid response // if ($Result ne "SUCCESS") // { // $retVal = $VALID; // } // } // else // { // $retVal = $ERROR; // } // return $retVal; }
/** *Procedure parameters: Filename which is a string representing a file on the local system *Parameters to TeleplanBroker are *ExternalAction = "AputRemit" *This is a RFC1867 Multi-part post *Results from TeleplanBroker are: * "SUCCESS" * "FAILURE" */ public TeleplanResponse putMSPFile(File f) throws FileNotFoundException { Part[] parts = { new StringPart("ExternalAction", "AputRemit"), new FilePart("submitFile", f) }; return processRequest(CONTACT_URL,parts); // // my ($filename) = @_; // my $request = POST $WEBBASE, Content_Type => 'form-data', // Content => ['submitFile' => [ $filename ], // 'ExternalAction' => 'AputRemit' // ]; // my $retVal = processRequest($request); // if ($retVal == $SUCCESS) // {#valid response // if ($Result ne "SUCCESS") // { // $retVal = $VALID; // } // } // else // { // $retVal = $ERROR; // } // return $retVal; // return null; }
@Test public void testSendMultiPartForm() throws Exception { HttpClient httpclient = new HttpClient(); File file = new File("src/main/resources/META-INF/NOTICE.txt"); PostMethod httppost = new PostMethod("http://localhost:" + getPort() + "/test"); Part[] parts = { new StringPart("comment", "A binary file of some kind"), new FilePart(file.getName(), file) }; MultipartRequestEntity reqEntity = new MultipartRequestEntity(parts, httppost.getParams()); httppost.setRequestEntity(reqEntity); int status = httpclient.executeMethod(httppost); assertEquals("Get a wrong response status", 200, status); String result = httppost.getResponseBodyAsString(); assertEquals("Get a wrong result", "A binary file of some kind", result); assertNotNull("Did not use custom multipart filter", httppost.getResponseHeader("MyMultipartFilter")); }
@Test public void testSendMultiPartFormOverrideEnableMultpartFilterFalse() throws Exception { HttpClient httpclient = new HttpClient(); File file = new File("src/main/resources/META-INF/NOTICE.txt"); PostMethod httppost = new PostMethod("http://localhost:" + getPort() + "/test2"); Part[] parts = { new StringPart("comment", "A binary file of some kind"), new FilePart(file.getName(), file) }; MultipartRequestEntity reqEntity = new MultipartRequestEntity(parts, httppost.getParams()); httppost.setRequestEntity(reqEntity); int status = httpclient.executeMethod(httppost); assertEquals("Get a wrong response status", 200, status); assertNotNull("Did not use custom multipart filter", httppost.getResponseHeader("MyMultipartFilter")); }
@Test public void testHttpClient() throws Exception { File jpg = new File("src/test/resources/java.jpg"); String body = "TEST"; Part[] parts = new Part[] {new StringPart("body", body), new FilePart(jpg.getName(), jpg)}; PostMethod method = new PostMethod("http://localhost:" + port2 + "/test/hello"); MultipartRequestEntity requestEntity = new MultipartRequestEntity(parts, method.getParams()); method.setRequestEntity(requestEntity); HttpClient client = new HttpClient(); client.executeMethod(method); String responseBody = method.getResponseBodyAsString(); assertEquals(body, responseBody); String numAttachments = method.getResponseHeader("numAttachments").getValue(); assertEquals(numAttachments, "2"); }
private List<Part> buildParts(BaseRequest request) { List<Part> parts = new ArrayList<Part>(); for (PartHolder h : TankHttpUtil.getPartsFromBody(request)) { if (h.getFileName() == null) { StringPart stringPart = new StringPart(h.getPartName(), new String(h.getBodyAsString())); if (h.isContentTypeSet()) { stringPart.setContentType(h.getContentType()); } parts.add(stringPart); } else { PartSource partSource = new ByteArrayPartSource(h.getFileName(), h.getBody()); FilePart p = new FilePart(h.getPartName(), partSource); if (h.isContentTypeSet()) { p.setContentType(h.getContentType()); } parts.add(p); } } return parts; }
@Test public void testUploadFile() throws IOException, URISyntaxException { final HttpClient c = loginWithCookie("administrator", "olat"); final URI uri = UriBuilder.fromUri(getNodeURI()).path("files").build(); // create single page final URL fileUrl = RepositoryEntriesITCase.class.getResource("singlepage.html"); assertNotNull(fileUrl); final File file = new File(fileUrl.toURI()); final PutMethod method = createPut(uri, MediaType.APPLICATION_JSON, true); method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); final Part[] parts = { new FilePart("file", file), new StringPart("filename", file.getName()) }; method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); final int code = c.executeMethod(method); assertEquals(code, 200); final OlatNamedContainerImpl folder = BCCourseNode.getNodeFolderContainer((BCCourseNode) bcNode, course1.getCourseEnvironment()); final VFSItem item = folder.resolve(file.getName()); assertNotNull(item); }
@Override public void write(String name, final File file, String fileName, String contentType, String charset, final boolean deleteAfterUpload) throws IOException { parts.add(new FilePart(name, fileName!=null && !fileName.isEmpty()? fileName: file.getName(), file, contentType, charset){ @Override protected void sendData(OutputStream out) throws IOException { super.sendData(out); if (deleteAfterUpload) { try { boolean deleted = file.delete(); if (!deleted) { LOGGER.warning("Unable to delete file: "+file.getAbsolutePath()); } } catch (SecurityException ex) { LOGGER.warning("Unable to delete file: "+file.getAbsolutePath()); } } } }); }
private MockHttpServletRequest getMultipartRequest( ) throws Exception { MockHttpServletRequest request = new MockHttpServletRequest( ); byte [ ] fileContent = new byte [ ] { 1, 2, 3 }; Part [ ] parts = new Part [ ] { new FilePart( "file1", new ByteArrayPartSource( "file1", fileContent ) ) }; MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity( parts, new PostMethod( ).getParams( ) ); // Serialize request body ByteArrayOutputStream requestContent = new ByteArrayOutputStream( ); multipartRequestEntity.writeRequest( requestContent ); // Set request body to HTTP servlet request request.setContent( requestContent.toByteArray( ) ); // Set content type to HTTP servlet request (important, includes Mime boundary string) request.setContentType( multipartRequestEntity.getContentType( ) ); request.setMethod( "POST" ); return request; }
/** * <p>This creates a HttpMethod with the message as its payload and image attachment. The message should be a properly formatted JSON * String (No validation is done on this).</p> * * <p>The message can be easily created using the {@link #getJsonPayload(Message)} method.</p> * * @param uri The full URI which we will post to * @param message A properly formatted JSON message. UTF-8 is expected * @param image A complete instance of ImageAttachment object * @throws IOException */ public HttpMethod getJsonPostForMultipartRequestEntity(String uri, String message, ImageAttachment image) throws IOException { PostMethod post = new PostMethod(uri); StringPart bodyPart = new StringPart("json", message); bodyPart.setContentType("application/json"); FilePart filePart= new FilePart("feedItemFileUpload", image.retrieveObjectFile()); filePart.setContentType(image.retrieveContentType()); Part[] parts = { bodyPart, filePart, }; post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); return post; }
/** * Imports a model from a JSON file. */ public static void importModel() throws Exception { // Upload file to H2O HttpClient client = new HttpClient(); PostMethod post = new PostMethod(URL + "/Upload.json?key=" + JSON_FILE.getName()); Part[] parts = { new FilePart(JSON_FILE.getName(), JSON_FILE) }; post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); if( 200 != client.executeMethod(post) ) throw new RuntimeException("Request failed: " + post.getStatusLine()); post.releaseConnection(); // Parse the key into a model GetMethod get = new GetMethod(URL + "/2/ImportModel.json?" // + "destination_key=MyImportedNeuralNet&" // + "type=NeuralNetModel&" // + "json=" + JSON_FILE.getName()); if( 200 != client.executeMethod(get) ) throw new RuntimeException("Request failed: " + get.getStatusLine()); get.releaseConnection(); }
@Override public boolean execute(org.mozilla.javascript.Context javascriptContext, Scriptable scope) throws EngineException { if (isEnabled()) { parts.clear(); evaluate(javascriptContext, scope, filename, "filename", true); if (evaluated != null) { String filepath = Engine.theApp.filePropertyManager.getFilepathFromProperty(evaluated.toString(), getProject().getName()); File fileupload = new File(filepath); if (!fileupload.exists()) { throw new EngineException("(HTTPUploadStatement) The file '" + fileupload.getAbsolutePath() + "' doesn't exist."); } if (!fileupload.isFile()) { throw new EngineException("(HTTPUploadStatement) The file '" + fileupload.getAbsolutePath() + "' isn't a file."); } String sHttpFilename = fileupload.getName(); if (httpFilename.length() > 0) { evaluate(javascriptContext, scope, httpFilename, "httpFilename", true); if (evaluated != null) { sHttpFilename = evaluated.toString(); } } try { parts.add(new FilePart(sHttpFilename, fileupload)); } catch (FileNotFoundException e) { throw new EngineException("(HTTPUploadStatement) The file is not found.", e); } } else { throw new EngineException("(HTTPUploadStatement) The filename expresion must return the file path in string."); } setHttpVerb(HttpMethodType.POST); return super.execute(javascriptContext, scope); } return false; }
public PostRequest buildMultipartPostRequest(File file) throws IOException { Part[] parts = { new FilePart("filedata", file.getName(), file, "application/zip", null) }; MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts, new HttpMethodParams()); ByteArrayOutputStream os = new ByteArrayOutputStream(); multipartRequestEntity.writeRequest(os); PostRequest postReq = new PostRequest(UPLOAD_URL, os.toByteArray(), multipartRequestEntity.getContentType()); return postReq; }
public MultiPartRequest build() throws IOException { List<Part> parts = new ArrayList<>(); if (fileData != null) { FilePart fp = new FilePart("filedata", fileData.getFileName(), fileData.getFile(), fileData.getMimetype(), null); // Get rid of the default values added upon FilePart instantiation fp.setCharSet(fileData.getEncoding()); fp.setContentType(fileData.getMimetype()); parts.add(fp); addPartIfNotNull(parts, "name", fileData.getFileName()); } addPartIfNotNull(parts, "relativepath", relativePath); addPartIfNotNull(parts, "updatenoderef", updateNodeRef); addPartIfNotNull(parts, "description", description); addPartIfNotNull(parts, "contenttype", contentTypeQNameStr); addPartIfNotNull(parts, "aspects", getCommaSeparated(aspects)); addPartIfNotNull(parts, "majorversion", majorVersion); addPartIfNotNull(parts, "overwrite", overwrite); addPartIfNotNull(parts, "autorename", autoRename); addPartIfNotNull(parts, "nodetype", nodeType); addPartIfNotNull(parts, "renditions", getCommaSeparated(renditionIds)); if (!properties.isEmpty()) { for (Entry<String, String> prop : properties.entrySet()) { parts.add(new StringPart(prop.getKey(), prop.getValue())); } } MultipartRequestEntity req = new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), new HttpMethodParams()); ByteArrayOutputStream os = new ByteArrayOutputStream(); req.writeRequest(os); return new MultiPartRequest(os.toByteArray(), req.getContentType(), req.getContentLength()); }
/** * Adds a binary file part * * @param parameterName The name of the parameter * @param parameterFile The name of the file. * @throws FileNotFoundException If the file cannot be found. */ public void addParameter(String parameterName, File parameterFile) throws FileNotFoundException { LOG.trace("enter MultipartPostMethod.addParameter(String parameterName, " + "File parameterFile)"); Part param = new FilePart(parameterName, parameterFile); parameters.add(param); }
public Part[] setupParts( String filePath, String installPackages ) throws FileNotFoundException { log.info("Setting up for package: " + filePath); File packageFile = new File( filePath ); Part[] parts = { new StringPart(Constants.NAME, packageFile.getName() ), new StringPart(Constants.FORCE, Constants.TRUE), new StringPart(Constants.INSTALL, installPackages), new FilePart( Constants.FILE, packageFile ) }; return parts; }
private void addMultipart_Parts( MultipartPostMethod method, Map<String, String> parameterizedMap){ for (Iterator it = model.getParameters().entrySet().iterator(); it.hasNext();) { Map.Entry me = (Map.Entry) it.next(); String key = (String) me.getKey(); List values = (List) me.getValue(); StringBuilder sb = new StringBuilder(); int cnt = 0; for (Iterator it2 = values.iterator(); it2.hasNext();) { String val = (String) it2.next(); if (cnt != 0) { sb.append(","); } sb.append(val); cnt++; } String parameterizedVal = ParseUtils.getParametizedArg(sb.toString(), parameterizedMap); if (parameterizedVal.startsWith("@")) { String path = ""; String contentType = ""; try { path = parameterizedVal.substring(1, parameterizedVal.length()).trim(); path = path.replace('\\', '/'); contentType = getContentType(getFileExt(path)); File f = new File(path); method.addPart(new FilePart(key, f, contentType, null)); // postMethod.addParameter("file", f); // postMethod.addPart(new FilePart("file", f)); } catch (FileNotFoundException fnfe) { ExceptionHandler.handle(fnfe); } } else { method.addPart(new StringPart(key, parameterizedVal)); } } }
public Response multPartURL(String fileParamName, String url, PostParameter[] params, File file, boolean authenticated, String token) throws WeiboException { PostMethod postMethod = new PostMethod(url); try { Part[] parts = null; if (params == null) { parts = new Part[1]; } else { parts = new Part[params.length + 1]; } if (params != null) { int i = 0; for (PostParameter entry : params) { parts[i++] = new StringPart(entry.getName(), (String) entry.getValue()); } } FilePart filePart = new FilePart(fileParamName, file.getName(), file, new MimetypesFileTypeMap().getContentType(file), "UTF-8"); filePart.setTransferEncoding("binary"); parts[parts.length - 1] = filePart; postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams())); return httpRequest(postMethod, token); } catch (Exception ex) { throw new WeiboException(ex.getMessage(), ex, -1); } }
public void uploadItem(final WorkspaceInfo workspaceInfo, final PendingChange change, Object projectOrComponent, String progressTitle) throws TfsException, IOException { TfsRequestManager.executeRequest(myServerUri, projectOrComponent, new TfsRequestManager.Request<Void>(progressTitle) { @Override public Void execute(Credentials credentials, URI serverUri, @Nullable ProgressIndicator pi) throws Exception { String uploadUrl = TfsUtil.appendPath(myServerUri, myBeans.getUploadUrl(credentials, pi)); File file = VersionControlPath.getFile(change.getLocal()); long fileLength = file.length(); ArrayList<Part> parts = new ArrayList<Part>(); parts.add(new StringPart(SERVER_ITEM_FIELD, change.getItem(), "UTF-8")); parts.add(new StringPart(WORKSPACE_NAME_FIELD, workspaceInfo.getName())); parts.add(new StringPart(WORKSPACE_OWNER_FIELD, workspaceInfo.getOwnerName())); parts.add(new StringPart(LENGTH_FIELD, Long.toString(fileLength))); final byte[] hash = TfsFileUtil.calculateMD5(file); parts.add(new StringPart(HASH_FIELD, Base64.encode(hash))); // TODO: handle files too large to fit in a single POST parts.add(new StringPart(RANGE_FIELD, String.format("bytes=0-%d/%d", fileLength - 1, fileLength))); FilePart filePart = new FilePart(CONTENT_FIELD, SERVER_ITEM_FIELD, file); parts.add(filePart); filePart.setCharSet(null); WebServiceHelper .httpPost(uploadUrl, parts.toArray(new Part[parts.size()]), null, credentials, serverUri, myBeans.getUploadDownloadClient(false)); return null; } }); }
public HttpMethod buildMultipartRequest(URI location, Map<Path, byte[]> toUpload) throws HttpException, IOException { PostMethod filePost = new PostMethod(location.toASCIIString()); List<Part> parts = new ArrayList<Part>(toUpload.size()); for (Entry<Path, byte[]> entry : toUpload.entrySet()) parts.add(new FilePart(entry.getKey().toString(), new ByteArrayPartSource(entry.getKey().toString(), entry.getValue()))); filePost.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[0]), filePost.getParams())); return filePost; }
public static int sendFile(final String host, final String port, final String path, final String fileName, final InputStream inputStream, final long lengthInBytes) { HttpClient client = new HttpClient(); try { client.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1); client.getParams().setSoTimeout(3600 * 1000); // One hour PostMethod post = new PostMethod("http://" + host + ":" + port + "/" + path); Part[] parts = { new FilePart(fileName, new PartSource() { @Override public long getLength() { return lengthInBytes; } @Override public String getFileName() { return "fileName"; } @Override public InputStream createInputStream() throws IOException { return new BufferedInputStream(inputStream); } }) }; post.setRequestEntity(new MultipartRequestEntity(parts, new HttpMethodParams())); client.executeMethod(post); if (post.getStatusCode() >= 400) { String errorString = "POST Status Code: " + post.getStatusCode() + "\n"; if (post.getResponseHeader("Error") != null) { errorString += "ServletException: " + post.getResponseHeader("Error").getValue(); } throw new HttpException(errorString); } return post.getStatusCode(); } catch (Exception e) { LOGGER.error("Caught exception while sending file", e); Utils.rethrowException(e); throw new AssertionError("Should not reach this"); } }
public void addFile(String name, File file) { try { parts.add(new FilePart(name, file)); params.add(new Param(name, file.getPath())); } catch (FileNotFoundException e) { LOG.error(e, "Unable to add to MultiPartPostBuilder. File not found:" + file); } }
public void addFile(final int executionId, final String uid, final File file) throws Exception { PostMethod method = new PostMethod(baseUri + "executions/" + executionId + "/details/" + uid + "/file/"); Part[] parts = new Part[] { new FilePart("file", file) }; method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); final int responseCode = client.executeMethod(method); handleResponseCode(method, responseCode); }
@Test public void testImportCp() throws HttpException, IOException, URISyntaxException { final URL cpUrl = RepositoryEntriesITCase.class.getResource("cp-demo.zip"); assertNotNull(cpUrl); final File cp = new File(cpUrl.toURI()); final HttpClient c = loginWithCookie("administrator", "olat"); final PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true); method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); final Part[] parts = { new FilePart("file", cp), new StringPart("filename", "cp-demo.zip"), new StringPart("resourcename", "CP demo"), new StringPart("displayname", "CP demo") }; method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); final int code = c.executeMethod(method); assertTrue(code == 200 || code == 201); final String body = method.getResponseBodyAsString(); method.releaseConnection(); final RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class); assertNotNull(vo); final Long key = vo.getKey(); final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(key); assertNotNull(re); assertNotNull(re.getOwnerGroup()); assertNotNull(re.getOlatResource()); assertEquals("CP demo", re.getDisplayname()); }
@Test public void testImportTest() throws HttpException, IOException, URISyntaxException { final URL cpUrl = RepositoryEntriesITCase.class.getResource("qti-demo.zip"); assertNotNull(cpUrl); final File cp = new File(cpUrl.toURI()); final HttpClient c = loginWithCookie("administrator", "olat"); final PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true); method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); final Part[] parts = { new FilePart("file", cp), new StringPart("filename", "qti-demo.zip"), new StringPart("resourcename", "QTI demo"), new StringPart("displayname", "QTI demo") }; method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); final int code = c.executeMethod(method); assertTrue(code == 200 || code == 201); final String body = method.getResponseBodyAsString(); method.releaseConnection(); final RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class); assertNotNull(vo); final Long key = vo.getKey(); final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(key); assertNotNull(re); assertNotNull(re.getOwnerGroup()); assertNotNull(re.getOlatResource()); assertEquals("QTI demo", re.getDisplayname()); log.info(re.getOlatResource().getResourceableTypeName()); }
@Test public void testImportQuestionnaire() throws HttpException, IOException, URISyntaxException { final URL cpUrl = RepositoryEntriesITCase.class.getResource("questionnaire-demo.zip"); assertNotNull(cpUrl); final File cp = new File(cpUrl.toURI()); final HttpClient c = loginWithCookie("administrator", "olat"); final PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true); method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); final Part[] parts = { new FilePart("file", cp), new StringPart("filename", "questionnaire-demo.zip"), new StringPart("resourcename", "Questionnaire demo"), new StringPart("displayname", "Questionnaire demo") }; method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); final int code = c.executeMethod(method); assertTrue(code == 200 || code == 201); final String body = method.getResponseBodyAsString(); method.releaseConnection(); final RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class); assertNotNull(vo); final Long key = vo.getKey(); final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(key); assertNotNull(re); assertNotNull(re.getOwnerGroup()); assertNotNull(re.getOlatResource()); assertEquals("Questionnaire demo", re.getDisplayname()); log.info(re.getOlatResource().getResourceableTypeName()); }
@Test public void testImportWiki() throws HttpException, IOException, URISyntaxException { final URL cpUrl = RepositoryEntriesITCase.class.getResource("wiki-demo.zip"); assertNotNull(cpUrl); final File cp = new File(cpUrl.toURI()); final HttpClient c = loginWithCookie("administrator", "olat"); final PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true); method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); final Part[] parts = { new FilePart("file", cp), new StringPart("filename", "wiki-demo.zip"), new StringPart("resourcename", "Wiki demo"), new StringPart("displayname", "Wiki demo") }; method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); final int code = c.executeMethod(method); assertTrue(code == 200 || code == 201); final String body = method.getResponseBodyAsString(); method.releaseConnection(); final RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class); assertNotNull(vo); final Long key = vo.getKey(); final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(key); assertNotNull(re); assertNotNull(re.getOwnerGroup()); assertNotNull(re.getOlatResource()); assertEquals("Wiki demo", re.getDisplayname()); log.info(re.getOlatResource().getResourceableTypeName()); }
@Test public void testImportBlog() throws HttpException, IOException, URISyntaxException { final URL cpUrl = RepositoryEntriesITCase.class.getResource("blog-demo.zip"); assertNotNull(cpUrl); final File cp = new File(cpUrl.toURI()); final HttpClient c = loginWithCookie("administrator", "olat"); final PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true); method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); final Part[] parts = { new FilePart("file", cp), new StringPart("filename", "blog-demo.zip"), new StringPart("resourcename", "Blog demo"), new StringPart("displayname", "Blog demo") }; method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); final int code = c.executeMethod(method); assertTrue(code == 200 || code == 201); final String body = method.getResponseBodyAsString(); method.releaseConnection(); final RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class); assertNotNull(vo); final Long key = vo.getKey(); final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(key); assertNotNull(re); assertNotNull(re.getOwnerGroup()); assertNotNull(re.getOlatResource()); assertEquals("Blog demo", re.getDisplayname()); log.info(re.getOlatResource().getResourceableTypeName()); }
@Test public void testPortrait() throws IOException, URISyntaxException { final URL portraitUrl = RepositoryEntriesITCase.class.getResource("portrait.jpg"); assertNotNull(portraitUrl); final File portrait = new File(portraitUrl.toURI()); final HttpClient c = loginWithCookie("rest-one", "A6B7C8"); // upload portrait final String request = "/users/" + id1.getKey() + "/portrait"; final PostMethod method = createPost(request, MediaType.APPLICATION_JSON, true); method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); final Part[] parts = { new FilePart("file", portrait), new StringPart("filename", "portrait.jpg") }; method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); final int code = c.executeMethod(method); assertEquals(code, 200); method.releaseConnection(); // check if big and small portraits exist final DisplayPortraitManager dps = DisplayPortraitManager.getInstance(); final File uploadDir = dps.getPortraitDir(id1); assertTrue(new File(uploadDir, DisplayPortraitManager.PORTRAIT_SMALL_FILENAME).exists()); assertTrue(new File(uploadDir, DisplayPortraitManager.PORTRAIT_BIG_FILENAME).exists()); // check get portrait final String getRequest = "/users/" + id1.getKey() + "/portrait"; final GetMethod getMethod = createGet(getRequest, MediaType.APPLICATION_OCTET_STREAM, true); final int getCode = c.executeMethod(getMethod); assertEquals(getCode, 200); final InputStream in = getMethod.getResponseBodyAsStream(); int b = 0; int count = 0; while ((b = in.read()) > -1) { count++; } assertEquals(-1, b);// up to end of file assertTrue(count > 1000);// enough bytes method.releaseConnection(); }