List of usage examples for org.apache.commons.httpclient.methods.multipart ByteArrayPartSource ByteArrayPartSource
public ByteArrayPartSource(String paramString, byte[] paramArrayOfByte)
From source file:org.safecreative.api.wrapper.SafeCreativeAPIWrapper.java
/** * Uploads a data buffer for register or update a work * //from www. j a va 2 s. c o m * @param data Byte array of data to upload * @param fileName filename to use for upload file * @param byPost true - upload file using POST, false - upload by API * @param uploadListener Upload progress listener to notify if not <code>null</code> * @return upload ticket or null if fails * @throws ApiException */ public String uploadBytes(byte[] data, String fileName, boolean byPost, UploadProgressListener uploadListener) throws ApiException { return uploadFileSource(new ByteArrayPartSource(fileName, data), byPost, uploadListener); }
From source file:org.sakaiproject.nakamura.proxy.ProxyClientServiceImpl.java
/** * Executes a HTTP call using a path in the JCR to point to a template and a map of * properties to populate that template with. An example might be a SOAP call. * * <pre>/* w w w . j ava 2 s . c om*/ * {http://www.w3.org/2001/12/soap-envelope}Envelope:{ * {http://www.w3.org/2001/12/soap-envelope}Body:{ * {http://www.example.org/stock}GetStockPriceResponse:{ * >body:[ ] * {http://www.example.org/stock}Price:{ * >body:[34.5] * } * } * >body:[ ] * } * >body:[ ] * {http://www.w3.org/2001/12/soap-envelope}encodingStyle:[http://www.w3.org/2001/12/soap-encoding] * } * * </pre> * * @param resource * the resource containing the proxy end point specification. * @param headers * a map of headers to set int the request. * @param input * a map of parameters for all templates (both url and body) * @param requestInputStream * containing the request body (can be null if the call requires no body or the * template will be used to generate the body) * @param requestContentLength * if the requestImputStream is specified, the length specifies the lenght of * the body. * @param requerstContentType * the content type of the request, if null the node property * sakai:proxy-request-content-type will be used. * @throws ProxyClientException */ public ProxyResponse executeCall(Node node, Map<String, String> headers, Map<String, Object> input, InputStream requestInputStream, long requestContentLength, String requestContentType) throws ProxyClientException { try { bindNode(node); if (node != null && node.hasProperty(SAKAI_REQUEST_PROXY_ENDPOINT)) { // setup the post request String endpointURL = JcrUtils.getMultiValueString(node.getProperty(SAKAI_REQUEST_PROXY_ENDPOINT)); if (isUnsafeProxyDefinition(node)) { try { URL u = new URL(endpointURL); String host = u.getHost(); if (host.indexOf('$') >= 0) { throw new ProxyClientException( "Invalid Endpoint template, relies on request to resolve valid URL " + u); } } catch (MalformedURLException e) { throw new ProxyClientException( "Invalid Endpoint template, relies on request to resolve valid URL", e); } } // Find all velocity replacement variable(s) in the endpointURL, // copy any equivalent keys from the input Map, to a new Map that // can be process by Velocity. In the new Map, the Map value field // has been changed from RequestParameter[] to String. Map<String, String> inputContext = new HashMap<String, String>(); int startPosition = endpointURL.indexOf("${"); while (startPosition > -1) { int endPosition = endpointURL.indexOf("}", startPosition); if (endPosition > -1) { String key = endpointURL.substring(startPosition + 2, endPosition); Object value = input.get(key); if (value instanceof RequestParameter[]) { // now change input value object from RequestParameter[] to String // and add to inputContext Map. RequestParameter[] requestParameters = (RequestParameter[]) value; inputContext.put(key, requestParameters[0].getString()); } else { // KERN-1346 regression; see KERN-1409 inputContext.put(key, String.valueOf(value)); } // look for the next velocity replacement variable startPosition = endpointURL.indexOf("${", endPosition); } else { break; } } VelocityContext context = new VelocityContext(inputContext); // add in the config properties from the bundle overwriting everythign else. context.put("config", configProperties); endpointURL = processUrlTemplate(endpointURL, context); ProxyMethod proxyMethod = ProxyMethod.GET; if (node.hasProperty(SAKAI_REQUEST_PROXY_METHOD)) { try { proxyMethod = ProxyMethod.valueOf(node.getProperty(SAKAI_REQUEST_PROXY_METHOD).getString()); } catch (Exception e) { logger.debug("The Proxy request specified by " + node + " failed, cause follows:", e); } } HttpMethod method = null; switch (proxyMethod) { case GET: if (node.hasProperty(SAKAI_LIMIT_GET_SIZE)) { long maxSize = node.getProperty(SAKAI_LIMIT_GET_SIZE).getLong(); method = new HeadMethod(endpointURL); HttpMethodParams params = new HttpMethodParams(method.getParams()); // make certain we reject the body of a head params.setBooleanParameter("http.protocol.reject-head-body", true); method.setParams(params); method.setFollowRedirects(true); populateMethod(method, node, headers); int result = httpClient.executeMethod(method); if (externalAuthenticatingProxy && result == 407) { method.releaseConnection(); method.setDoAuthentication(true); result = httpClient.executeMethod(method); } if (result == 200) { // Check if the content-length is smaller than the maximum (if any). Header contentLengthHeader = method.getResponseHeader("Content-Length"); if (contentLengthHeader != null) { long length = Long.parseLong(contentLengthHeader.getValue()); if (length > maxSize) { return new ProxyResponseImpl(HttpServletResponse.SC_PRECONDITION_FAILED, "Response too large", method); } } } else { return new ProxyResponseImpl(result, method); } } method = new GetMethod(endpointURL); // redirects work automatically for get, options and head, but not for put and // post method.setFollowRedirects(true); break; case HEAD: method = new HeadMethod(endpointURL); HttpMethodParams params = new HttpMethodParams(method.getParams()); // make certain we reject the body of a head params.setBooleanParameter("http.protocol.reject-head-body", true); method.setParams(params); // redirects work automatically for get, options and head, but not for put and // post method.setFollowRedirects(true); break; case OPTIONS: method = new OptionsMethod(endpointURL); // redirects work automatically for get, options and head, but not for put and // post method.setFollowRedirects(true); break; case POST: method = new PostMethod(endpointURL); break; case PUT: method = new PutMethod(endpointURL); break; default: method = new GetMethod(endpointURL); // redirects work automatically for get, options and head, but not for put and // post method.setFollowRedirects(true); } populateMethod(method, node, headers); if (requestInputStream == null && !node.hasProperty(SAKAI_PROXY_REQUEST_TEMPLATE)) { if (method instanceof PostMethod) { PostMethod postMethod = (PostMethod) method; ArrayList<Part> parts = new ArrayList<Part>(); for (Entry<String, Object> param : input.entrySet()) { String key = param.getKey(); Object value = param.getValue(); if (value instanceof RequestParameter[]) { for (RequestParameter val : (RequestParameter[]) param.getValue()) { Part part = null; if (val.isFormField()) { part = new StringPart(param.getKey(), val.getString()); } else { ByteArrayPartSource source = new ByteArrayPartSource(key, val.get()); part = new FilePart(key, source); } parts.add(part); } } else { parts.add(new StringPart(key, value.toString())); } Part[] partsArray = parts.toArray(new Part[parts.size()]); postMethod.setRequestEntity(new MultipartRequestEntity(partsArray, method.getParams())); } } } else { if (method instanceof EntityEnclosingMethod) { String contentType = requestContentType; if (contentType == null && node.hasProperty(SAKAI_REQUEST_CONTENT_TYPE)) { contentType = node.getProperty(SAKAI_REQUEST_CONTENT_TYPE).getString(); } if (contentType == null) { contentType = APPLICATION_OCTET_STREAM; } EntityEnclosingMethod eemethod = (EntityEnclosingMethod) method; if (requestInputStream != null) { eemethod.setRequestEntity(new InputStreamRequestEntity(requestInputStream, requestContentLength, contentType)); } else { // build the request Template template = velocityEngine.getTemplate(node.getPath()); StringWriter body = new StringWriter(); template.merge(context, body); byte[] soapBodyContent = body.toString().getBytes("UTF-8"); eemethod.setRequestEntity(new ByteArrayRequestEntity(soapBodyContent, contentType)); } } } int result = httpClient.executeMethod(method); if (externalAuthenticatingProxy && result == 407) { method.releaseConnection(); method.setDoAuthentication(true); result = httpClient.executeMethod(method); } if (result == 302 && method instanceof EntityEnclosingMethod) { // handle redirects on post and put String url = method.getResponseHeader("Location").getValue(); method = new GetMethod(url); method.setFollowRedirects(true); method.setDoAuthentication(false); result = httpClient.executeMethod(method); if (externalAuthenticatingProxy && result == 407) { method.releaseConnection(); method.setDoAuthentication(true); result = httpClient.executeMethod(method); } } return new ProxyResponseImpl(result, method); } } catch (ProxyClientException e) { throw e; } catch (Exception e) { throw new ProxyClientException("The Proxy request specified by " + node + " failed, cause follows:", e); } finally { unbindNode(); } throw new ProxyClientException( "The Proxy request specified by " + node + " does not contain a valid endpoint specification "); }
From source file:org.seasar.cubby.controller.impl.MultipartRequestParserImplMultipartRequestTest.java
@Test public void getParameterMap() throws Exception { final PartSource filePartSource = new ByteArrayPartSource("upload.txt", "upload test".getBytes("UTF-8")); final PostMethod method = new PostMethod(); final Part[] parts = new Part[] { new StringPart("a", "12345"), new StringPart("b", "abc"), new StringPart("b", "def"), new FilePart("file", filePartSource) }; this.entity = new MultipartRequestEntity(parts, method.getParams()); final ByteArrayOutputStream out = new ByteArrayOutputStream(); this.entity.writeRequest(out); out.flush();/*from w w w .j a v a 2s. co m*/ out.close(); this.input = new ByteArrayInputStream(out.toByteArray()); this.attributes.put("c", new String[] { "999" }); final Map<String, Object[]> parameterMap = requestParser.getParameterMap(request); assertEquals("parameterMap.size()", 4, parameterMap.size()); final Object[] a = parameterMap.get("a"); assertEquals("a.length", 1, a.length); assertEquals("a[0]", "12345", a[0]); final Object[] b = parameterMap.get("b"); assertEquals("b.length", 2, b.length); assertEquals("b[0]", "abc", b[0]); assertEquals("b[1]", "def", b[1]); final Object[] c = parameterMap.get("c"); assertEquals("c.length", 1, c.length); assertEquals("c[0]", "999", c[0]); final Object[] file = parameterMap.get("file"); assertEquals("file.length", 1, file.length); assertTrue("file[0]", file[0] instanceof FileItem); final FileItem item = (FileItem) file[0]; assertEquals("upload test", new String(item.get(), "UTF-8")); }
From source file:org.xwiki.test.rest.AttachmentsResourceTest.java
@Test public void testPOSTAttachment() throws Exception { final String attachmentName = String.format("%s.txt", UUID.randomUUID()); final String content = "ATTACHMENT CONTENT"; String attachmentsUri = buildURIForThisPage(AttachmentsResource.class, attachmentName); HttpClient httpClient = new HttpClient(); httpClient.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials( TestUtils.ADMIN_CREDENTIALS.getUserName(), TestUtils.ADMIN_CREDENTIALS.getPassword())); httpClient.getParams().setAuthenticationPreemptive(true); Part[] parts = new Part[1]; ByteArrayPartSource baps = new ByteArrayPartSource(attachmentName, content.getBytes()); parts[0] = new FilePart(attachmentName, baps); PostMethod postMethod = new PostMethod(attachmentsUri); MultipartRequestEntity mpre = new MultipartRequestEntity(parts, postMethod.getParams()); postMethod.setRequestEntity(mpre);//from www .j av a 2 s. c om httpClient.executeMethod(postMethod); Assert.assertEquals(getHttpMethodInfo(postMethod), HttpStatus.SC_CREATED, postMethod.getStatusCode()); this.unmarshaller.unmarshal(postMethod.getResponseBodyAsStream()); Header location = postMethod.getResponseHeader("location"); GetMethod getMethod = executeGet(location.getValue()); Assert.assertEquals(getHttpMethodInfo(getMethod), HttpStatus.SC_OK, getMethod.getStatusCode()); Assert.assertEquals(content, getMethod.getResponseBodyAsString()); }
From source file:org.xwiki.test.storage.framework.StoreTestUtils.java
public static HttpMethod doUpload(final String address, final UsernamePasswordCredentials userNameAndPassword, final Map<String, byte[]> uploads) throws IOException { final HttpClient client = new HttpClient(); final PostMethod method = new PostMethod(address); if (userNameAndPassword != null) { client.getState().setCredentials(AuthScope.ANY, userNameAndPassword); client.getParams().setAuthenticationPreemptive(true); }/*from w w w. j a v a 2 s . com*/ Part[] parts = new Part[uploads.size()]; int i = 0; for (Map.Entry<String, byte[]> e : uploads.entrySet()) { parts[i++] = new FilePart("filepath", new ByteArrayPartSource(e.getKey(), e.getValue())); } MultipartRequestEntity entity = new MultipartRequestEntity(parts, method.getParams()); method.setRequestEntity(entity); client.executeMethod(method); return method; }
From source file:pl.umk.mat.zawodyweb.compiler.classes.LanguageMAIN.java
/** * Sprawdza rozwizanie na input//from w ww . j a v a2 s . co m * @param path kod rdowy * @param input w formacie: * <pre>c=NUMER_KONKURSU<br/>t=NUMER_ZADANIA<br/>m=MAX_POINTS</pre> * @return */ @Override public TestOutput runTest(String path, TestInput input) { TestOutput result = new TestOutput(null); Integer contest_id = null; Integer task_id = null; Integer max_points = null; try { try { Matcher matcher = null; matcher = Pattern.compile("c=([0-9]+)").matcher(input.getInputText()); if (matcher.find()) { contest_id = Integer.valueOf(matcher.group(1)); } matcher = Pattern.compile("t=([0-9]+)").matcher(input.getInputText()); if (matcher.find()) { task_id = Integer.valueOf(matcher.group(1)); } matcher = Pattern.compile("m=([0-9]+)").matcher(input.getInputText()); if (matcher.find()) { max_points = Integer.valueOf(matcher.group(1)); } if (contest_id == null) { throw new IllegalArgumentException("task_id == null"); } if (task_id == null) { throw new IllegalArgumentException("task_id == null"); } } catch (PatternSyntaxException ex) { throw new IllegalArgumentException(ex); } catch (NumberFormatException ex) { throw new IllegalArgumentException(ex); } catch (IllegalStateException ex) { throw new IllegalArgumentException(ex); } } catch (IllegalArgumentException e) { logger.error("Exception when parsing input", e); result.setStatus(ResultsStatusEnum.UNDEF.getCode()); result.setNotes(e.getMessage()); result.setOutputText("MAIN IllegalArgumentException"); return result; } logger.debug("Contest id = " + contest_id); logger.debug("Task id = " + task_id); logger.debug("Max points = " + max_points); String loginUrl = "http://main.edu.pl/pl/login"; String login = properties.getProperty("main_edu_pl.login"); String password = properties.getProperty("main_edu_pl.password"); HttpClient client = new HttpClient(); HttpClientParams params = client.getParams(); params.setParameter("http.useragent", "Opera/9.64 (Windows NT 6.0; U; pl) Presto/2.1.1"); //params.setParameter("http.protocol.handle-redirects", true); client.setParams(params); /* logowanie */ logger.debug("Logging in"); PostMethod postMethod = new PostMethod(loginUrl); NameValuePair[] dataLogging = { new NameValuePair("auth", "1"), new NameValuePair("login", login), new NameValuePair("pass", password) }; postMethod.setRequestBody(dataLogging); try { client.executeMethod(postMethod); if (Pattern.compile("Logowanie udane").matcher(postMethod.getResponseBodyAsString(1024 * 1024)) .find() == false) { logger.error("Unable to login (" + login + ":" + password + ")"); result.setStatus(ResultsStatusEnum.UNDEF.getCode()); result.setOutputText("Logging in failed"); postMethod.releaseConnection(); return result; } } catch (HttpException e) { logger.error("Exception when logging in", e); result.setStatus(ResultsStatusEnum.UNDEF.getCode()); result.setNotes(e.getMessage()); result.setOutputText("HttpException"); postMethod.releaseConnection(); return result; } catch (IOException e) { logger.error("Exception when logging in", e); result.setStatus(ResultsStatusEnum.UNDEF.getCode()); result.setNotes(e.getMessage()); result.setOutputText("IOException"); postMethod.releaseConnection(); return result; } postMethod.releaseConnection(); /* wchodzenie na stron z wysyaniem zada i pobieranie pl z hidden */ logger.debug("Getting submit page"); ArrayList<Part> values = new ArrayList<Part>(); try { GetMethod getMethod = new GetMethod("http://main.edu.pl/user.phtml?op=submit&m=insert&c=" + contest_id); client.executeMethod(getMethod); String response = getMethod.getResponseBodyAsString(1024 * 1024); getMethod.releaseConnection(); Matcher tagMatcher = Pattern.compile("<input[^>]*>").matcher(response); Pattern namePattern = Pattern.compile("name\\s*=\"([^\"]*)\""); Pattern valuePattern = Pattern.compile("value\\s*=\"([^\"]*)\""); while (tagMatcher.find()) { Matcher matcher = null; String name = null; String value = null; String inputTag = tagMatcher.group(); matcher = namePattern.matcher(inputTag); if (matcher.find()) { name = matcher.group(1); } matcher = valuePattern.matcher(inputTag); if (matcher.find()) { value = matcher.group(1); } if (name != null && value != null && name.equals("solution") == false) { values.add(new StringPart(name, value)); } } } catch (HttpException ex) { logger.error("Exception when getting submit page", ex); result.setStatus(ResultsStatusEnum.UNDEF.getCode()); result.setNotes(ex.getMessage()); result.setOutputText("IOException"); return result; } catch (IOException ex) { logger.error("Exception when getting submit page", ex); result.setStatus(ResultsStatusEnum.UNDEF.getCode()); result.setNotes(ex.getMessage()); result.setOutputText("IOException"); return result; } values.add(new StringPart("task", task_id.toString())); String filename = properties.getProperty("CODE_FILENAME"); filename = filename.replaceAll("\\." + properties.getProperty("CODEFILE_EXTENSION") + "$", ""); filename = filename + "." + properties.getProperty("CODEFILE_EXTENSION"); FilePart filePart = new FilePart("solution", new ByteArrayPartSource(filename, path.getBytes())); values.add(filePart); /* wysyanie rozwizania */ logger.debug("Submiting solution"); Integer solution_id = null; postMethod = new PostMethod("http://main.edu.pl/user.phtml?op=submit&m=db_insert&c=" + contest_id); postMethod.setRequestEntity(new MultipartRequestEntity(values.toArray(new Part[0]), client.getParams())); try { try { client.executeMethod(postMethod); HttpMethod method = postMethod; /* check if redirect */ Header locationHeader = postMethod.getResponseHeader("location"); if (locationHeader != null) { String redirectLocation = locationHeader.getValue(); GetMethod getMethod = new GetMethod( new URI(postMethod.getURI(), new URI(redirectLocation, false)).getURI()); client.executeMethod(getMethod); method = getMethod; } BufferedReader br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } Matcher matcher = Pattern.compile("<tr id=\"rptr\">.*?</tr>", Pattern.DOTALL) .matcher(sb.toString()); if (matcher.find()) { Matcher idMatcher = Pattern.compile("id=([0-9]+)").matcher(matcher.group()); if (idMatcher.find()) { solution_id = Integer.parseInt(idMatcher.group(1)); } } if (solution_id == null) { throw new IllegalArgumentException("solution_id == null"); } } catch (HttpException e) { new IllegalArgumentException(e); } catch (IOException e) { new IllegalArgumentException(e); } catch (NumberFormatException e) { new IllegalArgumentException(e); } catch (IllegalStateException e) { new IllegalArgumentException(e); } } catch (IllegalArgumentException e) { logger.error("Exception when submiting solution", e); result.setStatus(ResultsStatusEnum.UNDEF.getCode()); result.setNotes(e.getMessage()); result.setOutputText("IllegalArgumentException"); postMethod.releaseConnection(); return result; } postMethod.releaseConnection(); /* sprawdzanie statusu */ logger.debug("Checking result for main.id=" + solution_id); Pattern resultRowPattern = Pattern.compile("id=" + solution_id + ".*?</tr>", Pattern.DOTALL); Pattern resultPattern = Pattern.compile( "</td>.*?<td.*?>.*?</td>.*?<td.*?>(.*?)</td>.*?<td.*?>.*?</td>.*?<td.*?>(.*?)</td>", Pattern.DOTALL); result_loop: while (true) { try { Thread.sleep(7000); } catch (InterruptedException e) { result.setStatus(ResultsStatusEnum.UNDEF.getCode()); result.setNotes(e.getMessage()); result.setOutputText("InterruptedException"); return result; } GetMethod getMethod = new GetMethod("http://main.edu.pl/user.phtml?op=zgloszenia&c=" + contest_id); try { client.executeMethod(getMethod); String response = getMethod.getResponseBodyAsString(1024 * 1024); getMethod.releaseConnection(); Matcher matcher = resultRowPattern.matcher(response); // "</td>.*?<td.*?>.*?[NAZWA_ZADANIA]</td>.*?<td.*?>(.*?[STATUS])</td>.*?<td.*?>.*?</td>.*?<td.*?>(.*?[PUNKTY])</td>" while (matcher.find()) { Matcher resultMatcher = resultPattern.matcher(matcher.group()); if (resultMatcher.find() && resultMatcher.groupCount() == 2) { String resultType = resultMatcher.group(1); if (resultType.equals("?")) { continue; } else if (resultType.matches("B..d kompilacji")) { // CE result.setStatus(ResultsStatusEnum.CE.getCode()); result.setPoints( calculatePoints(resultMatcher.group(2), input.getMaxPoints(), max_points)); } else if (resultType.matches("Program wyw.aszczony")) { // TLE result.setStatus(ResultsStatusEnum.TLE.getCode()); result.setPoints( calculatePoints(resultMatcher.group(2), input.getMaxPoints(), max_points)); } else if (resultType.matches("B..d wykonania")) { // RTE result.setStatus(ResultsStatusEnum.RE.getCode()); result.setPoints( calculatePoints(resultMatcher.group(2), input.getMaxPoints(), max_points)); } else if (resultType.matches("Z.a odpowied.")) { // WA result.setStatus(ResultsStatusEnum.WA.getCode()); result.setPoints( calculatePoints(resultMatcher.group(2), input.getMaxPoints(), max_points)); } else if (resultType.equals("OK")) { // AC result.setStatus(ResultsStatusEnum.ACC.getCode()); result.setPoints( calculatePoints(resultMatcher.group(2), input.getMaxPoints(), max_points)); } else { result.setStatus(ResultsStatusEnum.UNDEF.getCode()); result.setNotes("Unknown status: \"" + resultType + "\""); } break result_loop; } } } catch (HttpException ex) { result.setStatus(ResultsStatusEnum.UNDEF.getCode()); result.setNotes(ex.getMessage()); result.setOutputText("HttpException"); return result; } catch (IOException ex) { result.setStatus(ResultsStatusEnum.UNDEF.getCode()); result.setNotes(ex.getMessage()); result.setOutputText("IOException"); return result; } } return result; }