List of usage examples for org.apache.commons.httpclient.methods PostMethod addParameter
public void addParameter(String paramString1, String paramString2) throws IllegalArgumentException
From source file:org.apache.jackrabbit.spi2davex.RepositoryServiceImpl.java
@Override public void copy(SessionInfo sessionInfo, String srcWorkspaceName, NodeId srcNodeId, NodeId destParentNodeId, Name destName) throws RepositoryException { if (srcWorkspaceName.equals(sessionInfo.getWorkspaceName())) { super.copy(sessionInfo, srcWorkspaceName, srcNodeId, destParentNodeId, destName); return;//www. j a va2 s.co m } PostMethod method = null; try { method = new PostMethod(getWorkspaceURI(sessionInfo)); NamePathResolver resolver = getNamePathResolver(sessionInfo); StringBuilder args = new StringBuilder(); args.append(srcWorkspaceName); args.append(","); args.append(resolver.getJCRPath(getPath(srcNodeId, sessionInfo, srcWorkspaceName))); args.append(","); String destParentPath = resolver.getJCRPath(getPath(destParentNodeId, sessionInfo)); String destPath = (destParentPath.endsWith("/") ? destParentPath + resolver.getJCRName(destName) : destParentPath + "/" + resolver.getJCRName(destName)); args.append(destPath); method.addParameter(PARAM_COPY, args.toString()); addIfHeader(sessionInfo, method); getClient(sessionInfo).executeMethod(method); method.checkSuccess(); } catch (IOException e) { throw new RepositoryException(e); } catch (DavException e) { throw ExceptionConverter.generate(e, method); } finally { if (method != null) { method.releaseConnection(); } } }
From source file:org.apache.jackrabbit.spi2davex.RepositoryServiceImpl.java
@Override public void clone(SessionInfo sessionInfo, String srcWorkspaceName, NodeId srcNodeId, NodeId destParentNodeId, Name destName, boolean removeExisting) throws RepositoryException { PostMethod method = null; try {//from www .j av a 2 s . com method = new PostMethod(getWorkspaceURI(sessionInfo)); NamePathResolver resolver = getNamePathResolver(sessionInfo); StringBuilder args = new StringBuilder(); args.append(srcWorkspaceName); args.append(","); args.append(resolver.getJCRPath(getPath(srcNodeId, sessionInfo, srcWorkspaceName))); args.append(","); String destParentPath = resolver.getJCRPath(getPath(destParentNodeId, sessionInfo)); String destPath = (destParentPath.endsWith("/") ? destParentPath + resolver.getJCRName(destName) : destParentPath + "/" + resolver.getJCRName(destName)); args.append(destPath); args.append(","); args.append(Boolean.toString(removeExisting)); method.addParameter(PARAM_CLONE, args.toString()); addIfHeader(sessionInfo, method); getClient(sessionInfo).executeMethod(method); method.checkSuccess(); if (removeExisting) { clearItemUriCache(sessionInfo); } } catch (IOException e) { throw new RepositoryException(e); } catch (DavException e) { throw ExceptionConverter.generate(e, method); } finally { if (method != null) { method.releaseConnection(); } } }
From source file:org.apache.jetspeed.portlets.sso.SSOWebContentPortlet.java
protected byte[] doPreemptiveAuthentication(HttpClient client, HttpMethod method, RenderRequest request, RenderResponse response) {// w ww .ja v a 2 s . com byte[] result = super.doPreemptiveAuthentication(client, method, request, response); if (result != null) { // already handled return result; } // System.out.println("SSOWebContentPortlet.doPreemptiveAuthentication..."); PortletPreferences prefs = request.getPreferences(); String type = getSingleSignOnAuthType(prefs); if (type.equalsIgnoreCase(SSO_TYPE_BASIC_PREEMPTIVE)) { // Preemptive, basic authentication String userName = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_USERNAME); if (userName == null) userName = ""; String password = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_PASSWORD); if (password == null) password = ""; // System.out.println("...performing preemptive basic authentication with userName: "+userName+", and password: "+password); method.setDoAuthentication(true); method.getHostAuthState().setPreemptive(); client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password)); // handled! return result; } else if (type.startsWith(SSO_TYPE_FORM)) { try { Boolean formAuth = (Boolean) PortletMessaging.receive(request, FORM_AUTH_STATE); if (formAuth != null) { // already been here, done that return (formAuth.booleanValue() ? result : null); } else { // stop recursion, but assume failure, ...for now PortletMessaging.publish(request, FORM_AUTH_STATE, Boolean.FALSE); } String formAction = prefs.getValue(SSO_TYPE_FORM_ACTION_URL, ""); if (formAction == null || formAction.length() == 0) { log.warn("sso.type specified as 'form', but no: " + SSO_TYPE_FORM_ACTION_URL + ", action was specified - unable to preemptively authenticate by form."); return null; } String userNameField = prefs.getValue(SSO_TYPE_FORM_USERNAME_FIELD, ""); if (userNameField == null || userNameField.length() == 0) { log.warn("sso.type specified as 'form', but no: " + SSO_TYPE_FORM_USERNAME_FIELD + ", username field was specified - unable to preemptively authenticate by form."); return null; } String passwordField = prefs.getValue(SSO_TYPE_FORM_PASSWORD_FIELD, "password"); if (passwordField == null || passwordField.length() == 0) { log.warn("sso.type specified as 'form', but no: " + SSO_TYPE_FORM_PASSWORD_FIELD + ", password field was specified - unable to preemptively authenticate by form."); return null; } String userName = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_USERNAME); if (userName == null) userName = ""; String password = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_PASSWORD); if (password == null) password = ""; // get submit method int i = type.indexOf('.'); boolean isPost = i > 0 ? type.substring(i + 1).equalsIgnoreCase("post") : true; // default to post, since it is a form // get parameter map HashMap formParams = new HashMap(); formParams.put(userNameField, new String[] { userName }); formParams.put(passwordField, new String[] { password }); String formArgs = prefs.getValue(SSO_TYPE_FORM_ACTION_ARGS, ""); if (formArgs != null && formArgs.length() > 0) { StringTokenizer iter = new StringTokenizer(formArgs, ";"); while (iter.hasMoreTokens()) { String pair = iter.nextToken(); i = pair.indexOf('='); if (i > 0) formParams.put(pair.substring(0, i), new String[] { pair.substring(i + 1) }); } } // resuse client - in case new cookies get set - but create a new method (for the formAction) String formMethod = (isPost) ? FORM_POST_METHOD : FORM_GET_METHOD; method = getHttpMethod(client, getURLSource(formAction, formParams, request, response), formParams, formMethod, request); // System.out.println("...posting credentials"); result = doHttpWebContent(client, method, 0, request, response); // System.out.println("Result of attempted authorization: "+success); PortletMessaging.publish(request, FORM_AUTH_STATE, Boolean.valueOf(result != null)); return result; } catch (Exception ex) { // bad log.error("Form-based authentication failed", ex); } } else if (type.equalsIgnoreCase(SSO_TYPE_URL) || type.equalsIgnoreCase(SSO_TYPE_URL_BASE64)) { // set user name and password parameters in the HttpMethod String userNameParam = prefs.getValue(SSO_TYPE_URL_USERNAME_PARAM, ""); if (userNameParam == null || userNameParam.length() == 0) { log.warn("sso.type specified as 'url', but no: " + SSO_TYPE_URL_USERNAME_PARAM + ", username parameter was specified - unable to preemptively authenticate by URL."); return null; } String passwordParam = prefs.getValue(SSO_TYPE_URL_PASSWORD_PARAM, ""); if (passwordParam == null || passwordParam.length() == 0) { log.warn("sso.type specified as 'url', but no: " + SSO_TYPE_URL_PASSWORD_PARAM + ", password parameter was specified - unable to preemptively authenticate by URL."); return null; } String userName = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_USERNAME); if (userName == null) userName = ""; String password = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_PASSWORD); if (password == null) password = ""; if (type.equalsIgnoreCase(SSO_TYPE_URL_BASE64)) { Base64 encoder = new Base64(); userName = new String(encoder.encode(userName.getBytes())); password = new String(encoder.encode(password.getBytes())); } // GET and POST accept args differently if (method instanceof PostMethod) { // add POST data PostMethod postMethod = (PostMethod) method; postMethod.addParameter(userNameParam, userName); postMethod.addParameter(passwordParam, password); } else { // augment GET query string NameValuePair[] authPairs = new NameValuePair[] { new NameValuePair(userNameParam, userName), new NameValuePair(passwordParam, password) }; String existingQuery = method.getQueryString(); method.setQueryString(authPairs); if (existingQuery != null && existingQuery.length() > 0) { // augment existing query with new auth query existingQuery = existingQuery + '&' + method.getQueryString(); method.setQueryString(existingQuery); } } return result; } // else System.out.println("...sso.type: "+type+", no pre-emptive authentication"); // not handled return null; }
From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC3Impl.java
private String sendPostData(PostMethod post) throws IOException { // Buffer to hold the post body, except file content StringBuilder postedBody = new StringBuilder(1000); HTTPFileArg[] files = getHTTPFiles(); // Check if we should do a multipart/form-data or an // application/x-www-form-urlencoded post request if (getUseMultipartForPost()) { // If a content encoding is specified, we use that as the // encoding of any parameter values String contentEncoding = getContentEncoding(); if (isNullOrEmptyTrimmed(contentEncoding)) { contentEncoding = null;/* w w w. ja va 2 s . c om*/ } final boolean browserCompatible = getDoBrowserCompatibleMultipart(); // We don't know how many entries will be skipped List<PartBase> partlist = new ArrayList<>(); // Create the parts // Add any parameters for (JMeterProperty jMeterProperty : getArguments()) { HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue(); String parameterName = arg.getName(); if (arg.isSkippable(parameterName)) { continue; } StringPart part = new StringPart(arg.getName(), arg.getValue(), contentEncoding); if (browserCompatible) { part.setTransferEncoding(null); part.setContentType(null); } partlist.add(part); } // Add any files for (HTTPFileArg file : files) { File inputFile = FileServer.getFileServer().getResolvedFile(file.getPath()); // We do not know the char set of the file to be uploaded, so we set it to null ViewableFilePart filePart = new ViewableFilePart(file.getParamName(), inputFile, file.getMimeType(), null); filePart.setCharSet(null); // We do not know what the char set of the file is partlist.add(filePart); } // Set the multipart for the post int partNo = partlist.size(); Part[] parts = partlist.toArray(new Part[partNo]); MultipartRequestEntity multiPart = new MultipartRequestEntity(parts, post.getParams()); post.setRequestEntity(multiPart); // Set the content type String multiPartContentType = multiPart.getContentType(); post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE, multiPartContentType); // If the Multipart is repeatable, we can send it first to // our own stream, without the actual file content, so we can return it if (multiPart.isRepeatable()) { // For all the file multiparts, we must tell it to not include // the actual file content for (int i = 0; i < partNo; i++) { if (parts[i] instanceof ViewableFilePart) { ((ViewableFilePart) parts[i]).setHideFileData(true); // .sendMultipartWithoutFileContent(bos); } } // Write the request to our own stream ByteArrayOutputStream bos = new ByteArrayOutputStream(); multiPart.writeRequest(bos); bos.flush(); // We get the posted bytes using the encoding used to create it postedBody.append(new String(bos.toByteArray(), contentEncoding == null ? "US-ASCII" // $NON-NLS-1$ this is the default used by HttpClient : contentEncoding)); bos.close(); // For all the file multiparts, we must revert the hiding of // the actual file content for (int i = 0; i < partNo; i++) { if (parts[i] instanceof ViewableFilePart) { ((ViewableFilePart) parts[i]).setHideFileData(false); } } } else { postedBody.append("<Multipart was not repeatable, cannot view what was sent>"); // $NON-NLS-1$ } } else { // Check if the header manager had a content type header // This allows the user to specify his own content-type for a POST request Header contentTypeHeader = post.getRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE); boolean hasContentTypeHeader = contentTypeHeader != null && contentTypeHeader.getValue() != null && contentTypeHeader.getValue().length() > 0; // If there are no arguments, we can send a file as the body of the request // TODO: needs a multiple file upload scenerio if (!hasArguments() && getSendFileAsPostBody()) { // If getSendFileAsPostBody returned true, it's sure that file is not null HTTPFileArg file = files[0]; if (!hasContentTypeHeader) { // Allow the mimetype of the file to control the content type if (file.getMimeType() != null && file.getMimeType().length() > 0) { post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType()); } else { post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE, HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED); } } FileRequestEntity fileRequestEntity = new FileRequestEntity(new File(file.getPath()), null); post.setRequestEntity(fileRequestEntity); // We just add placeholder text for file content postedBody.append("<actual file content, not shown here>"); } else { // In a post request which is not multipart, we only support // parameters, no file upload is allowed // If a content encoding is specified, we set it as http parameter, so that // the post body will be encoded in the specified content encoding String contentEncoding = getContentEncoding(); boolean haveContentEncoding = false; if (isNullOrEmptyTrimmed(contentEncoding)) { contentEncoding = null; } else { post.getParams().setContentCharset(contentEncoding); haveContentEncoding = true; } // If none of the arguments have a name specified, we // just send all the values as the post body if (getSendParameterValuesAsPostBody()) { // Allow the mimetype of the file to control the content type // This is not obvious in GUI if you are not uploading any files, // but just sending the content of nameless parameters // TODO: needs a multiple file upload scenerio if (!hasContentTypeHeader) { HTTPFileArg file = files.length > 0 ? files[0] : null; if (file != null && file.getMimeType() != null && file.getMimeType().length() > 0) { post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType()); } else { // TODO - is this the correct default? post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE, HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED); } } // Just append all the parameter values, and use that as the post body StringBuilder postBody = new StringBuilder(); for (JMeterProperty jMeterProperty : getArguments()) { HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue(); String value; if (haveContentEncoding) { value = arg.getEncodedValue(contentEncoding); } else { value = arg.getEncodedValue(); } postBody.append(value); } StringRequestEntity requestEntity = new StringRequestEntity(postBody.toString(), post.getRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE).getValue(), contentEncoding); post.setRequestEntity(requestEntity); } else { // It is a normal post request, with parameter names and values // Set the content type if (!hasContentTypeHeader) { post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE, HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED); } // Add the parameters for (JMeterProperty jMeterProperty : getArguments()) { HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue(); // The HTTPClient always urlencodes both name and value, // so if the argument is already encoded, we have to decode // it before adding it to the post request String parameterName = arg.getName(); if (arg.isSkippable(parameterName)) { continue; } String parameterValue = arg.getValue(); if (!arg.isAlwaysEncoded()) { // The value is already encoded by the user // Must decode the value now, so that when the // httpclient encodes it, we end up with the same value // as the user had entered. String urlContentEncoding = contentEncoding; if (urlContentEncoding == null || urlContentEncoding.length() == 0) { // Use the default encoding for urls urlContentEncoding = EncoderCache.URL_ARGUMENT_ENCODING; } parameterName = URLDecoder.decode(parameterName, urlContentEncoding); parameterValue = URLDecoder.decode(parameterValue, urlContentEncoding); } // Add the parameter, httpclient will urlencode it post.addParameter(parameterName, parameterValue); } /* // // Alternative implementation, to make sure that HTTPSampler and HTTPSampler2 // // sends the same post body. // // // Only include the content char set in the content-type header if it is not // // an APPLICATION_X_WWW_FORM_URLENCODED content type // String contentCharSet = null; // if(!post.getRequestHeader(HEADER_CONTENT_TYPE).getValue().equals(APPLICATION_X_WWW_FORM_URLENCODED)) { // contentCharSet = post.getRequestCharSet(); // } // StringRequestEntity requestEntity = new StringRequestEntity(getQueryString(contentEncoding), post.getRequestHeader(HEADER_CONTENT_TYPE).getValue(), contentCharSet); // post.setRequestEntity(requestEntity); */ } // If the request entity is repeatable, we can send it first to // our own stream, so we can return it if (post.getRequestEntity().isRepeatable()) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); post.getRequestEntity().writeRequest(bos); bos.flush(); // We get the posted bytes using the encoding used to create it postedBody.append(new String(bos.toByteArray(), post.getRequestCharSet())); bos.close(); } else { postedBody.append("<RequestEntity was not repeatable, cannot view what was sent>"); } } } // Set the content length post.setRequestHeader(HTTPConstants.HEADER_CONTENT_LENGTH, Long.toString(post.getRequestEntity().getContentLength())); return postedBody.toString(); }
From source file:org.apache.marmotta.ucuenca.wk.commons.function.TranslateForSemanticDistance.java
private synchronized String http2(String s, Map<String, String> mp) throws SQLException, IOException { String md = s + mp.toString(); Statement stmt = conn.createStatement(); String sql;// w ww .j a va 2 s . c om sql = "SELECT * FROM cache where cache.key='" + commonservices.getMD5(md) + "'"; java.sql.ResultSet rs = stmt.executeQuery(sql); String resp = ""; if (rs.next()) { resp = rs.getString("value"); rs.close(); stmt.close(); } else { rs.close(); stmt.close(); HttpClient client = new HttpClient(); PostMethod method = new PostMethod(s); //Add any parameter if u want to send it with Post req. for (Map.Entry<String, String> mcc : mp.entrySet()) { method.addParameter(mcc.getKey(), mcc.getValue()); } int statusCode = client.executeMethod(method); if (statusCode != -1) { InputStream in = method.getResponseBodyAsStream(); final Scanner reader = new Scanner(in, "UTF-8"); while (reader.hasNextLine()) { final String line = reader.nextLine(); resp += line + "\n"; } reader.close(); try { JsonParser parser = new JsonParser(); parser.parse(resp); PreparedStatement stmt2 = conn.prepareStatement("INSERT INTO cache (key, value) values (?, ?)"); stmt2.setString(1, commonservices.getMD5(md)); stmt2.setString(2, resp); stmt2.executeUpdate(); stmt2.close(); } catch (Exception e) { } } } return resp; }
From source file:org.apache.sling.commons.testing.integration.SlingIntegrationTestClient.java
/** Create a node under given path, using a POST to Sling * @param url under which node is created * @param multiPart if true, does a multipart POST * @param localFile file to upload/*w w w . j av a 2s. c o m*/ * @param fieldName name of the file field * @param typeHint typeHint of the file field * @return the URL that Sling provides to display the node */ public String createNode(String url, NameValuePairList clientNodeProperties, Map<String, String> requestHeaders, boolean multiPart, File localFile, String fieldName, String typeHint) throws IOException { final PostMethod post = new PostMethod(url); post.setFollowRedirects(false); // create a private copy of the properties to not tamper with // the properties of the client NameValuePairList nodeProperties = new NameValuePairList(clientNodeProperties); // add sling specific properties nodeProperties.prependIfNew(":redirect", "*"); nodeProperties.prependIfNew(":displayExtension", ""); nodeProperties.prependIfNew(":status", "browser"); // add fake property - otherwise the node is not created if (clientNodeProperties == null) { nodeProperties.add("jcr:created", ""); } // force form encoding to UTF-8, which is what we use to convert the // string parts into stream data nodeProperties.addOrReplace("_charset_", "UTF-8"); if (nodeProperties.size() > 0) { if (multiPart) { final List<Part> partList = new ArrayList<Part>(); for (NameValuePair e : nodeProperties) { if (e.getValue() != null) { partList.add(new StringPart(e.getName(), e.getValue(), "UTF-8")); } } if (localFile != null) { partList.add(new FilePart(fieldName, localFile)); if (typeHint != null) { partList.add(new StringPart(fieldName + "@TypeHint", typeHint)); } } final Part[] parts = partList.toArray(new Part[partList.size()]); post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); } else { post.getParams().setContentCharset("UTF-8"); for (NameValuePair e : nodeProperties) { post.addParameter(e.getName(), e.getValue()); } } } if (requestHeaders != null) { for (Map.Entry<String, String> e : requestHeaders.entrySet()) { post.addRequestHeader(e.getKey(), e.getValue()); } } final int expected = 302; final int status = httpClient.executeMethod(post); if (status != expected) { throw new HttpStatusCodeException(expected, status, "POST", url, HttpTestBase.getResponseBodyAsStream(post, 0)); } String location = post.getResponseHeader("Location").getValue(); post.releaseConnection(); // simple check if host is missing if (!location.startsWith("http://")) { String host = HttpTestBase.HTTP_BASE_URL; int idx = host.indexOf('/', 8); if (idx > 0) { host = host.substring(0, idx); } location = host + location; } return location; }
From source file:org.apache.sling.commons.testing.integration.SlingIntegrationTestClient.java
public int post(String url, Map<String, String> properties) throws HttpException, IOException { final PostMethod post = new PostMethod(url); post.getParams().setContentCharset("UTF-8"); for (Entry<String, String> e : properties.entrySet()) { post.addParameter(e.getKey(), e.getValue()); }//from w w w .ja v a 2 s .c o m return httpClient.executeMethod(post); }
From source file:org.apache.sling.ide.osgi.impl.HttpOsgiClient.java
@Override public void installLocalBundle(final String explodedBundleLocation) throws OsgiClientException { if (explodedBundleLocation == null) { throw new IllegalArgumentException("explodedBundleLocation may not be null"); }/* w ww .j av a 2 s . c o m*/ new LocalBundleInstaller(getHttpClient(), repositoryInfo) { @Override void configureRequest(PostMethod method) { method.addParameter("dir", explodedBundleLocation); } }.installBundle(); }
From source file:org.apache.sling.launchpad.webapp.integrationtest.jcrinstall.JcrinstallTestBase.java
protected void enableJcrinstallService(boolean enable) throws IOException { if (enable != getJcrinstallServiceEnabled()) { final PostMethod post = new PostMethod(HTTP_BASE_URL + JCRINSTALL_STATUS_PATH); post.setFollowRedirects(false);// w w w . ja v a2 s. c o m post.addParameter("enabled", String.valueOf(enable)); final int status = httpClient.executeMethod(post); assertEquals("Expected status 200 in enableJcrinstallService", 200, status); assertEquals("Expected jcrinstall.enabled to be " + enable, enable, getJcrinstallServiceEnabled()); } }
From source file:org.apache.sling.launchpad.webapp.integrationtest.servlets.post.CustomPostOperationTest.java
private void assertCustomPostOperation(String operationName, String markerPropertyName) throws Exception { final String jsonPath = testNode.nodeUrl + ".tidy.json"; assertFalse("Expecting no marker before POST", getContent(jsonPath, CONTENT_TYPE_JSON).contains(markerPropertyName)); final PostMethod post = new PostMethod(testNode.nodeUrl); post.addParameter(":operation", operationName); assertEquals("Expecting 200 status on POST", 200, httpClient.executeMethod(post)); assertTrue("Expecting marker to be present after POST", getContent(jsonPath, CONTENT_TYPE_JSON).contains(markerPropertyName)); }