org.apache.commons.httpclient.NameValuePair Java Examples

The following examples show how to use org.apache.commons.httpclient.NameValuePair. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UserMgmtITCase.java    From olat with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #2
Source File: UserMgmtITCase.java    From olat with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #3
Source File: CatalogITCase.java    From olat with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #4
Source File: RFC2965Spec.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example #5
Source File: RFC2965Spec.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example #6
Source File: GDataAuthStrategy.java    From rome with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example #7
Source File: UsernamePasswordAuthentication.java    From JavaChatterRESTApi with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * <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());
}
 
Example #8
Source File: PushoverMessage.java    From build-notifications-plugin with MIT License 6 votes vote down vote up
@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();
  }
}
 
Example #9
Source File: FlexPostMethod.java    From flex-blazeds with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #10
Source File: PostMethod.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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;
}
 
Example #11
Source File: PaymentServiceProviderBeanTest.java    From development with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example #12
Source File: PaymentServiceProviderBeanTest.java    From development with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example #13
Source File: UserMgmtITCase.java    From olat with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #14
Source File: RefreshTokenAuthentication.java    From JavaChatterRESTApi with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * <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());
}
 
Example #15
Source File: PaymentServiceProviderBean.java    From development with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #16
Source File: BaseJavascriptTest.java    From seldon-server with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #17
Source File: RFC2109Spec.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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();
}
 
Example #18
Source File: PaymentServiceProviderBean.java    From development with Apache License 2.0 6 votes vote down vote up
/**
 * 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())));

}
 
Example #19
Source File: PaymentServiceProviderBean.java    From development with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #20
Source File: HttpProtocolHandler.java    From shopping with Apache License 2.0 6 votes vote down vote up
/**
 * 将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();
}
 
Example #21
Source File: HttpClientIT.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #22
Source File: UserMgmtITCase.java    From olat with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #23
Source File: HttpProtocolHandler.java    From Shop-for-JavaWeb with MIT License 6 votes vote down vote up
/**
 * 将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();
}
 
Example #24
Source File: GetStackByNameCommand.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
@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);
	}
}
 
Example #25
Source File: Zulip.java    From zulip-plugin with MIT License 5 votes vote down vote up
public String sendStreamMessage(String stream, String subject, String message) {
    NameValuePair[] body = {new NameValuePair("api-key", this.getApiKey()),
                            new NameValuePair("email",   this.getEmail()),
                            new NameValuePair("type",    "stream"),
                            new NameValuePair("to",      stream),
                            new NameValuePair("subject", subject),
                            new NameValuePair("content", message)};
    return post("messages", body);
}
 
Example #26
Source File: Hc3HttpUtils.java    From wpcleaner with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #27
Source File: CourseSecurityITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void testAdminCanEditCourse() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    // 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-admin-0"),
            new NameValuePair("longTitle", "Structure-long-admin-0"), new NameValuePair("objectives", "Structure-objectives-admin-0") });
    final int code = c.executeMethod(method);
    assertEquals(200, code);
}
 
Example #28
Source File: ParameterParser.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** 
 * Extracts a list of {@link NameValuePair}s from the given array of 
 * characters.
 *
 * @param chars the array of characters that contains a sequence of 
 * name/value pairs
 * @param offset - the initial offset.
 * @param length - the length.
 * 
 * @return a list of {@link NameValuePair}s
 */
public List parse(final char[] chars, int offset, int length, char separator) {

    if (chars == null) {
        return new ArrayList();
    }
    List params = new ArrayList();
    this.chars = chars;
    this.pos = offset;
    this.len = length;
    
    String paramName = null;
    String paramValue = null;
    while (hasChar()) {
        paramName = parseToken(new char[] {'=', separator});
        paramValue = null;
        if (hasChar() && (chars[pos] == '=')) {
            pos++; // skip '='
            paramValue = parseQuotedToken(new char[] {separator});
        }
        if (hasChar() && (chars[pos] == separator)) {
            pos++; // skip separator
        }
        if (paramName != null && !(paramName.equals("") && paramValue == null)) {
            params.add(new NameValuePair(paramName, paramValue));
        }
    }        
    return params;
}
 
Example #29
Source File: CourseSecurityITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #30
Source File: CatalogITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void testPutCategoryQuery() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    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", "Sub-entry-2"), new NameValuePair("description", "Sub-entry-description-2"),
            new NameValuePair("type", String.valueOf(CatalogEntry.TYPE_NODE)) });

    final int code = c.executeMethod(method);
    assertEquals(200, code);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final CatalogEntryVO vo = parse(body, CatalogEntryVO.class);
    assertNotNull(vo);

    final List<CatalogEntry> children = catalogService.getChildrenOf(entry1);
    boolean saved = false;
    for (final CatalogEntry child : children) {
        if (vo.getKey().equals(child.getKey())) {
            saved = true;
            break;
        }
    }

    assertTrue(saved);
}