@SuppressWarnings("unchecked")
  public <T> T executeRetrieveObject(
      final Type returnObjectType, final String uri, final Map<String, String> parameters)
      throws CloudstackRESTException {
    final GetMethod gm = (GetMethod) createMethod(GET_METHOD_TYPE, uri);
    gm.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE);
    if (parameters != null && !parameters.isEmpty()) {
      final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(parameters.size());
      for (final Entry<String, String> e : parameters.entrySet()) {
        nameValuePairs.add(new NameValuePair(e.getKey(), e.getValue()));
      }
      gm.setQueryString(nameValuePairs.toArray(new NameValuePair[0]));
    }

    executeMethod(gm);

    if (gm.getStatusCode() != HttpStatus.SC_OK) {
      final String errorMessage = responseToErrorMessage(gm);
      gm.releaseConnection();
      s_logger.error("Failed to retrieve object : " + errorMessage);
      throw new CloudstackRESTException("Failed to retrieve object : " + errorMessage);
    }

    T returnValue;
    try {
      returnValue = (T) gson.fromJson(gm.getResponseBodyAsString(), returnObjectType);
    } catch (final IOException e) {
      s_logger.error("IOException while retrieving response body", e);
      throw new CloudstackRESTException(e);
    } finally {
      gm.releaseConnection();
    }
    return returnValue;
  }
Example #2
0
  private String getXmlToken() {
    String token = null;
    HttpClient httpclient = getHttpClient();
    GetMethod get = new GetMethod(restUrl.getTokenUrl());
    get.addRequestHeader("Accept", "application/xml");

    NameValuePair userParam = new NameValuePair(USERNAME_PARAM, satelite.getUser());
    NameValuePair passwordParam = new NameValuePair(PASSWORD_PARAM, satelite.getPassword());
    NameValuePair[] params = new NameValuePair[] {userParam, passwordParam};

    get.setQueryString(params);
    try {
      int statusCode = httpclient.executeMethod(get);
      if (statusCode != HttpStatus.SC_OK) {
        logger.error("Method failed: " + get.getStatusLine());
      }
      token = parseToken(get.getResponseBodyAsString());
    } 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 token;
  }
Example #3
0
  /** AKA scraping */
  public TorrentStatus getStatus() throws IOException {
    if (!isGetStatusSupported()) {
      throw new IllegalStateException("Get status (scraping) not supported on this tracker");
    }
    String path = announceUrl.getFile();
    int i = path.lastIndexOf('/');
    path = path.substring(0, i + 1) + "scrape" + path.substring(i + ANNOUNCE.length() + 1);

    GetMethod method = new GetMethod(path);
    method.setRequestHeader("User-Agent", "BlackBits/0.1");
    StringBuffer queryString =
        new StringBuffer(announceUrl.getQuery() == null ? "" : announceUrl.getQuery());
    queryString.append("info_hash=" + URLUtils.encode(infoHash.getBytes()));
    method.setQueryString(queryString.toString());
    httpClient.executeMethod(method);

    BDecoder decoder = new BDecoder(method.getResponseBodyAsStream());
    BDictionary dictionary = (BDictionary) decoder.decodeNext();
    BDictionary files = (BDictionary) dictionary.get("files");
    String key = (String) files.keySet().iterator().next();
    BDictionary info = (BDictionary) files.get(key);
    BLong seeders = (BLong) info.get("complete");
    BLong leechers = (BLong) info.get("incomplete");
    BLong numberOfDownloads = (BLong) info.get("downloaded");
    return new TorrentStatus(seeders.intValue(), leechers.intValue(), numberOfDownloads.intValue());
  }
  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);
  }
  /**
   * Send the command to Solr using a GET
   *
   * @param queryString
   * @param url
   * @return
   * @throws IOException
   */
  private static String sendGetCommand(String queryString, String url) throws IOException {
    String results = null;
    HttpClient client = new HttpClient();
    GetMethod get = new GetMethod(url);
    get.setQueryString(queryString.trim());

    client.executeMethod(get);
    try {
      // Execute the method.
      int statusCode = client.executeMethod(get);

      if (statusCode != HttpStatus.SC_OK) {
        System.err.println("Method failed: " + get.getStatusLine());
        results = "Method failed: " + get.getStatusLine();
      }

      results = getStringFromStream(get.getResponseBodyAsStream());
    } catch (HttpException e) {
      System.err.println("Fatal protocol violation: " + e.getMessage());
      e.printStackTrace();
    } catch (IOException e) {
      System.err.println("Fatal transport error: " + e.getMessage());
      e.printStackTrace();
    } finally {
      // Release the connection.
      get.releaseConnection();
    }
    return results;
  }
 private String getHistoryFile(Configuration conf, String jobId) throws IOException {
   String jtAddress = "scheme://" + conf.get("mapred.job.tracker");
   String jtHttpAddr = "scheme://" + conf.get("mapred.job.tracker.http.address");
   try {
     String host = new URI(jtAddress).getHost();
     int port = new URI(jtHttpAddr).getPort();
     HttpClient client = new HttpClient();
     String jobUrl = "http://" + host + ":" + port + "/jobdetails.jsp";
     GetMethod get = new GetMethod(jobUrl);
     get.setQueryString("jobid=" + jobId);
     get.setFollowRedirects(false);
     int status = client.executeMethod(get);
     String file = null;
     if (status == HttpStatus.SC_MOVED_PERMANENTLY || status == HttpStatus.SC_MOVED_TEMPORARILY) {
       file = get.getResponseHeader("Location").toString();
       file = file.substring(file.lastIndexOf('=') + 1);
       file = JobHistory.JobInfo.decodeJobHistoryFileName(file);
     } else {
       LOG.warn("JobURL {} for id: {} returned {}", jobUrl, jobId, status);
     }
     return file;
   } catch (URISyntaxException e) {
     throw new IOException("JT Address: " + jtAddress + ", http Address: " + jtHttpAddr, e);
   }
 }
 @NotNull
 @Override
 protected GetMethod getMultipleIssuesSearchMethod(String jql, int max) {
   GetMethod method = super.getMultipleIssuesSearchMethod(jql, max);
   method.setQueryString(
       method.getQueryString() + "&fields=" + JiraIssueApi2.REQUIRED_RESPONSE_FIELDS);
   return method;
 }
 @NotNull
 @Override
 protected GetMethod getSingleIssueSearchMethod(String key) {
   final GetMethod method = super.getSingleIssueSearchMethod(key);
   final String oldParams = method.getQueryString() == null ? "" : method.getQueryString();
   method.setQueryString(oldParams + "&fields=" + JiraIssueApi2.REQUIRED_RESPONSE_FIELDS);
   return method;
 }
Example #9
0
 public void testGetMethodOverwriteQueryString() throws Exception {
   this.server.setHttpService(new QueryInfoService());
   GetMethod method = new GetMethod("/");
   method.setQueryString("query=string");
   method.setQueryString(
       new NameValuePair[] {
         new NameValuePair("param", "eter"), new NameValuePair("para", "meter")
       });
   try {
     this.client.executeMethod(method);
     assertEquals(200, method.getStatusCode());
     String response = method.getResponseBodyAsString();
     assertFalse(response.indexOf("QueryString=\"query=string\"") >= 0);
     assertTrue(response.indexOf("QueryString=\"param=eter&para=meter\"") >= 0);
   } finally {
     method.releaseConnection();
   }
 }
Example #10
0
  /**
   * http 통신을 한다.GET 방식
   *
   * @param url
   * @param queryString
   * @return 서버에서 받은 body 스트링
   */
  public String execute(String url, String queryString, boolean sslExceptionIgnore)
      throws HttpNetAgentException {

    GetMethod getMethod = new GetMethod(url);
    getMethod.setQueryString(queryString);
    String responseBody = send(getMethod, sslExceptionIgnore);

    return responseBody;
  }
Example #11
0
  /**
   * GET 요청을 처리한다.
   *
   * @param baseUrl 기본 URL
   * @param httpInvocation 기본 URL뒤에 붙는 경로
   * @return
   */
  public <T> T get(String baseUrl, HttpInvocation<T> httpInvocation) {
    Assert.notNull(httpInvocation, "httpInvocation 값은 null일 수 없다.");

    GetMethod getMethod = new GetMethod(baseUrl + httpInvocation.getUri());
    if (httpInvocation.getParameters().length > 0) {
      getMethod.setQueryString(httpInvocation.getParameters());
    }
    return invoke(getMethod, httpInvocation);
  }
Example #12
0
 protected String doHttpGet(String param) throws URISyntaxException, HttpException, IOException {
   URI uri = new URI(HTTP_LOCALHOST_60198);
   GetMethod getMethod = new GetMethod(uri.toString());
   getMethod.setQueryString("param=" + param);
   HttpConnection cnn = new HttpConnection(uri.getHost(), uri.getPort());
   cnn.open();
   getMethod.execute(new HttpState(), cnn);
   System.out.println("GetResponse: " + getMethod.getResponseBodyAsString());
   return getMethod.getResponseBodyAsString();
 }
  @Override
  public long getTargetVersion(PublishingTargetItem target, String site) {
    long version = -1;
    if (target.getVersionUrl() != null && !target.getVersionUrl().isEmpty()) {
      LOGGER.debug(String.format("Get deployment agent version for target ", target.getName()));
      URL versionUrl = null;
      try {
        versionUrl = new URL(target.getVersionUrl());
      } catch (MalformedURLException e) {
        LOGGER.error(String.format("Invalid get version URL for target [%s]", target.getName()), e);
      }
      GetMethod getMethod = null;
      HttpClient client = null;
      try {
        getMethod = new GetMethod(target.getVersionUrl());
        String siteId = target.getSiteId();
        if (StringUtils.isEmpty(siteId)) {
          siteId = site;
        }
        getMethod.setQueryString(
            new NameValuePair[] {
              new NameValuePair(TARGET_REQUEST_PARAMETER, target.getTarget()),
              new NameValuePair(SITE_REQUEST_PARAMETER, siteId)
            });
        client = new HttpClient();
        int status = client.executeMethod(getMethod);
        if (status == HttpStatus.SC_OK) {
          String responseText = getMethod.getResponseBodyAsString();
          if (responseText != null && !responseText.isEmpty()) {
            version = Long.parseLong(responseText.trim());
          } else {
            version = 0;
          }
        }

      } catch (Exception e) {
        // LOGGER.error(String.format("Target (%s) responded with error while checking target
        // version. Get version failed for url %s", target.getName(), target.getVersionUrl()));

      } finally {
        if (client != null) {
          HttpConnectionManager mgr = client.getHttpConnectionManager();
          if (mgr instanceof SimpleHttpConnectionManager) {
            ((SimpleHttpConnectionManager) mgr).shutdown();
          }
        }
        if (getMethod != null) {
          getMethod.releaseConnection();
        }
        getMethod = null;
        client = null;
      }
    }
    return version;
  }
  @Override
  protected RemoteOperationResult run(OwnCloudClient client) {
    RemoteOperationResult result = null;
    int status = -1;

    GetMethod get = null;

    try {
      // Get Method
      get = new GetMethod(client.getBaseUri() + ShareUtils.SHARING_API_PATH);

      // Add Parameters to Get Method
      get.setQueryString(
          new NameValuePair[] {
            new NameValuePair(PARAM_PATH, mRemoteFilePath),
            new NameValuePair(PARAM_RESHARES, String.valueOf(mReshares)),
            new NameValuePair(PARAM_SUBFILES, String.valueOf(mSubfiles))
          });

      get.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE);

      status = client.executeMethod(get);

      if (isSuccess(status)) {
        String response = get.getResponseBodyAsString();

        // Parse xml response and obtain the list of shares
        ShareToRemoteOperationResultParser parser =
            new ShareToRemoteOperationResultParser(new ShareXMLParser());
        parser.setOwnCloudVersion(client.getOwnCloudVersion());
        parser.setServerBaseUri(client.getBaseUri());
        result = parser.parse(response);

        if (result.isSuccess()) {
          Log_OC.d(TAG, "Got " + result.getData().size() + " shares");
        }

      } else {
        result = new RemoteOperationResult(false, status, get.getResponseHeaders());
      }

    } catch (Exception e) {
      result = new RemoteOperationResult(e);
      Log_OC.e(TAG, "Exception while getting shares", e);

    } finally {
      if (get != null) {
        get.releaseConnection();
      }
    }
    return result;
  }
Example #15
0
 /**
  * Test that {@link GetMethod#addParameter(java.lang.String,java.lang.String)} works with a
  * parameter name but no value.
  */
 public void testGetMethodParameterWithoutValue() throws Exception {
   this.server.setHttpService(new QueryInfoService());
   GetMethod method = new GetMethod("/");
   method.setQueryString(new NameValuePair[] {new NameValuePair("param-without-value", null)});
   try {
     this.client.executeMethod(method);
     assertEquals(200, method.getStatusCode());
     String response = method.getResponseBodyAsString();
     assertTrue(response.indexOf("QueryString=\"param-without-value=\"") >= 0);
   } finally {
     method.releaseConnection();
   }
 }
Example #16
0
 /**
  * Test that {@link GetMethod#setQueryString(java.lang.String)} can include a leading question
  * mark.
  */
 public void testGetMethodQueryString() throws Exception {
   this.server.setHttpService(new QueryInfoService());
   GetMethod method = new GetMethod("/");
   method.setQueryString("?hadQuestionMark=true");
   try {
     this.client.executeMethod(method);
     assertEquals(200, method.getStatusCode());
     String response = method.getResponseBodyAsString();
     assertTrue(response.indexOf("QueryString=\"hadQuestionMark=true\"") >= 0);
   } finally {
     method.releaseConnection();
   }
 }
Example #17
0
 /**
  * Test that {@link GetMethod#addParameter(java.lang.String,java.lang.String)} works with a
  * parameter name that occurs more than once.
  */
 public void testGetMethodParameterAppearsTwice() throws Exception {
   this.server.setHttpService(new QueryInfoService());
   GetMethod method = new GetMethod("/");
   method.setQueryString(
       new NameValuePair[] {new NameValuePair("foo", "one"), new NameValuePair("foo", "two")});
   try {
     this.client.executeMethod(method);
     assertEquals(200, method.getStatusCode());
     String response = method.getResponseBodyAsString();
     assertTrue(response.indexOf("QueryString=\"foo=one&foo=two\"") >= 0);
   } finally {
     method.releaseConnection();
   }
 }
  /**
   * 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, final HashMap<String, String> params)
      throws RepositoryException {

    GetMethod get = null;
    try {
      get = new GetMethod(url);
      Set<String> paramKeys = params.keySet();
      NameValuePair[] paramsArray = new NameValuePair[paramKeys.size()];

      Iterator<String> iterator = paramKeys.iterator();
      int i = 0;
      while (iterator.hasNext()) {
        String key = iterator.next();
        String value = params.get(key);
        paramsArray[i] = new NameValuePair(key, value);
        i++;
      }
      if (params.size() > 0) {
        String queryString = EncodingUtil.formUrlEncode(paramsArray, "UTF-8");
        get.setQueryString(queryString);
      }
      // get.setQueryString(paramsArray);
      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;
  }
Example #19
0
 /**
  * GET请求方法
  *
  * @param url
  * @return
  * @throws IOException
  */
 public static GetMethod getMethod(String url, Map<String, String> parameter) throws IOException {
   GetMethod get = new GetMethod(url);
   // get.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
   if (parameter != null) {
     NameValuePair[] params = new NameValuePair[parameter.keySet().size()];
     Iterator<String> it = parameter.keySet().iterator();
     int i = 0;
     String key = "";
     while (it.hasNext()) {
       key = it.next();
       params[i] = new NameValuePair(key, parameter.get(key));
       i++;
     }
     get.setQueryString(params);
   }
   return get;
 }
  @Override
  protected ServerStatus _doIt() {
    try {
      /* get available orgs */
      URI targetURI = URIUtil.toURI(target.getUrl());
      URI orgsURI = targetURI.resolve("/v2/organizations");

      GetMethod getDomainsMethod = new GetMethod(orgsURI.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 orgs */
      JSONObject orgs = status.getJsonData();

      if (orgs.getInt(CFProtocolConstants.V2_KEY_TOTAL_RESULTS) < 1) {
        return new ServerStatus(IStatus.OK, HttpServletResponse.SC_OK, null, null);
      }

      /* look if the domain is available */
      JSONObject result = new JSONObject();
      int resources = orgs.getJSONArray(CFProtocolConstants.V2_KEY_RESOURCES).length();
      for (int k = 0; k < resources; ++k) {
        JSONObject orgJSON =
            orgs.getJSONArray(CFProtocolConstants.V2_KEY_RESOURCES).getJSONObject(k);
        List<Space> spaces = new ArrayList<Space>();
        status = getSpaces(spaces, orgJSON);
        if (!status.isOK()) return status;
        OrgWithSpaces orgWithSpaces = new OrgWithSpaces();
        orgWithSpaces.setCFJSON(orgJSON);
        orgWithSpaces.setSpaces(spaces);
        result.append("Orgs", orgWithSpaces.toJSON());
      }

      return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, result);
    } catch (Exception e) {
      String msg =
          NLS.bind("An error occured when performing operation {0}", commandName); // $NON-NLS-1$
      logger.error(msg, e);
      return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
    }
  }
  @Override
  public TranslationResult translate(String word, String from, String to) {

    log.debug(
        "Request for translation of {} from language {} to {}", new String[] {word, from, to});

    String langPair = from + "|" + to;

    GetMethod getMethod = new GetMethod();
    //		getMethod.setRequestHeader(new Header("Referer", "http://www.somesite.com"));
    getMethod.setQueryString(
        new NameValuePair[] {
          new NameValuePair("v", "1.0"),
          new NameValuePair("q", word),
          new NameValuePair("langpair", langPair)
        });
    getMethod.setPath("/ajax/services/language/translate");
    try {
      HttpClient client = new HttpClient();
      client.startSession("ajax.googleapis.com", 80);
      client.executeMethod(getMethod);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }

    String response = getMethod.getResponseBodyAsString();
    log.debug("Response of API: {}", response);

    Word translatedWord = null;
    try {
      JSONObject jsonObject = new JSONObject(response);
      JSONObject responseObject = jsonObject.getJSONObject("responseData");
      String translatedText = responseObject.getString("translatedText");
      translatedWord = new Word(translatedText);
    } catch (JSONException e) {
      throw new RuntimeException(e);
    }

    List<Word> words = Lists.newArrayList();
    words.add(translatedWord);

    return new TranslationResult(words);
  }
 // TODO Jean
 public static URL createQuery(final int port, final CidsBean bean) {
   if ((port < 0) || (port > 65535)) {
     log.warn("Crossover: verdisCrossoverPort ist ungültig: " + port);
   } else {
     try {
       // ToDo ugly because is static
       PARAMETER_KASSENZEICHEN.setValue(
           String.valueOf(bean.getProperty("kassenzeichennummer8"))); // kz.getId().toString());
       final GetMethod tmp = new GetMethod(server + port + request);
       tmp.setQueryString(new NameValuePair[] {PARAMETER_KASSENZEICHEN});
       if (log.isDebugEnabled()) {
         log.debug("Crossover: verdisCrossOverQuery: " + tmp.getURI().toString());
       }
       return new URL(tmp.getURI().toString());
     } catch (Exception ex) {
       log.error("Crossover: Fehler beim fernsteuern von VerdIS.", ex);
     }
   }
   return null;
 }
Example #23
0
 /**
  * Test that {@link GetMethod#addParameter(java.lang.String,java.lang.String)} works with multiple
  * parameters.
  */
 public void testGetMethodMultiParameters() throws Exception {
   this.server.setHttpService(new QueryInfoService());
   GetMethod method = new GetMethod("/");
   method.setQueryString(
       new NameValuePair[] {
         new NameValuePair("param-one", "param-value"),
         new NameValuePair("param-two", "param-value2"),
         new NameValuePair("special-chars", ":/?~.")
       });
   try {
     this.client.executeMethod(method);
     assertEquals(200, method.getStatusCode());
     String response = method.getResponseBodyAsString();
     assertTrue(
         response.indexOf(
                 "QueryString=\"param-one=param-value&param-two=param-value2&special-chars=:/?~.\"")
             >= 0);
   } finally {
     method.releaseConnection();
   }
 }
Example #24
0
 private TrackerResponse sendEvent(
     long uploadedBytes, long downloadedBytes, long bytesLeftToDownload, String event)
     throws IOException, TrackerCommunicationException {
   GetMethod method = new GetMethod(announceUrl.getFile());
   method.setRequestHeader("User-Agent", "BlackBits/0.1");
   StringBuffer queryString =
       new StringBuffer(announceUrl.getQuery() == null ? "" : announceUrl.getQuery());
   queryString.append("info_hash=" + URLUtils.encode(infoHash.getBytes()));
   queryString.append("&peer_id=" + URLUtils.encode(localPeer.getId()));
   queryString.append("&port=" + localPeer.getPort());
   queryString.append("&uploaded=" + uploadedBytes);
   queryString.append("&downloaded=" + downloadedBytes);
   queryString.append("&left=" + bytesLeftToDownload);
   if (event != null) {
     queryString.append("&event=" + event);
   }
   if (localPeer.getAddress() != null) {
     queryString.append("&ip=" + localPeer.getAddress());
   }
   method.setQueryString(queryString.toString());
   httpClient.executeMethod(method);
   return decodeResponse(method);
 }
Example #25
0
  private void checkUpdate()
      throws IOException, SAXException, ParserConfigurationException, XPathExpressionException {
    String url;
    try {
      url = Registry.getProperty("updater.url");
    } catch (Exception e) {
      throw new IOException(e.getMessage()); // i hate leaking "exception"
    }
    HttpClient client = new HttpClient();

    Map<String, Object> params = new HashMap<String, Object>();
    params.put("version", Build.getVersion());
    params.put("release", "" + Build.getRelease());
    if (PreferencesManager.getVersionIndependentPreferences()
        .getBoolean("updater.include.usageData", true)) {
      params.put("uuid", Application.getUUID());
      params.put("platform.arch", Platform.getArch());
      params.put("platform.os", Platform.getOS().getCanonicalName());
      params.put("platform.os.version", Platform.getOS().getVersion());
      params.put("locale.country", LanguageBundle.getCurrentLocale().getCountry());
      params.put("locale.language", LanguageBundle.getCurrentLocale().getLanguage());
    }

    List<NameValuePair> nvp = new ArrayList<NameValuePair>();
    for (String key : params.keySet()) nvp.add(new NameValuePair(key, "" + params.get(key)));

    GetMethod request = new GetMethod(url);
    request.setQueryString(nvp.toArray(new NameValuePair[nvp.size()]));
    LogFactory.getLog(getClass()).info(String.format("Checking for updates: %s", request.getURI()));
    client.executeMethod(request);
    String response = request.getResponseBodyAsString();
    Document doc = DomUtil.parseXMLString(response);
    availableRelease = XPathHelper.xpathAsDouble(doc, "/korsakow/release");
    availableVersion = XPathHelper.xpathAsString(doc, "/korsakow/version");
    message = XPathHelper.xpathAsString(doc, "/korsakow/message");
  }
  @Override
  protected void doRequest(
      HttpServletRequest request, HttpServletResponse response, RequestType requestType)
      throws ServletException, IOException {
    RegexHelper MATCH_URL_REGEX = new RegexHelper("/+(.+)", "i");
    RegexHelper TEST_HOST_IN_URL_REGEX = new RegexHelper("^http\\:/{2}([^/]+)/", "i");
    RegexHelper SQUARE_BRACKETS_REGEX = new RegexHelper("\\[\\]", "g");

    logRequest(logger, request, requestType);

    String url = MATCH_URL_REGEX.matchFirst(request.getPathInfo());
    url =
        url.replaceFirst(
            "http:/{1,2}", "http://"); // stupid hack as tomcat 6.0 removes second forward slash
    String queryString = request.getQueryString();

    if (0 < url.length()) {
      if (!TEST_HOST_IN_URL_REGEX.test(url)) { // no host here, will self
        url = "http://localhost:" + String.valueOf(request.getLocalPort()) + "/" + url;
      }
      logger.debug("Will access [{}]", url);

      GetMethod getMethod = new GetMethod(url);

      if (null != queryString) {
        queryString = SQUARE_BRACKETS_REGEX.replace(queryString, "%5B%5D");
        getMethod.setQueryString(queryString);
      }

      Enumeration requestHeaders = request.getHeaderNames();
      while (requestHeaders.hasMoreElements()) {
        String name = (String) requestHeaders.nextElement();
        String value = request.getHeader(name);
        if (null != value) {
          getMethod.setRequestHeader(name, value);
        }
      }

      try {
        httpClient.executeMethod(getMethod);

        int statusCode = getMethod.getStatusCode();
        long contentLength = getMethod.getResponseContentLength();
        logger.debug("Got response [{}], length [{}]", statusCode, contentLength);

        Header[] responseHeaders = getMethod.getResponseHeaders();
        for (Header responseHeader : responseHeaders) {
          String name = responseHeader.getName();
          String value = responseHeader.getValue();
          if (null != name
              && null != value
              && !(name.equals("Server")
                  || name.equals("Date")
                  || name.equals("Transfer-Encoding"))) {
            response.setHeader(responseHeader.getName(), responseHeader.getValue());
          }
        }

        if (200 != statusCode) {
          response.setStatus(statusCode);
        }

        InputStream inStream = getMethod.getResponseBodyAsStream();
        if (null != inStream) {
          BufferedReader in = new BufferedReader(new InputStreamReader(inStream));

          BufferedWriter out =
              new BufferedWriter(new OutputStreamWriter(response.getOutputStream()));

          CharBuffer buffer = CharBuffer.allocate(PROXY_BUFFER_SIZE);
          while (in.read(buffer) >= 0) {
            buffer.flip();
            out.append(buffer);
            buffer.clear();
          }

          in.close();
          out.close();
        }
      } catch (Exception x) {
        if (x.getClass().getName().equals("org.apache.catalina.connector.ClientAbortException")) {
          logger.warn("Client aborted connection");
        } else {
          logger.error("Caught an exception:", x);
          response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, x.getMessage());
        }
      } finally {
        getMethod.releaseConnection();
      }
    }
  }
Example #27
0
  private void buscarOrganizacion(String token) {
    Organizacion organizacion = null;
    if (logger.isDebugEnabled()) logger.debug("Buscando Organizaciones para Satelite: " + satelite);

    HttpClient httpclient = getHttpClient();

    GetMethod get = new GetMethod(restUrl.getOrganizacionUrl());
    get.addRequestHeader("Accept", "application/xml");
    NameValuePair tokenParam = new NameValuePair("token", token);
    int id = 0;
    //		if(satelite.getLastOrgId() != null)
    //			id = satelite.getLastOrgId();

    int leap = idLeap;

    while (true) {
      id = id + 1;

      if (logger.isTraceEnabled()) {
        logger.trace("Buscando Organizacion con id: " + id + " en el Satelite: " + satelite);
      }

      NameValuePair passwordParam = new NameValuePair("id", String.valueOf(id));
      NameValuePair[] params = new NameValuePair[] {tokenParam, passwordParam};

      get.setQueryString(params);
      String queryString = get.getQueryString();

      int statusCode;
      try {
        if (logger.isTraceEnabled()) {
          logger.trace("Query String: " + queryString);
        }

        statusCode = httpclient.executeMethod(get);
        if (statusCode != HttpStatus.SC_OK) {
          logger.error("Method failed: " + get.getStatusLine());
        } else {
          String xmlString = get.getResponseBodyAsString();
          if (logger.isInfoEnabled()) {
            logger.info("Xml Received.");
          }

          String xmlHash = constructXmlHash(xmlString);

          organizacion = organizacionService.findByHash(xmlHash);
          if (organizacion == null) {
            organizacion = parseOrganizacion(xmlString);
            if (organizacion == null) {
              leap--;
              if (leap <= 0) {
                logger.info(
                    "Se llegó al fin de las Organizaciones. Saliendo del Satelite: " + satelite);
                break;
              } else {
                logger.info("Leap: " + leap);
              }
            } else {
              if (organizacion.getSatelites() == null) {
                organizacion.setSatelites(new HashSet<OrganizacionSatelite>());
              }
              boolean sateliteFound = false;
              for (OrganizacionSatelite sat : organizacion.getSatelites()) {
                if (sat.getSatelite().getName().equals(satelite.getName())) {
                  sateliteFound = true;
                  break;
                }
              }
              if (!sateliteFound) {
                OrganizacionSatelite newSat = new OrganizacionSatelite();
                newSat.setSatelite(satelite);
                newSat.setOrganizacion(organizacion);
                organizacion.getSatelites().add(newSat);
              }

              organizacion.setXmlHash(xmlHash);
              organizacionService.saveOrganization(organizacion);

              int numEmpresas = 0;
              if (satelite.getNumEmpresas() != null) {
                numEmpresas = satelite.getNumEmpresas();
              }
              numEmpresas++;

              Date now = new Date();
              satelite.setNumEmpresas(numEmpresas);
              satelite.setLastRetrieval(new Timestamp(now.getTime()));
              satelite.setLastOrgId(id);
              sateliteService.saveSatelite(satelite);
            }
          } else {
            if (logger.isInfoEnabled()) {
              logger.info("Organizacion with id: " + id + " already in centraldir");
            }
          }
        }
      } 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());
      } catch (ServiceException e) {
        logger.error(e.getMessage());
      } catch (NoSuchAlgorithmException e) {
        logger.error(e.getMessage());
      } finally {
        get.releaseConnection();
      }
    }
  }
  @Override
  protected ServerStatus _doIt() {
    MultiServerStatus status = new MultiServerStatus();

    try {
      URI targetURI = URIUtil.toURI(target.getUrl());

      // get app details
      // TODO: it should be passed along with App object
      String appsUrl =
          target
              .getSpace()
              .getCFJSON()
              .getJSONObject("entity")
              .getString("apps_url"); // $NON-NLS-1$//$NON-NLS-2$
      URI appsURI = targetURI.resolve(appsUrl);
      GetMethod getAppsMethod = new GetMethod(appsURI.toString());
      ServerStatus confStatus = HttpUtil.configureHttpMethod(getAppsMethod, target.getCloud());
      if (!confStatus.isOK()) return confStatus;

      getAppsMethod.setQueryString(
          "q=name:" + appName + "&inline-relations-depth=1"); // $NON-NLS-1$ //$NON-NLS-2$

      ServerStatus appsStatus = HttpUtil.executeMethod(getAppsMethod);
      status.add(appsStatus);
      if (!status.isOK()) return status;

      JSONObject jsonData = appsStatus.getJsonData();
      if (!jsonData.has("resources")
          || jsonData.getJSONArray("resources").length() == 0) // $NON-NLS-1$//$NON-NLS-2$
      return new ServerStatus(
            IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, "Application not found", null);
      JSONArray apps = jsonData.getJSONArray("resources");

      // get app routes
      String routesUrl = apps.getJSONObject(0).getJSONObject("entity").getString("routes_url");
      URI routesURI = targetURI.resolve(routesUrl);
      GetMethod getRoutesMethod = new GetMethod(routesURI.toString());
      confStatus = HttpUtil.configureHttpMethod(getRoutesMethod, target.getCloud());
      if (!confStatus.isOK()) return confStatus;

      ServerStatus routesStatus = HttpUtil.executeMethod(getRoutesMethod);
      status.add(routesStatus);
      if (!status.isOK()) return status;

      jsonData = routesStatus.getJsonData();
      if (!jsonData.has("resources")
          || jsonData.getJSONArray("resources").length() == 0) // $NON-NLS-1$//$NON-NLS-2$
      return new ServerStatus(IStatus.OK, HttpServletResponse.SC_OK, "No routes for the app", null);
      JSONArray routes = jsonData.getJSONArray("resources");

      for (int i = 0; i < routes.length(); ++i) {
        JSONObject route = routes.getJSONObject(i);

        // delete route
        String routeUrl =
            route
                .getJSONObject(CFProtocolConstants.V2_KEY_METADATA)
                .getString(CFProtocolConstants.V2_KEY_URL);
        URI routeURI = targetURI.resolve(routeUrl); // $NON-NLS-1$
        DeleteMethod deleteRouteMethod = new DeleteMethod(routeURI.toString());
        confStatus = HttpUtil.configureHttpMethod(deleteRouteMethod, target.getCloud());
        if (!confStatus.isOK()) return confStatus;

        ServerStatus deleteStatus = HttpUtil.executeMethod(deleteRouteMethod);
        status.add(deleteStatus);
        if (!status.isOK()) return status;
      }

      return status;

    } catch (Exception e) {
      String msg = NLS.bind("An error occured when performing operation {0}", commandName);
      logger.error(msg, e);
      return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
    }
  }