Esempio n. 1
0
  /**
   * 发生Get请求
   *
   * @param url 请求url
   * @return
   * @throws PortalException [参数说明]
   * @return String [返回类型说明]
   * @exception throws [违例类型] [违例说明]
   * @see [类、类#方法、类#成员]
   */
  public String get(String url) {
    GetMethod httpMethod = new GetMethod(url);

    // 设置header信息,传输XML格式的
    httpMethod.setRequestHeader(CONTENT_TYPE_NAME, CONTENT_TYPE_VALUE_XML_UTF_8);

    // 获取响应报文
    String response = null;
    try {
      // 处理响应结果码
      int resultCode = httpClient.executeMethod(httpMethod);
      if (HttpStatus.SC_OK == resultCode) {
        byte[] resBody = httpMethod.getResponseBody();
        if (null != resBody && resBody.length > 0) {
          response = new String(resBody, UTF_8);
        } else {
          LogUtil.error("Http resultCode=200, but responseBody is empty.");
        }
      } else {
        LogUtil.error("Http resultCode=" + resultCode);
      }
    } catch (Exception ex) {
      LogUtil.error("send http request error.", ex);
    } finally {
      if (null != httpMethod) {
        httpMethod.releaseConnection();
      }
    }

    return response;
  }
Esempio n. 2
0
  private Capacidad buscarCapacidad(int capacityCode) {
    HttpClient httpclient = getHttpClient();
    GetMethod get = new GetMethod(restUrl.getCapacidadUrl());
    get.addRequestHeader("Accept", "application/xml");
    Capacidad ret = null;
    try {
      int result = httpclient.executeMethod(get);
      if (logger.isTraceEnabled()) logger.trace("Response status code: " + result);
      String xmlString = get.getResponseBodyAsString();
      if (logger.isTraceEnabled()) logger.trace("Response body: " + xmlString);

      ret = importCapacidad(xmlString, capacityCode);
    } catch (HttpException e) {
      logger.error(e.getMessage());
    } catch (IOException e) {
      logger.error(e.getMessage());
    } catch (ParserConfigurationException e) {
      logger.error(e.getMessage());
    } catch (SAXException e) {
      logger.error(e.getMessage());
    } finally {
      get.releaseConnection();
    }
    return ret;
  }
Esempio n. 3
0
  private Sector buscarSector(int sectorCode) {
    HttpClient httpclient = getHttpClient();
    GetMethod get = new GetMethod(restUrl.getSectorUrl());
    get.addRequestHeader("Accept", "application/xml");
    Sector ret = null;
    try {
      int result = httpclient.executeMethod(get);
      logger.info("Response status code: " + result);
      String xmlString = get.getResponseBodyAsString();
      logger.info("Response body: " + xmlString);

      ret = importSector(xmlString, sectorCode);
    } catch (HttpException e) {
      logger.error(e.getMessage());
    } catch (IOException e) {
      logger.error(e.getMessage());
    } catch (ParserConfigurationException e) {
      logger.error(e.getMessage());
    } catch (SAXException e) {
      logger.error(e.getMessage());
    } finally {
      get.releaseConnection();
    }
    return ret;
  }
  /** Makes sure that a connection gets released after the content of the body is read. */
  public void testResponseAutoRelease() throws Exception {

    this.server.setHttpService(new EchoService());

    MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    connectionManager.getParams().setDefaultMaxConnectionsPerHost(1);

    client.setHttpConnectionManager(connectionManager);
    // we shouldn't have to wait if a connection is available
    client.getParams().setConnectionManagerTimeout(1);

    GetMethod getMethod = new GetMethod("/");

    try {
      client.executeMethod(getMethod);
    } catch (Exception e) {
      fail("error reading from server: " + e);
    }

    // this should release the connection
    getMethod.getResponseBody();

    getMethod = new GetMethod("/");

    try {
      // this should fail quickly if the connection has not been released
      client.executeMethod(getMethod);
    } catch (HttpException e) {
      fail("httpConnection does not appear to have been released: " + e);
    } catch (IOException e) {
      fail("error reading from server; " + e);
    }
  }
  protected ResponseStatus simpleHttpGet(
      final BiServerConnection connection, final String restUrl, boolean authenticate) {

    ResponseStatus responseStatus = new ResponseStatus();

    HttpClient client = getSimpleHttpClient(connection, authenticate);

    final String url =
        connection.getUrl().endsWith("/")
            ? (connection.getUrl() + restUrl)
            : (connection.getUrl() + "/" + restUrl);

    GetMethod get = createGetMethod(url, authenticate);

    try {
      // execute the GET
      client.executeMethod(get);

      responseStatus.setStatus(get.getStatusCode());
      responseStatus.setMessage(get.getResponseBodyAsString());

    } catch (Exception e) {

      responseStatus.setStatus(-1);
      responseStatus.setMessage(e.getMessage());

    } finally {
      // release any connection resources used by the method
      get.releaseConnection();
    }

    return responseStatus;
  }
Esempio n. 6
0
  /** Checks all the servers marked as being online if they still are online. */
  private synchronized void checkOnlineServers() {
    Iterator itr;
    itr = online.listIterator();
    while (itr.hasNext()) {
      Server server = (Server) itr.next();
      String url = getServerURL(server);
      GetMethod get = new GetMethod(url);
      get.setFollowRedirects(false);

      try {
        httpClient.executeMethod(get);
        if (!okServerResponse(get.getStatusCode())) {
          offline.add(server);
          itr.remove();
          log.debug("Server going OFFLINE! " + getServerURL(server));
          listener.serverOffline(server);
        }
      } catch (Exception e) {
        offline.add(server);
        itr.remove();
        log.debug("Server going OFFLINE! " + getServerURL(server));
        listener.serverOffline(server);
      } finally {
        get.releaseConnection();
      }
    }
  }
Esempio n. 7
0
 private HttpMethod redirectMethod(PostMethod postMethod) {
   GetMethod method = new GetMethod(postMethod.getResponseHeader("Location").getValue());
   for (Header header : postMethod.getRequestHeaders()) {
     method.addRequestHeader(header);
   }
   return method;
 }
  @Test
  public void testDELETEObjectUnAuthorized() throws Exception {
    Object objectToBeDeleted = getObject("XWiki.TagClass");

    DeleteMethod deleteMethod =
        executeDelete(
            getUriBuilder(ObjectResource.class)
                .build(
                    getWiki(),
                    "Main",
                    "WebHome",
                    objectToBeDeleted.getClassName(),
                    objectToBeDeleted.getNumber())
                .toString());
    Assert.assertEquals(
        getHttpMethodInfo(deleteMethod), HttpStatus.SC_UNAUTHORIZED, deleteMethod.getStatusCode());

    GetMethod getMethod =
        executeGet(
            getUriBuilder(ObjectResource.class)
                .build(
                    getWiki(),
                    "Main",
                    "WebHome",
                    objectToBeDeleted.getClassName(),
                    objectToBeDeleted.getNumber())
                .toString());
    Assert.assertEquals(getHttpMethodInfo(getMethod), HttpStatus.SC_OK, getMethod.getStatusCode());
  }
  @Override
  @Before
  public void setUp() throws Exception {
    super.setUp();

    GetMethod getMethod =
        executeGet(
            getUriBuilder(PageResource.class).build(getWiki(), "Main", "WebHome").toString());
    Assert.assertEquals(getHttpMethodInfo(getMethod), HttpStatus.SC_OK, getMethod.getStatusCode());

    Page page = (Page) unmarshaller.unmarshal(getMethod.getResponseBodyAsStream());
    Link link = getFirstLinkByRelation(page, Relations.OBJECTS);

    /* Create a tag object if it doesn't exist yet */
    if (link == null) {
      Object object = objectFactory.createObject();
      object.setClassName("XWiki.TagClass");

      PostMethod postMethod =
          executePostXml(
              getUriBuilder(ObjectsResource.class).build(getWiki(), "Main", "WebHome").toString(),
              object,
              "Admin",
              "admin");
      Assert.assertEquals(
          getHttpMethodInfo(postMethod), HttpStatus.SC_CREATED, postMethod.getStatusCode());
    }
  }
  /**
   * Call the GetMethod.
   *
   * @param url The URL for the HTTP GET method.
   * @return GetMethod
   * @throws WebserverSystemException If connection failed.
   */
  public GetMethod get(final String url) throws RepositoryException {

    GetMethod get = null;
    try {
      get = new GetMethod(url);
      int responseCode = getHttpClient().executeMethod(get);
      if ((responseCode / 100) != (HTTP_RESPONSE_OK / 100)) {

        String message = get.getResponseBodyAsString();
        if (message == null) {
          Header header = get.getResponseHeader("eSciDocException");
          String value = header.getValue();
          if (value != null) {
            message = "GET-Request with url " + url + " results with Exception:" + value + " .";
          } else {
            message = "Connection to '" + url + "' failed with response code " + responseCode;
          }
        }

        get.releaseConnection();
        log.info(message);
        throw new RepositoryException(message);
      }
    } catch (HttpException e) {
      throw new RepositoryException(e.getMessage(), e);
    } catch (IOException e) {
      throw new RepositoryException(e.getMessage(), e);
    }

    return get;
  }
  @Test
  public void testPOSTObject() throws Exception {
    final String TAG_VALUE = "TAG";

    Property property = new Property();
    property.setName("tags");
    property.setValue(TAG_VALUE);
    Object object = objectFactory.createObject();
    object.setClassName("XWiki.TagClass");
    object.getProperties().add(property);

    PostMethod postMethod =
        executePostXml(
            getUriBuilder(ObjectsResource.class).build(getWiki(), "Main", "WebHome").toString(),
            object,
            "Admin",
            "admin");
    Assert.assertEquals(
        getHttpMethodInfo(postMethod), HttpStatus.SC_CREATED, postMethod.getStatusCode());

    object = (Object) unmarshaller.unmarshal(postMethod.getResponseBodyAsStream());

    Assert.assertEquals(TAG_VALUE, getProperty(object, "tags").getValue());

    GetMethod getMethod =
        executeGet(
            getUriBuilder(ObjectResource.class)
                .build(getWiki(), "Main", "WebHome", object.getClassName(), object.getNumber())
                .toString());
    Assert.assertEquals(getHttpMethodInfo(getMethod), HttpStatus.SC_OK, getMethod.getStatusCode());

    object = (Object) unmarshaller.unmarshal(getMethod.getResponseBodyAsStream());

    Assert.assertEquals(TAG_VALUE, getProperty(object, "tags").getValue());
  }
Esempio n. 12
0
  @Test
  public void testGetXmlAndValidateXmlSchema()
      throws IOException, ParserConfigurationException, SAXException {
    HttpClient httpClient = new HttpClient();
    GetMethod get = new GetMethod("http://localhost/ch13personal/personal.xml");
    Document document;
    try {
      httpClient.executeMethod(get);
      InputStream input = get.getResponseBodyAsStream();
      // Parse the XML document into a DOM tree
      DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      document = parser.parse(input);
    } finally {
      get.releaseConnection();
    }

    // Create a SchemaFactory capable of understanding WXS schemas
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    // load a WXS schema, represented by a Schema instance
    Source schemaFile = new StreamSource(new File("src/main/webapp/personal.xsd"));
    Schema schema = factory.newSchema(schemaFile);

    // create a Validator instance, which can be used to validate an
    // instance document
    Validator validator = schema.newValidator();

    // validate the DOM tree
    validator.validate(new DOMSource(document));
  }
Esempio n. 13
0
 public PidListType getNextPid(int numPids, String namespace) throws IOException {
   PidListType result = null;
   try {
     StringBuilder uri = new StringBuilder(getBaseUrl());
     uri.append("/objects/nextPID?numPIDs=");
     uri.append(numPids);
     if (namespace != null) {
       uri.append("&namespace=");
       uri.append(namespace);
     }
     uri.append("&format=xml");
     GetMethod method = new GetMethod(uri.toString());
     int status = executeMethod(method);
     if (status == HttpStatus.SC_OK) {
       JAXBContext jc = JAXBContext.newInstance(PidListType.class);
       Unmarshaller um = jc.createUnmarshaller();
       InputStream in = method.getResponseBodyAsStream();
       result = (PidListType) um.unmarshal(in);
       in.close();
     }
     method.releaseConnection();
   } catch (JAXBException jaxbe) {
     log.error("Failed parsing result", jaxbe);
   }
   return result;
 }
Esempio n. 14
0
  public DatastreamProfile getDatastream(String pid, String dsId) throws IOException {
    DatastreamProfile result = null;

    try {
      StringBuilder uri = new StringBuilder(getBaseUrl());
      uri.append("/objects/");
      uri.append(pid);
      uri.append("/datastreams/");
      uri.append(dsId);
      uri.append(".xml");

      GetMethod method = new GetMethod(uri.toString());
      int status = executeMethod(method, true);
      if (status == 200) {
        JAXBContext jc = JAXBContext.newInstance(DatastreamProfile.class);
        Unmarshaller um = jc.createUnmarshaller();
        InputStream in = method.getResponseBodyAsStream();

        result = (DatastreamProfile) um.unmarshal(in);
        in.close();
      }
      method.releaseConnection();
    } catch (JAXBException jaxbe) {
      log.error("Failed parsing result", jaxbe);
    }

    return result;
  }
Esempio n. 15
0
 /**
  * 抓取网页静态内容: 下载 void
  *
  * @author wx
  */
 private void fetchStaticResources() {
   HttpClient client = new HttpClient();
   Set<String> urlSet = staticModels.keySet();
   Iterator<String> ite = urlSet.iterator();
   while (ite.hasNext()) {
     String key = ite.next();
     StaticResourceModel model = staticModels.get(key);
     // 执行下载
     GetMethod get = new GetMethod(model.getUrl());
     try {
       client.executeMethod(get);
       File path = new File(siteSaveFolder + model.savePath());
       if (!path.exists()) {
         path.mkdirs();
       }
       File storeFile = new File(siteSaveFolder + model.getFilePath());
       FileOutputStream output = new FileOutputStream(storeFile);
       // 得到网络资源的字节数组,并写入文件
       output.write(get.getResponseBody());
       output.close();
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
  @Test
  public void testPOSTObjectFormUrlEncoded() throws Exception {
    final String TAG_VALUE = "TAG";

    NameValuePair[] nameValuePairs = new NameValuePair[2];
    nameValuePairs[0] = new NameValuePair("className", "XWiki.TagClass");
    nameValuePairs[1] = new NameValuePair("property#tags", TAG_VALUE);

    PostMethod postMethod =
        executePostForm(
            getUriBuilder(ObjectsResource.class).build(getWiki(), "Main", "WebHome").toString(),
            nameValuePairs,
            "Admin",
            "admin");
    Assert.assertEquals(
        getHttpMethodInfo(postMethod), HttpStatus.SC_CREATED, postMethod.getStatusCode());

    Object object = (Object) unmarshaller.unmarshal(postMethod.getResponseBodyAsStream());

    Assert.assertEquals(TAG_VALUE, getProperty(object, "tags").getValue());

    GetMethod getMethod =
        executeGet(
            getUriBuilder(ObjectResource.class)
                .build(getWiki(), "Main", "WebHome", object.getClassName(), object.getNumber())
                .toString());
    Assert.assertEquals(getHttpMethodInfo(getMethod), HttpStatus.SC_OK, getMethod.getStatusCode());

    object = (Object) unmarshaller.unmarshal(getMethod.getResponseBodyAsStream());

    Assert.assertEquals(TAG_VALUE, getProperty(object, "tags").getValue());
  }
  @Override
  public String getReportTextContent(String rqAppId, String urlReport) throws Exception {
    logger.info("Get report contents as String");

    JRSConfig jrsConfig = configurationRepository.findJasperUser(rqAppId);
    JRSAuthen jrsAuthen = jrsConfig.getJrsAuthen();
    String passwordEncrypted = AES128Cipher.decrypt(jrsAuthen.getPassword());

    this.jasperAuthen(jrsAuthen.getUsername(), passwordEncrypted);

    Header mtHeader = new Header();
    mtHeader.setName("content-type");
    mtHeader.setValue("application/x-www-form-urlencoded");
    mtHeader.setName("accept");

    GetMethod mGet = new GetMethod(urlReport);
    mGet.addRequestHeader(mtHeader);
    httpClient.executeMethod(mGet);

    String value = mGet.getResponseBodyAsString().trim();
    logger.debug("Response Body is {}", value);

    if (isHTML(value)) {
      logger.error("The contents are HTML");
      throw new CustomGenericException("Cannot get the report contents as String");
    }

    return value;
  }
Esempio n. 18
0
 @Override
 public void download(String url, OutputStream output) {
   Cookie cookie = new Cookie(".dmm.co.jp", SESSION_ID_KEY, sessionId, "/", null, false);
   HttpClient client = new HttpClient();
   client.getState().addCookie(cookie);
   GetMethod method = new GetMethod(url);
   try {
     downloding.set(true);
     client.executeMethod(method);
     InputStream input = method.getResponseBodyAsStream();
     try {
       IOUtils.copyLarge(input, output);
       byte[] buffer = new byte[4096];
       int n = 0;
       while (downloding.get() && -1 != (n = input.read(buffer))) {
         output.write(buffer, 0, n);
       }
       if (!downloding.get()) {
         LOGGER.warn("interrupted to download " + url);
       }
     } finally {
       IOUtils.closeQuietly(input);
     }
   } catch (IOException e) {
     throw new EgetException("failed to download " + url, e);
   } finally {
     downloding.set(false);
     method.releaseConnection();
   }
 }
  private String extractResponse(GetMethod method) throws IOException {
    Header header = method.getResponseHeader("FIRST");

    assertNotNull("Received FIRST header", header);

    String result = header.getValue();

    assertNotNull("FIRST header not null", result);

    header = method.getResponseHeader("SECOND");

    assertNotNull("Received SECOND header", header);

    String second = header.getValue();

    assertNotNull("FIRST header not null", second);

    result.concat(second);

    // Read the response body.
    byte[] responseBody = method.getResponseBody();
    // Use caution: ensure correct character encoding and is not binary data
    result.concat(new String(responseBody));

    // Release the connection.
    //   method.releaseConnection();

    return result;
  }
Esempio n. 20
0
 public static boolean downloadFile(String url, String filePath) {
   HttpClient client = new HttpClient();
   GetMethod method = new GetMethod(url);
   method
       .getParams()
       .setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
   try {
     int statusCode = client.executeMethod(method);
     if (statusCode != HttpStatus.SC_OK) {
       logger.error("downloadFile fail.url={},status={}", url, statusCode);
       return false;
     }
     BufferedInputStream bis = new BufferedInputStream(method.getResponseBodyAsStream());
     FileOutputStream fos = new FileOutputStream(new File(filePath));
     BufferedOutputStream bos = new BufferedOutputStream(fos);
     int len;
     while ((len = bis.read()) != -1) {
       bos.write(len);
     }
     bos.flush();
     bos.close();
     fos.close();
     bis.close();
     return true;
   } catch (Exception e) {
     logger.error("url=" + url, e);
     return false;
   } finally {
     method.releaseConnection();
   }
 }
  public void testDroppedThread() throws Exception {

    this.server.setHttpService(new EchoService());

    MultiThreadedHttpConnectionManager mthcm = new MultiThreadedHttpConnectionManager();
    client.setHttpConnectionManager(mthcm);
    WeakReference wr = new WeakReference(mthcm);

    GetMethod method = new GetMethod("/");
    client.executeMethod(method);
    method.releaseConnection();

    mthcm = null;
    client = null;
    method = null;

    System.gc();

    // this sleep appears to be necessary in order to give the JVM
    // time to clean up the miscellaneous pointers to the connection manager
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      fail("shouldn't be interrupted.");
    }

    Object connectionManager = wr.get();
    assertNull("connectionManager should be null", connectionManager);
  }
  private String sendRequest(String url) {

    String body = "";
    client = new HttpClient();
    method = new GetMethod(url);
    // 设置timeout
    method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
    // 设置请求重试处理
    method
        .getParams()
        .setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
    int statusCode;
    try {
      statusCode = client.executeMethod(method);
      // 判断访问状态码
      if (statusCode != 200) {
        LOG.error("获取映射关系失败");
        return body;
      }
      body = method.getResponseBodyAsString();
    } catch (HttpException e) {
      LOG.error("请求映射关系失败", e);
    } catch (IOException e) {
      LOG.error("请求映射关系失败", e);
    }
    return body;
  }
  public void testGetFromMultipleThreads() {

    this.server.setHttpService(new EchoService());

    client.setHttpConnectionManager(new MultiThreadedHttpConnectionManager());
    ExecuteMethodThread[] threads = new ExecuteMethodThread[10];

    for (int i = 0; i < threads.length; i++) {
      GetMethod method = new GetMethod("/");
      method.setFollowRedirects(true);

      threads[i] = new ExecuteMethodThread(method, client);
      threads[i].start();
    }

    for (int i = 0; i < threads.length; i++) {
      try {
        // wait until this thread finishes. we'll give it 10 seconds,
        // but it shouldn't take that long
        threads[i].join(10000);
      } catch (InterruptedException e) {
      }
      // make sure an exception did not occur
      Exception e = threads[i].getException();
      if (e != null) {
        fail("An error occured in the get: " + e);
      }
      // we should have a 200 status
      assertEquals(threads[i].getMethod().getStatusCode(), HttpStatus.SC_OK);
    }
  }
Esempio n. 24
0
  public void httpOnline() throws HttpException, IOException {
    /* 1 生成 HttpClinet 对象并设置参数*/
    HttpClient httpClient = new HttpClient();
    // 设置 Http 连接超时为5秒
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
    /*2 生成 GetMethod 对象并设置参数*/
    GetMethod getMethod = new GetMethod(m_ipAddr);
    // 设置 get 请求超时为 5 秒
    getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
    // 设置请求重试处理,用的是默认的重试处理:请求三次
    getMethod
        .getParams()
        .setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
    /*3 执行 HTTP GET 请求*/

    long startTime = System.currentTimeMillis();
    if (HttpStatus.SC_OK == httpClient.executeMethod(getMethod)) {
      statusCode = "Up";
      responseTime = System.currentTimeMillis() - startTime;
    } else {
      statusCode = "Down";
      responseTime = -1;
    }

    /*6 .释放连接*/
    getMethod.releaseConnection();
  }
Esempio n. 25
0
  private void doGet(
      String realm,
      String host,
      String user,
      String pass,
      String url,
      boolean handshake,
      boolean preemtive,
      int result)
      throws Exception {
    HttpClient client = new HttpClient();
    client.getParams().setAuthenticationPreemptive(preemtive);
    client
        .getState()
        .setCredentials(
            new AuthScope(host, -1, realm), new UsernamePasswordCredentials(user, pass));
    GetMethod get = new GetMethod(url);
    get.setDoAuthentication(handshake);

    try {
      int status = client.executeMethod(get);
      assertEquals(result, status);
    } finally {
      get.releaseConnection();
    }
  }
Esempio n. 26
0
  protected void loadNetImage() {
    String url = "http://ww2.sinaimg.cn/thumbnail/675e5a2bjw1e0pydwgwgnj.jpg";
    HttpClient httpClient = null;
    GetMethod httpGet = null;
    Bitmap bitmap = null;

    try {
      httpClient = getHttpClient();
      httpGet = getHttpGet(url, null, null);
      if (httpClient.executeMethod(httpGet) == HttpStatus.SC_OK) {
        InputStream inStream = httpGet.getResponseBodyAsStream();
        bitmap = BitmapFactory.decodeStream(inStream);
        inStream.close();

        mImageView03.setImageBitmap(bitmap);
      }
    } catch (HttpException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      httpGet.releaseConnection();
      httpClient = null;
    }
  }
Esempio n. 27
0
  private ClasificacionOrganizacion findRestClasificacionOrganizacion(Integer id) {
    HttpClient httpclient = getHttpClient();
    GetMethod get = new GetMethod(restUrl.getClassOrganizacionUrl());
    get.addRequestHeader("Accept", "application/xml");
    ClasificacionOrganizacion ret = null;
    try {
      int result = httpclient.executeMethod(get);
      logger.info("Response status code: " + result);
      String xmlString = get.getResponseBodyAsString();
      logger.info("Response body: " + xmlString);

      ret = importClasificacionOrganizacion(xmlString, id);
    } catch (HttpException e) {
      logger.error(e.getMessage());
    } catch (IOException e) {
      logger.error(e.getMessage());
    } catch (ParserConfigurationException e) {
      logger.error(e.getMessage());
    } catch (SAXException e) {
      logger.error(e.getMessage());
    } finally {
      get.releaseConnection();
    }
    return ret;
  }
Esempio n. 28
0
  protected void dialImpl(String number) throws ExceptionLP {
    myLogger.info("Dialing <" + number + "> ...");

    GetMethod method = getHttpMethod(number);

    try {
      prepareClient(client, method);
      int status = client.executeMethod(method);

      myLogger.info("Dialing done with HTTP Status: <" + status + ">");
      if (status != HttpStatus.SC_OK) {
        byte[] responseBody = method.getResponseBody();
        String s = new String(responseBody);

        myLogger.debug("Done dialing with response <" + s + ">");
      }
    } catch (HttpException ex) {
      myLogger.debug("Got HttpException <" + ex.getMessage() + ">");
      throw new ExceptionLP(EJBExceptionLP.FEHLER_TELEFON_WAHLVORGANG, ex.getMessage(), ex);
    } catch (IOException ex) {
      myLogger.debug("Got IOException <" + ex.getMessage() + ">");
      throw new ExceptionLP(EJBExceptionLP.FEHLER_TELEFON_WAHLVORGANG, ex.getMessage(), ex);
    } finally {
      method.releaseConnection();
    }
  }
  private ServerStatus getSpaces(List<Space> spaces, JSONObject orgJSON) throws Exception {
    URI targetURI = URIUtil.toURI(target.getUrl());
    URI spaceURI = targetURI.resolve(orgJSON.getJSONObject("entity").getString("spaces_url"));

    GetMethod getDomainsMethod = new GetMethod(spaceURI.toString());
    HttpUtil.configureHttpMethod(getDomainsMethod, target);
    getDomainsMethod.setQueryString("inline-relations-depth=1"); // $NON-NLS-1$

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

    /* extract available spaces */
    JSONObject orgs = status.getJsonData();

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

    /* look if the domain is available */
    int resources = orgs.getJSONArray(CFProtocolConstants.V2_KEY_RESOURCES).length();
    for (int k = 0; k < resources; ++k) {
      JSONObject spaceJSON =
          orgs.getJSONArray(CFProtocolConstants.V2_KEY_RESOURCES).getJSONObject(k);
      spaces.add(new Space().setCFJSON(spaceJSON));
    }

    return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK);
  }
  /*
   * Tests a combination of the <tt>havingHeader</tt> methods.
   */
  @Test
  public void havingHeader() throws Exception {

    onRequest()
        .havingHeader("hdr1")
        .havingHeader("hdr1", not(empty()))
        .havingHeader("hDR1", hasSize(1))
        .havingHeader("hdr1", everyItem(not(isEmptyOrNullString())))
        .havingHeader("hdr1", contains("h1v1"))
        .havingHeaderEqualTo("hdr1", "h1v1")
        .havingHeader("HDr2")
        .havingHeader("hdr2", hasSize(2))
        .havingHeader("hdr2", contains("h2v1", "h2v2"))
        .havingHeader("hdr2", hasItem("h2v1"))
        .havingHeader("hdr3", nullValue())
        .havingHeaderEqualTo("hdr2", "h2v1")
        .havingHeaderEqualTo("HDR2", "h2v2")
        .havingHeaders("hDR1", "hdr2")
        .respond()
        .withStatus(201);

    final GetMethod method = new GetMethod("http://localhost:" + port());
    method.addRequestHeader("hdr1", "h1v1");
    method.addRequestHeader("hdr2", "h2v1");
    method.addRequestHeader("hdr2", "h2v2");

    int status = client.executeMethod(method);
    assertThat(status, is(201));
  }