org.apache.http.HttpException Java Examples

The following examples show how to use org.apache.http.HttpException. 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: TaskActionHandler.java    From Repeat with Apache License 2.0 6 votes vote down vote up
@Override
protected void handleWithBackend(HttpRequest request, HttpAsyncExchange exchange, HttpContext context)
		throws HttpException, IOException {
	String method = request.getRequestLine().getMethod();
	if (!method.equalsIgnoreCase(ACCEPTED_METHOD)) {
		LOGGER.warning("Ignoring request with unknown method " + method);
		CliRpcCodec.prepareResponse(exchange, 400, "Method must be " + ACCEPTED_METHOD);
		return;
	}

	JsonNode requestData = CliRpcCodec.decodeRequest(getRequestBody(request));
	if (requestData == null) {
		LOGGER.warning("Failed to parse request into JSON!");
		CliRpcCodec.prepareResponse(exchange, 400, "Cannot parse request!");
		return;
	}

	handleTaskActionWithBackend(exchange, requestData);
}
 
Example #2
Source File: HttpClientConfigurer.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {

            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);

            if (authState.getAuthScheme() != null || authState.hasAuthOptions()) {
                return;
            }

            // If no authState has been established and this is a PUT or POST request, add preemptive authorisation
            String requestMethod = request.getRequestLine().getMethod();
            if (requestMethod.equals(HttpPut.METHOD_NAME) || requestMethod.equals(HttpPost.METHOD_NAME)) {
                CredentialsProvider credentialsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
                HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
                Credentials credentials = credentialsProvider.getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()));
                if (credentials == null) {
                    throw new HttpException("No credentials for preemptive authentication");
                }
                authState.update(authScheme, credentials);
            }
        }
 
Example #3
Source File: ControlFileModelTest.java    From datasync with MIT License 6 votes vote down vote up
@Test
public void testSyntheticColumns() throws IOException, LongRunningQueryException, InterruptedException, HttpException, URISyntaxException {
    ControlFile cf = getTestControlFile();
    ControlFileModel model = getTestModel(cf);

    String fieldName = "testLoc";
    LocationColumn location = new LocationColumn();
    location.address = "1234 fake street";
    location.latitude = "90";
    location.longitude = "90";
    //Test that we can add to the synthetic location when none exist
    model.setSyntheticLocation(fieldName,location);
    TestCase.assertEquals(model.getSyntheticLocations().get(fieldName),location);

    //Test that we can add another one when one already exists
    String anotherColumn = "anotherColumn";
    LocationColumn newLocation = new LocationColumn();
    newLocation.address = "742 evergreen terrace";
    model.setSyntheticLocation(anotherColumn,newLocation);
    TestCase.assertEquals(model.getSyntheticLocations().get(anotherColumn), newLocation);
}
 
Example #4
Source File: AbstractTaskActivationConstructorActionHandler.java    From Repeat with Apache License 2.0 6 votes vote down vote up
@Override
protected final Void handleAllowedRequestWithBackend(HttpRequest request, HttpAsyncExchange exchange, HttpContext context)
		throws HttpException, IOException {
	Map<String, String> params = HttpServerUtilities.parseSimplePostParameters(request);
	if (params == null) {
		return HttpServerUtilities.prepareHttpResponse(exchange, 400, "Failed to get POST parameters.");
	}

	String id = params.get("id");
	if (id == null) {
		return HttpServerUtilities.prepareHttpResponse(exchange, 400, "Failed to get task activation constructor ID.");
	}

	TaskActivationConstructor constructor = taskActivationConstructorManager.get(id);
	if (constructor == null) {
		return HttpServerUtilities.prepareHttpResponse(exchange, 404, "No constructor found for ID '" + id + "'.");
	}

	return handleRequestWithBackendAndConstructor(exchange, constructor, params);
}
 
Example #5
Source File: GzipResponseInterceptor.java    From fanfouapp-opensource with Apache License 2.0 6 votes vote down vote up
@Override
public void process(final HttpResponse response, final HttpContext context)
        throws HttpException, IOException {
    final HttpEntity entity = response.getEntity();
    final Header encoding = entity.getContentEncoding();
    if (encoding != null) {
        for (final HeaderElement element : encoding.getElements()) {
            if (element.getName().equalsIgnoreCase(
                    GzipResponseInterceptor.ENCODING_GZIP)) {
                response.setEntity(new GzipDecompressingEntity(response
                        .getEntity()));
                break;
            }
        }
    }
}
 
Example #6
Source File: JolokiaClientFactory.java    From hawkular-agent with Apache License 2.0 6 votes vote down vote up
public void process(final HttpRequest request, final HttpContext context)
        throws HttpException, IOException {
    AuthState authState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE);

    if (authState.getAuthScheme() == null) {
        CredentialsProvider credsProvider = (CredentialsProvider) context
                .getAttribute(HttpClientContext.CREDS_PROVIDER);
        HttpHost targetHost = (HttpHost) context.getAttribute(HttpClientContext.HTTP_TARGET_HOST);
        Credentials creds = credsProvider
                .getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()));
        if (creds == null) {
            throw new HttpException("No credentials given for preemptive authentication");
        }
        authState.update(authScheme, creds);
    }
}
 
Example #7
Source File: Tools.java    From android-tv-launcher with MIT License 6 votes vote down vote up
public static void download(String url, String path,
		final IOAuthCallBack iOAuthCallBack) {
	HttpUtils http = new HttpUtils();
	HttpHandler<File> handler = http.download(url, path, false, // 如果目标文件存在,接着未完成的部分继续下载。服务器不支持RANGE时将从新下载。
			false, // 如果从请求返回信息中获取到文件名,下载完成后自动重命名。
			new RequestCallBack<File>() {

				@Override
				public void onSuccess(ResponseInfo<File> arg0) {
					if (d)
						Log.d("-----downfile-----", "success");
					iOAuthCallBack.getIOAuthCallBack(arg0.result.getName(),
							0);
				}

                   @Override
                   public void onFailure(com.lidroid.xutils.exception.HttpException e, String s) {
                       if (d)
                           Log.d("-----downfile-----", "fail");
                       iOAuthCallBack.getIOAuthCallBack(e.toString(), 1);
                   }
               });
}
 
Example #8
Source File: UpdateCustomPageRequest.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected String doExecute(final HttpClient httpClient) throws IOException, HttpException {
    final HttpPut updatePageRequest = new HttpPut(
            String.format(getURLBase() + PORTAL_UPDATE_PAGE_API, pageToUpdate.getId()));
    updatePageRequest.setHeader(API_TOKEN_HEADER, getAPITokenFromCookie());
    final EntityBuilder entityBuilder = EntityBuilder.create();
    entityBuilder.setContentType(ContentType.APPLICATION_JSON);
    if(pageToUpdate.getProcessDefinitionId() != null) {
        entityBuilder.setText(String.format("{\"pageZip\" : \"%s\", \"processDefinitionId\" : \"%s\" }", uploadedFileToken,pageToUpdate.getProcessDefinitionId()));
    }else {
        entityBuilder.setText(String.format("{\"pageZip\" : \"%s\" }", uploadedFileToken));
    }
    updatePageRequest.setEntity(entityBuilder.build());
    final HttpResponse response = httpClient.execute(updatePageRequest);
    final int status = response.getStatusLine().getStatusCode();
    String responseContent = contentAsString(response);
    if (status != HttpURLConnection.HTTP_OK) {
        throw new HttpException(responseContent.isEmpty() ? String.format("Add custom page failed with status: %s. Open Engine log for more details.", status) : responseContent);
    }
    return responseContent;
}
 
Example #9
Source File: FutureRestApiV1.java    From zheshiyigeniubidexiangmu with MIT License 6 votes vote down vote up
@Override
public String future_position(String symbol, String contractType)
		throws HttpException, IOException {
	// 构造参数签名
	Map<String, String> params = new HashMap<String, String>();
	if (!StringUtil.isEmpty(symbol )) {
		params.put("symbol", symbol);
	}
	if (!StringUtil.isEmpty(contractType )) {
		params.put("contract_type", contractType);
	}
	params.put("api_key", api_key);
	String sign = MD5Util.buildMysignV1(params, secret_key);
	params.put("sign", sign);
	// 发送post请求

	HttpUtilManager httpUtil = HttpUtilManager.getInstance();
	String result = httpUtil.requestHttpPost(url_prex,this.FUTURE_POSITION_URL,
			params);
	// System.out.println(result);
	return result;

}
 
Example #10
Source File: MockHttpClient.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
@Override
protected RequestDirector createClientRequestDirector(
    HttpRequestExecutor requestExec,
    ClientConnectionManager conman,
    ConnectionReuseStrategy reustrat,
    ConnectionKeepAliveStrategy kastrat,
    HttpRoutePlanner rouplan,
    HttpProcessor httpProcessor,
    HttpRequestRetryHandler retryHandler,
    RedirectHandler redirectHandler,
    AuthenticationHandler targetAuthHandler,
    AuthenticationHandler proxyAuthHandler,
    UserTokenHandler stateHandler,
    HttpParams params) {
  return new RequestDirector() {
    @Beta
    public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context)
        throws HttpException, IOException {
      return new BasicHttpResponse(HttpVersion.HTTP_1_1, responseCode, null);
    }
  };
}
 
Example #11
Source File: AddCustomPageRequest.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected String doExecute(final HttpClient httpClient) throws IOException, HttpException {
    final HttpPost addPageRequest = new HttpPost(getURLBase() + PORTAL_ADD_PAGE_API);
    addPageRequest.setHeader(API_TOKEN_HEADER, getAPITokenFromCookie());
    final EntityBuilder entityBuilder = EntityBuilder.create();
    entityBuilder.setContentType(ContentType.APPLICATION_JSON);
    entityBuilder.setText(String.format("{\"pageZip\" : \"%s\" }", uploadedFileToken));
    addPageRequest.setEntity(entityBuilder.build());
    final HttpResponse response = httpClient.execute(addPageRequest);
    final int status = response.getStatusLine().getStatusCode();
    String responseContent = contentAsString(response);
    if (status != HttpURLConnection.HTTP_OK) {
        throw new HttpException(responseContent.isEmpty() ? String.format("Add custom page failed with status: %s. Open Engine log for more details.", status) : responseContent);
    }
    return responseContent;
}
 
Example #12
Source File: StockRestApi.java    From zheshiyigeniubidexiangmu with MIT License 6 votes vote down vote up
@Override
	public String ticker(String symbol) throws HttpException, IOException {
		HttpUtilManager httpUtil = HttpUtilManager.getInstance();
		String param = "";
//		if(!StringUtil.isEmpty(symbol )) {
//			if (!param.equals("")) {
//				param += "&";
//			}
//			param += "symbol=" + symbol;
//		}
		String[] params = {"secret_key=" + secret_key,"symbol=" + symbol, "api_key=" + api_key};
		params = StringSort.getUrlParam(params);
		param = StringSort.getText(params, "&");
		param = param + "&sign=" + CryptoUtils.encodeMD5(param);

		String result = httpUtil.requestHttpGet(url_prex, TICKER_URL, param);
	    return result;
	}
 
Example #13
Source File: ApacheHttpClientEdgeGridRoutePlanner.java    From AkamaiOPEN-edgegrid-java with Apache License 2.0 6 votes vote down vote up
@Override
public HttpRoute determineRoute(HttpHost host, HttpRequest request, HttpContext context) throws HttpException {
    try {
        ClientCredential clientCredential = binding.getClientCredentialProvider().getClientCredential(binding.map(request));
        String hostname = clientCredential.getHost();
        int port = -1;
        final int pos = hostname.lastIndexOf(":");
        if (pos > 0) {
            try {
                port = Integer.parseInt(hostname.substring(pos + 1));
            } catch (NumberFormatException ex) {
                throw new IllegalArgumentException("Host contains invalid port number: " + hostname);
            }
            hostname = hostname.substring(0, pos);
        }
        HttpHost target = new HttpHost(hostname, port, "https");
        return super.determineRoute(target, request, context);
    } catch (NoMatchingCredentialException e) {
        throw new RuntimeException(e);
    }
}
 
Example #14
Source File: MenuImportTaskActionHandler.java    From Repeat with Apache License 2.0 6 votes vote down vote up
@Override
protected Void handleAllowedRequestWithBackend(HttpRequest request, HttpAsyncExchange exchange, HttpContext context) throws HttpException, IOException {
	Map<String, String> params = HttpServerUtilities.parseSimplePostParameters(request);
	if (params == null) {
		return HttpServerUtilities.prepareHttpResponse(exchange, 400, "Failed to get POST parameters.");
	}
	String path = params.get("path");
	if (path == null) {
		return HttpServerUtilities.prepareHttpResponse(exchange, 400, "Path must be provided.");
	}
	if (!Files.isRegularFile(Paths.get(path))) {
		return HttpServerUtilities.prepareHttpResponse(exchange, 400, "Path '" + path + "' is not a file.");
	}

	backEndHolder.importTasks(new File(path));
	return emptySuccessResponse(exchange);
}
 
Example #15
Source File: RestTemplateCustomizerLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public void customize(RestTemplate restTemplate) {
    HttpHost proxy = new HttpHost(PROXY_SERVER_HOST, PROXY_SERVER_PORT);
    HttpClient httpClient = HttpClientBuilder.create()
        .setRoutePlanner(new DefaultProxyRoutePlanner(proxy) {
            @Override
            public HttpHost determineProxy(HttpHost target, HttpRequest request, HttpContext context) throws HttpException {
                return super.determineProxy(target, request, context);
            }
        })
        .build();
    restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient));
}
 
Example #16
Source File: HttpResponseWarcRecord.java    From BUbiNG with Apache License 2.0 5 votes vote down vote up
@Override
protected InputStream writePayload(final ByteArraySessionOutputBuffer buffer) throws IOException {
	final DefaultHttpResponseWriter pw = new DefaultHttpResponseWriter(buffer);
	try {
		pw.write(this);
	} catch (HttpException e) {
		throw new RuntimeException("Unexpected HttpException.", e);
	}
	buffer.contentLength(buffer.size() + this.entity.getContentLength());
	return new SequenceInputStream(buffer.toInputStream(), this.entity.getContent()); // TODO: we never close the getContent() inputstream...
}
 
Example #17
Source File: HttpCommandEffectorHttpBinTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context)
        throws HttpException, IOException {
    Navigator<MutableMap<Object, Object>> j = Jsonya.newInstance().map();
    BasicHttpRequest req = (BasicHttpRequest)request;
    String url = req.getRequestLine().getUri();
    URI uri = URI.create(url);
    String method = req.getRequestLine().getMethod();
    boolean expectsPost = uri.getPath().equals("/post");
    if (expectsPost && !method.equals("POST") ||
            !expectsPost && !method.equals("GET")) {
        throw new IllegalStateException("Method " + method + " not allowed on " + url);
    }
    List<NameValuePair> params = URLEncodedUtils.parse(uri, "UTF-8");
    if (!params.isEmpty()) {
        j.push().at("args");
        for (NameValuePair param : params) {
            j.put(param.getName(), param.getValue());
        }
        j.pop();
    }
    j.put("origin", "127.0.0.1");
    j.put("url", serverUrl + url);

    response.setHeader("Content-Type", "application/json");
    response.setStatusCode(200);
    response.setEntity(new StringEntity(j.toString()));
}
 
Example #18
Source File: NexusHttpRoutePlanner.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected HttpHost determineProxy(final HttpHost host,
                                  final HttpRequest request,
                                  final HttpContext context)
    throws HttpException
{
  if (noProxyFor(host.getHostName())) {
    return null;
  }
  return proxies.get(host.getSchemeName());
}
 
Example #19
Source File: ActionMoveTaskUpHandler.java    From Repeat with Apache License 2.0 5 votes vote down vote up
@Override
protected Void handleAllowedRequestWithBackend(HttpRequest request, HttpAsyncExchange exchange, HttpContext context)
		throws HttpException, IOException {
	Map<String, String> params = HttpServerUtilities.parseSimplePostParameters(request);
	if (params == null) {
		return HttpServerUtilities.prepareTextResponse(exchange, 400, "Failed to parse POST data.");
	}
	String taskId = CommonTask.getTaskIdFromRequest(backEndHolder, params);
	if (taskId == null || taskId.isEmpty()) {
		return HttpServerUtilities.prepareTextResponse(exchange, 400, "Cannot find task from request data.");
	}

	backEndHolder.moveTaskUp(taskId);
	return renderedTaskForGroup(exchange);
}
 
Example #20
Source File: ResponseCommand.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
private ExpectedResult parseExpectedResponse(Element element, Evaluator evaluator, ResultRecorder resultRecorder) {
  String contents = getTextAndRemoveIndent(element);

  contents = replaceVariableReferences(evaluator, contents, resultRecorder);

  SessionInputBufferImpl buffer = new SessionInputBufferImpl(new HttpTransportMetricsImpl(), contents.length());
  buffer.bind(new ByteArrayInputStream(contents.getBytes(StandardCharsets.UTF_8)));
  DefaultHttpResponseParser defaultHttpResponseParser = new DefaultHttpResponseParser(buffer);

  ExpectedResult.ExpectedResultBuilder builder = expectedResult();
  String body = null;
  try {
    HttpResponse httpResponse = defaultHttpResponseParser.parse();
    StatusLine statusLine = httpResponse.getStatusLine();
    builder.withStatus(statusLine.getStatusCode());

    for (Header header : httpResponse.getAllHeaders()) {
      builder.withHeader(header.getName(), header.getValue());
    }

    if (buffer.hasBufferedData()) {
      body = "";

      while (buffer.hasBufferedData()) {
        body += (char) buffer.read();
      }
    }
    builder.withBody(body);
  } catch (IOException | HttpException e) {
    e.printStackTrace();
  }

  return builder.build();
}
 
Example #21
Source File: HttpHandlerWithBackend.java    From Repeat with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(HttpRequest request, HttpAsyncExchange exchange, HttpContext context)
		throws HttpException, IOException {
	if (backEndHolder == null) {
		LOGGER.warning("Missing backend...");
		HttpServerUtilities.prepareTextResponse(exchange, 500, "");
		return;
	}

	handleWithBackend(request, exchange, context);
}
 
Example #22
Source File: InsecureHttpsServer.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Starts the server.
 * @throws Exception in case of exception
 */
public void start() throws Exception {
    final URL url = getClass().getClassLoader().getResource("insecureSSL.keystore");
    final KeyStore keystore = KeyStore.getInstance("jks");
    final char[] pwd = "nopassword".toCharArray();
    keystore.load(url.openStream(), pwd);

    final TrustManagerFactory trustManagerFactory = createTrustManagerFactory();
    trustManagerFactory.init(keystore);
    final TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

    final KeyManagerFactory keyManagerFactory = createKeyManagerFactory();
    keyManagerFactory.init(keystore, pwd);
    final KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();

    final SSLContext serverSSLContext = SSLContext.getInstance("TLS");
    serverSSLContext.init(keyManagers, trustManagers, null);

    localServer_ = new LocalTestServer(serverSSLContext);

    if (html_ != null) {
        final HttpRequestHandler handler = new HttpRequestHandler() {
            @Override
            public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
                response.setEntity(new StringEntity(html_, ContentType.TEXT_HTML));
            }
        };
        localServer_.register("*", handler);
    }
    localServer_.start();
}
 
Example #23
Source File: WingtipsHttpClientBuilderTest.java    From wingtips with Apache License 2.0 5 votes vote down vote up
@Override
public CloseableHttpResponse execute(HttpRoute route, HttpRequestWrapper request,
                                     HttpClientContext clientContext,
                                     HttpExecutionAware execAware) throws IOException, HttpException {
    capturedSpan = Tracer.getInstance().getCurrentSpan();
    
    doReturn(statusLineMock).when(response).getStatusLine();
    
    if (exceptionToThrow != null) {
        throw exceptionToThrow;
    }
    // Return a graceful 500 from the response
    doReturn(500).when(statusLineMock).getStatusCode();
    return response;
}
 
Example #24
Source File: GetRenderedTaskGroupsDropdown.java    From Repeat with Apache License 2.0 5 votes vote down vote up
@Override
protected Void handleAllowedRequestWithBackend(HttpRequest request, HttpAsyncExchange exchange, HttpContext context)
		throws HttpException, IOException {
	Map<String, Object> data = new HashMap<>();
	TaskGroup group = backEndHolder.getCurrentTaskGroup();
	data.put("taskGroup", RenderedTaskGroupButton.fromTaskGroups(group, backEndHolder.getTaskGroups()));

	String page = objectRenderer.render("fragments/task_groups_dropdown", data);
	if (page == null) {
		return HttpServerUtilities.prepareHttpResponse(exchange, 500, "Failed to render page.");
	}

	return HttpServerUtilities.prepareHttpResponse(exchange, HttpStatus.SC_OK, page);
}
 
Example #25
Source File: SdkProxyRoutePlanner.java    From ibm-cos-sdk-java with Apache License 2.0 5 votes vote down vote up
@Override
protected HttpHost determineProxy(
    final HttpHost target,
    final HttpRequest request,
    final HttpContext context) throws HttpException {

    return doesTargetMatchNonProxyHosts(target) ? null : proxy;
}
 
Example #26
Source File: BonitaPagesRequest.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected String doExecute(HttpClient httpClient) throws IOException, HttpException {
    final HttpGet request = new HttpGet(
            String.format("%s%s?p=0&c=%s", getURLBase(), PORTAL_BONITA_PAGE_API, Integer.MAX_VALUE));
    request.setHeader(API_TOKEN_HEADER, getAPITokenFromCookie());
    HttpResponse response = httpClient.execute(request);
    if (response.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_OK) {
        throw new HttpException(
                String.format("Bonita Pages request failed with status: %s", response.getStatusLine().getStatusCode()));
    }
    return contentAsString(response);
}
 
Example #27
Source File: BasicHttpSolrClientTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public void process(HttpRequest request, HttpContext context) throws HttpException,
IOException {
  log.info("Intercepted params: {}", context);

  HttpRequestWrapper wrapper = (HttpRequestWrapper) request;
  URIBuilder uribuilder = new URIBuilder(wrapper.getURI());
  uribuilder.addParameter("b", "\u4321");
  try {
    wrapper.setURI(uribuilder.build());
  } catch (URISyntaxException ex) {
    throw new HttpException("Invalid request URI", ex);
  }
}
 
Example #28
Source File: Logger.java    From VideoRecord with MIT License 5 votes vote down vote up
public static void printStackTrace(String TAG, HttpException e) {
	if (IsDebug) {
		e.printStackTrace();
	} else {
		logException(TAG, e);
	}
}
 
Example #29
Source File: IndexPageHandler.java    From Repeat with Apache License 2.0 5 votes vote down vote up
@Override
protected Void handleAllowedRequestWithBackend(HttpRequest request, HttpAsyncExchange exchange, HttpContext context)
		throws HttpException, IOException {
	Map<String, Object> data = new HashMap<>();
	data.put("replayConfig", RenderedReplayConfig.fromReplayConfig(backEndHolder.getReplayConfig()));
	data.put("runTaskConfig", RenderedRunTaskConfig.fromRunTaskConfig(backEndHolder.getRunActionConfig()));

	TaskGroup group = backEndHolder.getCurrentTaskGroup();
	data.put("taskGroup", RenderedTaskGroupButton.fromTaskGroups(group, backEndHolder.getTaskGroups()));
	List<RenderedUserDefinedAction> taskList = group.getTasks().stream().map(RenderedUserDefinedAction::fromUserDefinedAction).collect(Collectors.toList());
	data.put("tasks", taskList);
	data.put("tooltips", new TooltipsIndexPage());

	data.put("executionTime", getExecutionTime());
	data.put("config", RenderedConfig.fromConfig(backEndHolder.getConfig(), backEndHolder.getRecorder()));

	Language selectedLanguage = backEndHolder.getSelectedLanguage();
	List<RenderedCompilingLanguage> languages = new ArrayList<>();
	for (Language language : Language.values()) {
		languages.add(RenderedCompilingLanguage.forLanguage(language, language == selectedLanguage));
	}
	data.put("compilingLanguages", languages);
	boolean displayManualBuild = backEndHolder.getSelectedLanguage() == Language.MANUAL_BUILD;
	data.put("displayManualBuild", displayManualBuild);
	if (displayManualBuild) {
		String id = manuallyBuildActionConstructorManager.addNew();
		Map<String, Object> manuallyBuildBodyData = ManuallyBuildActionBuilderBody.bodyData(manuallyBuildActionConstructorManager, id);
		data.putAll(manuallyBuildBodyData);
	}

	return renderedPage(exchange, "index", data);
}
 
Example #30
Source File: GzipRequestInterceptor.java    From fanfouapp-opensource with Apache License 2.0 5 votes vote down vote up
@Override
public void process(final HttpRequest request, final HttpContext context)
        throws HttpException, IOException {
    if (!request
            .containsHeader(GzipRequestInterceptor.HEADER_ACCEPT_ENCODING)) {
        request.addHeader(GzipRequestInterceptor.HEADER_ACCEPT_ENCODING,
                GzipRequestInterceptor.ENCODING_GZIP);
    }
}