Java Code Examples for org.apache.http.HttpException

The following are top voted examples for showing how to use org.apache.http.HttpException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: smart_plan   File: DatabaseDataRequestHandler.java   View source code 8 votes vote down vote up
@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
    RequestLine line = request.getRequestLine();
    Uri uri = Uri.parse(line.getUri());
    DatabaseDataEntity entity;
    if (uri != null) {
        String database = uri.getQueryParameter("database");
        String tableName = uri.getQueryParameter("table");
        entity = getDataResponse(database, tableName);
        if (entity != null) {
            response.setStatusCode(200);
            response.setEntity(new StringEntity(ParserJson.getSafeJsonStr(entity), "utf-8"));
            return;
        }
    }
    entity = new DatabaseDataEntity();
    entity.setDataList(new ArrayList<Map<String, String>>());
    entity.setCode(BaseEntity.FAILURE_CODE);
    response.setStatusCode(200);
    response.setEntity(new StringEntity(ParserJson.getSafeJsonStr(entity), "utf-8"));
}
 
Example 2
Project: Reer   File: HttpClientConfigurer.java   View source code 7 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 || 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 (alwaysSendAuth || requestMethod.equals(HttpPut.METHOD_NAME) || requestMethod.equals(HttpPost.METHOD_NAME)) {
                CredentialsProvider credentialsProvider = (CredentialsProvider) context.getAttribute(HttpClientContext.CREDS_PROVIDER);
                HttpHost targetHost = (HttpHost) context.getAttribute(HttpCoreContext.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
Project: dhus-core   File: InterruptibleHttpClient.java   View source code 7 votes vote down vote up
/**
 * Gets a part of the given URL, writes the content into the given channel.
 * Fails if the returned HTTP status is not "206 partial content".
 *
 * @param <IWC> a generic type for any class that implements InterruptibleChannel and WritableByteChannel
 * @param url to get
 * @param output written with the content of the HTTP response
 * @param etag value of the If-Range header
 * @param range_start range byte start (inclusive)
 * @param range_end range byte end (inclusive)
 *
 * @return a response (contains the HTTP Headers, the status code, ...)
 *
 * @throws IOException IO error
 * @throws InterruptedException interrupted
 * @throws RuntimeException containing the actual exception if it is not an instance of IOException
 */
public <IWC extends InterruptibleChannel & WritableByteChannel>
      HttpResponse interruptibleGetRange(String url, final IWC output, String etag, long range_start, long range_end)
      throws IOException, InterruptedException
{
   HttpGet get = new HttpGet(url);
   get.setHeader("If-Range", etag);
   get.setHeader("Range", String.format("bytes=%d-%d", range_start, range_end));
   // This validator throws an IOException if the response code is not 206 partial content
   ResponseValidator val = new ResponseValidator()
   {
      @Override
      public void validate(HttpResponse response) throws HttpException, IOException
      {
         if (response.getStatusLine().getStatusCode() != HttpStatus.SC_PARTIAL_CONTENT)
         {
            throw new IOException("Range request does not return partial content");
         }
      }
   };
   return interruptibleRequest(get, output, val);
}
 
Example 4
Project: dhus-core   File: TestInterruptibleHttpClient.java   View source code 7 votes vote down vote up
/**
 * Starts the HTTP server.
 *
 * @return the listening port.
 */
static int start () throws IOException
{

   server = ServerBootstrap.bootstrap ().registerHandler ("*",
         new HttpRequestHandler ()
         {

            @Override
            public void handle (HttpRequest request, HttpResponse response,
                  HttpContext context)
                  throws HttpException, IOException
            {

               response.setStatusCode (HttpStatus.SC_OK);
               response.setEntity (new StringEntity ("0123456789"));
            }
         })
         .create ();
   server.start ();

   return server.getLocalPort ();
}
 
Example 5
Project: allure-java   File: AllureHttpClientRequest.java   View source code 6 votes vote down vote up
@Override
public void process(final HttpRequest request,
                    final HttpContext context) throws HttpException, IOException {
    final HttpRequestAttachment.Builder builder = create("Request", request.getRequestLine().getUri())
            .withMethod(request.getRequestLine().getMethod());

    Stream.of(request.getAllHeaders())
            .forEach(header -> builder.withHeader(header.getName(), header.getValue()));

    if (request instanceof HttpEntityEnclosingRequest) {
        final HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();

        final ByteArrayOutputStream os = new ByteArrayOutputStream();
        entity.writeTo(os);

        final String body = new String(os.toByteArray(), StandardCharsets.UTF_8);
        builder.withBody(body);
    }

    final HttpRequestAttachment requestAttachment = builder.build();
    processor.addAttachment(requestAttachment, renderer);
}
 
Example 6
Project: allure-java   File: AllureHttpClientResponse.java   View source code 6 votes vote down vote up
@Override
public void process(final HttpResponse response,
                    final HttpContext context) throws HttpException, IOException {

    final HttpResponseAttachment.Builder builder = create("Response")
            .withResponseCode(response.getStatusLine().getStatusCode());

    Stream.of(response.getAllHeaders())
            .forEach(header -> builder.withHeader(header.getName(), header.getValue()));

    final ByteArrayOutputStream os = new ByteArrayOutputStream();
    response.getEntity().writeTo(os);

    final String body = new String(os.toByteArray(), StandardCharsets.UTF_8);
    builder.withBody(body);

    final HttpResponseAttachment responseAttachment = builder.build();
    processor.addAttachment(responseAttachment, renderer);
}
 
Example 7
Project: ticketing-service-paqx-parent-sample   File: TicketingIntegrationService.java   View source code 6 votes vote down vote up
private Map put(String url, String data) throws IOException, HttpException {
	Map<String,Object> map = null;
	CredentialsProvider credentials = credentialsProvider();
	CloseableHttpClient httpclient = HttpClients.custom()
               .setDefaultCredentialsProvider(credentials)
               .build();

	try {
		HttpPut httpPut = new HttpPut(url);
 		httpPut.setHeader("Accept", "application/json");
 		httpPut.setHeader("Content-Type", "application/json");
        HttpEntity entity = new ByteArrayEntity(data.getBytes("utf-8"));
 		httpPut.setEntity(entity);
	        
	    System.out.println("Executing request " + httpPut.getRequestLine());
	    CloseableHttpResponse response = httpclient.execute(httpPut);
	    try {
	        LOG.debug("----------------------------------------");
	        LOG.debug((String)response.getStatusLine().getReasonPhrase());
	        String responseBody = EntityUtils.toString(response.getEntity());
	        LOG.debug(responseBody);
	        Gson gson = new Gson();
	        map = new HashMap<String,Object>();
			map = (Map<String,Object>) gson.fromJson(responseBody, map.getClass());
	        LOG.debug(responseBody);
	    } finally {
	        response.close();
	    }
	} finally {
	    httpclient.close();
	}

	return map;
}
 
Example 8
Project: karate   File: ResponseLoggingInterceptor.java   View source code 6 votes vote down vote up
@Override
public void process(HttpResponse response, HttpContext httpContext) throws HttpException, IOException {
    if (!context.logger.isDebugEnabled()) {
        return;
    }        
    int id = counter.get();
    StringBuilder sb = new StringBuilder();
    sb.append('\n').append(id).append(" < ").append(response.getStatusLine().getStatusCode()).append('\n');
    LoggingUtils.logHeaders(sb, id, '<', response);
    HttpEntity entity = response.getEntity();
    if (LoggingUtils.isPrintable(entity)) {
        LoggingEntityWrapper wrapper = new LoggingEntityWrapper(entity);
        String buffer = FileUtils.toString(wrapper.getContent());
        sb.append(buffer).append('\n');
        response.setEntity(wrapper);
    }
    context.logger.debug(sb.toString());
}
 
Example 9
Project: vrops-export   File: Exporter.java   View source code 6 votes vote down vote up
private void registerFields() throws IOException, HttpException, ExporterException {
String parentType = null;
  	List<Config.Field> parentFields = new ArrayList<Config.Field>();
  	int pos = 2; // Advance past timestamp and resource name
      for(Config.Field fld : conf.getFields()) {
      	boolean isMetric = fld.hasMetric();
      	String name = isMetric ? fld.getMetric() : fld.getProp();
      	
      	// Parse parent reference if present.
      	//
      	Matcher m = Patterns.parentPattern.matcher(name);
      	if(m.matches()) {
      		String pn = m.group(1);
      		if(parentType == null) {
      			parentType = pn;
      		} else if(!pn.equals(parentType)) 
      			throw new ExporterException("References to multiple parents not supported");
      		String fn = m.group(2);
      		parentFields.add(new Config.Field(fld.getAlias(), fn, isMetric));
      	}
          if(statPos.get(fld.getMetric()) == null) {
              statPos.put(name, pos);
          }
          ++pos;
      }
  }
 
Example 10
Project: lams   File: RequestDefaultHeaders.java   View source code 6 votes vote down vote up
public void process(final HttpRequest request, final HttpContext context)
        throws HttpException, IOException {
    if (request == null) {
        throw new IllegalArgumentException("HTTP request may not be null");
    }

    String method = request.getRequestLine().getMethod();
    if (method.equalsIgnoreCase("CONNECT")) {
        return;
    }

    // Add default headers
    @SuppressWarnings("unchecked")
    Collection<Header> defHeaders = (Collection<Header>) request.getParams().getParameter(
            ClientPNames.DEFAULT_HEADERS);

    if (defHeaders != null) {
        for (Header defHeader : defHeaders) {
            request.addHeader(defHeader);
        }
    }
}
 
Example 11
Project: ibm-cos-sdk-java   File: SdkHttpRequestExecutor.java   View source code 6 votes vote down vote up
@Override
protected HttpResponse doReceiveResponse(
        final HttpRequest          request,
        final HttpClientConnection conn,
        final HttpContext          context)
            throws HttpException, IOException {
    AWSRequestMetrics awsRequestMetrics = (AWSRequestMetrics) context
            .getAttribute(AWSRequestMetrics.class.getSimpleName());
    if (awsRequestMetrics == null) {
        return super.doReceiveResponse(request, conn, context);
    }
    awsRequestMetrics.startEvent(Field.HttpClientReceiveResponseTime);
    try {
        return super.doReceiveResponse(request, conn, context);
    } finally {
        awsRequestMetrics.endEvent(Field.HttpClientReceiveResponseTime);
    }
}
 
Example 12
Project: bitstd   File: HttpUtilManager.java   View source code 6 votes vote down vote up
public String requestHttpGet(String url_prex, String type) throws HttpException, IOException {
	String url = url_prex + type;
	HttpRequestBase method = this.httpGetMethod(url, "");
	method.setConfig(requestConfig);
	long start = System.currentTimeMillis();
	HttpResponse response = client.execute(method);
	long end = System.currentTimeMillis();
	Logger.getGlobal().log(Level.INFO, String.valueOf(end - start));
	HttpEntity entity = response.getEntity();
	if (entity == null) {
		return "";
	}
	InputStream is = null;
	String responseData = "";
	try {
		is = entity.getContent();
		responseData = IOUtils.toString(is, "UTF-8");
	} finally {
		if (is != null) {
			is.close();
		}
	}
	return responseData;
}
 
Example 13
Project: lams   File: RequestConnControl.java   View source code 6 votes vote down vote up
public void process(final HttpRequest request, final HttpContext context)
        throws HttpException, IOException {
    if (request == null) {
        throw new IllegalArgumentException("HTTP request may not be null");
    }

    String method = request.getRequestLine().getMethod();
    if (method.equalsIgnoreCase("CONNECT")) {
        return;
    }

    if (!request.containsHeader(HTTP.CONN_DIRECTIVE)) {
        // Default policy is to keep connection alive
        // whenever possible
        request.addHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
    }
}
 
Example 14
Project: lams   File: HttpService.java   View source code 6 votes vote down vote up
/**
 * Handles the given exception and generates an HTTP response to be sent
 * back to the client to inform about the exceptional condition encountered
 * in the course of the request processing.
 *
 * @param ex the exception.
 * @param response the HTTP response.
 */
protected void handleException(final HttpException ex, final HttpResponse response) {
    if (ex instanceof MethodNotSupportedException) {
        response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED);
    } else if (ex instanceof UnsupportedHttpVersionException) {
        response.setStatusCode(HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED);
    } else if (ex instanceof ProtocolException) {
        response.setStatusCode(HttpStatus.SC_BAD_REQUEST);
    } else {
        response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
    }
    String message = ex.getMessage();
    if (message == null) {
        message = ex.toString();
    }
    byte[] msg = EncodingUtils.getAsciiBytes(message);
    ByteArrayEntity entity = new ByteArrayEntity(msg);
    entity.setContentType("text/plain; charset=US-ASCII");
    response.setEntity(entity);
}
 
Example 15
Project: vscrawler   File: ProxyFeedBackClientExecChain.java   View source code 6 votes vote down vote up
@Override
public CloseableHttpResponse execute(HttpRoute route, HttpRequestWrapper request, HttpClientContext clientContext,
        HttpExecutionAware execAware) throws IOException, HttpException {
    Proxy proxy = (Proxy) clientContext.getAttribute(VSCrawlerConstant.VSCRAWLER_AVPROXY_KEY);
    if (proxy != null) {
        proxy.recordUsage();
    }
    try {
        return delegate.execute(route, request, clientContext, execAware);
    } catch (IOException ioe) {
        if (proxy != null) {
            proxy.recordFailed();
        }
        throw ioe;
    }
}
 
Example 16
Project: lams   File: RequestExpectContinue.java   View source code 6 votes vote down vote up
public void process(final HttpRequest request, final HttpContext context)
        throws HttpException, IOException {
    if (request == null) {
        throw new IllegalArgumentException("HTTP request may not be null");
    }
    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity();
        // Do not send the expect header if request body is known to be empty
        if (entity != null && entity.getContentLength() != 0) {
            ProtocolVersion ver = request.getRequestLine().getProtocolVersion();
            if (HttpProtocolParams.useExpectContinue(request.getParams())
                    && !ver.lessEquals(HttpVersion.HTTP_1_0)) {
                request.addHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE);
            }
        }
    }
}
 
Example 17
Project: vrops-export   File: Exporter.java   View source code 6 votes vote down vote up
public Exporter(String urlBase, String username, String password, int threads, Config conf, boolean verbose, boolean useTempFile, int maxRows,
		KeyStore extendedTrust)
		throws IOException, HttpException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException, ExporterException {
	if(conf != null)  {
		this.rspFactory = rspFactories.get(conf.getOutputFormat());
		if(rspFactory == null)
			throw new ExporterException("Unknown output format: " + conf.getOutputFormat());
	}
		
	
	this.verbose = verbose;
	this.useTempFile = useTempFile;
	this.conf = conf;
	this.maxRows = maxRows;
	this.client = new Client(urlBase, username, password, threads, extendedTrust);
	
	// Calling this with a null conf is only valid if we're printing field names and nothing else. 
	// Everything else will crash miserably! (Yeah, this is a bit of a hack...)
	//
	if(conf != null) {
		this.registerFields();
	}
	this.executor = new ThreadPoolExecutor(threads, threads, 5, TimeUnit.SECONDS,
				new ArrayBlockingQueue<>(20), new ThreadPoolExecutor.CallerRunsPolicy());
}
 
Example 18
Project: lams   File: EntitySerializer.java   View source code 6 votes vote down vote up
/**
 * Writes out the content of the given HTTP entity to the session output
 * buffer based on properties of the given HTTP message.
 *
 * @param outbuffer the output session buffer.
 * @param message the HTTP message.
 * @param entity the HTTP entity to be written out.
 * @throws HttpException in case of HTTP protocol violation.
 * @throws IOException in case of an I/O error.
 */
public void serialize(
        final SessionOutputBuffer outbuffer,
        final HttpMessage message,
        final HttpEntity entity) throws HttpException, IOException {
    if (outbuffer == null) {
        throw new IllegalArgumentException("Session output buffer may not be null");
    }
    if (message == null) {
        throw new IllegalArgumentException("HTTP message may not be null");
    }
    if (entity == null) {
        throw new IllegalArgumentException("HTTP entity may not be null");
    }
    OutputStream outstream = doSerialize(outbuffer, message);
    entity.writeTo(outstream);
    outstream.close();
}
 
Example 19
Project: boohee_v5.6   File: AsyncHttpClient$3.java   View source code 6 votes vote down vote up
public void process(HttpRequest request, HttpContext context) throws HttpException,
        IOException {
    AuthState authState = (AuthState) context.getAttribute("http.auth.target-scope");
    CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute("http.auth" +
            ".credentials-provider");
    HttpHost targetHost = (HttpHost) context.getAttribute("http.target_host");
    if (authState.getAuthScheme() == null) {
        Credentials creds = credsProvider.getCredentials(new AuthScope(targetHost.getHostName
                (), targetHost.getPort()));
        if (creds != null) {
            authState.setAuthScheme(new BasicScheme());
            authState.setCredentials(creds);
        }
    }
}
 
Example 20
Project: cyberduck   File: OAuth2RequestInterceptor.java   View source code 6 votes vote down vote up
@Override
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    if(tokens.isExpired()) {
        try {
            tokens = this.refresh(tokens);
        }
        catch(BackgroundException e) {
            log.warn(String.format("Failure refreshing OAuth 2 tokens. %s", e.getDetail()));
            throw new IOException(e);
        }
    }
    if(StringUtils.isNotBlank(tokens.getAccessToken())) {
        if(log.isInfoEnabled()) {
            log.info(String.format("Authorizing service request with OAuth2 access token %s", tokens.getAccessToken()));
        }
        request.removeHeaders(HttpHeaders.AUTHORIZATION);
        request.addHeader(new BasicHeader(HttpHeaders.AUTHORIZATION, String.format("Bearer %s", tokens.getAccessToken())));
    }
}
 
Example 21
Project: cyberduck   File: B2ErrorResponseInterceptor.java   View source code 6 votes vote down vote up
@Override
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    if(StringUtils.contains(request.getRequestLine().getUri(), "b2_authorize_account")) {
        // Skip setting token for
        if(log.isDebugEnabled()) {
            log.debug("Skip setting token in b2_authorize_account");
        }
        return;
    }
    switch(request.getRequestLine().getMethod()) {
        case "POST":
            // Do not override Authorization header for upload requests with upload URL token
            break;
        default:
            if(StringUtils.isNotBlank(authorizationToken)) {
                request.removeHeaders(HttpHeaders.AUTHORIZATION);
                request.addHeader(HttpHeaders.AUTHORIZATION, authorizationToken);
            }
    }
}
 
Example 22
Project: vrops-export   File: TestStatsProcessor.java   View source code 5 votes vote down vote up
@Test
public void testProcess() throws IOException, ExporterException, HttpException  {
	Config conf = ConfigLoader.parse(new FileReader("testdata/vmfields.yaml"));
	StatsProcessor sp = new StatsProcessor(conf, null, new LRUCache<>(10), false);
	RowsetProcessor rp = new CSVPrinter(new BufferedWriter(new OutputStreamWriter(System.out)), new SimpleDateFormat("yyy-MM-dd HH:mm"), null, null, null);
	sp.process(new FileInputStream("testdata/stats.json"), rp, System.currentTimeMillis() - 300000, System.currentTimeMillis());
}
 
Example 23
Project: smart_plan   File: DataAndTableRequestHandler.java   View source code 5 votes vote down vote up
@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
    Log.d("plan", "DataAndTableRequestHandler");
    DataAndTableEntity entity = getDatabaseAndTable();
    if (entity == null) {
        entity = new DataAndTableEntity();
        entity.setCode(BaseEntity.FAILURE_CODE);
        entity.setDataList(new ArrayList<Map<String, List<SimpleNameEntity>>>());
    }
    response.setStatusCode(200);
    response.setEntity(new StringEntity(ParserJson.getSafeJsonStr(entity), "utf-8"));
}
 
Example 24
Project: outcomes   File: TestHttpCore.java   View source code 5 votes vote down vote up
@Test
public void test() throws ExecutionException, InterruptedException {


    HttpHost target = new HttpHost("localhost");
    BasicConnPool connpool = new BasicConnPool();
    connpool.setMaxTotal(200);
    connpool.setDefaultMaxPerRoute(10);
    connpool.setMaxPerRoute(target, 20);
    Future<BasicPoolEntry> future = connpool.lease(target, null);
    BasicPoolEntry poolEntry = future.get();
    HttpClientConnection conn = poolEntry.getConnection();

    HttpProcessor httpproc = HttpProcessorBuilder.create()
            .add(new ResponseDate())
            .add(new ResponseServer("MyServer-HTTP/1.1"))
            .add(new ResponseContent())
            .add(new ResponseConnControl())
            .build();

    HttpRequestHandler myRequestHandler = new HttpRequestHandler() {

        public void handle(
                HttpRequest request,
                HttpResponse response,
                HttpContext context) throws HttpException, IOException {
            response.setStatusCode(HttpStatus.SC_OK);
            response.setEntity(
                    new StringEntity("some important message",
                            ContentType.TEXT_PLAIN));
        }

    };

    UriHttpRequestHandlerMapper handlerMapper = new UriHttpRequestHandlerMapper();
    handlerMapper.register("/service/*", myRequestHandler);
    HttpService httpService = new HttpService(httpproc, handlerMapper);
}
 
Example 25
Project: ticketing-service-paqx-parent-sample   File: TicketingIntegrationService.java   View source code 5 votes vote down vote up
private Map post(String url, String data) throws IOException, HttpException {
	Map<String,Object> map = null;
	CredentialsProvider credentials = credentialsProvider();
	CloseableHttpClient httpclient = HttpClients.custom()
               .setDefaultCredentialsProvider(credentials)
               .build();

	try {
		HttpPost httpPost = new HttpPost(url);
 		httpPost.setHeader("Accept", "application/json");
 		httpPost.setHeader("Content-Type", "application/json");
        HttpEntity entity = new ByteArrayEntity(data.getBytes("utf-8"));
 		httpPost.setEntity(entity);
	        
	    System.out.println("Executing request " + httpPost.getRequestLine());
	    CloseableHttpResponse response = httpclient.execute(httpPost);
	    try {
	        LOG.debug("----------------------------------------");
	        LOG.debug((String)response.getStatusLine().getReasonPhrase());
	        String responseBody = EntityUtils.toString(response.getEntity());
	        LOG.debug(responseBody);
	        Gson gson = new Gson();
	        map = new HashMap<String,Object>();
			map = (Map<String,Object>) gson.fromJson(responseBody, map.getClass());
	        LOG.debug(responseBody);
	    } finally {
	        response.close();
	    }
	} finally {
	    httpclient.close();
	}

	return map;
}
 
Example 26
Project: cyberduck   File: UDTProxyConfigurator.java   View source code 5 votes vote down vote up
@Override
public HttpResponse execute(final HttpRequest request, final HttpClientConnection conn, final HttpContext context) throws IOException, HttpException {
    for(Header h : headers) {
        request.addHeader(new BasicHeader(h.getName(), h.getValue()));
    }
    return super.execute(request, conn, context);
}
 
Example 27
Project: ticketing-service-paqx-parent-sample   File: TicketingIntegrationService.java   View source code 5 votes vote down vote up
/**
 * 
 * Calls service now api to create a ticket
 *
 * @param message
 * @return
 * @throws IOException
 * @throws HttpException
 */
public String createTicket(TicketServiceRequest message) throws IOException, HttpException {
	
	LOG.debug("Create a service now ticket");
	String incidentId = "";
	String incidentTitle = "";
	String incidentNote = "";
	
	//fall back to using canned messages for demo purposes, if no ticket service request message
	if (message == null) {
		incidentTitle = "Test title";	
		incidentNote = "test note";
	} else {
		 incidentTitle = message.getTicketDetails().getIncidentTitle().replace('"',' ');
		 incidentNote = message.getTicketDetails().getIncidentNote().replace('"',' ');
	}
	

	// TODO CLEAN UP - example test code to create ServiceNow object
		// This must be valid json string with valid fields and values from table
 	String data = "{\"short_description\":\"" + incidentTitle + "\"}";
 	LOG.info("Received new incident: Title: '" + incidentTitle + "' Description: '" + incidentNote + "'");	
 	LOG.debug("POST data: " + data);
 	Map result = post("https://" + HOST+CREATE_URL, data);
 	incidentId = (String)((Map)result.get("result")).get("sys_id");
 	
 	INCIDENT = incidentId;	 
 	LOG.info("Created incident: " + incidentId);		
	return incidentId;
}
 
Example 28
Project: ticketing-service-paqx-parent-sample   File: TicketingIntegrationService.java   View source code 5 votes vote down vote up
/**
 * Calls service now api to update a ticket
 * 
 * @param message
 * @return
 * @throws IOException
 * @throws HttpException
 */

public String updateTicket(TicketServiceRequest message) throws IOException, HttpException {
	
	LOG.debug("Update a service now ticket");
	String incidentId = "";
	String incidentTitle = "";
	String incidentNote = "";
	
	//fall back to using canned messages for demo purposes, if no ticket service request message
	if (message == null) {
		incidentTitle = "Test title";	
		incidentNote = "test note added by Symphony";
		incidentId = INCIDENT;
	} else {
		incidentTitle = message.getTicketDetails().getIncidentTitle().replace('"',' ');
		incidentNote = message.getTicketDetails().getIncidentNote().replace('"',' ');
		incidentId = message.getTicketDetails().getIncidentId().replace('"',' ');
	}

	String data = "{\"element\": \"work_notes\"," +
						"\"element_id\": \"" + incidentId + "\"," +
   						"\"name\": \"task\"," +
   						"\"value\": \"" + incidentNote + "\"," +
						"}";
	LOG.debug("POST data: " + data);
	LOG.info("Updating incident: Title: '" + incidentTitle + "' Description: '" + incidentNote + "'");
 	Map result = post("https://" + HOST+NOTE_ADD_URL, data);	
 	LOG.info("Updated incident: " + incidentId);
	
	return "SUCCESS";
}
 
Example 29
Project: bitstd   File: HttpUtilManager.java   View source code 5 votes vote down vote up
public String requestHttpPost(String url_prex, String url, Map<String, String> params, String authorization)
		throws HttpException, IOException {

	url = url_prex + url;
	HttpPost method = this.httpPostMethod(url, authorization);
	String paramsstr = JSON.toJSONString(params);
	StringEntity sendEntity = new StringEntity(paramsstr);
	method.setEntity(sendEntity);
	method.setConfig(requestConfig);
	HttpEntity httpEntity = method.getEntity();
	for (int i = 0; i < method.getAllHeaders().length; i++) {
		Header header = method.getAllHeaders()[i];
	}

	HttpResponse response = client.execute(method);
	HttpEntity entity = response.getEntity();
	if (entity == null) {
		return "";
	}
	InputStream is = null;
	String responseData = "";
	try {
		is = entity.getContent();
		responseData = IOUtils.toString(is, "UTF-8");
	} finally {
		if (is != null) {
			is.close();
		}
	}
	return responseData;
}
 
Example 30
Project: PaoMovie   File: Logger.java   View source code 5 votes vote down vote up
public static void printStackTrace(String TAG, HttpException e) {
	if (IsDebug) {
		e.printStackTrace();
	} else {
		logException(TAG, e);
	}
}
 
Example 31
Project: JInsight   File: RequestExecutorBasedClientInstrumentationTest.java   View source code 5 votes vote down vote up
public HttpResponse doGET(URI url) throws IOException, HttpException {
  String uri = url.getRawPath() + (url.getRawQuery() != null ? "?" + url.getRawQuery() : "");
  HttpRequest request = new BasicHttpRequest("GET", uri);
  String hostHeader = (url.getPort() == 0 || url.getPort() == 80)
      ? url.getHost() : (url.getHost() + ":" + url.getPort());
  request.addHeader("Host", hostHeader);
  return execute(request);
}
 
Example 32
Project: Photato   File: PhotatoHandler.java   View source code 5 votes vote down vote up
@Override
public final void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
    if (!this.allowedVerbs.contains(request.getRequestLine().getMethod().toUpperCase())) {
        response.setStatusCode(http403.responseCode);
        response.setEntity(http403.entity);
    } else {
        Tuple<String, Map<String, String>> pathAndQueryTuple = PathHelper.splitPathAndQuery(request.getRequestLine().getUri().substring(this.prefix.length()));
        String path = pathAndQueryTuple.o1;

        Map<String, String> query = pathAndQueryTuple.o2;

        if (this.isAuthorized(path, query)) {
            try {
                Response res = getResponse(path, query);
                response.setStatusCode(res.responseCode);
                response.setHeaders(res.headers);
                response.setEntity(res.entity);
            } catch (Exception ex) {
                response.setStatusCode(http500.responseCode);
                response.setEntity(http500.entity);
                ex.printStackTrace();
            }
        } else {
            response.setStatusCode(http403.responseCode);
            response.setEntity(http403.entity);
        }
    }
}
 
Example 33
Project: karate   File: RequestLoggingInterceptor.java   View source code 5 votes vote down vote up
@Override
public void process(org.apache.http.HttpRequest request, HttpContext httpContext) throws HttpException, IOException {
    HttpRequest actual = new HttpRequest();
    int id = counter.incrementAndGet();
    String uri = (String) httpContext.getAttribute(ApacheHttpClient.URI_CONTEXT_KEY);
    String method = request.getRequestLine().getMethod();
    actual.setUri(uri);        
    actual.setMethod(method);
    StringBuilder sb = new StringBuilder();
    sb.append('\n').append(id).append(" > ").append(method).append(' ').append(uri).append('\n');
    LoggingUtils.logHeaders(sb, id, '>', request, actual);
    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request;
        HttpEntity entity = entityRequest.getEntity();
        if (LoggingUtils.isPrintable(entity)) {
            LoggingEntityWrapper wrapper = new LoggingEntityWrapper(entity); // todo optimize, preserve if stream
            if (context.logger.isDebugEnabled()) {
                String buffer = FileUtils.toString(wrapper.getContent());
                sb.append(buffer).append('\n');
            }
            actual.setBody(wrapper.getBytes());
            entityRequest.setEntity(wrapper);
        }
    }
    context.setPrevRequest(actual);
    if (context.logger.isDebugEnabled()) {
        context.logger.debug(sb.toString());
    }
}
 
Example 34
Project: BUbiNG   File: InfoWarcRecord.java   View source code 5 votes vote down vote up
private static Header[] readPayload(final BoundSessionInputBuffer buffer) throws IOException {
	try {
		return AbstractMessageParser.parseHeaders(buffer, -1, -1, null);
	} catch (HttpException e) {
		throw new WarcFormatException("Can't parse information", e);
	}
}
 
Example 35
Project: sling-org-apache-sling-testing-clients   File: StickyCookieInterceptor.java   View source code 5 votes vote down vote up
public void process(HttpRequest httpRequest, HttpContext httpContext) throws HttpException, IOException {
    final HttpClientContext clientContext = HttpClientContext.adapt(httpContext);
    List<Cookie> cookies = clientContext.getCookieStore().getCookies();
    boolean set = (null != StickyCookieHolder.getTestStickySessionCookie());
    boolean found = false;
    ListIterator<Cookie> it = cookies.listIterator();
    while (it.hasNext()) {
        Cookie cookie = it.next();
        if (cookie.getName().equals(StickyCookieHolder.COOKIE_NAME)) {
            found = true;
            if (set) {
                // set the cookie with the value saved for each thread using the rule
                it.set(StickyCookieHolder.getTestStickySessionCookie());
            } else {
                // if the cookie is not set in TestStickySessionRule, remove it from here
                it.remove();
            }
        }
    }
    // if the cookie needs to be set from TestStickySessionRule but did not exist in the client cookie list, add it here.
    if (!found && set) {
        cookies.add(StickyCookieHolder.getTestStickySessionCookie());
    }
    BasicCookieStore cs = new BasicCookieStore();
    cs.addCookies(cookies.toArray(new Cookie[cookies.size()]));
    httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cs);
}
 
Example 36
Project: sling-org-apache-sling-testing-clients   File: DelayRequestInterceptor.java   View source code 5 votes vote down vote up
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
    if (milliseconds <= 0) {
        return;
    }

    try {
        Thread.sleep(milliseconds);
    } catch (InterruptedException e) {
        throw new InterruptedIOException();
    }
}
 
Example 37
Project: sling-org-apache-sling-testing-clients   File: SlingClientWaitExistsTest.java   View source code 5 votes vote down vote up
@Override
protected void registerHandlers() throws IOException {
    serverBootstrap.registerHandler(GET_WAIT_PATH + ".json", new HttpRequestHandler() {
        @Override
        public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
            callCount++;
            if (callCount == waitCount) {
                response.setEntity(new StringEntity(OK_RESPONSE));
            } else {
                response.setEntity(new StringEntity(NOK_RESPONSE));
                response.setStatusCode(404);
            }
        }
    });
}
 
Example 38
Project: orange-mathoms-logging   File: HttpRequestHandlerWithMdcPropagation.java   View source code 5 votes vote down vote up
@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
	for (Entry<String, String> e : mdcName2HeaderName.entrySet()) {
		String mdcValue = MDC.get(e.getKey());
		if (mdcValue != null) {
			request.addHeader(new BasicHeader(e.getValue(), mdcValue));
		}
	}
}
 
Example 39
Project: lams   File: RequestTargetAuthentication.java   View source code 5 votes vote down vote up
public void process(final HttpRequest request, final HttpContext context)
        throws HttpException, IOException {
    if (request == null) {
        throw new IllegalArgumentException("HTTP request may not be null");
    }
    if (context == null) {
        throw new IllegalArgumentException("HTTP context may not be null");
    }

    String method = request.getRequestLine().getMethod();
    if (method.equalsIgnoreCase("CONNECT")) {
        return;
    }

    if (request.containsHeader(AUTH.WWW_AUTH_RESP)) {
        return;
    }

    // Obtain authentication state
    AuthState authState = (AuthState) context.getAttribute(
            ClientContext.TARGET_AUTH_STATE);
    if (authState == null) {
        this.log.debug("Target auth state not set in the context");
        return;
    }
    if (this.log.isDebugEnabled()) {
        this.log.debug("Target auth state: " + authState.getState());
    }
    process(authState, request, context);
}
 
Example 40
Project: lams   File: RequestClientConnControl.java   View source code 5 votes vote down vote up
public void process(final HttpRequest request, final HttpContext context)
        throws HttpException, IOException {
    if (request == null) {
        throw new IllegalArgumentException("HTTP request may not be null");
    }

    String method = request.getRequestLine().getMethod();
    if (method.equalsIgnoreCase("CONNECT")) {
        request.setHeader(PROXY_CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
        return;
    }

    // Obtain the client connection (required)
    HttpRoutedConnection conn = (HttpRoutedConnection) context.getAttribute(
            ExecutionContext.HTTP_CONNECTION);
    if (conn == null) {
        this.log.debug("HTTP connection not set in the context");
        return;
    }

    HttpRoute route = conn.getRoute();

    if (route.getHopCount() == 1 || route.isTunnelled()) {
        if (!request.containsHeader(HTTP.CONN_DIRECTIVE)) {
            request.addHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
        }
    }
    if (route.getHopCount() == 2 && !route.isTunnelled()) {
        if (!request.containsHeader(PROXY_CONN_DIRECTIVE)) {
            request.addHeader(PROXY_CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
        }
    }
}