Java Code Examples for org.apache.http.client.HttpResponseException

The following are top voted examples for showing how to use org.apache.http.client.HttpResponseException. 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: boohee_v5.6   File: RangeFileAsyncHttpResponseHandler.java   View source code 7 votes vote down vote up
public void sendResponseMessage(HttpResponse response) throws IOException {
    if (!Thread.currentThread().isInterrupted()) {
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() == 416) {
            if (!Thread.currentThread().isInterrupted()) {
                sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), null);
            }
        } else if (status.getStatusCode() >= 300) {
            if (!Thread.currentThread().isInterrupted()) {
                sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null,
                        new HttpResponseException(status.getStatusCode(), status
                                .getReasonPhrase()));
            }
        } else if (!Thread.currentThread().isInterrupted()) {
            Header header = response.getFirstHeader(AsyncHttpClient.HEADER_CONTENT_RANGE);
            if (header == null) {
                this.append = false;
                this.current = 0;
            } else {
                Log.v(LOG_TAG, "Content-Range: " + header.getValue());
            }
            sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(),
                    getResponseData(response.getEntity()));
        }
    }
}
 
Example 2
Project: sealtalk-android-master   File: BinaryHttpResponseHandler.java   View source code 7 votes vote down vote up
@Override
public final void sendResponseMessage(HttpResponse response) throws IOException {
    StatusLine status = response.getStatusLine();
    Header[] contentTypeHeaders = response.getHeaders("Content-Type");
    if (contentTypeHeaders.length != 1) {
        //malformed/ambiguous HTTP Header, ABORT!
        sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException(status.getStatusCode(), "None, or more than one, Content-Type Header found!"));
        return;
    }
    Header contentTypeHeader = contentTypeHeaders[0];
    boolean foundAllowedContentType = false;
    for (String anAllowedContentType : getAllowedContentTypes()) {
        try {
            if (Pattern.matches(anAllowedContentType, contentTypeHeader.getValue())) {
                foundAllowedContentType = true;
            }
        } catch (PatternSyntaxException e) {
        }
    }
    if (!foundAllowedContentType) {
        //Content-Type not in allowed list, ABORT!
        sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException(status.getStatusCode(), "Content-Type not allowed!"));
        return;
    }
    super.sendResponseMessage(response);
}
 
Example 3
Project: airtable.java   File: TableConverterTest.java   View source code 6 votes vote down vote up
@Test
public void testConvertMovie() throws AirtableException, HttpResponseException {

    
    Table<Movie> movieTable = base.table("Movies", Movie.class);
    Movie movie = movieTable.find("recFj9J78MLtiFFMz");
    assertNotNull(movie);
    
    assertEquals(movie.getId(),"recFj9J78MLtiFFMz");
    assertEquals(movie.getName(),"The Godfather");
    assertEquals(movie.getPhotos().size(),2);
    assertEquals(movie.getDirector().size(),1);
    assertEquals(movie.getActors().size(),2);
    assertEquals(movie.getGenre().size(),1);
    //TODO Test für Datum
              
}
 
Example 4
Project: airtable.java   File: TableConverterTest.java   View source code 6 votes vote down vote up
@Test
public void testConvertAttachement() throws AirtableException, HttpResponseException {

    
    Table<Movie> movieTable = base.table("Movies", Movie.class);
    Movie movie = movieTable.find("recFj9J78MLtiFFMz");
    assertNotNull(movie);
    
    assertEquals(movie.getPhotos().size(),2);
    
    Attachment photo1 = movie.getPhotos().get(0);
    assertNotNull(photo1);
    Attachment photo2 = movie.getPhotos().get(0);
    assertNotNull(photo2);
    
    assertEquals(photo1.getId(),"attk3WY5B28GVcFGU");
    assertEquals(photo1.getUrl(),"https://dl.airtable.com/9UhUUeAtSym1PzBdA0q0_AlPacinoandMarlonBrando.jpg");
    assertEquals(photo1.getFilename(),"AlPacinoandMarlonBrando.jpg");
    assertEquals(photo1.getSize(),35698,0);
    assertEquals(photo1.getType(),"image/jpeg");
    assertEquals(photo1.getThumbnails().size(),2);
    
}
 
Example 5
Project: airtable.java   File: TableConverterTest.java   View source code 6 votes vote down vote up
@Test
public void testConvertThumbnails() throws AirtableException, HttpResponseException {
            
    Table<Movie> movieTable = base.table("Movies", Movie.class);
    Movie movie = movieTable.find("recFj9J78MLtiFFMz");
    assertNotNull(movie);
    
    assertEquals(movie.getPhotos().get(0).getThumbnails().size(),2);
    assertEquals(movie.getPhotos().get(1).getThumbnails().size(),2);
    Map<String, Thumbnail> thumbnails = movie.getPhotos().get(1).getThumbnails();
    Thumbnail thumb = thumbnails.get("small");
    assertEquals(thumb.getUrl(),"https://dl.airtable.com/rlQ8MyQ4RuqN7rT03ALq_small_The%20Godfather%20poster.jpg");
    assertEquals(thumb.getHeight(),36.0, 0);
    assertEquals(thumb.getWidth(),24.0, 0);
    
}
 
Example 6
Project: airtable.java   File: TableSelectJacksonOMTest.java   View source code 6 votes vote down vote up
@Test
public void testSelectTableSorted() throws AirtableException, HttpResponseException {

    Table table = base.table("Movies", Movie.class);

    List<Movie> retval = table.select(new Sort("Name", Sort.Direction.asc));
    assertNotNull(retval);
    assertEquals(9, retval.size());
    Movie mov = retval.get(0);
    assertEquals("Billy Madison", mov.getName());

    retval = table.select(new Sort("Name", Sort.Direction.desc));
    assertNotNull(retval);
    assertEquals(9, retval.size());
    mov = retval.get(0);
    assertEquals("You've Got Mail", mov.getName());

}
 
Example 7
Project: airtable.java   File: TableSelectTest.java   View source code 6 votes vote down vote up
@Test
public void testSelectTableSorted() throws AirtableException, HttpResponseException {

    Table table = base.table("Movies", Movie.class);

    List<Movie> retval = table.select(new Sort("Name", Sort.Direction.asc));
    assertNotNull(retval);
    assertEquals(9, retval.size());
    Movie mov = retval.get(0);
    assertEquals("Billy Madison", mov.getName());

    retval = table.select(new Sort("Name", Sort.Direction.desc));
    assertNotNull(retval);
    assertEquals(9, retval.size());
    mov = retval.get(0);
    assertEquals("You've Got Mail", mov.getName());

}
 
Example 8
Project: airtable.java   File: TableParameterTest.java   View source code 6 votes vote down vote up
@Test
public void fieldsParamTest() throws AirtableException, HttpResponseException {

    Table<Movie> movieTable = base.table("Movies", Movie.class);

    String[] fields = new String[1];
    fields[0] = "Name";

    List<Movie> listMovies = movieTable.select(fields);
    assertNotNull(listMovies);
    assertNotNull(listMovies.get(0).getName());
    assertNull(listMovies.get(0).getDirector());
    assertNull(listMovies.get(0).getActors());
    assertNull(listMovies.get(0).getDescription());

}
 
Example 9
Project: write_api_service   File: ResourceUtilities.java   View source code 6 votes vote down vote up
public static Optional<String> getResponseAsString(HttpRequestBase httpRequest, HttpClient client) {
    Optional<String> result = Optional.empty();
    final int waitTime = 60000;
    try {
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(waitTime).setConnectTimeout(waitTime)
                .setConnectionRequestTimeout(waitTime).build();
        httpRequest.setConfig(requestConfig);
        result = Optional.of(client.execute(httpRequest, responseHandler));
    } catch (HttpResponseException httpResponseException) {
        LOG.error("getResponseAsString(): caught 'HttpResponseException' while processing request <{}> :=> <{}>", httpRequest,
                httpResponseException.getMessage());
    } catch (IOException ioe) {
        LOG.error("getResponseAsString(): caught 'IOException' while processing request <{}> :=> <{}>", httpRequest, ioe.getMessage());
    } finally {
        httpRequest.releaseConnection();
    }
    return result;
}
 
Example 10
Project: jfrog-idea-plugin   File: XrayImpl.java   View source code 6 votes vote down vote up
private HttpResponse setHeadersAndExecute(HttpUriRequest request, Map<String, String> headers) throws IOException {
    setHeaders(request, headers);
    HttpResponse response = client.execute(request);
    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    if (statusNotOk(statusCode)) {
        String body = null;
        if (response.getEntity() != null) {
            try {
                body = readStream(response.getEntity().getContent());
                EntityUtils.consume(response.getEntity());
            } catch (IOException e) {
                // Ignore
            }
        }
        String message = String.format("Received %d %s response from Xray", statusCode, statusLine);
        if (StringUtils.isNotBlank(body)) {
            message += ". " + body;
        }
        throw new HttpResponseException(statusCode, message);
    }
    return response;
}
 
Example 11
Project: boohee_v5.6   File: AsyncHttpResponseHandler.java   View source code 6 votes vote down vote up
public void sendResponseMessage(HttpResponse response) throws IOException {
    if (!Thread.currentThread().isInterrupted()) {
        StatusLine status = response.getStatusLine();
        byte[] responseBody = getResponseData(response.getEntity());
        if (!Thread.currentThread().isInterrupted()) {
            if (status.getStatusCode() >= 300) {
                sendFailureMessage(status.getStatusCode(), response.getAllHeaders(),
                        responseBody, new HttpResponseException(status.getStatusCode(),
                                status.getReasonPhrase()));
            } else {
                sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(),
                        responseBody);
            }
        }
    }
}
 
Example 12
Project: sealtalk-android-master   File: AsyncHttpResponseHandler.java   View source code 6 votes vote down vote up
@Override
public void sendResponseMessage(HttpResponse response) throws IOException {
    // do not process if request has been cancelled
    if (!Thread.currentThread().isInterrupted()) {
        StatusLine status = response.getStatusLine();
        byte[] responseBody;
        responseBody = getResponseData(response.getEntity());
        // additional cancellation check as getResponseData() can take non-zero time to process
        if (!Thread.currentThread().isInterrupted()) {
            if (status.getStatusCode() >= 300) {
                sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), responseBody, new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()));
            } else {
                sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody);
            }
        }
    }
}
 
Example 13
Project: android-project-gallery   File: AsyncHttpResponseHandler.java   View source code 6 votes vote down vote up
@Override
public void sendResponseMessage(HttpResponse response) throws IOException {
    // do not process if request has been cancelled
    if (!Thread.currentThread().isInterrupted()) {
        StatusLine status = response.getStatusLine();
        byte[] responseBody;
        responseBody = getResponseData(response.getEntity());
        // additional cancellation check as getResponseData() can take non-zero time to process
        if (!Thread.currentThread().isInterrupted()) {
            if (status.getStatusCode() >= 300) {
                sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), responseBody, new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()));
            } else {
                sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody);
            }
        }
    }
}
 
Example 14
Project: android-project-gallery   File: RangeFileAsyncHttpResponseHandler.java   View source code 6 votes vote down vote up
@Override
public void sendResponseMessage(HttpResponse response) throws IOException {
    if (!Thread.currentThread().isInterrupted()) {
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() == HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE) {
            //already finished
            if (!Thread.currentThread().isInterrupted())
                sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), null);
        } else if (status.getStatusCode() >= 300) {
            if (!Thread.currentThread().isInterrupted())
                sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()));
        } else {
            if (!Thread.currentThread().isInterrupted()) {
                Header header = response.getFirstHeader(AsyncHttpClient.HEADER_CONTENT_RANGE);
                if (header == null) {
                    append = false;
                    current = 0;
                } else
                    Log.v(LOG_TAG, AsyncHttpClient.HEADER_CONTENT_RANGE + ": " + header.getValue());
                sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), getResponseData(response.getEntity()));
            }
        }
    }
}
 
Example 15
Project: rongyunDemo   File: AsyncHttpResponseHandler.java   View source code 6 votes vote down vote up
@Override
public void sendResponseMessage(HttpResponse response) throws IOException {
    // do not process if request has been cancelled
    if (!Thread.currentThread().isInterrupted()) {
        StatusLine status = response.getStatusLine();
        byte[] responseBody;
        responseBody = getResponseData(response.getEntity());
        // additional cancellation check as getResponseData() can take non-zero time to process
        if (!Thread.currentThread().isInterrupted()) {
            if (status.getStatusCode() >= 300) {
                sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), responseBody, new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()));
            } else {
                sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody);
            }
        }
    }
}
 
Example 16
Project: rongyunDemo   File: BinaryHttpResponseHandler.java   View source code 6 votes vote down vote up
@Override
public final void sendResponseMessage(HttpResponse response) throws IOException {
    StatusLine status = response.getStatusLine();
    Header[] contentTypeHeaders = response.getHeaders("Content-Type");
    if (contentTypeHeaders.length != 1) {
        //malformed/ambiguous HTTP Header, ABORT!
        sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException(status.getStatusCode(), "None, or more than one, Content-Type Header found!"));
        return;
    }
    Header contentTypeHeader = contentTypeHeaders[0];
    boolean foundAllowedContentType = false;
    for (String anAllowedContentType : getAllowedContentTypes()) {
        try {
            if (Pattern.matches(anAllowedContentType, contentTypeHeader.getValue())) {
                foundAllowedContentType = true;
            }
        } catch (PatternSyntaxException e) {
        }
    }
    if (!foundAllowedContentType) {
        //Content-Type not in allowed list, ABORT!
        sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException(status.getStatusCode(), "Content-Type not allowed!"));
        return;
    }
    super.sendResponseMessage(response);
}
 
Example 17
Project: Mobike   File: AsyncHttpResponseHandler.java   View source code 6 votes vote down vote up
@Override
public void sendResponseMessage(HttpResponse response) throws IOException {
    // do not process if request has been cancelled
    if (!Thread.currentThread().isInterrupted()) {
        StatusLine status = response.getStatusLine();
        byte[] responseBody;
        responseBody = getResponseData(response.getEntity());
        // additional cancellation check as getResponseData() can take non-zero time to process
        if (!Thread.currentThread().isInterrupted()) {
            if (status.getStatusCode() >= 300) {
                sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), responseBody, new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()));
            } else {
                sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody);
            }
        }
    }
}
 
Example 18
Project: Mobike   File: RangeFileAsyncHttpResponseHandler.java   View source code 6 votes vote down vote up
@Override
public void sendResponseMessage(HttpResponse response) throws IOException {
    if (!Thread.currentThread().isInterrupted()) {
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() == HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE) {
            //already finished
            if (!Thread.currentThread().isInterrupted())
                sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), null);
        } else if (status.getStatusCode() >= 300) {
            if (!Thread.currentThread().isInterrupted())
                sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()));
        } else {
            if (!Thread.currentThread().isInterrupted()) {
                Header header = response.getFirstHeader(AsyncHttpClient.HEADER_CONTENT_RANGE);
                if (header == null) {
                    append = false;
                    current = 0;
                } else {
                    Log.v(LOG_TAG, AsyncHttpClient.HEADER_CONTENT_RANGE + ": " + header.getValue());
                }
                sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), getResponseData(response.getEntity()));
            }
        }
    }
}
 
Example 19
Project: geoportal-server-harvester   File: WafFile.java   View source code 6 votes vote down vote up
/**
 * Reads content.
 * @param httpClient HTTP client
 * @param since since date
 * @return content reference
 * @throws IOException if reading content fails
 * @throws URISyntaxException if file url is an invalid URI
 */
public SimpleDataReference readContent(CloseableHttpClient httpClient, Date since) throws IOException, URISyntaxException {
  HttpGet method = new HttpGet(fileUrl.toExternalForm());
  method.setConfig(DEFAULT_REQUEST_CONFIG);
  method.setHeader("User-Agent", HttpConstants.getUserAgent());
  HttpClientContext context = creds!=null && !creds.isEmpty()? createHttpClientContext(fileUrl, creds): null;
  
  try (CloseableHttpResponse httpResponse = httpClient.execute(method,context); InputStream input = httpResponse.getEntity().getContent();) {
    if (httpResponse.getStatusLine().getStatusCode()>=400) {
      throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase());
    }
    Date lastModifiedDate = readLastModifiedDate(httpResponse);
    MimeType contentType = readContentType(httpResponse);
    boolean readBody = since==null || lastModifiedDate==null || lastModifiedDate.getTime()>=since.getTime();
    SimpleDataReference ref = new SimpleDataReference(broker.getBrokerUri(), broker.getEntityDefinition().getLabel(), fileUrl.toExternalForm(), lastModifiedDate, fileUrl.toURI());
    ref.addContext(contentType, readBody? IOUtils.toByteArray(input): null);
    return ref;
  }
}
 
Example 20
Project: geoportal-server-harvester   File: HtmlUrlScrapper.java   View source code 6 votes vote down vote up
/**
 * Scrap HTML page for URL's
 * @param root root of the page
 * @return list of found URL's
 * @throws IOException if error reading data
 * @throws URISyntaxException if invalid URL
 */
public List<URL> scrap(URL root) throws IOException, URISyntaxException {
  ContentAnalyzer analyzer = new ContentAnalyzer(root);
  HttpGet method = new HttpGet(root.toExternalForm());
  method.setConfig(DEFAULT_REQUEST_CONFIG);
  method.setHeader("User-Agent", HttpConstants.getUserAgent());
  HttpClientContext context = creds!=null && !creds.isEmpty()? createHttpClientContext(root, creds): null;
  
  try (CloseableHttpResponse httpResponse = httpClient.execute(method, context); InputStream input = httpResponse.getEntity().getContent();) {
    if (httpResponse.getStatusLine().getStatusCode()>=400) {
      throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase());
    }
    String content = IOUtils.toString(input, "UTF-8");
    return analyzer.analyze(content);
  }
}
 
Example 21
Project: geoportal-server-harvester   File: Client.java   View source code 6 votes vote down vote up
private <T> T execute(HttpUriRequest req, Class<T> clazz) throws IOException, URISyntaxException {
  try (CloseableHttpResponse httpResponse = httpClient.execute(req); InputStream contentStream = httpResponse.getEntity().getContent();) {
    String reasonMessage = httpResponse.getStatusLine().getReasonPhrase();
    String responseContent = IOUtils.toString(contentStream, "UTF-8");
    LOG.trace(String.format("RESPONSE: %s, %s", responseContent, reasonMessage));

    if (httpResponse.getStatusLine().getStatusCode() >= 400) {
      T value = null;
      try {
        value = mapper.readValue(responseContent, clazz);
      } catch (Exception ex) {
        throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase());
      }
      if (value == null) {
        throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase());
      }
      return value;
    }

    return mapper.readValue(responseContent, clazz);
  }
}
 
Example 22
Project: geoportal-server-harvester   File: GeometryService.java   View source code 6 votes vote down vote up
public MultiPoint project(MultiPoint mp, int fromWkid, int toWkid) throws IOException, URISyntaxException {
  HttpPost request = new HttpPost(createProjectUrl().toURI());
  
  HashMap<String, String> params = new HashMap<>();
  params.put("f", "json");
  params.put("inSR", Integer.toString(fromWkid));
  params.put("outSR", Integer.toString(toWkid));
  params.put("geometries", createGeometries(mp));
  
  HttpEntity entrity = new UrlEncodedFormEntity(params.entrySet().stream()
          .map(e -> new BasicNameValuePair(e.getKey(), e.getValue())).collect(Collectors.toList()), "UTF-8");
  request.setEntity(entrity);
  
  try (CloseableHttpResponse httpResponse = httpClient.execute(request); InputStream contentStream = httpResponse.getEntity().getContent();) {
    if (httpResponse.getStatusLine().getStatusCode()>=400) {
      throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase());
    }
    MultiPointGeometry geom = mapper.readValue(contentStream, MultiPointGeometry.class);
    MultiPoint result  = new MultiPoint();
    geom.geometries[0].points.forEach(pt->result.add(pt[0], pt[1]));
    return result;
  }
}
 
Example 23
Project: geoportal-server-harvester   File: AgsClient.java   View source code 6 votes vote down vote up
/**
 * Lists folder content.
 *
 * @param folder folder or <code>null</code>
 * @return content response
 * @throws URISyntaxException if invalid URL
 * @throws IOException if accessing token fails
 */
public ContentResponse listContent(String folder) throws URISyntaxException, IOException {
  String url = rootUrl.toURI().resolve("rest/services/").resolve(StringUtils.stripToEmpty(folder)).toASCIIString();
  HttpGet get = new HttpGet(url + String.format("?f=%s", "json"));

  try (CloseableHttpResponse httpResponse = httpClient.execute(get); InputStream contentStream = httpResponse.getEntity().getContent();) {
    if (httpResponse.getStatusLine().getStatusCode()>=400) {
      throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase());
    }
    String responseContent = IOUtils.toString(contentStream, "UTF-8");
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    ContentResponse response = mapper.readValue(responseContent, ContentResponse.class);
    response.url = url;
    return response;
  }
}
 
Example 24
Project: geoportal-server-harvester   File: AgsClient.java   View source code 6 votes vote down vote up
/**
 * Reads service information.
 *
 * @param folder folder
 * @param si service info obtained through {@link listContent}
 * @return service response
 * @throws URISyntaxException if invalid URL
 * @throws IOException if accessing token fails
 */
public ServerResponse readServiceInformation(String folder, ServiceInfo si) throws URISyntaxException, IOException {
  String url = rootUrl.toURI().resolve("rest/services/").resolve(StringUtils.stripToEmpty(folder)).resolve(si.name + "/" + si.type).toASCIIString();
  HttpGet get = new HttpGet(url + String.format("?f=%s", "json"));

  try (CloseableHttpResponse httpResponse = httpClient.execute(get); InputStream contentStream = httpResponse.getEntity().getContent();) {
    if (httpResponse.getStatusLine().getStatusCode()>=400) {
      throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase());
    }
    String responseContent = IOUtils.toString(contentStream, "UTF-8");
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.configure(Feature.ALLOW_NON_NUMERIC_NUMBERS, true);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    ServerResponse response = mapper.readValue(responseContent, ServerResponse.class);
    response.url = url;
    response.json = responseContent;
    return response;
  }
}
 
Example 25
Project: geoportal-server-harvester   File: AgsClient.java   View source code 6 votes vote down vote up
/**
 * Reads layer information.
 *
 * @param folder folder
 * @param si service info obtained through {@link listContent}
 * @param lRef layer reference
 * @return service response
 * @throws URISyntaxException if invalid URL
 * @throws IOException if accessing token fails
 */
public LayerInfo readLayerInformation(String folder, ServiceInfo si, LayerRef lRef) throws URISyntaxException, IOException {
  String url = rootUrl.toURI().resolve("rest/services/").resolve(StringUtils.stripToEmpty(folder)).resolve(si.name + "/" + si.type + "/" + lRef.id).toASCIIString();
  HttpGet get = new HttpGet(url + String.format("?f=%s", "json"));

  try (CloseableHttpResponse httpResponse = httpClient.execute(get); InputStream contentStream = httpResponse.getEntity().getContent();) {
    if (httpResponse.getStatusLine().getStatusCode()>=400) {
      throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase());
    }
    String responseContent = IOUtils.toString(contentStream, "UTF-8");
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    LayerInfo response = mapper.readValue(responseContent, LayerInfo.class);
    response.url = url;
    response.json = responseContent;
    return response;
  }
}
 
Example 26
Project: geoportal-server-harvester   File: Client.java   View source code 6 votes vote down vote up
private Response execute(HttpUriRequest req) throws IOException, URISyntaxException {
  try (CloseableHttpResponse httpResponse = httpClient.execute(req); InputStream contentStream = httpResponse.getEntity().getContent();) {
    String reasonMessage = httpResponse.getStatusLine().getReasonPhrase();
    String responseContent = IOUtils.toString(contentStream, "UTF-8");
    LOG.trace(String.format("RESPONSE: %s, %s", responseContent, reasonMessage));
    
    if (httpResponse.getStatusLine().getStatusCode()>=400) {
      Response value = null;
      try {
        value = mapper.readValue(responseContent, Response.class);
      } catch (Exception ex) {
        throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase());
      }
      if (value==null) {
        throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase());
      }
      return value;
    }
    
    return mapper.readValue(responseContent, Response.class);
  }
}
 
Example 27
Project: RongCloudJcenter   File: AsyncHttpResponseHandler.java   View source code 6 votes vote down vote up
@Override
public void sendResponseMessage(HttpResponse response) throws IOException {
    // do not process if request has been cancelled
    if (!Thread.currentThread().isInterrupted()) {
        StatusLine status = response.getStatusLine();
        byte[] responseBody;
        responseBody = getResponseData(response.getEntity());
        // additional cancellation check as getResponseData() can take non-zero time to process
        if (!Thread.currentThread().isInterrupted()) {
            if (status.getStatusCode() >= 300) {
                sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), responseBody, new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()));
            } else {
                sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody);
            }
        }
    }
}
 
Example 28
Project: RongCloudJcenter   File: BinaryHttpResponseHandler.java   View source code 6 votes vote down vote up
@Override
public final void sendResponseMessage(HttpResponse response) throws IOException {
    StatusLine status = response.getStatusLine();
    Header[] contentTypeHeaders = response.getHeaders("Content-Type");
    if (contentTypeHeaders.length != 1) {
        //malformed/ambiguous HTTP Header, ABORT!
        sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException(status.getStatusCode(), "None, or more than one, Content-Type Header found!"));
        return;
    }
    Header contentTypeHeader = contentTypeHeaders[0];
    boolean foundAllowedContentType = false;
    for (String anAllowedContentType : getAllowedContentTypes()) {
        try {
            if (Pattern.matches(anAllowedContentType, contentTypeHeader.getValue())) {
                foundAllowedContentType = true;
            }
        } catch (PatternSyntaxException e) {
        }
    }
    if (!foundAllowedContentType) {
        //Content-Type not in allowed list, ABORT!
        sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException(status.getStatusCode(), "Content-Type not allowed!"));
        return;
    }
    super.sendResponseMessage(response);
}
 
Example 29
Project: TAG   File: AsyncHttpResponseHandler.java   View source code 6 votes vote down vote up
@Override
public void sendResponseMessage(HttpResponse response) throws IOException {
    // do not process if request has been cancelled
    if (!Thread.currentThread().isInterrupted()) {
        StatusLine status = response.getStatusLine();
        byte[] responseBody;
        responseBody = getResponseData(response.getEntity());
        // additional cancellation check as getResponseData() can take non-zero time to process
        if (!Thread.currentThread().isInterrupted()) {
            if (status.getStatusCode() >= 300) {
                sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), responseBody, new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()));
            } else {
                sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody);
            }
        }
    }
}
 
Example 30
Project: TAG   File: RangeFileAsyncHttpResponseHandler.java   View source code 6 votes vote down vote up
@Override
public void sendResponseMessage(HttpResponse response) throws IOException {
    if (!Thread.currentThread().isInterrupted()) {
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() == HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE) {
            //already finished
            if (!Thread.currentThread().isInterrupted())
                sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), null);
        } else if (status.getStatusCode() >= 300) {
            if (!Thread.currentThread().isInterrupted())
                sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()));
        } else {
            if (!Thread.currentThread().isInterrupted()) {
                Header header = response.getFirstHeader(AsyncHttpClient.HEADER_CONTENT_RANGE);
                if (header == null) {
                    append = false;
                    current = 0;
                } else
                    Log.v(LOG_TAG, AsyncHttpClient.HEADER_CONTENT_RANGE + ": " + header.getValue());
                sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), getResponseData(response.getEntity()));
            }
        }
    }
}
 
Example 31
Project: jenkins-test-job-generator   File: JenkinsHelper.java   View source code 6 votes vote down vote up
public void runJob(String test, JSONObject repository) throws Exception {
    String jobName = ConfigParser.parseConfigString(repository.getString("jobName"), test);
    Map<String, String> params = new HashMap<>();
    if (repository.has("buildParams")) {
        JSONObject buildParams = repository.getJSONObject("buildParams");
        Iterator keys = buildParams.keys();
        while (keys.hasNext()) {
            String key = (String) keys.next();
            params.put(key, buildParams.getString(key));
        }
        System.out.println("Running job with parameters [" + jobName + "]");
        runJob(test, repository, params);
    }
    else {
        System.out.println("Running job without parameters [" + jobName + "]");
        try {
            jenkins.getJob(jobName).build(crumbsFlag);
        } catch (HttpResponseException e) {
            System.out.println("Running job [" + jobName + "] without parameters failed, were there supposed to be parameters?");
            e.printStackTrace();
        }
    }
}
 
Example 32
Project: RongChat   File: AsyncHttpResponseHandler.java   View source code 6 votes vote down vote up
@Override
public void sendResponseMessage(HttpResponse response) throws IOException {
    // do not process if request has been cancelled
    if (!Thread.currentThread().isInterrupted()) {
        StatusLine status = response.getStatusLine();
        byte[] responseBody;
        responseBody = getResponseData(response.getEntity());
        // additional cancellation check as getResponseData() can take non-zero time to process
        if (!Thread.currentThread().isInterrupted()) {
            if (status.getStatusCode() >= 300) {
                sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), responseBody, new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()));
            } else {
                sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody);
            }
        }
    }
}
 
Example 33
Project: RongChat   File: BinaryHttpResponseHandler.java   View source code 6 votes vote down vote up
@Override
public final void sendResponseMessage(HttpResponse response) throws IOException {
    StatusLine status = response.getStatusLine();
    Header[] contentTypeHeaders = response.getHeaders("Content-Type");
    if (contentTypeHeaders.length != 1) {
        //malformed/ambiguous HTTP Header, ABORT!
        sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException(status.getStatusCode(), "None, or more than one, Content-Type Header found!"));
        return;
    }
    Header contentTypeHeader = contentTypeHeaders[0];
    boolean foundAllowedContentType = false;
    for (String anAllowedContentType : getAllowedContentTypes()) {
        try {
            if (Pattern.matches(anAllowedContentType, contentTypeHeader.getValue())) {
                foundAllowedContentType = true;
            }
        } catch (PatternSyntaxException e) {
        }
    }
    if (!foundAllowedContentType) {
        //Content-Type not in allowed list, ABORT!
        sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException(status.getStatusCode(), "Content-Type not allowed!"));
        return;
    }
    super.sendResponseMessage(response);
}
 
Example 34
Project: zest-writer   File: TestModel.java   View source code 6 votes vote down vote up
@Test
public void testImport() throws IOException {
    File workspace = new File(new File(TEST_DIR), "zworkspace");
    if(!workspace.exists()) {
        workspace.mkdirs();
    }
    String filePath = GithubHttp.getGithubZipball ("steeve", "france.code-civil", workspace.getAbsolutePath());
    File folder = GithubHttp.unzipOnlineContent (filePath, workspace.getAbsolutePath());
    File off = new File(workspace, "france.code-civil");
    assertTrue(off.exists());
    try {
        Content loadContent = GithubHttp.loadManifest(folder.getAbsolutePath(), "steeve", "france.code-civil");
        checkManifestAntislash(loadContent);
        assertNotNull(loadContent);
        assertNotNull(loadContent.getTitle());
        assertNotNull(loadContent.getFilePath());
        assertNotNull(loadContent.getType());
        assertNotNull(loadContent.getLicence());
        assertTrue(loadContent.getChildren().size() > 0);
    } catch(HttpResponseException hhtpe) {
        
    }
}
 
Example 35
Project: AndroidWear-OpenWear   File: AsyncHttpResponseHandler.java   View source code 6 votes vote down vote up
@Override
public void sendResponseMessage(HttpResponse response) throws IOException {
    // do not process if request has been cancelled
    if (!Thread.currentThread().isInterrupted()) {
        StatusLine status = response.getStatusLine();
        byte[] responseBody;
        responseBody = getResponseData(response.getEntity());
        // additional cancellation check as getResponseData() can take non-zero time to process
        if (!Thread.currentThread().isInterrupted()) {
            if (status.getStatusCode() >= 300) {
                sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), responseBody, new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()));
            } else {
                sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody);
            }
        }
    }
}
 
Example 36
Project: surgeon-sim   File: LoginController.java   View source code 6 votes vote down vote up
private void handleLoginError(Throwable e) {
    System.out.println("Login failed: " + e);

    if (e instanceof WrongPasswordException) {
        error.setText("Error logging in, wrong password.");
    } else if (e instanceof HttpResponseException) {
        HttpResponseException responseException = (HttpResponseException) e;
        if (responseException.getStatusCode() == 404) {
            error.setText("Error logging in, user doesn't exist.");
        } else {
            error.setText("Error logging in, " + responseException.getStatusCode() + " " + responseException.getMessage());
        }
    } else {
        error.setText("Error logging in, " + e + ".");
    }
}
 
Example 37
Project: diadocsdk-java   File: DiadocApi.java   View source code 6 votes vote down vote up
public boolean CanSendInvoice(String boxId, byte [] certBytes) throws IOException {
    if (Tools.IsNullOrEmpty(boxId)) throw new NullPointerException("boxId");
    if (certBytes == null || certBytes.length == 0) throw new NullPointerException("certBytes");
    List<NameValuePair> parameters = new ArrayList<NameValuePair>();
    parameters.add(new BasicNameValuePair("boxId", boxId));
    HttpResponse httpResponse = ReceivePostHttpResponse("/CanSendInvoice", parameters, certBytes);
    int statusCode = httpResponse.getStatusLine().getStatusCode();
    byte[] responseContent = IOUtils.toByteArray(httpResponse.getEntity().getContent());
    switch (statusCode)
    {
        case HttpStatus.SC_OK:
            return true;
        case HttpStatus.SC_FORBIDDEN:
            return false;
        default:
            throw new HttpResponseException(statusCode, new String(responseContent,"UTF8"));
    }
}
 
Example 38
Project: azkaban   File: ExecutorApiClient.java   View source code 6 votes vote down vote up
/**Implementing the parseResponse function to return de-serialized Json object.
 * @param response  the returned response from the HttpClient.
 * @return de-serialized object from Json or null if the response doesn't have a body.
 * */
@Override
protected String parseResponse(HttpResponse response)
    throws HttpResponseException, IOException {
  final StatusLine statusLine = response.getStatusLine();
  String responseBody = response.getEntity() != null ?
      EntityUtils.toString(response.getEntity()) : "";

  if (statusLine.getStatusCode() >= 300) {

      logger.error(String.format("unable to parse response as the response status is %s",
          statusLine.getStatusCode()));

      throw new HttpResponseException(statusLine.getStatusCode(),responseBody);
  }

  return responseBody;
}
 
Example 39
Project: hybris-commerce-eclipse-plugin   File: ImportManager.java   View source code 6 votes vote down vote up
/**
 * Send HTTP POST request to {@link #getEndpointUrl(), imports impex
 *
 * @param file
 *            file to be imported
 * @return import status message
 * @throws IOException
 * @throws HttpResponseException
 */
private String postImpex(final IFile file) throws HttpResponseException, IOException {
	final Map<String, String> parameters = new HashMap<>();
	final HttpPost postRequest = new HttpPost(getEndpointUrl() + ImpexImport.IMPEX_IMPORT_PATH);
	final RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(getTimeout()).build();
	
	parameters.put(ImpexImport.Parameters.ENCODING, getEncoding());
	parameters.put(ImpexImport.Parameters.SCRIPT_CONTENT, getContentOfFile(file));
	parameters.put(ImpexImport.Parameters.MAX_THREADS, ImpexImport.Parameters.MAX_THREADS_VALUE);
	parameters.put(ImpexImport.Parameters.VALIDATION_ENUM, ImpexImport.Parameters.VALIDATION_ENUM_VALUE);
	
	postRequest.setConfig(requestConfig);
	postRequest.addHeader(getxCsrfToken(), getCsrfToken());
	postRequest.setEntity(new UrlEncodedFormEntity(createParametersList(parameters)));
	
	final HttpResponse response = getHttpClient().execute(postRequest, getContext());
	final String responseBody = new BasicResponseHandler().handleResponse(response);
	
	return getImportStatus(responseBody);
}
 
Example 40
Project: sealtalk-android   File: AsyncHttpResponseHandler.java   View source code 6 votes vote down vote up
@Override
public void sendResponseMessage(HttpResponse response) throws IOException {
    // do not process if request has been cancelled
    if (!Thread.currentThread().isInterrupted()) {
        StatusLine status = response.getStatusLine();
        byte[] responseBody;
        responseBody = getResponseData(response.getEntity());
        // additional cancellation check as getResponseData() can take non-zero time to process
        if (!Thread.currentThread().isInterrupted()) {
            if (status.getStatusCode() >= 300) {
                sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), responseBody, new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()));
            } else {
                sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody);
            }
        }
    }
}