Beispiel #1
0
 /**
  * Attempt to POST contents of support request form to {@link #requestUrl}.
  *
  * @throws WrapperException if there was a problem on the server.
  */
 protected String compute() {
   // logic ripped from the IDV's HttpFormEntry#doPost(List, String)
   try {
     while ((tryCount++ < POST_ATTEMPTS) && !isCancelled()) {
       method = buildPostMethod(validFormUrl, form);
       HttpClient client = new HttpClient();
       client.executeMethod(method);
       if (method.getStatusCode() >= 300 && method.getStatusCode() <= 399) {
         Header location = method.getResponseHeader("location");
         if (location == null) {
           return "Error: No 'location' given on the redirect";
         }
         validFormUrl = location.getValue();
         if (method.getStatusCode() == 301) {
           logger.warn("form post has been permanently moved to: {}", validFormUrl);
         }
         continue;
       }
       break;
     }
     return IOUtil.readContents(method.getResponseBodyAsStream());
   } catch (Exception e) {
     throw new WrapperException(POST_ERROR, e);
   }
 }
Beispiel #2
0
 private HttpMethod redirectMethod(PostMethod postMethod) {
   GetMethod method = new GetMethod(postMethod.getResponseHeader("Location").getValue());
   for (Header header : postMethod.getRequestHeaders()) {
     method.addRequestHeader(header);
   }
   return method;
 }
  public FormValidation validate() throws IOException {

    HttpClient hc = createClient();

    PostMethod post = new PostMethod(url + "Login");
    post.addParameter("userName", getUsername());

    if (getPassword() != null) {
      //          post.addParameter("password",getPassword());
      post.addParameter("password", getPassword().getPlainText());
    } else {
      post.addParameter("password", "");
    }

    hc.executeMethod(post);

    // if the login succeeds, we'll see a redirect
    Header loc = post.getResponseHeader("Location");
    if (loc != null && loc.getValue().endsWith("/Central")) return FormValidation.ok("Success!");

    if (!post.getResponseBodyAsString().contains("SOASTA"))
      return FormValidation.error(getUrl() + " doesn't look like a CloudTest server");

    // if it fails, the server responds with 200!
    return FormValidation.error("Invalid credentials.");
  }
Beispiel #4
0
  private Entry addEntry(String endpointAddress) throws Exception {
    Entry e = createBookEntry(256, "AtomBook");
    StringWriter w = new StringWriter();
    e.writeTo(w);

    PostMethod post = new PostMethod(endpointAddress);
    post.setRequestEntity(new StringRequestEntity(w.toString(), "application/atom+xml", null));
    HttpClient httpclient = new HttpClient();

    String location = null;
    try {
      int result = httpclient.executeMethod(post);
      assertEquals(201, result);
      location = post.getResponseHeader("Location").getValue();
      InputStream ins = post.getResponseBodyAsStream();
      Document<Entry> entryDoc = abdera.getParser().parse(copyIn(ins));
      assertEquals(entryDoc.getRoot().toString(), e.toString());
    } finally {
      post.releaseConnection();
    }

    Entry entry = getEntry(location, null);
    assertEquals(location, entry.getBaseUri().toString());
    assertEquals("AtomBook", entry.getTitle());
    return entry;
  }
  // 下载URL指定的网页
  public String downloadFile(String url) {
    String filePath = null;
    // 1.生成HttpClient对象并设置参数
    HttpClient httpclient = new HttpClient();
    // 设置HTTP链接超时 5s
    httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
    // 2.生成GetMethod对象并设置参数(或用PostMethod)
    // GetMethod getMethod = new GetMethod(url);
    PostMethod getMethod = new PostMethod(url);
    // 设置get请求超时 5s
    getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
    // 设置请求重试处理
    getMethod
        .getParams()
        .setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());

    // 3.执行HTTP GET请求
    try {
      int statusCode = httpclient.executeMethod(getMethod);
      // 判断访问的状态码
      if (statusCode != HttpStatus.SC_OK) {
        System.err.println("Method failed: " + getMethod.getStatusLine());
        filePath = null;
      }

      // 4.处理HTTP响应内容
      byte[] responseBody = getMethod.getResponseBody();
      // 根据网页URL生成保存时得文件名
      filePath =
          "temp\\" + getFileNameByUrl(url, getMethod.getResponseHeader("Content-Type").getValue());
      saveToLocal(responseBody, filePath);
    } catch (HttpException e) {
      // 发生致命的异常,可能是协议不对或者返回的内容有问题
      System.out.println("Please check your provided http address!");
      e.printStackTrace();
    } catch (IOException e) {
      // 发生网络异常
      e.printStackTrace();
    } finally {
      getMethod.releaseConnection();
    }

    return filePath;
  }
  protected JSONObject postQuery(HttpClient httpClient, String url, JSONObject body)
      throws UnsupportedEncodingException, IOException, HttpException, URIException, JSONException {
    PostMethod post = new PostMethod(url);
    if (body.toString().length() > DEFAULT_SAVEPOST_BUFFER) {
      post.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
    }
    post.setRequestEntity(
        new ByteArrayRequestEntity(body.toString().getBytes("UTF-8"), "application/json"));

    try {
      httpClient.executeMethod(post);

      if (post.getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY
          || post.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
        Header locationHeader = post.getResponseHeader("location");
        if (locationHeader != null) {
          String redirectLocation = locationHeader.getValue();
          post.setURI(new URI(redirectLocation, true));
          httpClient.executeMethod(post);
        }
      }

      if (post.getStatusCode() != HttpServletResponse.SC_OK) {
        throw new LuceneQueryParserException(
            "Request failed " + post.getStatusCode() + " " + url.toString());
      }

      Reader reader =
          new BufferedReader(
              new InputStreamReader(post.getResponseBodyAsStream(), post.getResponseCharSet()));
      // TODO - replace with streaming-based solution e.g. SimpleJSON ContentHandler
      JSONObject json = new JSONObject(new JSONTokener(reader));

      if (json.has("status")) {
        JSONObject status = json.getJSONObject("status");
        if (status.getInt("code") != HttpServletResponse.SC_OK) {
          throw new LuceneQueryParserException("SOLR side error: " + status.getString("message"));
        }
      }
      return json;
    } finally {
      post.releaseConnection();
    }
  }
Beispiel #7
0
  public WebResponse doPost(String url, NameValuePair[] params, String referer)
      throws WebBrowserException, WebServerException {
    try {
      PostMethod postMethod = new PostMethod(url);
      setHttpRequestHeader(postMethod);
      if (referer != null && referer.trim().length() != 0) {
        postMethod.setRequestHeader("Referer", referer);
      }
      postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      postMethod.setRequestBody(params);
      logHttpPostRequest(postMethod);
      int status = httpClient.executeMethod(postMethod);
      String strResp = postMethod.getResponseBodyAsString();
      byte[] byteResp = postMethod.getResponseBody();
      String respEnc = getResponseEncoding(postMethod);
      logHttpResponse(postMethod, strResp);
      postMethod.releaseConnection();

      // http:301,302,303,307
      if (status == HttpStatus.SC_MOVED_PERMANENTLY
          || status == HttpStatus.SC_MOVED_TEMPORARILY
          || status == HttpStatus.SC_SEE_OTHER
          || status == HttpStatus.SC_TEMPORARY_REDIRECT) {
        Header locationHeader = postMethod.getResponseHeader("Location");
        String location = locationHeader.getValue();
        if (logger.isDebugEnabled()) {
          logger.debug("Redirect To Location = " + location);
        }
        if (location.startsWith("http")) {
          return doGet(location);
        } else {
          return doGet("http://" + getResponseHost(postMethod) + location);
        }
      } else if (status == HttpStatus.SC_OK) { // http:200
        return new WebResponse(postMethod.getURI().toString(), byteResp, respEnc);
      } else {
        throw new WebServerException("Server Exception[code=" + status + "]");
      }
    } catch (HttpException e) {
      throw new WebBrowserException(e);
    } catch (IOException e) {
      throw new WebBrowserException(e);
    }
  }
  /**
   * Call the PostMethod.
   *
   * @param url The URL for the HTTP PUT request
   * @param body The body for the PUT request.
   * @return PutMethod
   * @throws WebserverSystemException If connection failed.
   */
  public PostMethod post(final String url, final String body) throws RepositoryException {

    PostMethod post = null;
    RequestEntity entity;
    try {

      entity = new StringRequestEntity(body, "text/xml", "UTF-8");
    } catch (UnsupportedEncodingException e) {
      throw new RepositoryException(e.getMessage(), e);
    }

    try {
      post = new PostMethod(url);
      post.setRequestEntity(entity);

      int responseCode = getHttpClient().executeMethod(post);
      if ((responseCode / 100) != (HTTP_RESPONSE_OK / 100)) {

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

        post.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 post;
  }
  /**
   * get grouper privileges lite web service with REST
   *
   * @param wsSampleRestType is the type of rest (xml, xhtml, etc)
   */
  @SuppressWarnings("deprecation")
  public static void getGrouperPrivilegesLite(WsSampleRestType wsSampleRestType) {

    try {

      HttpClient httpClient = new HttpClient();

      DefaultHttpParams.getDefaultParams()
          .setParameter(
              HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false));

      // URL e.g. http://localhost:8093/grouper-ws/servicesRest/v1_3_000/...
      // NOTE: aStem:aGroup urlencoded substitutes %3A for a colon
      PostMethod method =
          new PostMethod(
              RestClientSettings.URL + "/" + RestClientSettings.VERSION + "/grouperPrivileges");

      httpClient.getParams().setAuthenticationPreemptive(true);
      Credentials defaultcreds =
          new UsernamePasswordCredentials(RestClientSettings.USER, RestClientSettings.PASS);

      // no keep alive so response if easier to indent for tests
      method.setRequestHeader("Connection", "close");

      // e.g. localhost and 8093
      httpClient
          .getState()
          .setCredentials(
              new AuthScope(RestClientSettings.HOST, RestClientSettings.PORT), defaultcreds);

      // Make the body of the request, in this case with beans and marshaling, but you can make
      // your request document in whatever language or way you want
      WsRestGetGrouperPrivilegesLiteRequest wsRestGetGrouperPrivilegesLiteRequest =
          new WsRestGetGrouperPrivilegesLiteRequest();

      // set the act as id
      wsRestGetGrouperPrivilegesLiteRequest.setActAsSubjectId("GrouperSystem");

      wsRestGetGrouperPrivilegesLiteRequest.setSubjectId("test.subject.0");
      wsRestGetGrouperPrivilegesLiteRequest.setGroupName("aStem:aGroup");

      wsRestGetGrouperPrivilegesLiteRequest.setPrivilegeType("access");
      wsRestGetGrouperPrivilegesLiteRequest.setPrivilegeName("admin");

      // get the xml / json / xhtml / paramString
      String requestDocument =
          wsSampleRestType
              .getWsLiteRequestContentType()
              .writeString(wsRestGetGrouperPrivilegesLiteRequest);

      // make sure right content type is in request (e.g. application/xhtml+xml
      String contentType = wsSampleRestType.getWsLiteRequestContentType().getContentType();

      method.setRequestEntity(new StringRequestEntity(requestDocument, contentType, "UTF-8"));

      httpClient.executeMethod(method);

      // make sure a request came back
      Header successHeader = method.getResponseHeader("X-Grouper-success");
      String successString = successHeader == null ? null : successHeader.getValue();
      if (StringUtils.isBlank(successString)) {
        throw new RuntimeException("Web service did not even respond!");
      }
      boolean success = "T".equals(successString);
      String resultCode = method.getResponseHeader("X-Grouper-resultCode").getValue();

      String response = RestClientSettings.responseBodyAsString(method);

      // convert to object (from xhtml, xml, json, etc)
      WsGetGrouperPrivilegesLiteResult wsGetGrouperPrivilegesLiteResult =
          (WsGetGrouperPrivilegesLiteResult)
              wsSampleRestType.getWsLiteResponseContentType().parseString(response);

      String resultMessage =
          wsGetGrouperPrivilegesLiteResult.getResultMetadata().getResultMessage();

      // see if request worked or not
      if (!success) {
        throw new RuntimeException(
            "Bad response from web service: resultCode: " + resultCode + ", " + resultMessage);
      }

      System.out.println(
          "Server version: "
              + wsGetGrouperPrivilegesLiteResult.getResponseMetadata().getServerVersion()
              + ", result code: "
              + resultCode
              + ", result message: "
              + resultMessage);

    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
Beispiel #10
0
  /**
   * Post a file to the server. The different elements of the post are encoded in the specified
   * message.
   *
   * @param message The message that contains the post information.
   * @throws SWORDClientException if there is an error during the post operation.
   */
  public DepositResponse postFile(PostMessage message) throws SWORDClientException {
    if (message == null) {
      throw new SWORDClientException("Message cannot be null.");
    }

    PostMethod httppost = new PostMethod(message.getDestination());

    if (doAuthentication) {
      setBasicCredentials(username, password);
      httppost.setDoAuthentication(true);
    }

    DepositResponse response = null;

    String messageBody = "";

    try {
      if (message.isUseMD5()) {
        String md5 = ChecksumUtils.generateMD5(message.getFilepath());
        if (message.getChecksumError()) {
          md5 = "1234567890";
        }
        log.debug("checksum error is: " + md5);
        if (md5 != null) {
          httppost.addRequestHeader(new Header(HttpHeaders.CONTENT_MD5, md5));
        }
      }

      String filename = message.getFilename();
      if (!"".equals(filename)) {
        httppost.addRequestHeader(
            new Header(HttpHeaders.CONTENT_DISPOSITION, " filename=" + filename));
      }

      if (containsValue(message.getSlug())) {
        httppost.addRequestHeader(new Header(HttpHeaders.SLUG, message.getSlug()));
      }

      if (message.getCorruptRequest()) {
        // insert a header with an invalid boolean value
        httppost.addRequestHeader(new Header(HttpHeaders.X_NO_OP, "Wibble"));
      } else {
        httppost.addRequestHeader(
            new Header(HttpHeaders.X_NO_OP, Boolean.toString(message.isNoOp())));
      }
      httppost.addRequestHeader(
          new Header(HttpHeaders.X_VERBOSE, Boolean.toString(message.isVerbose())));

      String packaging = message.getPackaging();
      if (packaging != null && packaging.length() > 0) {
        httppost.addRequestHeader(new Header(HttpHeaders.X_PACKAGING, packaging));
      }

      String onBehalfOf = message.getOnBehalfOf();
      if (containsValue(onBehalfOf)) {
        httppost.addRequestHeader(new Header(HttpHeaders.X_ON_BEHALF_OF, onBehalfOf));
      }

      String userAgent = message.getUserAgent();
      if (containsValue(userAgent)) {
        httppost.addRequestHeader(new Header(HttpHeaders.USER_AGENT, userAgent));
      }

      FileRequestEntity requestEntity =
          new FileRequestEntity(new File(message.getFilepath()), message.getFiletype());
      httppost.setRequestEntity(requestEntity);

      client.executeMethod(httppost);
      status = new Status(httppost.getStatusCode(), httppost.getStatusText());

      log.info("Checking the status code: " + status.getCode());

      if (status.getCode() == HttpStatus.SC_ACCEPTED || status.getCode() == HttpStatus.SC_CREATED) {
        messageBody = readResponse(httppost.getResponseBodyAsStream());
        response = new DepositResponse(status.getCode());
        response.setLocation(httppost.getResponseHeader("Location").getValue());
        // added call for the status code.
        lastUnmarshallInfo = response.unmarshall(messageBody, new Properties());
      } else {
        messageBody = readResponse(httppost.getResponseBodyAsStream());
        response = new DepositResponse(status.getCode());
        response.unmarshallErrorDocument(messageBody);
      }
      return response;

    } catch (NoSuchAlgorithmException nex) {
      throw new SWORDClientException("Unable to use MD5. " + nex.getMessage(), nex);
    } catch (HttpException ex) {
      throw new SWORDClientException(ex.getMessage(), ex);
    } catch (IOException ioex) {
      throw new SWORDClientException(ioex.getMessage(), ioex);
    } catch (UnmarshallException uex) {
      throw new SWORDClientException(uex.getMessage() + "(<pre>" + messageBody + "</pre>)", uex);
    } finally {
      httppost.releaseConnection();
    }
  }
  // 授权,生成access_token
  // 使用情形:①程序初始化;②每隔一天左右重新授权access_token
  public static void generate() {
    initAccountInfo();
    accessToken.clear();

    logger.info("用户授权中...");
    try {
      // https://api.weibo.com/oauth2/authorize?client_id=750123511&redirect_uri=https://api.weibo.com/oauth2/default.html&response_type=code
      String url = "https://api.weibo.com/oauth2/authorize";
      String redirectUri = "https://api.weibo.com/oauth2/default.html";

      for (int i = 0; i < accountInfo.size(); i++) {
        // 获取应用的信息
        clientId = WeiboConfig.getValue("client_ID");
        clientSecret = WeiboConfig.getValue("client_SERCRET");

        // 构造授权的url参数
        PostMethod postMethod = new PostMethod(url);
        postMethod.addParameter("client_id", clientId);
        postMethod.addParameter("redirect_uri", redirectUri);
        postMethod.addParameter("userId", accountInfo.get(i).getUserId());
        postMethod.addParameter("passwd", accountInfo.get(i).getPasswd());
        postMethod.addParameter("isLoginSina", "0");
        postMethod.addParameter("action", "submit");
        postMethod.addParameter("response_type", "code");
        HttpMethodParams param = postMethod.getParams();
        param.setContentCharset("UTF-8");

        // 伪造头部域信息
        List<Header> headers = new ArrayList<Header>();
        headers.add(
            new Header(
                "Referer",
                "https://api.weibo.com/oauth2/authorize?client_id="
                    + clientId
                    + "&redirect_uri="
                    + redirectUri
                    + "&from=sina&response_type=code"));
        headers.add(new Header("Host", "api.weibo.com"));
        headers.add(
            new Header(
                "User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0"));

        // 发送HTTP请求
        HttpClient client = new HttpClient();
        client.getHostConfiguration().getParams().setParameter("http.default-headers", headers);
        client.executeMethod(postMethod);

        // 获取授权响应
        int status = postMethod.getStatusCode();
        if (status == 302) {
          Header location = postMethod.getResponseHeader("location");
          if (location != null) {
            String retUrl = location.getValue();
            int begin = retUrl.indexOf("code=");
            int end = retUrl.length();
            String code = retUrl.substring(begin + 5, end);
            if (code != null) {
              Oauth oauth = new Oauth();
              String token = oauth.getAccessTokenByCode(code).getAccessToken();
              accessToken.add(token);
              logger.info("第" + (i + 1) + "个access_token:" + token);
            }
          }
        } else {
          logger.error("第" + (i + 1) + "个用户授权失败了!");
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      logger.error("授权发生异常!");
    }
  }
  /**
   * Main render method to send the file to ICE service
   *
   * @param sourceFile : File to be rendered
   * @return file returned by ICE service
   * @throws TransformerException
   */
  private File render(File sourceFile) throws TransformerException {
    log.info("Converting {}...", sourceFile);
    String filename = sourceFile.getName();
    String basename = FilenameUtils.getBaseName(filename);
    String ext = FilenameUtils.getExtension(filename);
    int status = HttpStatus.SC_OK;

    // Grab our config
    JsonObject object = itemConfig.getObject("resize");
    Map<String, JsonSimple> resizeConfig = JsonSimple.toJavaMap(object);

    if (resizeConfig == null || resizeConfig.isEmpty()) {
      // Try system config instead
      object = config.getObject("resize");
      resizeConfig = JsonSimple.toJavaMap(object);
      if (resizeConfig == null || resizeConfig.isEmpty()) {
        throw new TransformerException("No resizing configuration found.");
      }
    }

    String resizeJson = "";
    for (String key : resizeConfig.keySet()) {
      JsonSimple j = resizeConfig.get(key);
      resizeJson += "\"" + key + "\":" + j.toString() + ",";
    }

    PostMethod post = new PostMethod(convertUrl);
    try {
      Part[] parts = {
        new StringPart("zip", "on"),
        new StringPart("dc", "on"),
        new StringPart("toc", "on"),
        new StringPart("pdflink", "on"),
        new StringPart("addThumbnail", "on"),
        new StringPart("pathext", ext),
        new StringPart("template", getTemplate()),
        new StringPart(
            "multipleImageOptions", "{" + StringUtils.substringBeforeLast(resizeJson, ",") + "}"),
        new StringPart("mode", "download"),
        new FilePart("file", sourceFile)
      };
      post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
      BasicHttpClient client = new BasicHttpClient(convertUrl);
      log.debug("Using conversion URL: {}", convertUrl);
      status = client.executeMethod(post);
      log.debug("HTTP status: {} {}", status, HttpStatus.getStatusText(status));
    } catch (IOException ioe) {
      throw new TransformerException("Failed to send ICE conversion request", ioe);
    }
    try {
      if (status != HttpStatus.SC_OK) {
        String xmlError = post.getResponseBodyAsString();
        log.debug("Error: {}", xmlError);
        throw new TransformerException(xmlError);
      }
      String type = post.getResponseHeader("Content-Type").getValue();
      if ("application/zip".equals(type)) {
        filename = basename + ".zip";
      } else if (type.startsWith("image/")) {
        filename = basename + "_thumbnail.jpg";
      } else if ("video/x-flv".equals(type)) {
        filename = basename + ".flv";
      } else if ("audio/mpeg".equals(type)) {
        filename = basename + ".mp3";
      }
      File outputFile = new File(outputDir, filename);
      if (outputFile.exists()) {
        outputFile.delete();
      }
      InputStream in = post.getResponseBodyAsStream();
      FileOutputStream out = new FileOutputStream(outputFile);
      IOUtils.copy(in, out);
      in.close();
      out.close();
      log.debug("ICE output file: {}", outputFile);
      return outputFile;
    } catch (IOException ioe) {
      throw new TransformerException("Failed to process ICE output", ioe);
    }
  }
  public byte[] timeStamp(byte[] data, RevocationData revocationData) throws Exception {
    // digest the message
    MessageDigest messageDigest = MessageDigest.getInstance(this.digestAlgo);
    byte[] digest = messageDigest.digest(data);

    // generate the TSP request
    BigInteger nonce = new BigInteger(128, new SecureRandom());
    TimeStampRequestGenerator requestGenerator = new TimeStampRequestGenerator();
    requestGenerator.setCertReq(true);
    if (null != this.requestPolicy) {
      requestGenerator.setReqPolicy(this.requestPolicy);
    }
    TimeStampRequest request = requestGenerator.generate(this.digestAlgoOid, digest, nonce);
    byte[] encodedRequest = request.getEncoded();

    // create the HTTP client
    HttpClient httpClient = new HttpClient();
    if (null != this.username) {
      Credentials credentials = new UsernamePasswordCredentials(this.username, this.password);
      httpClient.getState().setCredentials(AuthScope.ANY, credentials);
    }
    if (null != this.proxyHost) {
      httpClient.getHostConfiguration().setProxy(this.proxyHost, this.proxyPort);
    }

    // create the HTTP POST request
    PostMethod postMethod = new PostMethod(this.tspServiceUrl);
    RequestEntity requestEntity =
        new ByteArrayRequestEntity(encodedRequest, "application/timestamp-query");
    postMethod.addRequestHeader("User-Agent", this.userAgent);
    postMethod.setRequestEntity(requestEntity);

    // invoke TSP service
    int statusCode = httpClient.executeMethod(postMethod);
    if (HttpStatus.SC_OK != statusCode) {
      LOG.error("Error contacting TSP server " + this.tspServiceUrl);
      throw new Exception("Error contacting TSP server " + this.tspServiceUrl);
    }

    // HTTP input validation
    Header responseContentTypeHeader = postMethod.getResponseHeader("Content-Type");
    if (null == responseContentTypeHeader) {
      throw new RuntimeException("missing Content-Type header");
    }
    String contentType = responseContentTypeHeader.getValue();
    if (!contentType.startsWith("application/timestamp-reply")) {
      LOG.debug("response content: " + postMethod.getResponseBodyAsString());
      throw new RuntimeException("invalid Content-Type: " + contentType);
    }
    if (0 == postMethod.getResponseContentLength()) {
      throw new RuntimeException("Content-Length is zero");
    }

    // TSP response parsing and validation
    InputStream inputStream = postMethod.getResponseBodyAsStream();
    TimeStampResponse timeStampResponse = new TimeStampResponse(inputStream);
    timeStampResponse.validate(request);

    if (0 != timeStampResponse.getStatus()) {
      LOG.debug("status: " + timeStampResponse.getStatus());
      LOG.debug("status string: " + timeStampResponse.getStatusString());
      PKIFailureInfo failInfo = timeStampResponse.getFailInfo();
      if (null != failInfo) {
        LOG.debug("fail info int value: " + failInfo.intValue());
        if (PKIFailureInfo.unacceptedPolicy == failInfo.intValue()) {
          LOG.debug("unaccepted policy");
        }
      }
      throw new RuntimeException(
          "timestamp response status != 0: " + timeStampResponse.getStatus());
    }
    TimeStampToken timeStampToken = timeStampResponse.getTimeStampToken();
    SignerId signerId = timeStampToken.getSID();
    BigInteger signerCertSerialNumber = signerId.getSerialNumber();
    X500Principal signerCertIssuer = signerId.getIssuer();
    LOG.debug("signer cert serial number: " + signerCertSerialNumber);
    LOG.debug("signer cert issuer: " + signerCertIssuer);

    // TSP signer certificates retrieval
    CertStore certStore =
        timeStampToken.getCertificatesAndCRLs("Collection", BouncyCastleProvider.PROVIDER_NAME);
    Collection<? extends Certificate> certificates = certStore.getCertificates(null);
    X509Certificate signerCert = null;
    Map<String, X509Certificate> certificateMap = new HashMap<String, X509Certificate>();
    for (Certificate certificate : certificates) {
      X509Certificate x509Certificate = (X509Certificate) certificate;
      if (signerCertIssuer.equals(x509Certificate.getIssuerX500Principal())
          && signerCertSerialNumber.equals(x509Certificate.getSerialNumber())) {
        signerCert = x509Certificate;
      }
      String ski = Hex.encodeHexString(getSubjectKeyId(x509Certificate));
      certificateMap.put(ski, x509Certificate);
      LOG.debug(
          "embedded certificate: " + x509Certificate.getSubjectX500Principal() + "; SKI=" + ski);
    }

    // TSP signer cert path building
    if (null == signerCert) {
      throw new RuntimeException("TSP response token has no signer certificate");
    }
    List<X509Certificate> tspCertificateChain = new LinkedList<X509Certificate>();
    X509Certificate certificate = signerCert;
    do {
      LOG.debug("adding to certificate chain: " + certificate.getSubjectX500Principal());
      tspCertificateChain.add(certificate);
      if (certificate.getSubjectX500Principal().equals(certificate.getIssuerX500Principal())) {
        break;
      }
      String aki = Hex.encodeHexString(getAuthorityKeyId(certificate));
      certificate = certificateMap.get(aki);
    } while (null != certificate);

    // verify TSP signer signature
    timeStampToken.validate(tspCertificateChain.get(0), BouncyCastleProvider.PROVIDER_NAME);

    // verify TSP signer certificate
    this.validator.validate(tspCertificateChain, revocationData);

    LOG.debug("time-stamp token time: " + timeStampToken.getTimeStampInfo().getGenTime());

    byte[] timestamp = timeStampToken.getEncoded();
    return timestamp;
  }
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    PostMethod httpPost = null;

    try {
      String url = RequestUtil.getParameter(request, PARAM_URL, defaultProxyUrl);
      String host = url.split("/")[2];

      // Get the proxy parameters
      // TODO: Add dependency injection to set proxy config from GeoNetwork settings, using also the
      // credentials configured
      String proxyHost = System.getProperty("http.proxyHost");
      String proxyPort = System.getProperty("http.proxyPort");

      // Get rest of parameters to pass to proxied url
      HttpMethodParams urlParams = new HttpMethodParams();

      Enumeration paramNames = request.getParameterNames();
      while (paramNames.hasMoreElements()) {
        String paramName = (String) paramNames.nextElement();
        if (!paramName.equalsIgnoreCase(PARAM_URL)) {
          urlParams.setParameter(paramName, request.getParameter(paramName));
        }
      }

      // Checks if allowed host
      if (!isAllowedHost(host)) {
        // throw new ServletException("This proxy does not allow you to access that location.");
        returnExceptionMessage(response, "This proxy does not allow you to access that location.");
        return;
      }

      if (url.startsWith("http://") || url.startsWith("https://")) {
        httpPost = new PostMethod(url);
        httpPost.setParams(urlParams);

        // Transfer bytes from in to out
        PrintWriter out = response.getWriter();
        String body = RequestUtil.inputStreamAsString(request);

        HttpClient client = new HttpClient();

        // Added support for proxy
        if (proxyHost != null && proxyPort != null) {
          client.getHostConfiguration().setProxy(proxyHost, Integer.valueOf(proxyPort));
        }

        httpPost.setRequestBody(body);

        client.executeMethod(httpPost);

        if (httpPost.getStatusCode() == HttpStatus.SC_OK) {
          Header contentType = httpPost.getResponseHeader(HEADER_CONTENT_TYPE);
          String[] contentTypesReturned = contentType.getValue().split(";");
          if (!isValidContentType(contentTypesReturned[0])) {
            contentTypesReturned = contentType.getValue().split(" ");
            if (!isValidContentType(contentTypesReturned[0])) {
              throw new ServletException("Status: 415 Unsupported media type");
            }
          }

          // Sets response contentType
          response.setContentType(getResponseContentType(contentTypesReturned));

          String responseBody = httpPost.getResponseBodyAsString();

          out.print(responseBody);
          out.flush();
          out.close();

        } else {
          returnExceptionMessage(
              response, "Unexpected failure: " + httpPost.getStatusLine().toString());
        }

        httpPost.releaseConnection();

      } else {
        // throw new ServletException("only HTTP(S) protocol supported");
        returnExceptionMessage(response, "only HTTP(S) protocol supported");
      }
    } catch (Exception e) {
      e.printStackTrace();
      // throw new ServletException("Some unexpected error occurred. Error text was: " +
      // e.getMessage());
      returnExceptionMessage(
          response, "Some unexpected error occurred. Error text was: " + e.getMessage());
    } finally {
      if (httpPost != null) httpPost.releaseConnection();
    }
  }
  /**
   * Create a node under given path, using a POST to Sling
   *
   * @param url under which node is created
   * @param multiPart if true, does a multipart POST
   * @return the URL that Sling provides to display the node
   */
  public String createNode(
      String url,
      Map<String, String> clientNodeProperties,
      Map<String, String> requestHeaders,
      boolean multiPart)
      throws IOException {
    final PostMethod post = new PostMethod(url);
    post.setFollowRedirects(false);

    // create a private copy of the properties to not tamper with
    // the properties of the client
    Map<String, String> nodeProperties = new HashMap<String, String>();

    // add sling specific properties
    nodeProperties.put(":redirect", "*");
    nodeProperties.put(":displayExtension", "");
    nodeProperties.put(":status", "browser");

    // take over any client provided properties
    if (clientNodeProperties != null) {
      nodeProperties.putAll(clientNodeProperties);
    } else {
      // add fake property - otherwise the node is not created
      nodeProperties.put("jcr:created", "");
    }

    // force form encoding to UTF-8, which is what we use to convert the
    // string parts into stream data
    nodeProperties.put("_charset_", "UTF-8");

    if (nodeProperties.size() > 0) {
      if (multiPart) {
        final List<Part> partList = new ArrayList<Part>();
        for (Map.Entry<String, String> e : nodeProperties.entrySet()) {
          if (e.getValue() != null) {
            partList.add(new StringPart(e.getKey().toString(), e.getValue().toString(), "UTF-8"));
          }
        }
        final Part[] parts = partList.toArray(new Part[partList.size()]);
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
      } else {
        for (Map.Entry<String, String> e : nodeProperties.entrySet()) {
          post.addParameter(e.getKey(), e.getValue());
        }
      }
    }

    if (requestHeaders != null) {
      for (Map.Entry<String, String> e : requestHeaders.entrySet()) {
        post.addRequestHeader(e.getKey(), e.getValue());
      }
    }

    final int status = httpClient.executeMethod(post);
    if (status != 302) {
      throw new HttpStatusCodeException(302, status, "POST", url);
    }
    String location = post.getResponseHeader("Location").getValue();
    post.releaseConnection();
    // simple check if host is missing
    if (!location.startsWith("http://")) {
      String host = HttpTestBase.HTTP_BASE_URL;
      int idx = host.indexOf('/', 8);
      if (idx > 0) {
        host = host.substring(0, idx);
      }
      location = host + location;
    }
    return location;
  }