Java Code Examples for org.apache.commons.httpclient.HttpException

The following are top voted examples for showing how to use org.apache.commons.httpclient.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: lib-commons-httpclient   File: ExpectContinueMethod.java   Source Code and License 8 votes vote down vote up
/**
 * Sets the <tt>Expect</tt> header if it has not already been set, 
 * in addition to the "standard" set of headers.
 *
 * @param state the {@link HttpState state} information associated with this method
 * @param conn the {@link HttpConnection connection} used to execute
 *        this HTTP method
 *
 * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
 *                     can be recovered from.
 * @throws HttpException  if a protocol exception occurs. Usually protocol exceptions 
 *                    cannot be recovered from.
 */
protected void addRequestHeaders(HttpState state, HttpConnection conn)
throws IOException, HttpException {
    LOG.trace("enter ExpectContinueMethod.addRequestHeaders(HttpState, HttpConnection)");
    
    super.addRequestHeaders(state, conn);
    // If the request is being retried, the header may already be present
    boolean headerPresent = (getRequestHeader("Expect") != null);
    // See if the expect header should be sent
    // = HTTP/1.1 or higher
    // = request body present

    if (getParams().isParameterTrue(HttpMethodParams.USE_EXPECT_CONTINUE) 
    && getEffectiveVersion().greaterEquals(HttpVersion.HTTP_1_1) 
    && hasRequestContent())
    {
        if (!headerPresent) {
            setRequestHeader("Expect", "100-continue");
        }
    } else {
        if (headerPresent) {
            removeRequestHeader("Expect");
        }
    }
}
 
Example 2
Project: alfresco-repository   File: SolrQueryHTTPClient.java   Source Code and License 6 votes vote down vote up
protected JSONResult postSolrQuery(HttpClient httpClient, String url, JSONObject body, SolrJsonProcessor<?> jsonProcessor, String spellCheckParams)
            throws UnsupportedEncodingException, IOException, HttpException, URIException,
            JSONException
{
    JSONObject json = postQuery(httpClient, url, body);
    if (spellCheckParams != null)
    {
        SpellCheckDecisionManager manager = new SpellCheckDecisionManager(json, url, body, spellCheckParams);
        if (manager.isCollate())
        {
            json = postQuery(httpClient, manager.getUrl(), body);
        }
        json.put("spellcheck", manager.getSpellCheckJsonValue());
    }

        JSONResult results = jsonProcessor.getResult(json);

        if (s_logger.isDebugEnabled())
        {
            s_logger.debug("Sent :" + url);
            s_logger.debug("   with: " + body.toString());
            s_logger.debug("Got: " + results.getNumberFound() + " in " + results.getQueryTime() + " ms");
        }
        
        return results;
}
 
Example 3
Project: oscm   File: RequestHandlerBase.java   Source Code and License 6 votes vote down vote up
/**
 * Will write all request headers stored in the request to the method that
 * are not in the set of banned headers.
 * The Accept-Endocing header is also changed to allow compressed content
 * connection to the server even if the end client doesn't support that. 
 * A Via headers is created as well in compliance with the RFC.
 * 
 * @param method The HttpMethod used for this connection
 * @param request The incoming request
 * @throws HttpException 
 */
protected void setHeaders(HttpMethod method, HttpServletRequest request) throws HttpException {
    Enumeration headers = request.getHeaderNames();
    String connectionToken = request.getHeader("connection");
    
    while (headers.hasMoreElements()) {
        String name = (String) headers.nextElement();
        boolean isToken = (connectionToken != null && name.equalsIgnoreCase(connectionToken));
        
        if (!isToken && !bannedHeaders.contains(name.toLowerCase())) {
            Enumeration value = request.getHeaders(name);
            while (value.hasMoreElements()) {
                method.addRequestHeader(name, (String) value.nextElement());
            } 
        } 
    } 
    
    setProxySpecificHeaders(method, request);
}
 
Example 4
Project: bibliometrics   File: AuthorBuilder.java   Source Code and License 6 votes vote down vote up
/**
   * retrieves the ScopusAuthorID for an author and puts it into the <code>PublicationAuthor</code> object
   * @throws HttpException thrown upon connecting to the source
* @throws JDOMException thrown upon parsing the source response
* @throws IOException thrown upon reading profiles from disc
* @throws SAXException thrown when parsing the files from disc
*/
  public void retrieveScopusAuthorID() throws HttpException, JDOMException, IOException, SAXException {
      ScopusConnector connection = new ScopusConnector();
      Element result = connection.retrieveScopusAuthorID(author).asXML().detachRootElement().clone();
      
      List<String> allIDs = new ArrayList<>();
      for (Element child : result.getChildren()) {
          if (result.getName().equals("error")) continue;
          if (child.getName().equals("entry")) {
              Element identifier = child.getChild("identifier",DC_NS);
              String value = identifier.getValue().replace("AUTHOR_ID:", "");
              allIDs.add(value);
          }
      }
      if (allIDs.size() == 1) {
          author.setScopusAuthorID(allIDs.get(0));
          LOGGER.info("found ScopusID: " + author.getScopusAuthorID());
      } else
          author.setScopusAuthorID(toBeChecked);
  }
 
Example 5
Project: bibliometrics   File: Institution.java   Source Code and License 6 votes vote down vote up
public JSONObject createGeoJsonPoint() throws HttpException, JDOMException, IOException, SAXException {
	JSONObject geoJSONInd = new JSONObject();
	JSONObject geometry = new JSONObject();
	geometry.put("type", "Point");
	JSONArray coordinates = new JSONArray();
	coordinates.put(longitude).put(latitude);
	geometry.put("coordinates", coordinates);
	geoJSONInd.put("geometry", geometry);

	geoJSONInd.put("type", "Feature");
	JSONObject properties = new JSONObject();
	properties.put("name", city);
	geoJSONInd.put("properties", properties);
	String description = institution;
	if (!department.isEmpty())
		description = description + "<br />" + department;
	properties.put("popupContent", description);
	return geoJSONInd;
}
 
Example 6
Project: sling-org-apache-sling-launchpad-integration-tests   File: SlingPostProcessorTest.java   Source Code and License 6 votes vote down vote up
@Test
public void processorsActive() throws HttpException, IOException {
    final PostMethod post = new PostMethod(testUrl + SlingPostConstants.DEFAULT_CREATE_SUFFIX);
    post.setFollowRedirects(false);
    post.setParameter("DummyModification", "true");

    try {
        T.getHttpClient().executeMethod(post);
        final String content = post.getResponseBodyAsString();
        final int i1 = content.indexOf("source:SlingPostProcessorOne");
        assertTrue("Expecting first processor to be present", i1 > 0);
        final int i2 = content.indexOf("source:SlingPostProcessorTwo");
        assertTrue("Expecting second processor to be present", i2 > 0);
        assertTrue("Expecting service ranking to put processor one first", i1 < i2);
    } finally {
        
        post.releaseConnection();
    }

}
 
Example 7
Project: sling-org-apache-sling-launchpad-integration-tests   File: UploadFileTest.java   Source Code and License 6 votes vote down vote up
private void checkUploadedFileState(String urlOfFileNode) throws IOException,
		HttpException {
	final GetMethod get = new GetMethod(urlOfFileNode);
       final int status = httpClient.executeMethod(get);
       assertEquals(urlOfFileNode + " must be accessible after createNode",200,status);

       /*
       We should check the data, but nt:resources are not handled yet
       // compare data with local file (just length)
       final byte[] data = get.getResponseBody();
       assertEquals("size of file must be same", localFile.length(), data.length);
       */
       String data = get.getResponseBodyAsString();
       assertTrue("checking for content", data.contains("http://www.apache.org/licenses/LICENSE-2.0"));

       // download structure
       String json = getContent(urlOfFileNode + ".json", CONTENT_TYPE_JSON);
       // just check for some strings
       assertTrue("checking primary type", json.contains("\"jcr:primaryType\":\"nt:file\""));

       String content_json = getContent(urlOfFileNode + "/jcr:content.json", CONTENT_TYPE_JSON);
       // just check for some strings
       assertTrue("checking primary type", content_json.contains("\"jcr:primaryType\":\"nt:resource\""));
       assertTrue("checking mime type", content_json.contains("\"jcr:mimeType\":\"text/plain\""));
}
 
Example 8
Project: openNaEF   File: ExceptionUtils.java   Source Code and License 6 votes vote down vote up
public static ExternalServiceException getExternalServiceException(Exception e) {
    if (e instanceof ExternalServiceException) {
        return (ExternalServiceException) e;
    } else if (e instanceof RemoteException) {
        if (isLocalProblem((RemoteException) e)) {
            return new ExternalServiceException("Communication with the server could not be started.", e);
        }
        return new ExternalServiceException("An error occurred on the external server side.", e);
    } else if (e instanceof RuntimeException) {
        return new ExternalServiceException("An unexpected error occurred in the server. [" + e.getMessage() + "]", e);
    } else if (e instanceof HttpException) {
        return new ExternalServiceException("Unexpected error occurred in HTTP communication with external server. [" + e.getMessage() + "]", e);
    } else if (e instanceof ConnectException) {
        return new ExternalServiceException("Could not connect to external server. [" + e.getMessage() + "]", e);
    } else if (e instanceof IOException) {
        return new ExternalServiceException("An unexpected error occurred in the I / O with the external server. [" + e.getMessage() + "]", e);
    }
    return new ExternalServiceException("An unexpected error occurred. Response=[" + e.getMessage() + "]", e);
}
 
Example 9
Project: lib-commons-httpclient   File: MultipartPostMethod.java   Source Code and License 6 votes vote down vote up
/**
 * Adds a <tt>Content-Type</tt> request header.
 *
 * @param state current state of http requests
 * @param conn the connection to use for I/O
 *
 * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
 *                     can be recovered from.
 * @throws HttpException  if a protocol exception occurs. Usually protocol exceptions 
 *                    cannot be recovered from.
 * 
 * @since 3.0
 */
protected void addContentTypeRequestHeader(HttpState state,
                                             HttpConnection conn)
throws IOException, HttpException {
    LOG.trace("enter EntityEnclosingMethod.addContentTypeRequestHeader("
              + "HttpState, HttpConnection)");

    if (!parameters.isEmpty()) {
        StringBuffer buffer = new StringBuffer(MULTIPART_FORM_CONTENT_TYPE);
        if (Part.getBoundary() != null) {
            buffer.append("; boundary=");
            buffer.append(Part.getBoundary());
        }
        setRequestHeader("Content-Type", buffer.toString());
    }
}
 
Example 10
Project: lib-commons-httpclient   File: EntityEnclosingMethod.java   Source Code and License 6 votes vote down vote up
/**
 * Generates <tt>Content-Length</tt> or <tt>Transfer-Encoding: Chunked</tt>
 * request header, as long as no <tt>Content-Length</tt> request header
 * already exists.
 *
 * @param state current state of http requests
 * @param conn the connection to use for I/O
 *
 * @throws IOException when errors occur reading or writing to/from the
 *         connection
 * @throws HttpException when a recoverable error occurs
 */
protected void addContentLengthRequestHeader(HttpState state,
                                             HttpConnection conn)
throws IOException, HttpException {
    LOG.trace("enter EntityEnclosingMethod.addContentLengthRequestHeader("
              + "HttpState, HttpConnection)");

    if ((getRequestHeader("content-length") == null) 
        && (getRequestHeader("Transfer-Encoding") == null)) {
        long len = getRequestContentLength();
        if (len < 0) {
            if (getEffectiveVersion().greaterEquals(HttpVersion.HTTP_1_1)) {
                addRequestHeader("Transfer-Encoding", "chunked");
            } else {
                throw new ProtocolException(getEffectiveVersion() + 
                    " does not support chunk encoding");
            }
        } else {
            addRequestHeader("Content-Length", String.valueOf(len));
        }
    }
}
 
Example 11
Project: scribe   File: HTTPClient.java   Source Code and License 6 votes vote down vote up
private static void createAccount() throws HttpException, IOException {

    File input = new File(testFolder + "Account.xml");
    PostMethod post =
        new PostMethod(cadURL + "/object/User?_type=xml&externalServiceType=FBMC&externalUsername=8x8webservice&externalPassword=E4qtjWZLYKre");
    post.addRequestHeader("Content-Type", "application/xml");
    RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    post.setRequestEntity(entity);
    HttpClient httpclient = new HttpClient();
    try {
      System.out.println("URI: " + post.getURI());
      int result = httpclient.executeMethod(post);
      System.out.println("Response status code: " + result);
      System.out.println("Response body: " + post.getResponseBodyAsString());
    } finally {
      post.releaseConnection();
    }
  }
 
Example 12
Project: scribe   File: HTTPClient.java   Source Code and License 6 votes vote down vote up
private static void updateAccount() throws HttpException, IOException {
  System.out.println("Sent HTTP PUT request to update Account");
  File input = new File(testFolder + "Account.xml");
  PutMethod put =
      new PutMethod(cadURL + "/object/User?_type=xml&externalServiceType=FBMC&externalUsername=8x8webservice&externalPassword=E4qtjWZLYKre");
  put.addRequestHeader("Content-Type", "application/xml");
  RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
  put.setRequestEntity(entity);
  HttpClient httpclient = new HttpClient();
  try {
    int result = httpclient.executeMethod(put);
    System.out.println("Response status code: " + result);
    System.out.println("Response body: " + put.getResponseBodyAsString());
  } finally {
    put.releaseConnection();
  }
}
 
Example 13
Project: scribe   File: HTTPClient.java   Source Code and License 6 votes vote down vote up
private static void createCustomer() throws HttpException, IOException {
  System.out.println("Sent HTTP POST request to add Customer");
  File input = new File(testFolder + "Customer.xml");
  PostMethod post = new PostMethod(cadURL + "/object/customer?_type=xml");
  post.addRequestHeader("Content-Type", "application/xml");
  RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
  post.setRequestEntity(entity);
  HttpClient httpclient = new HttpClient();
  try {
    System.out.println("URI: " + post.getURI());
    int result = httpclient.executeMethod(post);
    System.out.println("Response status code: " + result);
    System.out.println("Response body: " + post.getResponseBodyAsString());
  } finally {
    post.releaseConnection();
  }
}
 
Example 14
Project: scribe   File: HTTPClient.java   Source Code and License 6 votes vote down vote up
private static void updateCustomer() throws HttpException, IOException {
  System.out.println("Sent HTTP PUT request to update Customer");
  File input = new File(testFolder + "Customer.xml");
  PutMethod put = new PutMethod(cadURL + "/object/customer?_type=xml");
  put.addRequestHeader("Content-Type", "application/xml");
  RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
  put.setRequestEntity(entity);
  HttpClient httpclient = new HttpClient();
  try {
    System.out.println("URI: " + put.getURI());
    int result = httpclient.executeMethod(put);
    System.out.println("Response status code: " + result);
    System.out.println("Response body: " + put.getResponseBodyAsString());
  } finally {
    put.releaseConnection();
  }
}
 
Example 15
Project: scribe   File: HTTPClient.java   Source Code and License 6 votes vote down vote up
private static void createLead() throws HttpException, IOException {
  System.out.println("Sent HTTP POST request to create Lead");
  File input = new File(testFolder + "Lead.xml");
  PostMethod post = new PostMethod(cadURL + "/object/lead?_type=xml");
  post.addRequestHeader("Content-Type", "application/xml");
  RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
  post.setRequestEntity(entity);
  HttpClient httpclient = new HttpClient();
  try {
    System.out.println("URI: " + post.getURI());
    int result = httpclient.executeMethod(post);
    System.out.println("Response status code: " + result);
    System.out.println("Response body: " + post.getResponseBodyAsString());
  } finally {
    post.releaseConnection();
  }
}
 
Example 16
Project: scribe   File: HTTPClient.java   Source Code and License 6 votes vote down vote up
private static void createContact() throws HttpException, IOException {
  System.out.println("Sent HTTP POST request to createContact");
  File input = new File(testFolder + "Contact.xml");
  PostMethod post = new PostMethod(cadURL + "/object/oltp?_type=xml");
  post.addRequestHeader("Content-Type", "application/xml");
  RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
  post.setRequestEntity(entity);
  HttpClient httpclient = new HttpClient();
  try {
    System.out.println("URI: " + post.getURI());
    int result = httpclient.executeMethod(post);
    System.out.println("Response status code: " + result);
    System.out.println("Response body: " + post.getResponseBodyAsString());
  } finally {
    post.releaseConnection();
  }
}
 
Example 17
Project: scribe   File: HTTPClient.java   Source Code and License 6 votes vote down vote up
private static void updateContact() throws HttpException, IOException {
  System.out.println("Sent HTTP POST request to createContact");
  File input = new File(testFolder + "Contact.xml");
  PutMethod put = new PutMethod(cadURL + "/object/oltp?_type=xml");
  put.addRequestHeader("Content-Type", "application/xml");
  RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
  put.setRequestEntity(entity);
  HttpClient httpclient = new HttpClient();
  try {
    System.out.println("URI: " + put.getURI());
    int result = httpclient.executeMethod(put);
    System.out.println("Response status code: " + result);
    System.out.println("Response body: " + put.getResponseBodyAsString());
  } finally {
    put.releaseConnection();
  }
}
 
Example 18
Project: scribe   File: HTTPClient.java   Source Code and License 6 votes vote down vote up
private static void createFAQCatagory() throws HttpException, IOException {
  System.out.println("Sent HTTP POST request to createFAQCatagory");
  File input = new File(testFolder + "FAQCatagory.xml");
  PostMethod post = new PostMethod(cadURL + "/object/faqcategory?_type=xml");
  post.addRequestHeader("Content-Type", "application/xml");
  RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
  post.setRequestEntity(entity);
  HttpClient httpclient = new HttpClient();
  try {
    System.out.println("URI: " + post.getURI());
    int result = httpclient.executeMethod(post);
    System.out.println("Response status code: " + result);
    System.out.println("Response body: " + post.getResponseBodyAsString());
  } finally {
    post.releaseConnection();
  }
}
 
Example 19
Project: scribe   File: HTTPClient.java   Source Code and License 6 votes vote down vote up
private static void readCustomers() throws HttpException, IOException {

    for (int i = 0; i < 1000; i++) {

      new Thread() {
        public void run() {
          GetMethod post = new GetMethod(cadURL + "/object/customer?_type=xml&tenant=dev1ten2");
          post.addRequestHeader("Content-Type", "application/xml");
          HttpClient httpclient = new HttpClient();
          try {

            try {
              System.out.println("URI: " + post.getURI());
              int result = httpclient.executeMethod(post);
              System.out.println("Response status code: " + result);
              System.out.println("Response body: " + post.getResponseBodyAsString());
            } catch (Exception exception) {
              System.err.println(exception);
            }
          } finally {
            post.releaseConnection();
          }
        }
      };
    }
  }
 
Example 20
Project: scribe   File: HTTPClient.java   Source Code and License 6 votes vote down vote up
private static void createUser() throws HttpException, IOException {

    File input = new File(testFolder + "User.xml");
    PostMethod post = new PostMethod(cadURL + "/object/user?_type=xml&batch=dummy");
    post.addRequestHeader("Content-Type", "application/xml");
    RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    post.setRequestEntity(entity);
    HttpClient httpclient = new HttpClient();
    try {
      System.out.println("URI: " + post.getURI());
      int result = httpclient.executeMethod(post);
      System.out.println("hii");
      System.out.println("Response status code: " + result);
      System.out.println("Response body: " + post.getResponseBodyAsString());
    } finally {
      post.releaseConnection();
    }
  }
 
Example 21
Project: scribe   File: HTTPClient.java   Source Code and License 6 votes vote down vote up
private static void updateUser() throws HttpException, IOException {

    File input = new File(testFolder + "User.xml");
    PutMethod put = new PutMethod(cadURL + "/object/user?_type=xml");
    put.addRequestHeader("Content-Type", "application/xml");
    RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    put.setRequestEntity(entity);
    HttpClient httpclient = new HttpClient();
    try {
      System.out.println("URI: " + put.getURI());
      int result = httpclient.executeMethod(put);
      System.out.println("Response status code: " + result);
      System.out.println("Response body: " + put.getResponseBodyAsString());
    } finally {
      put.releaseConnection();
    }
  }
 
Example 22
Project: scribe   File: HTTPClient.java   Source Code and License 6 votes vote down vote up
private static void createTask() throws HttpException, IOException {

    File input = new File(testFolder + "Task.xml");
    PostMethod post = new PostMethod(cadURL + "/object/task?_type=xml");
    post.addRequestHeader("Content-Type", "application/xml");
    RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    post.setRequestEntity(entity);
    HttpClient httpclient = new HttpClient();
    try {
      System.out.println("URI: " + post.getURI());
      int result = httpclient.executeMethod(post);
      System.out.println("Response status code: " + result);
      System.out.println("Response body: " + post.getResponseBodyAsString());
    } finally {
      post.releaseConnection();
    }
  }
 
Example 23
Project: scribe   File: HTTPClient.java   Source Code and License 6 votes vote down vote up
private static void createSupportCase() throws HttpException, IOException {

    File input = new File(testFolder + "SupportCase.xml");
    PostMethod post = new PostMethod(cadURL + "/object/supportcase?_type=xml");
    post.addRequestHeader("Content-Type", "application/xml");
    RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    post.setRequestEntity(entity);
    HttpClient httpclient = new HttpClient();
    try {
      System.out.println("URI: " + post.getURI());
      int result = httpclient.executeMethod(post);
      System.out.println("Response status code: " + result);
      System.out.println("Response body: " + post.getResponseBodyAsString());
    } finally {
      post.releaseConnection();
    }
  }
 
Example 24
Project: scribe   File: HTTPClient.java   Source Code and License 6 votes vote down vote up
private static void createPhoneCall() throws HttpException, IOException {

    File input = new File(testFolder + "PhoneCall.xml");
    PostMethod post = new PostMethod(cadURL + "/object/phonecall?_type=xml");
    post.addRequestHeader("Content-Type", "application/xml");
    RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    post.setRequestEntity(entity);
    HttpClient httpclient = new HttpClient();
    try {
      System.out.println("URI: " + post.getURI());
      int result = httpclient.executeMethod(post);
      System.out.println("Response status code: " + result);
      System.out.println("Response body: " + post.getResponseBodyAsString());
    } finally {
      post.releaseConnection();
    }
  }
 
Example 25
Project: scribe   File: HTTPClient.java   Source Code and License 6 votes vote down vote up
private static void createOpportunity() throws HttpException, IOException {

    File input = new File(testFolder + "Opportunity.xml");
    PostMethod post = new PostMethod(cadURL + "/object/opportunity?_type=xml");
    post.addRequestHeader("Content-Type", "application/xml");
    RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    post.setRequestEntity(entity);
    HttpClient httpclient = new HttpClient();
    try {
      System.out.println("URI: " + post.getURI());
      int result = httpclient.executeMethod(post);
      System.out.println("Response status code: " + result);
      System.out.println("Response body: " + post.getResponseBodyAsString());
    } finally {
      post.releaseConnection();
    }
  }
 
Example 26
Project: scribe   File: HTTPClient.java   Source Code and License 6 votes vote down vote up
private static void createIncident() throws HttpException, IOException {

    File input = new File(testFolder + "Incident.xml");
    PostMethod post = new PostMethod(cadURL + "/object/incident?_type=xml");
    post.addRequestHeader("Content-Type", "application/xml");
    RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    post.setRequestEntity(entity);
    HttpClient httpclient = new HttpClient();
    try {
      System.out.println("URI: " + post.getURI());
      int result = httpclient.executeMethod(post);
      System.out.println("Response status code: " + result);
      System.out.println("Response body: " + post.getResponseBodyAsString());
    } finally {
      post.releaseConnection();
    }
  }
 
Example 27
Project: scribe   File: HTTPClient.java   Source Code and License 6 votes vote down vote up
private static void createCase() throws HttpException, IOException {

    File input = new File(testFolder + "Case.xml");
    PostMethod post = new PostMethod(cadURL + "/object/oltp?_type=xml");
    post.addRequestHeader("Content-Type", "application/xml");
    RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    post.setRequestEntity(entity);
    HttpClient httpclient = new HttpClient();
    try {
      System.out.println("URI: " + post.getURI());
      int result = httpclient.executeMethod(post);
      System.out.println("Response status code: " + result);
      System.out.println("Response body: " + post.getResponseBodyAsString());
    } finally {
      post.releaseConnection();
    }
  }
 
Example 28
Project: scribe   File: HTTPClient.java   Source Code and License 6 votes vote down vote up
private static void updateCase() throws HttpException, IOException {

    File input = new File(testFolder + "Case.xml");
    PutMethod post = new PutMethod(cadURL + "/object/oltp?_type=xml");
    post.addRequestHeader("Content-Type", "application/xml");
    RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    post.setRequestEntity(entity);
    HttpClient httpclient = new HttpClient();
    try {
      System.out.println("URI: " + post.getURI());
      int result = httpclient.executeMethod(post);
      System.out.println("Response status code: " + result);
      System.out.println("Response body: " + post.getResponseBodyAsString());
    } finally {
      post.releaseConnection();
    }
  }
 
Example 29
Project: scribe   File: HTTPClient.java   Source Code and License 6 votes vote down vote up
private static void createFollowup() throws HttpException, IOException {

    File input = new File(testFolder + "Followup.xml");
    PostMethod post = new PostMethod(cadURL + "/object/oltp?_type=xml");
    post.addRequestHeader("Content-Type", "application/xml");
    RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    post.setRequestEntity(entity);
    HttpClient httpclient = new HttpClient();
    try {
      System.out.println("URI: " + post.getURI());
      int result = httpclient.executeMethod(post);
      System.out.println("Response status code: " + result);
      System.out.println("Response body: " + post.getResponseBodyAsString());
    } finally {
      post.releaseConnection();
    }
  }
 
Example 30
Project: scribe   File: HTTPClient.java   Source Code and License 6 votes vote down vote up
private static void updateFollowup() throws HttpException, IOException {

    File input = new File(testFolder + "Followup.xml");
    PutMethod post = new PutMethod(cadURL + "/object/oltp?_type=xml");
    post.addRequestHeader("Content-Type", "application/xml");
    RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    post.setRequestEntity(entity);
    HttpClient httpclient = new HttpClient();
    try {
      System.out.println("URI: " + post.getURI());
      int result = httpclient.executeMethod(post);
      System.out.println("Response status code: " + result);
      System.out.println("Response body: " + post.getResponseBodyAsString());
    } finally {
      post.releaseConnection();
    }
  }
 
Example 31
Project: document-management-system   File: MailUtils.java   Source Code and License 6 votes vote down vote up
/**
 * User tinyurl service as url shorter Depends on commons-httpclient:commons-httpclient:jar:3.0 because of
 * org.apache.jackrabbit:jackrabbit-webdav:jar:1.6.4
 */
public static String getTinyUrl(String fullUrl) throws HttpException, IOException {
	HttpClient httpclient = new HttpClient();

	// Prepare a request object
	HttpMethod method = new GetMethod("http://tinyurl.com/api-create.php");
	method.setQueryString(new NameValuePair[]{new NameValuePair("url", fullUrl)});
	httpclient.executeMethod(method);
	InputStreamReader isr = new InputStreamReader(method.getResponseBodyAsStream(), "UTF-8");
	StringWriter sw = new StringWriter();
	int c;
	while ((c = isr.read()) != -1)
		sw.write(c);
	isr.close();
	method.releaseConnection();

	return sw.toString();
}
 
Example 32
Project: ucsd-spark-plugin   File: SparkApi.java   Source Code and License 6 votes vote down vote up
/**
 * Requests a specific team member from the Spark servers and returns it as
 * a Java Object. If the team member does not exist (or cannot be found) it
 * returns null
 *
 * @param account
 *            Account to request from
 * @param teamId
 *            Team ID to check
 * @param personEmail
 *            User's email to check
 * @return Membership ID as a String
 * @throws SparkReportException
 *             if the report fails
 * @throws HttpException
 *             if there's a problem accessing the report
 * @throws IOException
 *             if there's a problem accessing the report
 * @see SparkRooms
 */
public static String getSparkTeamMemberships(SparkAccount account, String teamId, String personEmail)
		throws SparkReportException, HttpException, IOException {
	// Set up a request to the spark server
	SparkHttpConnection req = new SparkHttpConnection(account,
			SparkConstants.SPARK_TEAMS_MEMBERSHIP_URI + "?teamId=" + teamId + "&personEmail=" + personEmail,
			httpMethod.GET);
	req.execute();
	String json = req.getResponse();
	Gson gson = new Gson();
	SparkTeamMemberships members = gson.fromJson(json, SparkTeamMemberships.class);
	if (members.getItems().size() > 0) {
		// There is a bug (2016-07-15) which means searching via email
		// doesn't work - find it ourselves
		for (SparkTeamMembership member : members.getItems()) {
			if (personEmail.toLowerCase().equals(member.getPersonEmail().toLowerCase())) {
				return member.getId();
			}
		}
	}
	return null;
}
 
Example 33
Project: weixinmp4j   File: IPAddressService.java   Source Code and License 6 votes vote down vote up
/**
 * 
 */
public IP onSuccess() throws HttpException, IOException {
	//数据demo if(window.AA) {AA({"ip":"115.199.97.37","pro":"浙江省","city":"杭州市","region":"","addr":"浙江省杭州市","regionNames":""});} 
	String content=method.getResponseBodyAsString();
	String jsonData=content.substring(content.indexOf("{", content.indexOf("{")+1)/*左起第二个话括弧*/, content.indexOf("}")+1/*第一个反括号结束*/);
	JSONObject jsonObject=new JSONObject(jsonData);
	
	IP ip=new IP();
	ip.setIp(jsonObject.getString("ip"));
	ip.setAddr(jsonObject.getString("addr"));
	ip.setCity(jsonObject.getString("city"));
	ip.setPro(jsonObject.getString("pro"));
	ip.setRegion(jsonObject.getString("region"));
	ip.setRegionNames(jsonObject.getString("regionNames"));
	return ip;
	
	//反射效率太低
	//return (IP)JSONObject.toBean(jsonObject, IP.class);
}
 
Example 34
Project: motu   File: HttpClientCAS.java   Source Code and License 6 votes vote down vote up
public int executeMethod(HostConfiguration hostconfig, HttpMethod method, HttpState state, boolean addCasTicket)
        throws IOException, HttpException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("executeMethod(HostConfiguration, HttpMethod, HttpState) - entering");
    }

    try {
        if (this.isAddCasTicketParams()) {
            HttpClientCAS.addCASTicket(method);
        }
    } catch (MotuCasException e) {
        throw new HttpException(e.notifyException(), e);
    }

    int returnint = super.executeMethod(hostconfig, method, state);
    if (LOG.isDebugEnabled()) {
        LOG.debug("executeMethod(HostConfiguration, HttpMethod, HttpState) - exiting");
    }
    return returnint;
}
 
Example 35
Project: motu   File: HttpClientCAS.java   Source Code and License 6 votes vote down vote up
@Override
public int executeMethod(HttpMethod method) throws IOException, HttpException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("executeMethod(HttpMethod) - entering");
    }
    try {
        if (this.isAddCasTicketParams()) {
            HttpClientCAS.addCASTicket(method);
        }
    } catch (MotuCasException e) {
        throw new HttpException(e.notifyException(), e);
    }

    // int returnint = super.executeMethod(method);
    int returnint = super.executeMethod(null, method, null);
    if (LOG.isDebugEnabled()) {
        LOG.debug("executeMethod(HttpMethod) - exiting");
    }
    return returnint;
}
 
Example 36
Project: development   File: RequestHandlerBase.java   Source Code and License 6 votes vote down vote up
/**
 * Will write all request headers stored in the request to the method that
 * are not in the set of banned headers.
 * The Accept-Endocing header is also changed to allow compressed content
 * connection to the server even if the end client doesn't support that. 
 * A Via headers is created as well in compliance with the RFC.
 * 
 * @param method The HttpMethod used for this connection
 * @param request The incoming request
 * @throws HttpException 
 */
protected void setHeaders(HttpMethod method, HttpServletRequest request) throws HttpException {
    Enumeration headers = request.getHeaderNames();
    String connectionToken = request.getHeader("connection");
    
    while (headers.hasMoreElements()) {
        String name = (String) headers.nextElement();
        boolean isToken = (connectionToken != null && name.equalsIgnoreCase(connectionToken));
        
        if (!isToken && !bannedHeaders.contains(name.toLowerCase())) {
            Enumeration value = request.getHeaders(name);
            while (value.hasMoreElements()) {
                method.addRequestHeader(name, (String) value.nextElement());
            } 
        } 
    } 
    
    setProxySpecificHeaders(method, request);
}
 
Example 37
Project: osa   File: IngestAction.java   Source Code and License 6 votes vote down vote up
@HandlesEvent("getOnkiHttp")
public Resolution getOnkiHttp() throws HttpException, IOException {
    String json = "";
    String language = getUserLocale().toLanguageTag().split("-")[0];
    HttpClient httpClient = new HttpClient();
    httpClient.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
    httpClient.getParams().setParameter("http.protocol.content-charset", "UTF-8");
    
    GetMethod get = new GetMethod("http://onki.fi/key-"+this.getOnkiAccessKey()+"/api/v2/http/onto/" + ontologyId + "/search?q=" + term + "&l=" + language);
    httpClient.executeMethod(get);
    if (get.getStatusCode() == 200) {
        json = get.getResponseBodyAsString();
    }
    //logger.info("getOnkiHttp(): "+json);
    return new StreamingResolution(MIME_JS, json);
}
 
Example 38
Project: ffma   File: PronomSparqlClient.java   Source Code and License 6 votes vote down vote up
/**
	 * @param query
	 */
	public PronomSparqlClient(String query) {
		HttpClient client = new HttpClient();
		client.getHttpConnectionManager().getParams().
		setConnectionTimeout(10000);
		String url = query;
		try {
			HttpMethod method = new GetMethod(url);
			method.setFollowRedirects(false);
//		try {
			client.executeMethod(method);
			responseBody = method.getResponseBodyAsString();
			log.info("Response body: " + responseBody);
			method.releaseConnection();
		} catch (HttpException he) {
			log.fine("Http error connecting to �" + query + "�");
		} catch (IOException ioe) {
			log.fine("Unable to connect to �" + query + "�");
		} catch (Exception e) {
			log.fine("SPARQL client exception. Unable to parse response from �" + query + "� (Exception: " + e.getLocalizedMessage() + ")");
		}
//		method.releaseConnection();
	}
 
Example 39
Project: ffma   File: SPARQLClient.java   Source Code and License 6 votes vote down vote up
/**
	 * @param endpointURL
	 * @param sparql
	 */
	public SPARQLClient(String endpointURL, String sparql) {
		HttpClient client = new HttpClient();
		client.getHttpConnectionManager().getParams().
		setConnectionTimeout(10000);
		String url = endpointURL + sparql;
		HttpMethod method = new GetMethod(url);
		method.setFollowRedirects(false);
		try {
			client.executeMethod(method);
//			log.info("Response body: " + method.getResponseBodyAsString());
			InputStream ins = new ByteArrayInputStream(method.getResponseBodyAsString().getBytes("UTF-8"));
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser sax = factory.newSAXParser();
			sax.parse(ins, this);
		} catch (HttpException he) {
			log.fine("Http error connecting to �" + endpointURL + "�");
		} catch (IOException ioe) {
			log.fine("Unable to connect to �" + endpointURL + "�");
		} catch (SAXException se) {
			log.fine("Unable to parse response from �" + endpointURL + "� (Exception: " + se.getLocalizedMessage() + ")");
		} catch (ParserConfigurationException pce) {
			log.fine("Unable to parse response from �" + endpointURL + "� (Exception: " + pce.getLocalizedMessage() + ")");
		}
		method.releaseConnection();
	}
 
Example 40
Project: power-java   File: DBpediaLookupClient.java   Source Code and License 6 votes vote down vote up
public DBpediaLookupClient(String query) throws Exception {
  this.query = query;
  HttpClient client = new HttpClient();

  String query2 = query.replaceAll(" ", "+");
  HttpMethod method =
      new GetMethod("http://lookup.dbpedia.org/api/search.asmx/KeywordSearch?QueryString=" +
          query2);
  try {
    client.executeMethod(method);
    InputStream ins = method.getResponseBodyAsStream();
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser sax = factory.newSAXParser();
    sax.parse(ins, this);
  } catch (HttpException he) {
    System.err.println("Http error connecting to lookup.dbpedia.org");
  } catch (IOException ioe) {
    System.err.println("Unable to connect to lookup.dbpedia.org");
  }
  method.releaseConnection();
}
 
Example 41
Project: incubator-taverna-plugin-component   File: BaseProfileLocator.java   Source Code and License 6 votes vote down vote up
private long getRemoteBaseProfileTimestamp(HttpClient client)
		throws URISyntaxException, IOException, HttpException,
		ParseException {
	URI baseProfileURI = new URI(BASE_PROFILE_URI);
	HttpMethod method = new GetMethod(baseProfileURI.toString());
	int statusCode = client.executeMethod(method);
	if (statusCode != SC_OK) {
		logger.warn("HTTP status " + statusCode + " while getting "
				+ baseProfileURI);
		return -1;
	}
	Header h = method.getResponseHeader("Last-Modified");
	if (h == null)
		return -1;
	return parseTime(h.getValue());
}
 
Example 42
Project: Pinot   File: FileUploadUtils.java   Source Code and License 6 votes vote down vote up
public static int sendFile(final String host, final String port, final String path, final String fileName,
    final InputStream inputStream, final long lengthInBytes) {
  HttpClient client = new HttpClient();
  try {

    client.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
    client.getParams().setSoTimeout(3600 * 1000); // One hour
    PostMethod post = new PostMethod("http://" + host + ":" + port + "/" + path);
    Part[] parts = { new FilePart(fileName, new PartSource() {
      @Override
      public long getLength() {
        return lengthInBytes;
      }

      @Override
      public String getFileName() {
        return "fileName";
      }

      @Override
      public InputStream createInputStream() throws IOException {
        return new BufferedInputStream(inputStream);
      }
    }) };
    post.setRequestEntity(new MultipartRequestEntity(parts, new HttpMethodParams()));
    client.executeMethod(post);
    if (post.getStatusCode() >= 400) {
      String errorString = "POST Status Code: " + post.getStatusCode() + "\n";
      if (post.getResponseHeader("Error") != null) {
        errorString += "ServletException: " + post.getResponseHeader("Error").getValue();
      }
      throw new HttpException(errorString);
    }
    return post.getStatusCode();
  } catch (Exception e) {
    LOGGER.error("Caught exception while sending file", e);
    Utils.rethrowException(e);
    throw new AssertionError("Should not reach this");
  }
}
 
Example 43
Project: realtime-analytics   File: Simulator.java   Source Code and License 6 votes vote down vote up
private static void sendMessage() throws IOException, JsonProcessingException, JsonGenerationException,
            JsonMappingException, UnsupportedEncodingException, HttpException {
        ObjectMapper mapper = new ObjectMapper();

        Map<String, Object> m = new HashMap<String, Object>();

        m.put("si", "12345");
        m.put("ct", System.currentTimeMillis());
        
        String payload = mapper.writeValueAsString(m);
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod("http://localhost:8080/tracking/ingest/PulsarRawEvent");
//      method.addRequestHeader("Accept-Encoding", "gzip,deflate,sdch");
        method.setRequestEntity(new StringRequestEntity(payload, "application/json", "UTF-8"));
        int status = client.executeMethod(method);
        System.out.println(Arrays.toString(method.getResponseHeaders()));
        System.out.println("Status code: " + status + ", Body: " +  method.getResponseBodyAsString());
    }
 
Example 44
Project: olat   File: GroupMgmtITCase.java   Source Code and License 6 votes vote down vote up
@Test
public void testGetParticipantsAdmin() throws HttpException, IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final String request = "/groups/" + g1.getKey() + "/participants";
    final HttpMethod method = createGet(request, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    assertEquals(code, 200);
    final String body = method.getResponseBodyAsString();
    final List<UserVO> participants = parseUserArray(body);
    assertNotNull(participants);
    assertEquals(participants.size(), 2);

    Long idKey1 = null;
    Long idKey2 = null;
    for (final UserVO participant : participants) {
        if (participant.getKey().equals(part1.getKey())) {
            idKey1 = part1.getKey();
        } else if (participant.getKey().equals(part2.getKey())) {
            idKey2 = part2.getKey();
        }
    }
    assertNotNull(idKey1);
    assertNotNull(idKey2);
}
 
Example 45
Project: olat   File: GroupMgmtITCase.java   Source Code and License 6 votes vote down vote up
@Test
public void testGetOwnersAdmin() throws HttpException, IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");
    final String request = "/groups/" + g1.getKey() + "/owners";
    final HttpMethod method = createGet(request, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    assertEquals(code, 200);
    final String body = method.getResponseBodyAsString();
    final List<UserVO> owners = parseUserArray(body);
    assertNotNull(owners);
    assertEquals(owners.size(), 2);

    Long idKey1 = null;
    Long idKey2 = null;
    for (final UserVO participant : owners) {
        if (participant.getKey().equals(owner1.getKey())) {
            idKey1 = owner1.getKey();
        } else if (participant.getKey().equals(owner2.getKey())) {
            idKey2 = owner2.getKey();
        }
    }
    assertNotNull(idKey1);
    assertNotNull(idKey2);
}
 
Example 46
Project: olat   File: GroupMgmtITCase.java   Source Code and License 6 votes vote down vote up
@Test
public void testAddParticipant() throws HttpException, IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");
    final String request = "/groups/" + g1.getKey() + "/participants/" + part3.getKey();
    final HttpMethod method = createPut(request, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    method.releaseConnection();

    assertTrue(code == 200 || code == 201);

    final List<Identity> participants = securityManager.getIdentitiesOfSecurityGroup(g1.getPartipiciantGroup());
    boolean found = false;
    for (final Identity participant : participants) {
        if (participant.getKey().equals(part3.getKey())) {
            found = true;
        }
    }

    assertTrue(found);
}
 
Example 47
Project: olat   File: GroupMgmtITCase.java   Source Code and License 6 votes vote down vote up
@Test
public void testRemoveParticipant() throws HttpException, IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");
    final String request = "/groups/" + g1.getKey() + "/participants/" + part2.getKey();
    final HttpMethod method = createDelete(request, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    method.releaseConnection();

    assertTrue(code == 200);

    final List<Identity> participants = securityManager.getIdentitiesOfSecurityGroup(g1.getPartipiciantGroup());
    boolean found = false;
    for (final Identity participant : participants) {
        if (participant.getKey().equals(part2.getKey())) {
            found = true;
        }
    }

    assertFalse(found);
}
 
Example 48
Project: olat   File: GroupMgmtITCase.java   Source Code and License 6 votes vote down vote up
@Test
public void testAddTutor() throws HttpException, IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");
    final String request = "/groups/" + g1.getKey() + "/owners/" + owner3.getKey();
    final HttpMethod method = createPut(request, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    method.releaseConnection();

    assertTrue(code == 200 || code == 201);

    final List<Identity> owners = securityManager.getIdentitiesOfSecurityGroup(g1.getOwnerGroup());
    boolean found = false;
    for (final Identity owner : owners) {
        if (owner.getKey().equals(owner3.getKey())) {
            found = true;
        }
    }

    assertTrue(found);
}
 
Example 49
Project: olat   File: GroupMgmtITCase.java   Source Code and License 6 votes vote down vote up
@Test
public void testGetParticipantsAdmin() throws HttpException, IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final String request = "/groups/" + g1.getKey() + "/participants";
    final HttpMethod method = createGet(request, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    assertEquals(code, 200);
    final String body = method.getResponseBodyAsString();
    final List<UserVO> participants = parseUserArray(body);
    assertNotNull(participants);
    assertEquals(participants.size(), 2);

    Long idKey1 = null;
    Long idKey2 = null;
    for (final UserVO participant : participants) {
        if (participant.getKey().equals(part1.getKey())) {
            idKey1 = part1.getKey();
        } else if (participant.getKey().equals(part2.getKey())) {
            idKey2 = part2.getKey();
        }
    }
    assertNotNull(idKey1);
    assertNotNull(idKey2);
}
 
Example 50
Project: olat   File: GroupMgmtITCase.java   Source Code and License 6 votes vote down vote up
@Test
public void testGetOwnersAdmin() throws HttpException, IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");
    final String request = "/groups/" + g1.getKey() + "/owners";
    final HttpMethod method = createGet(request, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    assertEquals(code, 200);
    final String body = method.getResponseBodyAsString();
    final List<UserVO> owners = parseUserArray(body);
    assertNotNull(owners);
    assertEquals(owners.size(), 2);

    Long idKey1 = null;
    Long idKey2 = null;
    for (final UserVO participant : owners) {
        if (participant.getKey().equals(owner1.getKey())) {
            idKey1 = owner1.getKey();
        } else if (participant.getKey().equals(owner2.getKey())) {
            idKey2 = owner2.getKey();
        }
    }
    assertNotNull(idKey1);
    assertNotNull(idKey2);
}
 
Example 51
Project: olat   File: GroupMgmtITCase.java   Source Code and License 6 votes vote down vote up
@Test
public void testAddParticipant() throws HttpException, IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");
    final String request = "/groups/" + g1.getKey() + "/participants/" + part3.getKey();
    final HttpMethod method = createPut(request, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    method.releaseConnection();

    assertTrue(code == 200 || code == 201);

    final List<Identity> participants = securityManager.getIdentitiesOfSecurityGroup(g1.getPartipiciantGroup());
    boolean found = false;
    for (final Identity participant : participants) {
        if (participant.getKey().equals(part3.getKey())) {
            found = true;
        }
    }

    assertTrue(found);
}
 
Example 52
Project: olat   File: GroupMgmtITCase.java   Source Code and License 6 votes vote down vote up
@Test
public void testRemoveParticipant() throws HttpException, IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");
    final String request = "/groups/" + g1.getKey() + "/participants/" + part2.getKey();
    final HttpMethod method = createDelete(request, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    method.releaseConnection();

    assertTrue(code == 200);

    final List<Identity> participants = securityManager.getIdentitiesOfSecurityGroup(g1.getPartipiciantGroup());
    boolean found = false;
    for (final Identity participant : participants) {
        if (participant.getKey().equals(part2.getKey())) {
            found = true;
        }
    }

    assertFalse(found);
}
 
Example 53
Project: olat   File: GroupMgmtITCase.java   Source Code and License 6 votes vote down vote up
@Test
public void testAddTutor() throws HttpException, IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");
    final String request = "/groups/" + g1.getKey() + "/owners/" + owner3.getKey();
    final HttpMethod method = createPut(request, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    method.releaseConnection();

    assertTrue(code == 200 || code == 201);

    final List<Identity> owners = securityManager.getIdentitiesOfSecurityGroup(g1.getOwnerGroup());
    boolean found = false;
    for (final Identity owner : owners) {
        if (owner.getKey().equals(owner3.getKey())) {
            found = true;
        }
    }

    assertTrue(found);
}
 
Example 54
Project: olat   File: GroupMgmtITCase.java   Source Code and License 6 votes vote down vote up
@Test
public void testRemoveTutor() throws HttpException, IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");
    final String request = "/groups/" + g1.getKey() + "/owners/" + owner2.getKey();
    final HttpMethod method = createDelete(request, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    method.releaseConnection();

    assertTrue(code == 200);

    final List<Identity> owners = securityManager.getIdentitiesOfSecurityGroup(g1.getOwnerGroup());
    boolean found = false;
    for (final Identity owner : owners) {
        if (owner.getKey().equals(owner2.getKey())) {
            found = true;
        }
    }

    assertFalse(found);
}
 
Example 55
Project: community-edition-old   File: AlfrescoDwsServiceHandler.java   Source Code and License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected String doCreateDws(String dwsName, String title, SessionUser user) throws HttpException, IOException
{
    dwsName = sanitizeShortName(dwsName);
    // Find a unique name for the site, based on the requested one
    SiteInfo siteInfo = null;
    String uniqueDwsName = null;
    int i = 0;
    do {
        uniqueDwsName = dwsName + (i == 0 ? "" : "_" + i);
        siteInfo = siteService.getSite(uniqueDwsName);
        i++;
    } while (siteInfo != null);
    
    // Create and return the new site name
    shareUtils.createSite(user, "document-workspace", uniqueDwsName, title, "", true);
    return uniqueDwsName;
}
 
Example 56
Project: community-edition-old   File: SolrQueryHTTPClient.java   Source Code and License 6 votes vote down vote up
protected JSONResult postSolrQuery(HttpClient httpClient, String url, JSONObject body, SolrJsonProcessor<?> jsonProcessor, String spellCheckParams)
            throws UnsupportedEncodingException, IOException, HttpException, URIException,
            JSONException
{
    JSONObject json = postQuery(httpClient, url, body);
    if (spellCheckParams != null)
    {
        SpellCheckDecisionManager manager = new SpellCheckDecisionManager(json, url, body, spellCheckParams);
        if (manager.isCollate())
        {
            json = postQuery(httpClient, manager.getUrl(), body);
        }
        json.put("spellcheck", manager.getSpellCheckJsonValue());
    }

        JSONResult results = jsonProcessor.getResult(json);

        if (s_logger.isDebugEnabled())
        {
            s_logger.debug("Sent :" + url);
            s_logger.debug("   with: " + body.toString());
            s_logger.debug("Got: " + results.getNumberFound() + " in " + results.getQueryTime() + " ms");
        }
        
        return results;
}
 
Example 57
Project: Hue-Ctrip-DI   File: YarnJobCrawlerTask.java   Source Code and License 6 votes vote down vote up
private List<YarnJobsDo> getJobList(long maxStartTime)
		throws HttpException, IOException {
	List<YarnJobsDo> jobsList = new ArrayList<YarnJobsDo>();

	JSONObject json = getJson();
	JSONObject jobs = (JSONObject) json.get("jobs");
	JSONArray jobArray = (JSONArray) jobs.get("job");
	@SuppressWarnings("unchecked")
	ListIterator<JSONObject> iterator = jobArray.listIterator();
	while (iterator.hasNext()) {
		JSONObject jobObject = iterator.next();
		long startTime = jobObject.getLong("startTime");
		if (startTime > maxStartTime) {
			YarnJobsDo yarnJobsDo = toYarnJobsDo(jobObject);
			jobsList.add(yarnJobsDo);
		}
	}
	return jobsList;
}
 
Example 58
Project: conqat   File: BugzillaWebClient.java   Source Code and License 6 votes vote down vote up
/**
 * This executes an HTTP post on a Bugzilla URL and deals with the handling
 * of error messages.
 * 
 * @return the body of the HTTP response.
 * @throws BugzillaException
 *             If Bugzilla server responded with an error.
 * @throws IOException
 *             if an I/O problem occurs while obtaining the response from
 *             Bugzilla
 * @throws HttpException
 *             if a protocol exception occurs
 */
private String executePostMethod(String url, BugzillaFields fields)
		throws HttpException, IOException, BugzillaException {
	PostMethod postMethod = new PostMethod(server + "/" + url);

	postMethod.setRequestHeader("Content-Type",
			"application/x-www-form-urlencoded; charset=UTF-8");
	postMethod.setRequestBody(fields.createFormData());
	postMethod.setFollowRedirects(false);
	try {
		int result = client.executeMethod(postMethod);
		if (result != HttpStatus.SC_OK) {
			throw new BugzillaException(
					"Error occured when adding comment.");
		}

		String response = postMethod.getResponseBodyAsString();
		if (StringUtils.containsOneOf(response, ERROR_MARKERS)) {
			throw new BugzillaException(extractErrorMessage(response));
		}
		return response;
	} finally {
		postMethod.releaseConnection();
	}
}
 
Example 59
Project: osa   File: IngestAction.java   Source Code and License 6 votes vote down vote up
@HandlesEvent("getOnkiHttp")
public Resolution getOnkiHttp() throws HttpException, IOException {
    String json = "";
    String language = getUserLocale().toLanguageTag().split("-")[0];
    HttpClient httpClient = new HttpClient();
    httpClient.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
    httpClient.getParams().setParameter("http.protocol.content-charset", "UTF-8");
    
    GetMethod get = new GetMethod("http://onki.fi/key-"+this.getOnkiAccessKey()+"/api/v2/http/onto/" + ontologyId + "/search?q=" + term + "&l=" + language);
    httpClient.executeMethod(get);
    if (get.getStatusCode() == 200) {
        json = get.getResponseBodyAsString();
    }
    //logger.info("getOnkiHttp(): "+json);
    return new StreamingResolution(MIME_JS, json);
}
 
Example 60
Project: Kylin   File: RestClient.java   Source Code and License 6 votes vote down vote up
public void wipeCache(String type, String action, String name) throws IOException {
    String url = baseUrl + "/cache/" + type + "/" + name + "/" + action;
    HttpMethod request = new PutMethod(url);

    try {
        int code = client.executeMethod(request);
        String msg = Bytes.toString(request.getResponseBody());

        if (code != 200)
            throw new IOException("Invalid response " + code + " with cache wipe url " + url + "\n" + msg);

    } catch (HttpException ex) {
        throw new IOException(ex);
    } finally {
        request.releaseConnection();
    }
}