public Object installApplication(String absolutePath, String appName, IProgressMonitor submon)
      throws APIException {
    try {
      FileBody fileBody = new FileBody(new File(absolutePath));

      MultipartEntity entity = new MultipartEntity();
      entity.addPart("deployWar", fileBody); // $NON-NLS-1$

      HttpPost httpPost = new HttpPost();
      httpPost.setEntity(entity);

      Object response = httpJSONAPI(httpPost, getDeployURI(appName));

      if (response instanceof JSONObject) {
        JSONObject json = (JSONObject) response;

        if (isSuccess(json)) {
          System.out.println("installApplication: Sucess.\n\n"); // $NON-NLS-1$
        } else {
          if (isError(json)) {
            return json.getString("error"); // $NON-NLS-1$
          } else {
            return "installApplication error " + getDeployURI(appName); // $NON-NLS-1$
          }
        }
      }

      httpPost.releaseConnection();
    } catch (Exception e) {
      e.printStackTrace();
      return e.getMessage();
    }

    return null;
  }
  /**
   * Login in Google.
   *
   * @param galx The GALX id
   * @return <code>true</code> if login was successful
   * @throws GoogleAuthenticatorException
   */
  private boolean login(String galx) throws GoogleAuthenticatorException {
    _isLoggedIn = false;

    try {
      DataConfiguration config = GoogleConfigurator.getConfiguration();

      HttpPost httpPost = new HttpPost(config.getString("google.auth.loginAuthenticate"));
      GoogleUtils.setupHttpRequestDefaults(httpPost);
      httpPost.setEntity(new UrlEncodedFormEntity(setupFormInputs(config, galx), HTTP.UTF_8));
      HttpResponse response = _httpClient.execute(httpPost);
      GoogleUtils.toString(response.getEntity().getContent());
      httpPost.releaseConnection();
    } catch (UnsupportedEncodingException ex) {
      throw new GoogleAuthenticatorException(ex);
    } catch (ClientProtocolException ex) {
      throw new GoogleAuthenticatorException(ex);
    } catch (IOException ex) {
      throw new GoogleAuthenticatorException(ex);
    } catch (ConfigurationException ex) {
      throw new GoogleAuthenticatorException(ex);
    }

    _isLoggedIn = true;
    return _isLoggedIn;
  }
示例#3
0
  /**
   * Convenience method for executing an Action
   *
   * @param descriptor fully qualified descriptor string for the action - e.g.
   *     java://org.auraframework.components.test.java.controller.JavaTestController/ACTION$getString
   * @param params a set of name value string pairs to use as parameters to the post call.
   * @return a {@link HttpPost}
   * @throws Exception
   */
  protected HttpPost executeAuraAction(
      Class<?> serverControllerClass,
      String methodName,
      Map<String, String> actionParams,
      Map<String, String> postParams)
      throws Exception {
    Map<String, Object> message = new HashMap<>();
    Map<String, Object> actionInstance = new HashMap<>();
    String descriptor =
        "java://" + serverControllerClass.getCanonicalName() + "/ACTION$" + methodName;
    actionInstance.put("descriptor", descriptor);
    if (actionParams != null) {
      actionInstance.put("params", actionParams);
    }
    Map<?, ?>[] actions = {actionInstance};
    message.put("actions", actions);
    String jsonMessage = Json.serialize(message);

    if (postParams == null) {
      postParams = Maps.newHashMap();
    }
    postParams.put("message", jsonMessage);
    if (!postParams.containsKey("aura.token")) {
      postParams.put("aura.token", getCsrfToken());
    }
    if (!postParams.containsKey("aura.context")) {
      postParams.put(
          "aura.context",
          Aura.getContextService().getCurrentContext().serialize(EncodingStyle.Normal));
    }
    HttpPost post = obtainPostMethod("/aura", postParams);
    perform(post);
    post.releaseConnection();
    return post;
  }
示例#4
0
  public void send(GCMMessage messageBase) throws Exception {
    if (gcmURI == null) {
      throw new Exception("Error sending push. Google cloud messaging properties not provided.");
    }

    HttpPost httpPost = new HttpPost(gcmURI);
    httpPost.setHeader("Authorization", API_KEY);
    httpPost.setEntity(new StringEntity(messageBase.toJson(), ContentType.APPLICATION_JSON));

    try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
      HttpEntity entity = response.getEntity();
      String responseMsg = EntityUtils.toString(entity);
      if (response.getStatusLine().getStatusCode() == 200) {
        GCMResponseMessage gcmResponseMessage = gcmResponseReader.readValue(responseMsg);
        if (gcmResponseMessage.failure == 1) {
          if (gcmResponseMessage.results != null && gcmResponseMessage.results.length > 0) {
            throw new Exception(
                "Error sending push. Problem : " + gcmResponseMessage.results[0].error);
          } else {
            throw new Exception("Error sending push. Token : " + messageBase.getToken());
          }
        }
      } else {
        EntityUtils.consume(entity);
        throw new Exception(responseMsg);
      }
    } finally {
      httpPost.releaseConnection();
    }
  }
示例#5
0
  private String postFormFetchValue(String url, ArrayList<NameValuePair> params, String key)
      throws IOException {
    String line;

    HttpPost request = new HttpPost(url);
    request.setHeader("User-Agent", "GoogleLoginService/1.3 (crespo JZO54K)");
    request.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));

    try {
      HttpResponse response = this.httpclient.execute(request);
      HttpEntity entity = response.getEntity();
      if (entity == null) throw new IOException(response.getStatusLine().toString());

      this.token = null;
      Pattern key_value_pattern = Pattern.compile("^([^=]+)=(.+)$");
      BufferedReader body = new BufferedReader(new InputStreamReader(entity.getContent()));
      while ((line = body.readLine()) != null) {
        Matcher m = key_value_pattern.matcher(line);

        System.err.println(line);

        if (!m.matches())
          throw new IOException(line + " // " + response.getStatusLine().toString());

        if (key.equals(m.group(1))) return m.group(2);
      }

      throw new IOException("Can't find " + key + " // " + response.getStatusLine().toString());
    } finally {
      request.releaseConnection();
    }
  }
示例#6
0
  public void doCheckin() throws IOException {
    HttpPost request = new HttpPost("https://android.clients.google.com/checkin");
    request.setHeader("Content-type", "application/x-protobuffer");
    request.setHeader("Content-Encoding", "gzip");
    request.setHeader("Accept-Encoding", "gzip");
    request.setHeader("User-Agent", "Android-Checkin/2.0 (maguro JRO03L); gzip");

    request.setEntity(new ByteArrayEntity(generateCheckinPayload()));

    try {
      HttpResponse response = this.httpclient.execute(request);
      HttpEntity entity = response.getEntity();
      if (entity == null) throw new IOException(response.getStatusLine().toString());

      byte[] response_bytes = Helpers.inputStreamToBytes(entity.getContent());
      AndroidCheckinResponse parsed_response = AndroidCheckinResponse.parseFrom(response_bytes);

      long aid = parsed_response.getAndroidId();
      if (aid == 0)
        throw new IOException(
            "Can't find android_id" + " // " + response.getStatusLine().toString());

      this.androidId = Long.toString(aid, 16);
    } finally {
      request.releaseConnection();
    }
  }
示例#7
0
  public void GetOauthToken() {
    HttpClient httpclient = HttpClientBuilder.create().build();

    // Assemble the login request URL
    String loginURL =
        LOGINURL
            + GRANTSERVICE
            + "&client_id="
            + CLIENTID
            + "&client_secret="
            + CLIENTSECRET
            + "&username="******"&password="******"Error authenticating to Force.com: " + statusCode);
      // Error is in EntityUtils.toString(response.getEntity())
      return;
    }

    String getResult = null;
    try {
      getResult = EntityUtils.toString(response.getEntity());
    } catch (IOException ioException) {
      ioException.printStackTrace();
    }
    JSONObject jsonObject = null;

    try {
      jsonObject = (JSONObject) new JSONTokener(getResult).nextValue();
      loginAccessToken = jsonObject.getString("access_token");
      loginInstanceUrl = jsonObject.getString("instance_url");
    } catch (JSONException jsonException) {
      jsonException.printStackTrace();
    }
    System.out.println(response.getStatusLine());
    System.out.println("Successful login");
    System.out.println("  instance URL: " + loginInstanceUrl);
    System.out.println("  access token/session ID: " + loginAccessToken);

    // release connection
    httpPost.releaseConnection();
  }
 private void httpPost(String relativePath) {
   HttpPost request = new HttpPost(DEFAULT_HOST_URL + relativePath);
   try {
     HttpResponse response = httpClient.execute(request);
     assertEquals(200, response.getStatusLine().getStatusCode());
   } catch (Exception ex) {
     fail(ex.toString());
   } finally {
     request.releaseConnection();
   }
 }
 /**
  * 以POST方式发起一个请求,响应结果在用户的 ResponseHandler 处理
  *
  * @param url
  * @param httpEntity
  * @param rh
  * @throws ClientProtocolException
  * @throws IOException
  */
 public static <T> T post(String url, HttpEntity httpEntity, ResponseHandler<T> rh)
     throws ClientProtocolException, IOException {
   HttpPost method = new HttpPost(url);
   method.setEntity(httpEntity);
   // 发送请求
   try {
     return client.execute(method, rh);
   } finally {
     method.releaseConnection();
   }
 }
示例#10
0
 public static String post(String url, HttpEntity httpEntity, String encoding)
     throws ClientProtocolException, IOException {
   HttpPost postMethod = new HttpPost(url);
   postMethod.setEntity(httpEntity);
   // 发送请求
   try {
     HttpResponse httpResponse = client.execute(postMethod);
     return EntityUtils.toString(httpResponse.getEntity(), encoding); // 取出应答字符串
   } finally {
     postMethod.releaseConnection();
   }
 }
  private void annotateText(String text, JCas aJCas, int textOffset) {
    HttpPost httpPost = new HttpPost("http://spotlight.dbpedia.org/rest/annotate/");
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("disambiguator", "Default"));
    nvps.add(new BasicNameValuePair("confidence", Float.toString(confidence)));
    nvps.add(new BasicNameValuePair("support", Integer.toString(support)));
    nvps.add(new BasicNameValuePair("text", text));
    httpPost.addHeader("content-type", "application/x-www-form-urlencoded");
    httpPost.addHeader("Accept", "text/xml");
    try {
      httpPost.setEntity(new UrlEncodedFormEntity(nvps));

      HttpResponse response = httpClient.execute(httpPost);
      System.out.println(response.getStatusLine());

      HttpEntity entity = response.getEntity();

      Document doc = dBuilder.parse(entity.getContent());

      NodeList resources = doc.getElementsByTagName("Resource");
      int numOfResources = resources.getLength();
      System.out.println(String.format("Creating %d resources in text.", numOfResources));
      for (int i = 0; i < numOfResources; i++) {
        Node resource = resources.item(i);
        NamedNodeMap attributes = resource.getAttributes();
        String uri = attributes.getNamedItem("URI").getNodeValue();
        int offset =
            Integer.parseInt(attributes.getNamedItem("offset").getNodeValue()) + textOffset;
        double similarity =
            Double.parseDouble(attributes.getNamedItem("similarityScore").getNodeValue());
        String surface = attributes.getNamedItem("surfaceForm").getNodeValue();
        String types = attributes.getNamedItem("types").getNodeValue();

        createDbpediaResource(aJCas, uri, offset, surface, similarity, types);
      }
      System.out.println("Finish creating resources");

      EntityUtils.consume(entity);
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (IllegalStateException e) {
      e.printStackTrace();
    } catch (SAXException e) {
      e.printStackTrace();
    } finally {
      httpPost.releaseConnection();
    }
  }
 private String obtainResponseCheckStatus() throws Exception {
   String app = "preloadTest:test_Preload_Cmp_SameNameSpace";
   HttpPost post =
       new ServerAction("aura://ComponentController/ACTION$getApplication", null)
           .putParam("name", app)
           .setApp("preloadTest:test_Preload_Cmp_SameNameSpace", ApplicationDef.class)
           .getPostMethod();
   HttpResponse httpResponse = perform(post);
   int statusCode = getStatusCode(httpResponse);
   String response = getResponseBody(httpResponse);
   post.releaseConnection();
   assertTrue("Failed to reach aura servlet", statusCode == HttpStatus.SC_OK);
   assertFalse("Got error response " + response, response.endsWith("/*ERROR*/"));
   return response;
 }
  /**
   * Execute the given request through the HttpClient.
   *
   * <p>This method implements the basic processing workflow: The actual work happens in this
   * class's template methods.
   *
   * @see #createHttpPost
   * @see #setRequestBody
   * @see #executeHttpPost
   * @see #validateResponse
   * @see #getResponseBody
   */
  @Override
  protected RemoteInvocationResult doExecuteRequest(
      HttpInvokerClientConfiguration config, ByteArrayOutputStream baos)
      throws IOException, ClassNotFoundException {

    HttpPost postMethod = createHttpPost(config);
    setRequestBody(config, postMethod, baos);
    try {
      HttpResponse response = executeHttpPost(config, getHttpClient(), postMethod);
      validateResponse(config, response);
      InputStream responseBody = getResponseBody(config, response);
      return readRemoteInvocationResult(responseBody, config.getCodebaseUrl());
    } finally {
      postMethod.releaseConnection();
    }
  }
示例#14
0
 public int post(String url, String body) {
   HttpPost post = new HttpPost(getProtocol() + getHost() + "/" + url);
   post.setHeader("Content-Type", "application/xml");
   post.setHeader(
       "User-Agent",
       "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_4; en-us) AppleWebKit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16");
   try {
     post.setEntity(new StringEntity(body, "application/xml", "UTF8"));
     HttpResponse resp = getClient().execute(post);
     return resp.getStatusLine().getStatusCode();
   } catch (IOException e) {
     throw new RuntimeException(e);
   } finally {
     post.releaseConnection();
   }
 }
示例#15
0
  @SuppressWarnings({"rawtypes", "unchecked"})
  public static IMHttpResponse post(String url, Map params) {
    IMHttpResponse response = new IMHttpResponse();
    if (StringUtils.isEmpty(url)) {
      response.setStatusCode(404);
      return response;
    }

    CloseableHttpClient httpClient = null;
    HttpPost httpPost = null;
    try {
      httpPost = new HttpPost(url); // HTTP Get请求(POST雷同)
      List<NameValuePair> postData = new ArrayList<NameValuePair>();
      Iterator<Entry> piter = params.entrySet().iterator();
      while (piter.hasNext()) {
        Entry entry = piter.next();
        postData.add(
            new BasicNameValuePair(
                String.valueOf(entry.getKey()), String.valueOf(entry.getValue())));
      }
      StringEntity entity = new StringEntity(URLEncodedUtils.format(postData, "UTF-8"));
      httpPost.setEntity(entity);
      RequestConfig requestConfig =
          RequestConfig.custom()
              .setSocketTimeout(2000)
              .setConnectTimeout(2000)
              .build(); // 设置请求和传输超时时间
      httpPost.setConfig(requestConfig);
      httpClient = HttpClients.createDefault();
      CloseableHttpResponse hresp = httpClient.execute(httpPost); // 执行请求
      String responseString = EntityUtils.toString(hresp.getEntity());
      response.setStatusCode(hresp.getStatusLine().getStatusCode());
      response.setResponseBody(responseString);
      return response;
    } catch (Exception e) {
      logger.error("url: " + url, e);
    } finally {
      if (httpPost != null) {
        httpPost.releaseConnection();
      }
    }
    return response;
  }
 /*
  * Test for W-2109463
  * This test send a post request to server with dynamic-namespace (layout://rl_001_VIEW_ACCOUNT_HASH.c) in context,
  * in response, the server consider layout://rl_001_VIEW_ACCOUNT_HASH.c as "preloaded"
  * then serialize just the component's description into context, without putting down superDef/attributeDefs/etc
  */
 private String obtainResponseCheckStatusDN() throws Exception {
   String cmp = "preloadTest:test_dynamicNamespace";
   Map<String, Object> attribute = Maps.newHashMap();
   Object val = "mockRecordLayout";
   attribute.put("whatToDo", val);
   HttpPost post =
       new ServerAction("aura://ComponentController/ACTION$getComponent", null)
           .putParam("name", cmp)
           .putParam("attributes", attribute)
           .addDynamicName("rl_001_VIEW_ACCOUNT_HASH")
           .getPostMethod();
   HttpResponse httpResponse = perform(post);
   int statusCode = getStatusCode(httpResponse);
   String response = getResponseBody(httpResponse);
   post.releaseConnection();
   assertTrue("Failed to reach aura servlet", statusCode == HttpStatus.SC_OK);
   assertFalse("Got error response " + response, response.endsWith("/*ERROR*/"));
   return response;
 }
 private void deliverMessage(SendMessage sendMessage) throws IOException {
   logger.info("deliver {}", sendMessage);
   HttpPost post = new HttpPost(url);
   post.setHeader("Content-Type", "application/json; charset=UTF-8");
   StringEntity entity =
       new StringEntity(
           objectMapper.writeValueAsString(sendMessage),
           ContentType.create("application/json", "UTF-8"));
   post.setEntity(entity);
   HttpResponse response = client.execute(post);
   SendMessageResult result =
       objectMapper.readValue(response.getEntity().getContent(), SendMessageResult.class);
   post.releaseConnection();
   if (!result.isOk()) {
     logger.error(
         "could not deliver message: {} - {}", result.getErrorCode(), result.getDescription());
     throw new CouldNotSendMessageException();
   }
 }
示例#18
0
  protected void sendStatus(String label, GitHubStatus status) {
    logger.info("  ** " + label + " : " + status + "  ** ");

    HttpPost httpPostRequest = new HttpPost(githubEndpoint);

    try {
      String payload =
          String.format(
              "{\"state\": \"%s\", \"target_url\": \"%s\", \"description\": \"%s\", \"context\": \"%s\"}",
              status, "http://github.com", "This is a meaningful description", label);

      StringEntity params = new StringEntity(payload);

      httpPostRequest.addHeader("content-type", "application/json");
      httpPostRequest.addHeader("Authorization", "token " + githubToken);

      RequestConfig requestConfig =
          RequestConfig.custom()
              .setSocketTimeout(5000)
              .setConnectTimeout(5000)
              .setConnectionRequestTimeout(5000)
              .build();
      httpPostRequest.setConfig(requestConfig);

      httpPostRequest.setEntity(params);

      HttpResponse response = httpClient.execute(httpPostRequest);
      if (response.getStatusLine().getStatusCode() >= 300) {
        logger.error(response.getStatusLine().toString());
      }
      logger.info(response.getStatusLine().toString());
    } catch (Exception e) {
      logger.error(e.getMessage());
      e.printStackTrace();
    } finally {
      httpPostRequest.releaseConnection();
    }

    // post.s

  }
示例#19
0
  @Override
  public byte[] post(final String url, final byte[] content) throws DSSException {

    LOG.debug("Fetching data via POST from url " + url);

    HttpPost httpRequest = null;
    HttpResponse httpResponse = null;

    try {
      final URI uri = URI.create(url.trim());
      httpRequest = new HttpPost(uri);

      // The length for the InputStreamEntity is needed, because some receivers (on the other side)
      // need this information.
      // To determine the length, we cannot read the content-stream up to the end and re-use it
      // afterwards.
      // This is because, it may not be possible to reset the stream (= go to position 0).
      // So, the solution is to cache temporarily the complete content data (as we do not expect
      // much here) in a byte-array.
      final ByteArrayInputStream bis = new ByteArrayInputStream(content);

      final HttpEntity requestEntity = new InputStreamEntity(bis, content.length);
      httpRequest.setEntity(requestEntity);
      if (contentType != null) {
        httpRequest.setHeader(CONTENT_TYPE, contentType);
      }

      httpResponse = getHttpResponse(httpRequest, url);

      final byte[] returnedBytes = readHttpResponse(url, httpResponse);
      return returnedBytes;
    } finally {
      if (httpRequest != null) {
        httpRequest.releaseConnection();
      }
      if (httpResponse != null) {
        EntityUtils.consumeQuietly(httpResponse.getEntity());
      }
    }
  }
示例#20
0
  /**
   * <公共post提交> @创建时间 2014-12-29 下午2:52:05  @创建人:胡翔宇
   *
   * @param params
   * @return
   * @throws Exception
   * @see [类、类#方法、类#成员]
   */
  private JSONObject postExecute(List<BasicNameValuePair> params) throws Exception {

    HttpPost post = new HttpPost(URL);

    // 将参数进行编码
    UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(params, "UTF-8");
    // 将参数添加的POST请求中
    post.setEntity(uefEntity);
    HttpResponse loginHttpResponse = httpClient.execute(post);
    int code = loginHttpResponse.getStatusLine().getStatusCode();
    String xmlContent = null;
    if (code == 200) {
      HttpEntity entity = loginHttpResponse.getEntity();
      xmlContent = EntityUtils.toString(entity);
      System.out.println(xmlContent);
    }
    post.releaseConnection();
    if (xmlContent != null) {
      return JSONObject.fromObject(xmlContent);
    } else {
      return null;
    }
  }
示例#21
0
  @Override
  public void post() throws IOException, ParameterLoadException {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(endpoint);
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(Arrays.asList(pairs));

    int proxyPort = config.getInt(Config.PROXY_PORT);
    String proxyHostName = config.getString(Config.PROXY_HOST);
    String proxyUser = config.getString(Config.PROXY_USERNAME);
    String proxyPassword = config.getString(Config.PROXY_PASSWORD);
    String ntlmDomain = config.getString(Config.PROXY_NTLM_DOMAIN);
    proxyHostName = proxyHostName != null ? proxyHostName.trim() : "";
    proxyUser = proxyUser != null ? proxyUser.trim() : "";
    proxyPassword = proxyPassword != null ? proxyPassword.trim() : "";
    ntlmDomain = ntlmDomain != null ? ntlmDomain.trim() : "";

    post.addHeader("User-Agent", VersionInfo.info());
    post.setEntity(entity);

    // proxy
    if (proxyHostName.length() > 0) {
      InetSocketAddress proxyAddress = new InetSocketAddress(proxyHostName, proxyPort);
      HttpHost proxyHost = new HttpHost(proxyAddress.getHostName(), proxyAddress.getPort(), "http");
      AuthScope scope =
          new AuthScope(proxyAddress.getHostName(), proxyAddress.getPort(), null, null);
      Credentials credentials = new UsernamePasswordCredentials(proxyUser, proxyPassword);

      if (ntlmDomain.length() > 0) {
        credentials =
            new NTCredentials(
                proxyUser,
                proxyPassword,
                InetAddress.getLocalHost().getCanonicalHostName(),
                ntlmDomain);
      }

      client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost);
      client.getCredentialsProvider().setCredentials(scope, credentials);
    }

    try {
      if (ntlmDomain.length() > 0) {
        // need to send a HEAD request to trigger NTLM authentication
        HttpHead head = new HttpHead("http://salesforce.com");
        client.execute(head);
        head.releaseConnection();
      }
      HttpResponse response = client.execute(post);

      successful = response.getStatusLine().getStatusCode() < 400;
      statusCode = response.getStatusLine().getStatusCode();
      reasonPhrase = response.getStatusLine().getReasonPhrase();

      // copy input stream data into a new input stream because releasing the connection will close
      // the input stream
      ByteArrayOutputStream bOut = new ByteArrayOutputStream();
      IOUtils.copy(response.getEntity().getContent(), bOut);
      input = new ByteArrayInputStream(bOut.toByteArray());

      if (response.containsHeader("Content-Encoding")
          && response.getHeaders("Content-Encoding")[0].getValue().equals("gzip")) {
        input = new GZIPInputStream(input);
      }

    } finally {
      post.releaseConnection();
    }
  }
  public void send(String content, HttpPost _httpPost, final Object _callPushClient) {
    sendCounter++;
    Date dateSendCounter = new Date();
    log.error(
        "PushClient: sendCounter: "
            + sendCounter
            + " "
            + "callBackCompletedCounter:"
            + callBackCompletedCounter
            + " "
            + "callBackCounter:"
            + callBackCounter
            + " "
            + dateSendCounter.getHours()
            + ":"
            + dateSendCounter.getMinutes()
            + ":"
            + dateSendCounter.getSeconds());
    try {
      StringEntity entity = null;
      try {
        entity = new StringEntity(content);
        //				entity.setContentEncoding("UTF-8");
        //				entity.setContentType("text/xml");
      } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
      }
      _httpPost.setHeader("Content-Type", "text/xml; charset=UTF-8");
      _httpPost.setEntity(entity);

      int CountDownValue = PushClient.sendCounter - PushClient.callBackCompletedCounter;
      if (CountDownValue > limit) {
        creatLatch(CountDownValue);
      } else {
        flag = false;
        counterAfterBeyondLimit = 0;
      }

      //			Future<HttpResponse> future = asyClient.execute(_httpPost, new
      // FutureCallbackImpl(_callPushClient, flag, latch));
      //
      //			if(flag){
      //				System.out.println("%%%%%PushClient: latch.getCount():" + latch.getCount());
      //				Date dateBefore = new Date();
      //				try {
      //					latch.await(3, TimeUnit.SECONDS);
      //				} catch (InterruptedException e) {
      //					// TODO Auto-generated catch block
      //					e.printStackTrace();
      //				}
      //				Date dateAfter = new Date();
      //				if(((dateAfter.getTime() - dateBefore.getTime()) > 2500)){
      //					System.out.println("**********PushClient: restart asyClient!!!");
      //					log.info("**********PushClient: restart asyClient!!!");
      //					try {
      //						JmsSubscription.asyClient.shutdown();
      //						JmsSubscription.asyClient = new DefaultHttpAsyncClient();
      //						JmsSubscription.asyClient.start();
      //					} catch (InterruptedException e) {
      //						// TODO Auto-generated catch block
      //						e.printStackTrace();
      //					} catch (IOReactorException e) {
      //						// TODO Auto-generated catch block
      //						e.printStackTrace();
      //					}
      //				}
      //			}
      log.error("PushClient-flag:" + flag);
      sendThread sends = new sendThread(_httpPost, _callPushClient);
      JmsSubscription.pushpool.execute(sends);
      /*Future<HttpResponse> future = asyClient.execute(_httpPost, new FutureCallback<HttpResponse>() {

      				public void failed(Exception ex) {
      					// TODO Auto-generated method stub
      					System.out.println("Exception:" + ex.getLocalizedMessage());
      					ex.printStackTrace();

      					callBackCounter ++;
      					if(_callPushClient instanceof JmsSubscription){
      						((JmsSubscription) _callPushClient).setSuccessfulFlag(false);
      					}else if(_callPushClient instanceof SendNotification){
      						((SendNotification) _callPushClient).setSuccessfulFlag(false);
      					}
      					System.out.println("enter the failed function!!!");
      					log.error("enter the failed function!!!");
      //					log.info("enter the failed function!!!");
      				}

      				public void completed(HttpResponse result) {
      					// TODO Auto-generated method stub
      					if((flag) && (latch != null)){
      						latch.countDown();
      					}
      					callBackCounter ++;
      					callBackCompletedCounter ++;
      					int statusCode = result.getStatusLine().getStatusCode();
      					switch(statusCode){
      					case 200 :
      						if(flag){
      							counterAfterBeyondLimit ++;
      						}
      						if(_callPushClient instanceof JmsSubscription){
      							((JmsSubscription) _callPushClient).setSuccessfulFlag(true);
      						}else if(_callPushClient instanceof SendNotification){
      							((SendNotification) _callPushClient).setSuccessfulFlag(true);
      						}
      //						System.out.println("%%%%%PushClient:status:200");
      						log.error("%%%%%PushClient:status:200 number:" + counterAfterBeyondLimit);
      						break;
      					case 201 :
      						if(_callPushClient instanceof JmsSubscription){
      							((JmsSubscription) _callPushClient).setSuccessfulFlag(true);
      						}else if(_callPushClient instanceof SendNotification){
      							((SendNotification) _callPushClient).setSuccessfulFlag(true);
      						}
      						System.out.println("%%%%%PushClient:status:201");
      						log.error("%%%%%PushClient:status:201");
      						break;
      					case 202 :
      						if(_callPushClient instanceof JmsSubscription){
      							((JmsSubscription) _callPushClient).setSuccessfulFlag(true);
      						}else if(_callPushClient instanceof SendNotification){
      							((SendNotification) _callPushClient).setSuccessfulFlag(true);
      						}
      						System.out.println("%%%%%PushClient:status:202");
      						log.error("%%%%%PushClient:status:202");
      						break;
      					case 204 :
      						if(_callPushClient instanceof JmsSubscription){
      							((JmsSubscription) _callPushClient).setSuccessfulFlag(true);
      						}else if(_callPushClient instanceof SendNotification){
      							((SendNotification) _callPushClient).setSuccessfulFlag(true);
      						}
      						System.out.println("%%%%%PushClient:status:204");
      						log.error("%%%%%PushClient:status:204");
      						break;
      					case 400 :
      						if(_callPushClient instanceof JmsSubscription){
      							((JmsSubscription) _callPushClient).setSuccessfulFlag(false);
      						}else if(_callPushClient instanceof SendNotification){
      							((SendNotification) _callPushClient).setSuccessfulFlag(false);
      						}
      						System.out.println("%%%%%PushClient:status:400");
      						log.error("%%%%%PushClient:status:400");
      						break;
      					case 401 :
      						if(_callPushClient instanceof JmsSubscription){
      							((JmsSubscription) _callPushClient).setSuccessfulFlag(false);
      						}else if(_callPushClient instanceof SendNotification){
      							((SendNotification) _callPushClient).setSuccessfulFlag(false);
      						}
      						System.out.println("%%%%%PushClient:status:401");
      						log.error("%%%%%PushClient:status:401");
      						break;
      					case 403 :
      						if(_callPushClient instanceof JmsSubscription){
      							((JmsSubscription) _callPushClient).setSuccessfulFlag(false);
      						}else if(_callPushClient instanceof SendNotification){
      							((SendNotification) _callPushClient).setSuccessfulFlag(false);
      						}
      						System.out.println("%%%%%PushClient:status:403");
      						log.error("%%%%%PushClient:status:403");
      						break;
      					case 404 :
      						if(_callPushClient instanceof JmsSubscription){
      							((JmsSubscription) _callPushClient).setSuccessfulFlag(false);
      						}else if(_callPushClient instanceof SendNotification){
      							((SendNotification) _callPushClient).setSuccessfulFlag(false);
      						}
      						System.out.println("%%%%%PushClient:status:404");
      						log.error("%%%%%PushClient:status:404");
      						break;
      					case 500 :
      						if(_callPushClient instanceof JmsSubscription){
      							((JmsSubscription) _callPushClient).setSuccessfulFlag(false);
      						}else if(_callPushClient instanceof SendNotification){
      							((SendNotification) _callPushClient).setSuccessfulFlag(false);
      						}
      						System.out.println("%%%%%PushClient:status:500");
      						log.error("%%%%%PushClient:status:500");
      						break;
      					default :
      						if(_callPushClient instanceof JmsSubscription){
      							((JmsSubscription) _callPushClient).setSuccessfulFlag(true);
      						}else if(_callPushClient instanceof SendNotification){
      							((SendNotification) _callPushClient).setSuccessfulFlag(true);
      						}
      						System.out.println("%%%%%PushClient:status:default");
      						log.error("%%%%%PushClient:status:default");
      					}
      				}

      				public void cancelled() {
      					// TODO Auto-generated method stub
      					callBackCounter ++;
      					if(_callPushClient instanceof JmsSubscription){
      						((JmsSubscription) _callPushClient).setSuccessfulFlag(true);
      					}else if(_callPushClient instanceof SendNotification){
      						((SendNotification) _callPushClient).setSuccessfulFlag(true);
      					}
      					System.out.println("enter the cancelled function!!!");
      					log.error("enter the cancelled function!!!");
      				}
      			});
      */
      //			if(flag){
      //				Date dateBefore = new Date();
      //				log.error("dateBefore: " + dateBefore.getMinutes() + ":" + dateBefore.getSeconds());
      //				latch.await(80, TimeUnit.SECONDS);
      //				Date dateAfter = new Date();
      //				log.error("dateAfter: " + dateAfter.getMinutes() + ":" + dateAfter.getSeconds());
      //				log.error("Time-Diff:" + (dateAfter.getTime() - dateBefore.getTime()));
      //				if(((dateAfter.getTime() - dateBefore.getTime()) > 75000)){
      //					System.out.println("%%%%%PushClient: there is " + (sendCounter -
      // callBackCompletedCounter) + " callback left!!");
      //					log.error("%%%%%PushClient: there is " + (sendCounter - callBackCompletedCounter) + "
      // callback left!!");
      //					System.out.println("**********PushClient: restart asyClient!!!");
      //					log.error("**********PushClient: restart asyClient!!!");
      //					JmsSubscription.asyClient.shutdown();
      //					JmsSubscription.asyClient = null;
      //					Thread.sleep(3000);
      //					JmsSubscription.asyClient = new DefaultHttpAsyncClient();
      //					JmsSubscription.asyClient.start();
      //				}
      //				dateBefore = null;
      //				dateAfter = null;
      //			}
      //	        HttpResponse response = future.get();
      //	        System.out.println("Response: " + response.getStatusLine());
      //	        System.out.println("Shutting down")
      _httpPost.releaseConnection();
    } catch (Exception e) {
      log.error(
          "%%%%%PushClient: enter the outException in PushClient!!!" + e.getLocalizedMessage());
      e.printStackTrace();
      //	        System.out.println("Exception: " + e.getLocalizedMessage());
      //	        if(_callPushClient instanceof JmsSubscription){
      //	        	((JmsSubscription) _callPushClient).setSuccessfulFlag(false);
      //	        }else if(_callPushClient instanceof SendNotification){
      //	        	((SendNotification) _callPushClient).setSuccessfulFlag(false);
      //	        }
      try {
        JmsSubscription.asyClient.shutdown();
        PushClient.sendCounter = 0;
        PushClient.callBackCompletedCounter = 0;
        callBackCounter = 0;

        JmsSubscription.asyClient = null;
        Thread.sleep(3000);
        JmsSubscription.asyClient = new DefaultHttpAsyncClient();
        JmsSubscription.asyClient.start();
      } catch (InterruptedException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
      } catch (IOReactorException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
      }
    } finally {
      if (_httpPost != null) {
        _httpPost.releaseConnection();
      }
    }
    if (flag) {
      restart();
    }
  }
示例#23
0
  /**
   * 上传文件http请求客户端
   *
   * @param url 请求地址
   * @param srcPath 本地文件全路径
   * @param decPath 服务端存储目录
   * @param clusterId 集群id
   * @param owner 所属业务方
   * @return
   */
  static int uploadPost(Path localFile, String decPath, String clusterId, String owner) {
    SessionState ss = SessionState.get();
    Result result = new Result();

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    // 传入svn用户名和密码
    credsProvider.setCredentials(
        new AuthScope(
            AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthPolicy.BASIC),
        new UsernamePasswordCredentials("dw_zouruochen", "*****@*****.**"));
    CloseableHttpClient closeableHttpClient =
        HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    HttpPost httpPost = new HttpPost(UPLOAD_URL);

    try {
      FileBody srcFile = new FileBody(localFile.toFile());
      StringBody dec = new StringBody(decPath, Consts.UTF_8);
      StringBody id = new StringBody(clusterId, Consts.UTF_8);
      StringBody ownerStr = new StringBody(owner, Consts.UTF_8);

      MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
      String name = localFile.getFileName().toString();

      reqEntity.addPart("clusterId", id);
      reqEntity.addPart("decPath", dec);
      reqEntity.addPart("srcFile", srcFile);
      reqEntity.addPart("owner", ownerStr);

      StringBody fileName = new StringBody(name, Consts.UTF_8);
      reqEntity.addPart("fileName", fileName);

      httpPost.setEntity(reqEntity);
      HttpResponse response = closeableHttpClient.execute(httpPost);
      int statusCode = response.getStatusLine().getStatusCode();

      if (statusCode == HttpStatus.SC_OK) {
        // System.out.println("上传服务器正常响应.....");
        ss.info.println("上传服务器正常响应.....");
        HttpEntity resEntity = response.getEntity();
        ss.info.println("contentEncoding:" + resEntity.getContentEncoding());
        result.setData(EntityUtils.toString(resEntity));
        result.setCode(0);
        EntityUtils.consume(resEntity);
        ss.info.println(result.toString());
        return result.getCode();
      } else {
        result.setCode(-1);
        result.setMsg("uploadPost error!" + response.toString());
        ss.err.println(result.toString());
        return result.getCode();
      }
    } catch (Exception e) {
      LOG.error("uploadPost error!", e);
      result.setCode(-1);
      result.setMsg("uploadPost error!");
      ss.err.println(result.toString());
      return result.getCode();
    } finally {
      try {
        httpPost.releaseConnection();
      } catch (Exception ignore) {
        LOG.error("uploadPost error!", ignore);
      }
    }
  }
示例#24
0
  static int downloadPost(String srcPath, String decPath, String clusterId, String owner) {
    SessionState ss = SessionState.get();
    Result result = new Result();
    // 创建HttpClientBuilder
    // HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    // HttpClient
    // CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    // 传入svn用户名和密码
    credsProvider.setCredentials(
        new AuthScope(
            AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthPolicy.BASIC),
        new UsernamePasswordCredentials("dw_zouruochen", "*****@*****.**"));
    CloseableHttpClient closeableHttpClient =
        HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();

    HttpPost httpPost = new HttpPost(DOWNLOAD_URL);
    try {
      MultipartEntity reqEntity = new MultipartEntity();
      StringBody sp = new StringBody(srcPath, Consts.UTF_8);
      StringBody cId = new StringBody(clusterId, Consts.UTF_8);
      StringBody own = new StringBody(owner, Consts.UTF_8);

      reqEntity.addPart("path", sp);
      reqEntity.addPart("clusterId", cId);
      reqEntity.addPart("owner", own);
      httpPost.setEntity(reqEntity);
      // 执行get请求
      HttpResponse httpResponse = closeableHttpClient.execute(httpPost);
      // 获取响应消息实体
      HttpEntity entity = httpResponse.getEntity();
      // 响应状态
      int statusCode = httpResponse.getStatusLine().getStatusCode();
      System.out.println("status:" + statusCode);
      if (statusCode == HttpStatus.SC_OK) {
        // 判断响应实体是否为空
        if (entity != null) {
          ss.info.println("下载服务器正常响应.....");
          ss.info.println(
              "contentEncoding:" + entity.getContentEncoding() == null
                  ? ""
                  : entity.getContentEncoding());
          InputStream in = entity.getContent();
          // 必须用linux文件分隔符,不能是本地文件系统的分隔符
          String name = srcPath.substring(srcPath.lastIndexOf("/") + 1);
          FileOutputStream out = new FileOutputStream(new File(decPath + File.separator + name));

          byte[] b = new byte[BUFFER_SIZE];
          int len;
          while ((len = in.read(b)) != -1) {
            out.write(b, 0, len);
          }
          in.close();
          out.close();
        }
      } else {
        result.setCode(-1);
        result.setMsg("downLoadPost error!");
        ss.err.println(result.toString());
        return result.getCode();
      }

    } catch (Exception e) {
      LOG.error("downLoadPost error!", e);
      result.setCode(-1);
      result.setMsg("downLoadPost error!");
      ss.err.println(result.toString());
      return result.getCode();
    } finally {
      httpPost.releaseConnection();
    }

    result.setCode(0);
    result.setMsg("downLoadPost success!");
    ss.err.println(result.toString());
    return result.getCode();
  }