Java Code Examples for org.apache.commons.httpclient.methods.GetMethod#setQueryString()

The following examples show how to use org.apache.commons.httpclient.methods.GetMethod#setQueryString() . 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 testFindUsersByProperty() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final GetMethod method = createGet("/users", MediaType.APPLICATION_JSON, true);
    method.setQueryString(new NameValuePair[] { new NameValuePair("telMobile", "39847592"), new NameValuePair("gender", "Female"),
            new NameValuePair("birthDay", "12/12/2009") });
    method.addRequestHeader("Accept-Language", "en");
    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());
}
 
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: HttpClientUtil.java    From javabase with Apache License 2.0 6 votes vote down vote up
/**
 * 向目标发出一个GET请求并得到响应数据
 * @param url
 *            目标
 * @param params
 *            参数集合
 * @param timeout
 *            超时时间
 * @return 响应数据
 * @throws IOException 
 */
public static String sendGet(String url, Map<String, String> params, int timeout) throws Exception {
	GetMethod method = new GetMethod(url);
	if (params != null) {
		method.setQueryString(getQueryString(params));
	}
	byte[] content;
	String text = null, charset = null;
	try {
		content = executeMethod(method, timeout);
		charset = method.getResponseCharSet();
		text = new String(content, charset);
	} finally {
		method.releaseConnection();
	}
	return text;
}
 
Example 4
Source File: HttpParameterPollution.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
    try{
        String item = request.getParameter("item");
        
        //in HttpClient 4.x, there is no GetMethod anymore. Instead there is HttpGet
        HttpGet httpget = new HttpGet("http://host.com?param=" + URLEncoder.encode(item)); //OK
        HttpGet httpget2 = new HttpGet("http://host.com?param=" + item); //BAD
        
        GetMethod get = new GetMethod("http://host.com?param=" + item); //BAD
        get.setQueryString("item=" + item); //BAD
        //get.execute();

    }catch(Exception e){
      System.out.println(e);
    }
}
 
Example 5
Source File: HttpClientIT.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
@Test
public void hostConfig() {
    HttpClient client = new HttpClient();
    client.getParams().setConnectionManagerTimeout(CONNECTION_TIMEOUT);
    client.getParams().setSoTimeout(SO_TIMEOUT);

    HostConfiguration config = new HostConfiguration();
    config.setHost("weather.naver.com", 80, "http");
    GetMethod method = new GetMethod("/rgn/cityWetrMain.nhn");

    // 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(config, method);
    } catch (Exception ignored) {
    } finally {
        method.releaseConnection();
    }

    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();
}
 
Example 6
Source File: UserMgmtITCase.java    From olat with Apache License 2.0 6 votes vote down vote up
@Test
public void testFindUsersByProperty() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final GetMethod method = createGet("/users", MediaType.APPLICATION_JSON, true);
    method.setQueryString(new NameValuePair[] { new NameValuePair("telMobile", "39847592"), new NameValuePair("gender", "Female"),
            new NameValuePair("birthDay", "12/12/2009") });
    method.addRequestHeader("Accept-Language", "en");
    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());
}
 
Example 7
Source File: GetServiceByNameCommand.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected ServerStatus _doIt() {
	try {
		URI targetURI = URIUtil.toURI(target.getUrl());
		URI servicesURI = targetURI.resolve("/v2/spaces/" + target.getSpace().getGuid() + "/services"); //$NON-NLS-0$//$NON-NLS-1$

		GetMethod getServicesMethod = new GetMethod(servicesURI.toString());
		NameValuePair[] params = new NameValuePair[] { //
		new NameValuePair("q", "label:" + serviceName), //$NON-NLS-0$ //$NON-NLS-1$
				new NameValuePair("inline-relations-depth", "1") //$NON-NLS-0$ //$NON-NLS-1$
		};
		getServicesMethod.setQueryString(params);

		ServerStatus confStatus = HttpUtil.configureHttpMethod(getServicesMethod, target.getCloud());
		if (!confStatus.isOK())
			return confStatus;
		
		return HttpUtil.executeMethod(getServicesMethod);
	} 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 8
Source File: FindRouteCommand.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected ServerStatus _doIt() {
	try {

		/* create cloud foundry application */
		URI targetURI = URIUtil.toURI(target.getUrl());
		URI routesURI = targetURI.resolve("/v2/routes"); //$NON-NLS-1$

		GetMethod findRouteMethod = new GetMethod(routesURI.toString());
		ServerStatus confStatus = HttpUtil.configureHttpMethod(findRouteMethod, target.getCloud());
		if (!confStatus.isOK())
			return confStatus;
		
		findRouteMethod.setQueryString("inline-relations-depth=1&q=host:" + appHost + ";domain_guid:" + domainGUID); //$NON-NLS-1$ //$NON-NLS-2$

		ServerStatus status = HttpUtil.executeMethod(findRouteMethod);
		if (!status.isOK())
			return status;

		JSONObject response = status.getJsonData();
		if (response.getInt(CFProtocolConstants.V2_KEY_TOTAL_RESULTS) < 1)
			return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, "Route not found", null);

		/* retrieve the GUID */
		JSONArray resources = response.getJSONArray(CFProtocolConstants.V2_KEY_RESOURCES);
		JSONObject route = resources.getJSONObject(0);

		return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, route);

	} 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 9
Source File: AppsHandlerV1.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
private IStatus getApps(Target target) throws Exception {
	String appsUrl = target.getSpace().getCFJSON().getJSONObject("entity").getString("apps_url"); //$NON-NLS-1$//$NON-NLS-2$
	URI appsURI = URIUtil.toURI(target.getUrl()).resolve(appsUrl);

	GetMethod getAppsMethod = new GetMethod(appsURI.toString());
	ServerStatus confStatus = HttpUtil.configureHttpMethod(getAppsMethod, target.getCloud());
	if (!confStatus.isOK())
		return confStatus;
	
	getAppsMethod.setQueryString("inline-relations-depth=2"); //$NON-NLS-1$

	ServerStatus getAppsStatus = HttpUtil.executeMethod(getAppsMethod);
	if (!getAppsStatus.isOK())
		return getAppsStatus;

	/* extract available apps */
	JSONObject appsJSON = getAppsStatus.getJsonData();

	JSONObject result = new JSONObject();
	result.put("Apps", new JSONArray()); //$NON-NLS-1$

	if (appsJSON.getInt(CFProtocolConstants.V2_KEY_TOTAL_RESULTS) < 1) {
		return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, result);
	}

	JSONArray resources = appsJSON.getJSONArray(CFProtocolConstants.V2_KEY_RESOURCES);
	for (int k = 0; k < resources.length(); ++k) {
		JSONObject appJSON = resources.getJSONObject(k);
		App2 app = new App2();
		app.setCFJSON(appJSON);
		result.append("Apps", app.toJSON()); //$NON-NLS-1$
	}

	return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, result);
}
 
Example 10
Source File: OldHttpClientApi.java    From javabase with Apache License 2.0 5 votes vote down vote up
public void  get2(){
    String requesturl = "http://www.tuling123.com/openapi/api";
    GetMethod getMethod = new GetMethod(requesturl);
    try {
        String APIKEY = "4b441cb500f431adc6cc0cb650b4a5d0";
        String INFO ="北京时间";

        //get  参数
        NameValuePair nvp1=new NameValuePair("key",APIKEY);
        NameValuePair nvp2=new NameValuePair("info",INFO);
        NameValuePair[] nvp = new NameValuePair[2];
        nvp[0]=nvp1;
        nvp[1]=nvp2;
        String params=EncodingUtil.formUrlEncode(nvp, "UTF-8");
        //设置参数
        getMethod.setQueryString(params);

        byte[] responseBody = executeMethod(getMethod,10000);

         String content=new String(responseBody ,"utf-8");
        log.info(content);
    }catch (Exception e){
       log.error(""+e.getLocalizedMessage());
    }finally {
        //结束一定要关闭
        getMethod.releaseConnection();
    }
}
 
Example 11
Source File: JumpToCodeClient.java    From otroslogviewer with Apache License 2.0 5 votes vote down vote up
public Set<String> loggerPatterns() throws IOException {
  final GetMethod method = new GetMethod(getUrl());
  method.setQueryString(new NameValuePair[]{new NameValuePair("o", "loggersConfig")});
  final String content = executeAndGetContent(method);
  final Type type = new TypeToken<Collection<LoggerPatternsResponse>>() {
  }.getType();
  final List<LoggerPatternsResponse> o = new Gson().fromJson(content, type);
  return o.stream().flatMap(patterns -> patterns.getPatterns().stream()).collect(Collectors.toSet());
}
 
Example 12
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 13
Source File: HarvestQaManagerImpl.java    From webcurator with Apache License 2.0 5 votes vote down vote up
@Override
public void triggerAutoQA(ArcHarvestResult ahr) {
	TargetInstance ti = ahr.getTargetInstance();

	if (autoQAUrl != null && autoQAUrl.length() > 0 && ti.isUseAQA()) {
		GetMethod getMethod = new GetMethod(autoQAUrl);

		String primarySeed = "";

		// Might be nice to use the SeedHistory here, but as this won't
		// necessarily be turned on, we can't use it reliably
		Set<Seed> seeds = ti.getTarget().getSeeds();
		Iterator<Seed> it = seeds.iterator();
		while (it.hasNext()) {
			Seed seed = it.next();
			if (seed.isPrimary()) {
				primarySeed = seed.getSeed();
				break;
			}
		}

		NameValuePair[] params = { new NameValuePair("targetInstanceId", ti.getOid().toString()),
				new NameValuePair("harvestNumber", Integer.toString(ahr.getHarvestNumber())),
				new NameValuePair("primarySeed", primarySeed) };

		getMethod.setQueryString(params);
		HttpClient client = new HttpClient();
		try {
			int result = client.executeMethod(getMethod);
			if (result != HttpURLConnection.HTTP_OK) {
				log.error("Unable to initiate Auto QA. Response at " + autoQAUrl + " is " + result);
			}
		} catch (Exception e) {
			log.error("Unable to initiate Auto QA.", e);
		}
	}
}
 
Example 14
Source File: BaseHttpRequestMaker.java    From MesquiteCore with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static boolean contactServer(String s, String URI, StringBuffer response) {
	HttpClient client = new HttpClient();
	GetMethod method = new GetMethod(URI);
	NameValuePair[] pairs = new NameValuePair[1];
	pairs[0] = new NameValuePair("build", StringEscapeUtils.escapeHtml3("\t" + s + "\tOS =\t" + System.getProperty("os.name") + "\t" + System.getProperty("os.version") + "\tjava =\t" + System.getProperty("java.version") +"\t" + System.getProperty("java.vendor")));
	method.setQueryString(pairs);

	method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, 
    		new DefaultHttpMethodRetryHandler(3, false));
	
	return executeMethod(client, method, response);
}
 
Example 15
Source File: BaseHttpRequestMaker.java    From MesquiteCore with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static boolean sendInfoToServer(NameValuePair[] pairs, String URI, StringBuffer response, int retryCount) {
	HttpClient client = new HttpClient();
	GetMethod method = new GetMethod(URI);
	method.setQueryString(pairs);

//	if (retryCount>0)
		method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(retryCount, false));
	
	return executeMethod(client, method, response);
}
 
Example 16
Source File: GetAppCommand.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
public ServerStatus _doIt() {
	try {
		List<Object> key = Arrays.asList(target, name);
		app = appCache.get(key);
		if (app != null) {
			return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, this.app.toJSON());
		}
		URI targetURI = URIUtil.toURI(target.getUrl());

		// Find the app
		String appsUrl = target.getSpace().getCFJSON().getJSONObject("entity").getString("apps_url");
		URI appsURI = targetURI.resolve(appsUrl);
		GetMethod getAppsMethod = new GetMethod(appsURI.toString());
		ServerStatus confStatus = HttpUtil.configureHttpMethod(getAppsMethod, target.getCloud());
		if (!confStatus.isOK())
			return confStatus;
		
		getAppsMethod.setQueryString("q=name:" + URLEncoder.encode(name, "UTF8") + "&inline-relations-depth=1");

		ServerStatus getStatus = HttpUtil.executeMethod(getAppsMethod);
		if (!getStatus.isOK())
			return getStatus;

		JSONObject apps = getStatus.getJsonData();

		if (!apps.has("resources") || apps.getJSONArray("resources").length() == 0)
			return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, "Application not found", null);

		// Get more details about the app
		JSONObject appJSON = apps.getJSONArray("resources").getJSONObject(0).getJSONObject("metadata");

		String summaryAppUrl = appJSON.getString("url") + "/summary";
		URI summaryAppURI = targetURI.resolve(summaryAppUrl);

		GetMethod getSummaryMethod = new GetMethod(summaryAppURI.toString());
		confStatus = HttpUtil.configureHttpMethod(getSummaryMethod, target.getCloud());
		if (!confStatus.isOK())
			return confStatus;

		getStatus = HttpUtil.executeMethod(getSummaryMethod);
		if (!getStatus.isOK())
			return getStatus;

		JSONObject summaryJSON = getStatus.getJsonData();
		
		// instances
		String instancesUrl = appJSON.getString("url") + "/instances";
		URI instancesURI = targetURI.resolve(instancesUrl);

		GetMethod getInstancesMethod = new GetMethod(instancesURI.toString());
		confStatus = HttpUtil.configureHttpMethod(getInstancesMethod, target.getCloud());
		if (!confStatus.isOK())
			return confStatus;

		getStatus = HttpUtil.executeMethod(getInstancesMethod);
		JSONObject instancesJSON = getStatus.getJsonData();

		this.app = new App();
		this.app.setAppJSON(appJSON);
		this.app.setSummaryJSON(summaryJSON);
		this.app.setName(summaryJSON.getString("name"));
		this.app.setGuid(summaryJSON.getString("guid"));
		appCache.put(key, app);
		
		JSONObject result = this.app.toJSON();
		result.put("instances_details", instancesJSON);

		return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, this.app.toJSON());
	} 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 17
Source File: TunnelComponent.java    From olat with Apache License 2.0 4 votes vote down vote up
/**
 * @param tuReq
 * @param client
 * @return HttpMethod
 */
public HttpMethod fetch(final TURequest tuReq, final HttpClient client) {

    final String modulePath = tuReq.getUri();

    HttpMethod meth = null;
    final String method = tuReq.getMethod();
    if (method.equals("GET")) {
        final GetMethod cmeth = new GetMethod(modulePath);
        final String queryString = tuReq.getQueryString();
        if (queryString != null) {
            cmeth.setQueryString(queryString);
        }
        meth = cmeth;
        if (meth == null) {
            return null;
        }
        // if response is a redirect, follow it
        meth.setFollowRedirects(true);

    } else if (method.equals("POST")) {
        final String type = tuReq.getContentType();
        if (type == null || type.equals("application/x-www-form-urlencoded")) {
            // regular post, no file upload
        }

        final PostMethod pmeth = new PostMethod(modulePath);
        final Set postKeys = tuReq.getParameterMap().keySet();
        for (final Iterator iter = postKeys.iterator(); iter.hasNext();) {
            final String key = (String) iter.next();
            final String vals[] = (String[]) tuReq.getParameterMap().get(key);
            for (int i = 0; i < vals.length; i++) {
                pmeth.addParameter(key, vals[i]);
            }
            meth = pmeth;
        }
        if (meth == null) {
            return null;
            // Redirects are not supported when using POST method!
            // See RFC 2616, section 10.3.3, page 62
        }
    }

    // Add olat specific headers to the request, can be used by external
    // applications to identify user and to get other params
    // test page e.g. http://cgi.algonet.se/htbin/cgiwrap/ug/test.py
    meth.addRequestHeader("X-OLAT-USERNAME", tuReq.getUserName());
    meth.addRequestHeader("X-OLAT-LASTNAME", tuReq.getLastName());
    meth.addRequestHeader("X-OLAT-FIRSTNAME", tuReq.getFirstName());
    meth.addRequestHeader("X-OLAT-EMAIL", tuReq.getEmail());

    try {
        client.executeMethod(meth);
        return meth;
    } catch (final Exception e) {
        meth.releaseConnection();
    }
    return null;
}
 
Example 18
Source File: DeleteApplicationRoutesCommand.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
@Override
protected ServerStatus _doIt() {
	MultiServerStatus status = new MultiServerStatus();

	try {
		URI targetURI = URIUtil.toURI(target.getUrl());

		// get app details
		// TODO: it should be passed along with App object
		String appsUrl = target.getSpace().getCFJSON().getJSONObject("entity").getString("apps_url"); //$NON-NLS-1$//$NON-NLS-2$
		URI appsURI = targetURI.resolve(appsUrl);
		GetMethod getAppsMethod = new GetMethod(appsURI.toString());
		ServerStatus confStatus = HttpUtil.configureHttpMethod(getAppsMethod, target.getCloud());
		if (!confStatus.isOK())
			return confStatus;
		
		getAppsMethod.setQueryString("q=name:" + appName + "&inline-relations-depth=1"); //$NON-NLS-1$ //$NON-NLS-2$

		ServerStatus appsStatus = HttpUtil.executeMethod(getAppsMethod);
		status.add(appsStatus);
		if (!status.isOK())
			return status;

		JSONObject jsonData = appsStatus.getJsonData();
		if (!jsonData.has("resources") || jsonData.getJSONArray("resources").length() == 0) //$NON-NLS-1$//$NON-NLS-2$
			return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, "Application not found", null);
		JSONArray apps = jsonData.getJSONArray("resources");

		// get app routes
		String routesUrl = apps.getJSONObject(0).getJSONObject("entity").getString("routes_url");
		URI routesURI = targetURI.resolve(routesUrl);
		GetMethod getRoutesMethod = new GetMethod(routesURI.toString());
		confStatus = HttpUtil.configureHttpMethod(getRoutesMethod, target.getCloud());
		if (!confStatus.isOK())
			return confStatus;

		ServerStatus routesStatus = HttpUtil.executeMethod(getRoutesMethod);
		status.add(routesStatus);
		if (!status.isOK())
			return status;

		jsonData = routesStatus.getJsonData();
		if (!jsonData.has("resources") || jsonData.getJSONArray("resources").length() == 0) //$NON-NLS-1$//$NON-NLS-2$
			return new ServerStatus(IStatus.OK, HttpServletResponse.SC_OK, "No routes for the app", null);
		JSONArray routes = jsonData.getJSONArray("resources");

		for (int i = 0; i < routes.length(); ++i) {
			JSONObject route = routes.getJSONObject(i);

			// delete route
			String routeUrl = route.getJSONObject(CFProtocolConstants.V2_KEY_METADATA).getString(CFProtocolConstants.V2_KEY_URL);
			URI routeURI = targetURI.resolve(routeUrl); //$NON-NLS-1$
			DeleteMethod deleteRouteMethod = new DeleteMethod(routeURI.toString());
			confStatus = HttpUtil.configureHttpMethod(deleteRouteMethod, target.getCloud());
			if (!confStatus.isOK())
				return confStatus;

			ServerStatus deleteStatus = HttpUtil.executeMethod(deleteRouteMethod);
			status.add(deleteStatus);
			if (!status.isOK())
				return status;
		}

		return status;

	} catch (Exception e) {
		String msg = NLS.bind("An error occured when performing operation {0}", commandName);
		logger.error(msg, e);
		return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
	}
}
 
Example 19
Source File: BitlyUrlShortenerImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public String shortenUrl(String longUrl)
{
    if (log.isDebugEnabled())
    {
        log.debug("Shortening URL: " + longUrl);
    }
    String shortUrl = longUrl;
    if (longUrl.length() > urlLength)
    {
        GetMethod getMethod = new GetMethod();
        getMethod.setPath("/v3/shorten");

        List<NameValuePair> args = new ArrayList<NameValuePair>();
        args.add(new NameValuePair("login", username));
        args.add(new NameValuePair("apiKey", apiKey));
        args.add(new NameValuePair("longUrl", longUrl));
        args.add(new NameValuePair("format", "txt"));
        getMethod.setQueryString(args.toArray(new NameValuePair[args.size()]));

        try
        {
            int resultCode = httpClient.executeMethod(getMethod);
            if (resultCode == 200)
            {
                shortUrl = getMethod.getResponseBodyAsString();
            }
            else
            {
                log.warn("Failed to shorten URL " + longUrl + "  - response code == " + resultCode);
                log.warn(getMethod.getResponseBodyAsString());
            }
        }
        catch (Exception ex)
        {
            log.error("Failed to shorten URL " + longUrl, ex);
        }
        if (log.isDebugEnabled())
        {
            log.debug("URL " + longUrl + " has been shortened to " + shortUrl);
        }
    }
    return shortUrl.trim();
}
 
Example 20
Source File: TunnelComponent.java    From olat with Apache License 2.0 4 votes vote down vote up
/**
 * @param tuReq
 * @param client
 * @return HttpMethod
 */
public HttpMethod fetch(final TURequest tuReq, final HttpClient client) {

    final String modulePath = tuReq.getUri();

    HttpMethod meth = null;
    final String method = tuReq.getMethod();
    if (method.equals("GET")) {
        final GetMethod cmeth = new GetMethod(modulePath);
        final String queryString = tuReq.getQueryString();
        if (queryString != null) {
            cmeth.setQueryString(queryString);
        }
        meth = cmeth;
        if (meth == null) {
            return null;
        }
        // if response is a redirect, follow it
        meth.setFollowRedirects(true);

    } else if (method.equals("POST")) {
        final String type = tuReq.getContentType();
        if (type == null || type.equals("application/x-www-form-urlencoded")) {
            // regular post, no file upload
        }

        final PostMethod pmeth = new PostMethod(modulePath);
        final Set postKeys = tuReq.getParameterMap().keySet();
        for (final Iterator iter = postKeys.iterator(); iter.hasNext();) {
            final String key = (String) iter.next();
            final String vals[] = (String[]) tuReq.getParameterMap().get(key);
            for (int i = 0; i < vals.length; i++) {
                pmeth.addParameter(key, vals[i]);
            }
            meth = pmeth;
        }
        if (meth == null) {
            return null;
            // Redirects are not supported when using POST method!
            // See RFC 2616, section 10.3.3, page 62
        }
    }

    // Add olat specific headers to the request, can be used by external
    // applications to identify user and to get other params
    // test page e.g. http://cgi.algonet.se/htbin/cgiwrap/ug/test.py
    meth.addRequestHeader("X-OLAT-USERNAME", tuReq.getUserName());
    meth.addRequestHeader("X-OLAT-LASTNAME", tuReq.getLastName());
    meth.addRequestHeader("X-OLAT-FIRSTNAME", tuReq.getFirstName());
    meth.addRequestHeader("X-OLAT-EMAIL", tuReq.getEmail());

    try {
        client.executeMethod(meth);
        return meth;
    } catch (final Exception e) {
        meth.releaseConnection();
    }
    return null;
}