下面列出了怎么用org.apache.commons.httpclient.NameValuePair的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void testBasicSecurityPutCall() throws IOException {
final HttpClient c = loginWithCookie("rest-catalog-two", "A6B7C8");
final URI uri = UriBuilder.fromUri(getContextURI()).path("catalog").path(entry1.getKey().toString()).build();
final PutMethod method = createPut(uri, MediaType.APPLICATION_JSON, true);
method.setQueryString(new NameValuePair[] { new NameValuePair("name", "Not-sub-entry-3"), new NameValuePair("description", "Not-sub-entry-description-3"),
new NameValuePair("type", String.valueOf(CatalogEntry.TYPE_NODE)) });
final int code = c.executeMethod(method);
assertEquals(401, code);
method.releaseConnection();
final List<CatalogEntry> children = catalogService.getChildrenOf(entry1);
boolean saved = false;
for (final CatalogEntry child : children) {
if ("Not-sub-entry-3".equals(child.getName())) {
saved = true;
break;
}
}
assertFalse(saved);
}
@Test
public void testFindUsersByLogin() throws IOException {
final HttpClient c = loginWithCookie("administrator", "olat");
final GetMethod method = createGet("/users", MediaType.APPLICATION_JSON, true);
method.setQueryString(new NameValuePair[] { new NameValuePair("login", "administrator"), new NameValuePair("authProvider", "OLAT") });
final int code = c.executeMethod(method);
assertEquals(code, 200);
final String body = method.getResponseBodyAsString();
method.releaseConnection();
final List<UserVO> vos = parseUserArray(body);
final String[] authProviders = new String[] { "OLAT" };
final List<Identity> identities = securityManager.getIdentitiesByPowerSearch("administrator", null, true, null, null, authProviders, null, null, null, null,
Identity.STATUS_VISIBLE_LIMIT);
assertNotNull(vos);
assertFalse(vos.isEmpty());
assertEquals(vos.size(), identities.size());
boolean onlyLikeAdmin = true;
for (final UserVO vo : vos) {
if (!vo.getLogin().startsWith("administrator")) {
onlyLikeAdmin = false;
}
}
assertTrue(onlyLikeAdmin);
}
/**
* <p>Authenticate using a username and password. This is discouraged by the oauth flow,
* but it allows for transparent (and non human-intervention) authentication).</p>
*
* @return The response retrieved from the REST API (usually an XML string with all the tokens)
* @throws IOException
* @throws UnauthenticatedSessionException
* @throws AuthenticationException
*/
public ChatterAuthToken authenticate() throws IOException, UnauthenticatedSessionException, AuthenticationException {
String clientId = URLEncoder.encode(chatterData.getClientKey(), "UTF-8");
String clientSecret = chatterData.getClientSecret();
String username = chatterData.getUsername();
String password = chatterData.getPassword();
String authenticationUrl = "TEST".equalsIgnoreCase(chatterData.getEnvironment()) ? TEST_AUTHENTICATION_URL : PRODUCTION_AUTHENTICATION_URL;
PostMethod post = new PostMethod(authenticationUrl);
NameValuePair[] data = { new NameValuePair("grant_type", "password"), new NameValuePair("client_id", clientId),
new NameValuePair("client_secret", clientSecret), new NameValuePair("username", username),
new NameValuePair("password", password) };
post.setRequestBody(data);
int statusCode = getHttpClient().executeMethod(post);
if (statusCode == HttpStatus.SC_OK) {
return processResponse(post.getResponseBodyAsString());
}
throw new UnauthenticatedSessionException(statusCode + " " + post.getResponseBodyAsString());
}
@Override
public void send() {
HttpClient client = new HttpClient();
PostMethod post = new PostMethod("https://api.pushover.net/1/messages.json");
post.setRequestBody(new NameValuePair[]{
new NameValuePair("token", appToken),
new NameValuePair("user", userToken),
new NameValuePair("message", content + "\n\n" + extraMessage),
new NameValuePair("title", title),
new NameValuePair("priority", priority.toString()),
new NameValuePair("url", url),
new NameValuePair("url_title", urlTitle)
});
try {
client.executeMethod(post);
} catch (IOException e) {
LOGGER.severe("Error while sending notification: " + e.getMessage());
e.printStackTrace();
}
}
/**
* 将NameValuePairs数组转变为字符串
*
* @param nameValues
* @return
*/
protected String toString(NameValuePair[] nameValues) {
if (nameValues == null || nameValues.length == 0) {
return "null";
}
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < nameValues.length; i++) {
NameValuePair nameValue = nameValues[i];
if (i == 0) {
buffer.append(nameValue.getName() + "=" + nameValue.getValue());
} else {
buffer.append("&" + nameValue.getName() + "=" + nameValue.getValue());
}
}
return buffer.toString();
}
protected String getContentCharSet(Header contentheader)
{
String charset = null;
if (contentheader != null)
{
HeaderElement values[] = contentheader.getElements();
if (values.length == 1)
{
NameValuePair param = values[0].getParameterByName("charset");
if (param != null)
{
charset = param.getValue();
}
}
}
if (charset == null)
{
charset = "UTF-8";
}
return charset;
}
@Test
public void testFindUsersByLogin() throws IOException {
final HttpClient c = loginWithCookie("administrator", "olat");
final GetMethod method = createGet("/users", MediaType.APPLICATION_JSON, true);
method.setQueryString(new NameValuePair[] { new NameValuePair("login", "administrator"), new NameValuePair("authProvider", "OLAT") });
final int code = c.executeMethod(method);
assertEquals(code, 200);
final String body = method.getResponseBodyAsString();
method.releaseConnection();
final List<UserVO> vos = parseUserArray(body);
final String[] authProviders = new String[] { "OLAT" };
final List<Identity> identities = securityManager.getIdentitiesByPowerSearch("administrator", null, true, null, null, authProviders, null, null, null, null,
Identity.STATUS_VISIBLE_LIMIT);
assertNotNull(vos);
assertFalse(vos.isEmpty());
assertEquals(vos.size(), identities.size());
boolean onlyLikeAdmin = true;
for (final UserVO vo : vos) {
if (!vo.getLogin().startsWith("administrator")) {
onlyLikeAdmin = false;
}
}
assertTrue(onlyLikeAdmin);
}
/**
* <p>Using a valid Refresh token we can get a new accessToken.</p>
*
* @return The response retrieved from the REST API (usually an XML string with all the tokens)
* @throws IOException
* @throws UnauthenticatedSessionException
*/
@Override
public ChatterAuthToken authenticate() throws IOException, UnauthenticatedSessionException, AuthenticationException {
String authenticationUrl = "TEST".equalsIgnoreCase(chatterData.getEnvironment()) ? TEST_AUTHENTICATION_URL : PRODUCTION_AUTHENTICATION_URL;
PostMethod post = new PostMethod(authenticationUrl);
String clientId = URLEncoder.encode(chatterData.getClientKey(), "UTF-8");
String clientSecret = URLEncoder.encode(chatterData.getClientSecret(), "UTF-8");
NameValuePair[] data = { new NameValuePair("grant_type", "refresh_token"),
new NameValuePair("client_id", clientId), new NameValuePair("client_secret", clientSecret),
new NameValuePair("refresh_token", chatterData.getRefreshToken()) };
post.setRequestBody(data);
int statusCode = getHttpClient().executeMethod(post);
if (statusCode == HttpStatus.SC_OK) {
return processResponse(post.getResponseBodyAsString());
}
throw new UnauthenticatedSessionException(statusCode + " " + post.getResponseBodyAsString());
}
/**
* Initializes the parameters required for the POST call to the PSP for
* re-registration..
*
* @param paymentInfo
* The current payment information object.
* @param paymentType
* The payment type the iframe should be pre-configured for.
* @param supplierId
* Supplier context
* @return The properties required for the connection to the PSP in order to
* register the credit card or direct debit.
*/
private List<NameValuePair> initPostParametersForReRegistration(
RequestData data) {
List<NameValuePair> regParams = new ArrayList<NameValuePair>();
setBasicPostParameters(regParams, data);
// operation code for re-registration, we use credit card as default.
regParams.add(new NameValuePair(HeidelpayPostParameter.PAYMENT_CODE,
getHeidelPayPaymentType(data.getPaymentTypeId()) + ".RR"));
// also set the already stored reference id
regParams.add(new NameValuePair(
HeidelpayPostParameter.IDENTIFICATION_REFERENCEID, data
.getExternalIdentifier()));
initGeneralRegistrationPostData(regParams, data);
return regParams;
}
private <T> T retrievePayload(String path, NameValuePair[] queryParameters, Class<T> valueType) throws IOException {
GetMethod getMethod = new GetMethod(testState.getEndpoint() + path);
getMethod.setQueryString(queryParameters);
String httpReferer = testState.getHttpReferer();
if ( httpReferer != null ) {
getMethod.setRequestHeader("Referer", httpReferer);
}
client.executeMethod(getMethod);
String response = getMethod.getResponseBodyAsString();
// Remove jsonp prefix and suffix:
String payload = stripJsonp(response);
logger.info("Payload: " + payload);
return objectMapper.readValue(payload, valueType);
}
/**
* Create a RFC 2109 compliant <tt>"Cookie"</tt> header value containing all
* {@link Cookie}s in <i>cookies</i> suitable for sending in a <tt>"Cookie"
* </tt> header
* @param cookies an array of {@link Cookie}s to be formatted
* @return a string suitable for sending in a Cookie header.
*/
public String formatCookies(Cookie[] cookies) {
LOG.trace("enter RFC2109Spec.formatCookieHeader(Cookie[])");
int version = Integer.MAX_VALUE;
// Pick the lowerest common denominator
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
if (cookie.getVersion() < version) {
version = cookie.getVersion();
}
}
final StringBuffer buffer = new StringBuffer();
formatParam(buffer,
new NameValuePair("$Version", Integer.toString(version)),
version);
for (int i = 0; i < cookies.length; i++) {
buffer.append("; ");
formatCookieAsVer(buffer, cookies[i], version);
}
return buffer.toString();
}
/**
* Determines the required authentication parameters and sets them as
* parameters for th e POST call.
*
* @param regParams
* The list of name value paris the authentication parameters
* will be added to.
*/
private void setAuthenticationPostParameters(List<NameValuePair> regParams,
RequestData data) {
regParams.add(new NameValuePair(HeidelpayPostParameter.SECURITY_SENDER,
data.getProperty(HeidelpayConfigurationKey.PSP_SECURITY_SENDER
.name())));
regParams
.add(new NameValuePair(
HeidelpayPostParameter.TRANSACTION_CHANNEL,
data.getProperty(HeidelpayConfigurationKey.PSP_TRANSACTION_CHANNEL
.name())));
regParams.add(new NameValuePair(HeidelpayPostParameter.USER_LOGIN, data
.getProperty(HeidelpayConfigurationKey.PSP_USER_LOGIN.name())));
regParams.add(new NameValuePair(HeidelpayPostParameter.USER_PWD, data
.getProperty(HeidelpayConfigurationKey.PSP_USER_PWD.name())));
}
@Override
public RegistrationLink determineRegistrationLink(RequestData data)
throws PSPCommunicationException {
if (data == null) {
throw new IllegalArgumentException("requestData must not be null!");
}
setProxyForHTTPClient(data);
List<NameValuePair> registrationParameters = initPostParametersForRegistration(data);
String regLinkDetails = retrieveRegistrationLinkDetails(
registrationParameters, data);
String result = validateLinkDetails(regLinkDetails);
RegistrationLink link = new RegistrationLink();
link.setUrl(result);
link.setBrowserTarget("");
return link;
}
@Test
public void test() {
HttpClient client = new HttpClient();
client.getParams().setConnectionManagerTimeout(CONNECTION_TIMEOUT);
client.getParams().setSoTimeout(SO_TIMEOUT);
GetMethod method = new GetMethod(webServer.getCallHttpUrl());
// Provide custom retry handler is necessary
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
method.setQueryString(new NameValuePair[] { new NameValuePair("key2", "value2") });
try {
// Execute the method.
client.executeMethod(method);
} catch (Exception ignored) {
} finally {
method.releaseConnection();
}
PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
verifier.printCache();
}
@Test
public void testFindAdminByAuth() throws IOException {
final HttpClient c = loginWithCookie("administrator", "olat");
final GetMethod method = createGet("/users", MediaType.APPLICATION_JSON, true);
method.setQueryString(new NameValuePair[] { new NameValuePair("authUsername", "administrator"), new NameValuePair("authProvider", "OLAT") });
final int code = c.executeMethod(method);
assertEquals(code, 200);
final String body = method.getResponseBodyAsString();
method.releaseConnection();
final List<UserVO> vos = parseUserArray(body);
assertNotNull(vos);
assertFalse(vos.isEmpty());
assertEquals(1, vos.size());
assertEquals("administrator", vos.get(0).getLogin());
}
@Test
public void testFindAdminByAuth() throws IOException {
final HttpClient c = loginWithCookie("administrator", "olat");
final GetMethod method = createGet("/users", MediaType.APPLICATION_JSON, true);
method.setQueryString(new NameValuePair[] { new NameValuePair("authUsername", "administrator"), new NameValuePair("authProvider", "OLAT") });
final int code = c.executeMethod(method);
assertEquals(code, 200);
final String body = method.getResponseBodyAsString();
method.releaseConnection();
final List<UserVO> vos = parseUserArray(body);
assertNotNull(vos);
assertFalse(vos.isEmpty());
assertEquals(1, vos.size());
assertEquals("administrator", vos.get(0).getLogin());
}
/**
* 将NameValuePairs数组转变为字符串
*
* @param nameValues
* @return
*/
protected String toString(NameValuePair[] nameValues) {
if (nameValues == null || nameValues.length == 0) {
return "null";
}
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < nameValues.length; i++) {
NameValuePair nameValue = nameValues[i];
if (i == 0) {
buffer.append(nameValue.getName() + "=" + nameValue.getValue());
} else {
buffer.append("&" + nameValue.getName() + "="
+ nameValue.getValue());
}
}
return buffer.toString();
}
@Test
public void deregisterPaymentInformation_CreditCard()
throws PaymentDeregistrationException, XPathExpressionException,
ParserConfigurationException, SAXException, IOException {
// setup
RequestData requestData = createRequestData(CREDIT_CARD);
PostMethodStub.setStubReturnValue(sampleResponse);
PaymentInfo pi = createPaymentInfo(
PaymentCollectionType.PAYMENT_SERVICE_PROVIDER,
PaymentInfoType.CREDIT_CARD.name());
pi.setKey(2L);
// execute
psp.deregisterPaymentInformation(requestData);
// assert
NameValuePair[] requestBodyDetails = PostMethodStub
.getRequestBodyDetails();
Assert.assertNotNull("A request must have been generated",
requestBodyDetails);
Assert.assertEquals("Wrong number of parameters for the request", 1,
requestBodyDetails.length);
validateDeregistrationXMLResponse(pi, requestBodyDetails, "CC");
}
@Test
public void deregisterPaymentInformation_DirectDebit()
throws PaymentDeregistrationException, XPathExpressionException,
ParserConfigurationException, SAXException, IOException {
// setup
RequestData requestData = createRequestData(DIRECT_DEBIT);
PostMethodStub.setStubReturnValue(sampleResponse);
PaymentInfo pi = createPaymentInfo(
PaymentCollectionType.PAYMENT_SERVICE_PROVIDER,
PaymentInfoType.CREDIT_CARD.name());
pi.setKey(2L);
// execute
psp.deregisterPaymentInformation(requestData);
// assert
NameValuePair[] requestBodyDetails = PostMethodStub
.getRequestBodyDetails();
Assert.assertNotNull("A request must have been generated",
requestBodyDetails);
Assert.assertEquals("Wrong number of parameters for the request", 1,
requestBodyDetails.length);
validateDeregistrationXMLResponse(pi, requestBodyDetails, "DD");
}
/**
* Removes all parameter with the given paramName and paramValue. If there
* is more than one parameter with the given paramName, only one is
* removed. If there are none, then the request is ignored.
*
* @param paramName The parameter name to remove.
* @param paramValue The parameter value to remove.
*
* @return true if a parameter was removed.
*
* @throws IllegalArgumentException when param name or value are null
*
* @since 2.0
*/
public boolean removeParameter(String paramName, String paramValue)
throws IllegalArgumentException {
LOG.trace("enter PostMethod.removeParameter(String, String)");
if (paramName == null) {
throw new IllegalArgumentException("Parameter name may not be null");
}
if (paramValue == null) {
throw new IllegalArgumentException("Parameter value may not be null");
}
Iterator iter = this.params.iterator();
while (iter.hasNext()) {
NameValuePair pair = (NameValuePair) iter.next();
if (paramName.equals(pair.getName())
&& paramValue.equals(pair.getValue())) {
iter.remove();
return true;
}
}
return false;
}
private void init() throws ProponoException {
try {
final HttpClient httpClient = new HttpClient();
final PostMethod method = new PostMethod("https://www.google.com/accounts/ClientLogin");
final NameValuePair[] data = { new NameValuePair("Email", email), new NameValuePair("Passwd", password),
new NameValuePair("accountType", "GOOGLE"), new NameValuePair("service", service),
new NameValuePair("source", "ROME Propono Atompub Client") };
method.setRequestBody(data);
httpClient.executeMethod(method);
final String responseBody = method.getResponseBodyAsString();
final int authIndex = responseBody.indexOf("Auth=");
authToken = "GoogleLogin auth=" + responseBody.trim().substring(authIndex + 5);
} catch (final Throwable t) {
t.printStackTrace();
throw new ProponoException("ERROR obtaining Google authentication string", t);
}
}
/**
* Parse RFC 2965 specific cookie attribute and update the corresponsing
* {@link org.apache.commons.httpclient.Cookie} properties.
*
* @param attribute {@link org.apache.commons.httpclient.NameValuePair} cookie attribute from the
* <tt>Set-Cookie2</tt> header.
* @param cookie {@link org.apache.commons.httpclient.Cookie} to be updated
* @throws MalformedCookieException if an exception occurs during parsing
*/
public void parseAttribute(
final NameValuePair attribute, final Cookie cookie)
throws MalformedCookieException {
if (attribute == null) {
throw new IllegalArgumentException("Attribute may not be null.");
}
if (attribute.getName() == null) {
throw new IllegalArgumentException("Attribute Name may not be null.");
}
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null.");
}
final String paramName = attribute.getName().toLowerCase();
final String paramValue = attribute.getValue();
CookieAttributeHandler handler = findAttribHandler(paramName);
if (handler == null) {
// ignore unknown attribute-value pairs
if (LOG.isDebugEnabled())
LOG.debug("Unrecognized cookie attribute: " +
attribute.toString());
} else {
handler.parse(cookie, paramValue);
}
}
/**
* Return a string suitable for sending in a <tt>"Cookie"</tt> header as
* defined in RFC 2965
* @param cookie a {@link org.apache.commons.httpclient.Cookie} to be formatted as string
* @return a string suitable for sending in a <tt>"Cookie"</tt> header.
*/
public String formatCookie(final Cookie cookie) {
LOG.trace("enter RFC2965Spec.formatCookie(Cookie)");
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (cookie instanceof Cookie2) {
Cookie2 cookie2 = (Cookie2) cookie;
int version = cookie2.getVersion();
final StringBuffer buffer = new StringBuffer();
this.formatter.format(buffer, new NameValuePair("$Version", Integer.toString(version)));
buffer.append("; ");
doFormatCookie2(cookie2, buffer);
return buffer.toString();
} else {
// old-style cookies are formatted according to the old rules
return this.rfc2109.formatCookie(cookie);
}
}
/** posts a Bean to the bean log on the MesquiteServer*/
public void postBean(String notes, boolean notifyUser) {
if (!MesquiteTrunk.reportUse){
return;
}
if (MesquiteTrunk.noBeans) {
if (notifyUser)
logln("No beans were sent as the -nb flag was set.");
return;
}
int numPairs=3;
if (StringUtil.notEmpty(notes))
numPairs=4;
NameValuePair[] pairs = new NameValuePair[numPairs];
pairs[0] = new NameValuePair("module", StringUtil.tokenize(moduleInfo.getClassName()));
pairs[1] = new NameValuePair("version", StringUtil.tokenize(getVersion()));
pairs[2] = new NameValuePair("build", ""+getBuildNumberOfPackage());
if (numPairs>=4)
pairs[3] = new NameValuePair("notes", StringUtil.tokenize(notes));
if (notifyUser) { //send immediately and notify
if (BaseHttpRequestMaker.sendInfoToServer(pairs, beansReportURL, null, 0)){ // changed to not retry
if (notifyUser)
MesquiteMessage.println("Bean sent to Mesquite server.");
}
else
if (notifyUser)
logln("Sorry, Mesquite was unable to connect to the server to send the bean.");
}
else { //send on phone home thread
if (MesquiteTrunk.phoneHomeThread != null)
MesquiteTrunk.phoneHomeThread.postBean(pairs);
}
}
public MessageResult sendMessage(String mobile, String content,SmsDTO smsDTO) throws Exception{
log.info("sms content={}", content);
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod("http://api.1cloudsp.com/api/v2/single_send");
postMethod.getParams().setContentCharset("UTF-8");
postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
NameValuePair[] data = {
new NameValuePair("accesskey", smsDTO.getKeyId()),
new NameValuePair("secret", smsDTO.getKeySecret()),
new NameValuePair("sign", smsDTO.getSignId()),
new NameValuePair("templateId", smsDTO.getTemplateId()),
new NameValuePair("mobile", mobile),
new NameValuePair("content", URLEncoder.encode(content, "utf-8"))//(发送的短信内容是模板变量内容,多个变量中间用##或者$$隔开,采用utf8编码)
};
postMethod.setRequestBody(data);
int statusCode = httpClient.executeMethod(postMethod);
System.out.println("statusCode: " + statusCode + ", body: "
+ postMethod.getResponseBodyAsString());
log.info(" mobile : " + mobile + "content : " + content);
log.info("statusCode: " + statusCode + ", body: "
+ postMethod.getResponseBodyAsString());
return parseResult(postMethod.getResponseBodyAsString());
}
@Test
public void testAuthorCannotEditCourse() throws IOException {
// author but not owner
final HttpClient c = loginWithCookie("id-c-s-1", "A6B7C8");
// create an structure node
final URI newStructureUri = getElementsUri(course).path("structure").build();
final PutMethod method = createPut(newStructureUri, MediaType.APPLICATION_JSON, true);
method.setQueryString(new NameValuePair[] { new NameValuePair("position", "0"), new NameValuePair("shortTitle", "Structure-id-0"),
new NameValuePair("longTitle", "Structure-long-id-0"), new NameValuePair("objectives", "Structure-objectives-id-0") });
final int code = c.executeMethod(method);
assertEquals(401, code);
}
@Override
protected ServerStatus _doIt() {
try {
URI targetURI = URIUtil.toURI(target.getUrl());
URI servicesURI = targetURI.resolve("/v2/stacks"); //$NON-NLS-0$//$NON-NLS-1$
GetMethod getStacksMethod = new GetMethod(servicesURI.toString());
NameValuePair[] params = new NameValuePair[] { //
new NameValuePair("q", "name:" + stackName), //$NON-NLS-0$ //$NON-NLS-1$
new NameValuePair("inline-relations-depth", "1") //$NON-NLS-0$ //$NON-NLS-1$
};
getStacksMethod.setQueryString(params);
ServerStatus confStatus = HttpUtil.configureHttpMethod(getStacksMethod, target.getCloud());
if (!confStatus.isOK())
return confStatus;
ServerStatus getStacksStatus = HttpUtil.executeMethod(getStacksMethod);
if (!getStacksStatus.isOK())
return getStacksStatus;
JSONObject stacksJSON = getStacksStatus.getJsonData();
if (stacksJSON.getInt(CFProtocolConstants.V2_KEY_TOTAL_RESULTS) < 1) {
return getStacksStatus;
}
JSONArray resources = stacksJSON.getJSONArray(CFProtocolConstants.V2_KEY_RESOURCES);
JSONObject stackJSON = resources.getJSONObject(0);
stack = new Stack().setCFJSON(stackJSON);
return getStacksStatus;
} catch (Exception e) {
String msg = NLS.bind("An error occured when performing operation {0}", commandName); //$NON-NLS-1$
logger.error(msg, e);
return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
}
}
/**
* Create an HTTP GET Method.
*
* @param url URL of the request.
* @param properties Properties to drive the API.
* @return GET Method
* @throws URIException Exception if the URL is not correct.
*/
private static GetMethod createHttpGetMethod(
String url,
Map<String, String> properties) throws URIException {
// Initialize GET Method
org.apache.commons.httpclient.URI uri = new org.apache.commons.httpclient.URI(url, false, "UTF8");
GetMethod method = new GetMethod();
method.setURI(uri);
method.getParams().setSoTimeout(60000);
method.getParams().setContentCharset("UTF-8");
method.setRequestHeader("Accept-Encoding", "gzip");
// Manager query string
StringBuilder debugUrl = (DEBUG_URL) ? new StringBuilder("GET " + url) : null;
List<NameValuePair> params = new ArrayList<NameValuePair>();
if (properties != null) {
boolean first = true;
Iterator<Map.Entry<String, String>> iter = properties.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, String> property = iter.next();
String key = property.getKey();
String value = property.getValue();
params.add(new NameValuePair(key, value));
first = fillDebugUrl(debugUrl, first, key, value);
}
}
if (DEBUG_URL && (debugUrl != null)) {
debugText(debugUrl.toString());
}
NameValuePair[] tmpParams = new NameValuePair[params.size()];
method.setQueryString(params.toArray(tmpParams));
return method;
}
private InputStream retreiveXMLReply(String partOfSpeech, String word) {
HttpClient client = HttpClientFactory.getHttpClientInstance();
HttpMethod method = new GetMethod(MORPHOLOGICAL_SERVICE_ADRESS);
NameValuePair posValues = new NameValuePair(PART_OF_SPEECH_PARAM, partOfSpeech);
NameValuePair wordValues = new NameValuePair(GLOSS_TERM_PARAM, word);
if (log.isDebugEnabled()) {
String url = MORPHOLOGICAL_SERVICE_ADRESS + "?" + PART_OF_SPEECH_PARAM + "=" + partOfSpeech + "&" + GLOSS_TERM_PARAM + "=" + word;
log.debug("Send GET request to morph-service with URL: " + url);
}
method.setQueryString(new NameValuePair[] { posValues, wordValues });
try {
client.executeMethod(method);
int status = method.getStatusCode();
if (status == HttpStatus.SC_NOT_MODIFIED || status == HttpStatus.SC_OK) {
if (log.isDebugEnabled()) {
log.debug("got a valid reply!");
}
} else if (method.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
log.error("Morphological Service unavailable (404)::" + method.getStatusLine().toString());
} else {
log.error("Unexpected HTTP Status::" + method.getStatusLine().toString());
}
} catch (Exception e) {
log.error("Unexpected exception trying to get flexions!", e);
}
Header responseHeader = method.getResponseHeader("Content-Type");
if (responseHeader == null) {
// error
log.error("URL not found!");
}
HttpRequestMediaResource mr = new HttpRequestMediaResource(method);
InputStream inputStream = mr.getInputStream();
return inputStream;
}
protected List<NameValuePair> getQuery() {
List<NameValuePair> res = new ArrayList<NameValuePair>();
if (offsetParam != null) {
if (offset != OFFSET_NOT_DEFINED) {
res.add(new NameValuePair(offsetParam, Integer.toString(offset)));
}
Assert.assertTrue(fetchSizeParam != null, "fetchSizeParam!=null");
if (fetchSize != FETCH_SIZE_NOT_DEFINED) {
res.add(new NameValuePair(fetchSizeParam, Integer.toString(fetchSize)));
}
}
if (maxResultsParam != null && maxResults != MAX_RESULT_NOT_DEFINED) {
res.add(new NameValuePair(maxResultsParam, Integer.toString(maxResults)));
} else {
if (ngsi) {
res.add(new NameValuePair("limit", NGSI_LIMIT));
}
}
// ========= CREDIT: https://github.com/VivekKumar856
if (this.parameters != null && this.parameters.size() > 0) {
Iterator keys = this.parameters.keySet().iterator();
while (keys.hasNext()) {
String key = (String) keys.next();
Object val = this.parameters.get(key);
if (val instanceof String) {
if (val != null && !val.equals("") && !val.equals("''")) {
String curval = (String) val;
curval = curval.replaceAll("'", "");
res.add(new NameValuePair(key, curval));
}
}
}
}
// =========
return res;
}