protected String getRallyAPIError(String responseXML) {
    String errorMsg = "";

    try {

      org.jdom.input.SAXBuilder bSAX = new org.jdom.input.SAXBuilder();
      org.jdom.Document doc = bSAX.build(new StringReader(responseXML));
      Element root = doc.getRootElement();

      XPath xpath = XPath.newInstance("//Errors");
      List xlist = xpath.selectNodes(root);

      Iterator iter = xlist.iterator();
      while (iter.hasNext()) {

        Element item = (Element) iter.next();
        errorMsg = item.getChildText("OperationResultError");
      }

    } catch (Exception e) {
      errorMsg = e.toString();
    }

    return errorMsg;
  }
Exemple #2
0
  private void setSvnCredential(CIJob job) throws JDOMException, IOException {
    S_LOGGER.debug("Entering Method CIManagerImpl.setSvnCredential");
    try {
      String jenkinsTemplateDir = Utility.getJenkinsTemplateDir();
      String credentialFilePath = jenkinsTemplateDir + job.getRepoType() + HYPHEN + CREDENTIAL_XML;
      if (debugEnabled) {
        S_LOGGER.debug("credentialFilePath ... " + credentialFilePath);
      }
      File credentialFile = new File(credentialFilePath);

      SvnProcessor processor = new SvnProcessor(credentialFile);

      //			DataInputStream in = new DataInputStream(new FileInputStream(credentialFile));
      //			while (in.available() != 0) {
      //				System.out.println(in.readLine());
      //			}
      //			in.close();

      processor.changeNodeValue("credentials/entry//userName", job.getUserName());
      processor.changeNodeValue("credentials/entry//password", job.getPassword());
      processor.writeStream(new File(Utility.getJenkinsHome() + File.separator + job.getName()));

      // jenkins home location
      String jenkinsJobHome = System.getenv(JENKINS_HOME);
      StringBuilder builder = new StringBuilder(jenkinsJobHome);
      builder.append(File.separator);

      processor.writeStream(new File(builder.toString() + CI_CREDENTIAL_XML));
    } catch (Exception e) {
      S_LOGGER.error(
          "Entered into the catch block of CIManagerImpl.setSvnCredential "
              + e.getLocalizedMessage());
    }
  }
Exemple #3
0
 public List<CIBuild> getBuilds(CIJob job) throws PhrescoException {
   if (debugEnabled) {
     S_LOGGER.debug("Entering Method CIManagerImpl.getCIBuilds(CIJob job)");
   }
   List<CIBuild> ciBuilds = null;
   try {
     if (debugEnabled) {
       S_LOGGER.debug("getCIBuilds()  JobName = " + job.getName());
     }
     JsonArray jsonArray = getBuildsArray(job);
     ciBuilds = new ArrayList<CIBuild>(jsonArray.size());
     Gson gson = new Gson();
     CIBuild ciBuild = null;
     for (int i = 0; i < jsonArray.size(); i++) {
       ciBuild = gson.fromJson(jsonArray.get(i), CIBuild.class);
       setBuildStatus(ciBuild, job);
       String buildUrl = ciBuild.getUrl();
       String jenkinUrl = job.getJenkinsUrl() + ":" + job.getJenkinsPort();
       buildUrl =
           buildUrl.replaceAll(
               "localhost:" + job.getJenkinsPort(),
               jenkinUrl); // when displaying url it should display setup machine ip
       ciBuild.setUrl(buildUrl);
       ciBuilds.add(ciBuild);
     }
   } catch (Exception e) {
     if (debugEnabled) {
       S_LOGGER.debug(
           "Entering Method CIManagerImpl.getCIBuilds(CIJob job) " + e.getLocalizedMessage());
     }
   }
   return ciBuilds;
 }
Exemple #4
0
 private String sendBasic(HttpRequestBase request) throws HttpException {
   try {
     HttpResponse response = httpClient.execute(request);
     HttpEntity entity = response.getEntity();
     String body = "";
     if (entity != null) {
       body = EntityUtils.toString(entity, UTF_8);
       if (entity.getContentType() == null) {
         body = new String(body.getBytes(ISO_8859_1), UTF_8);
       }
     }
     int code = response.getStatusLine().getStatusCode();
     if (code < 200 || code >= 300) {
       throw new Exception(String.format(" code : '%s' , body : '%s'", code, body));
     }
     return body;
   } catch (Exception ex) {
     throw new HttpException(
         "Fail to send "
             + request.getMethod()
             + " request to url "
             + request.getURI()
             + ", "
             + ex.getMessage(),
         ex);
   } finally {
     request.releaseConnection();
   }
 }
Exemple #5
0
  public List parsePage(String pageCode) {
    List sections = new ArrayList();
    List folders = new ArrayList();
    List files = new ArrayList();
    int start = pageCode.indexOf("<div id=\"list-view\" class=\"view\"");
    int end = pageCode.indexOf("<div id=\"gallery-view\" class=\"view\"");
    String usefulSection = "";
    if (start != -1 && end != -1) {
      usefulSection = pageCode.substring(start, end);
    } else {
      debug("Could not parse page");
    }
    try {
      DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      InputSource is = new InputSource();
      is.setCharacterStream(new StringReader(usefulSection));
      Document doc = db.parse(is);

      NodeList divs = doc.getElementsByTagName("div");
      for (int i = 0; i < divs.getLength(); i++) {
        Element div = (Element) divs.item(i);
        boolean isFolder = false;
        if (div.getAttribute("class").equals("filename")) {
          NodeList imgs = div.getElementsByTagName("img");
          for (int j = 0; j < imgs.getLength(); j++) {
            Element img = (Element) imgs.item(j);
            if (img.getAttribute("class").indexOf("folder") > 0) {
              isFolder = true;
            } else {
              isFolder = false; // it's a file
            }
          }

          NodeList anchors = div.getElementsByTagName("a");
          Element anchor = (Element) anchors.item(0);
          String attr = anchor.getAttribute("href");
          String fileName = anchor.getAttribute("title");
          String fileURL;
          if (isFolder && !attr.equals("#")) {
            folders.add(attr);
            folders.add(fileName);
          } else if (!isFolder && !attr.equals("#")) {
            // Dropbox uses ajax to get the file for download, so the url isn't enough. We must be
            // sneaky here.
            fileURL = "https://dl.dropbox.com" + attr.substring(23) + "?dl=1";
            files.add(fileURL);
            files.add(fileName);
          }
        }
      }
    } catch (Exception e) {
      debug(e.toString());
    }

    sections.add(files);
    sections.add(folders);

    return sections;
  }
 /** @return {@link InputStream} from a {@link HttpResponse} */
 InputStream getStream(HttpResponse response) {
   try {
     return response.getEntity().getContent();
   } catch (Exception e) {
     log.error("Error reading response. " + e.getMessage());
     throw new CouchDbException(e);
   }
 }
Exemple #7
0
  public static final void main(String[] args) throws Exception {
    String uri = args[0];
    int reqNum = Integer.parseInt(args[1]);
    int reqTerm = Integer.parseInt(args[2]);

    try {
      // new ClientSimple().request1(uri, reqNum, reqTerm);
      new ClientSimple().request2(uri, reqNum, reqTerm);
    } catch (Exception e) {
      System.out.println("ERROR:" + e.getMessage());
    }
  }
Exemple #8
0
 public String getData(String url) {
   HttpClient client = new DefaultHttpClient();
   HttpGet get = new HttpGet(url);
   String response = "";
   try {
     ResponseHandler<String> responseHandler = new BasicResponseHandler();
     response = client.execute(get, responseHandler);
   } catch (Exception e) {
     debug(e.toString());
   }
   return response;
 }
Exemple #9
0
  private void setMailCredential(CIJob job) {
    if (debugEnabled) {
      S_LOGGER.debug("Entering Method CIManagerImpl.setMailCredential");
    }
    try {
      String jenkinsTemplateDir = Utility.getJenkinsTemplateDir();
      String mailFilePath = jenkinsTemplateDir + MAIL + HYPHEN + CREDENTIAL_XML;
      if (debugEnabled) {
        S_LOGGER.debug("configFilePath ... " + mailFilePath);
      }
      File mailFile = new File(mailFilePath);

      SvnProcessor processor = new SvnProcessor(mailFile);

      //			DataInputStream in = new DataInputStream(new FileInputStream(mailFile));
      //			while (in.available() != 0) {
      //				System.out.println(in.readLine());
      //			}
      //			in.close();

      // Mail have to go with jenkins running email address
      InetAddress ownIP = InetAddress.getLocalHost();
      processor.changeNodeValue(
          CI_HUDSONURL,
          HTTP_PROTOCOL
              + PROTOCOL_POSTFIX
              + ownIP.getHostAddress()
              + COLON
              + job.getJenkinsPort()
              + FORWARD_SLASH
              + CI
              + FORWARD_SLASH);
      processor.changeNodeValue("smtpAuthUsername", job.getSenderEmailId());
      processor.changeNodeValue("smtpAuthPassword", job.getSenderEmailPassword());
      processor.changeNodeValue("adminAddress", job.getSenderEmailId());

      // jenkins home location
      String jenkinsJobHome = System.getenv(JENKINS_HOME);
      StringBuilder builder = new StringBuilder(jenkinsJobHome);
      builder.append(File.separator);

      processor.writeStream(new File(builder.toString() + CI_MAILER_XML));
    } catch (Exception e) {
      S_LOGGER.error(
          "Entered into the catch block of CIManagerImpl.setMailCredential "
              + e.getLocalizedMessage());
    }
  }
  public @Nullable <T> T get(Class<T> classType, @Nonnull URI uri)
      throws CloudException, InternalException {
    InputStream responseAsStream = getAsStream(provider.getContext().getAccountNumber(), uri);

    if (responseAsStream == null) {
      logger.info("Unable to perform HTTP GET at following resource: " + uri.toString());
      return null;
    }
    try {
      JAXBContext context = JAXBContext.newInstance(classType);
      Unmarshaller u = context.createUnmarshaller();
      return (T) u.unmarshal(responseAsStream);
    } catch (Exception ex) {
      logger.error(ex.getMessage());
      throw new InternalException(ex);
    }
  }
Exemple #11
0
  public void request1(String uri, int reqNum, int reqTerm) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    if (reqNum == 0) {
      System.out.println(
          String.format("request to %s infinite times with term '%d' ms", uri, reqTerm));
    } else {
      System.out.println(
          String.format("request to %s '%d' times with term '%d' ms", uri, reqNum, reqTerm));
    }

    int i = 0, tick = 0;
    HttpGet httpGet = new HttpGet(uri);
    CloseableHttpResponse response;
    HttpEntity entity;

    while (true) {
      usleep(reqTerm);
      tick = (int) (Math.random() * 10) % 2;
      if (tick == 0) {
        continue;
      }
      System.out.println("request " + httpGet.getURI());
      response = httpclient.execute(httpGet);
      System.out.println("--> response status  = " + response.getStatusLine());
      // response handler
      try {
        entity = response.getEntity();
        EntityUtils.consume(entity);
      } catch (Exception e) {
        System.out.println("  --> http fail:" + e.getMessage());
      } finally {
        // Thread.sleep(5000); //테스트에만 썼다. close 지연시키려고.
        response.close();
      }

      System.out.println("----------------------------------------");
      if (reqNum != 0 && reqNum < ++i) {
        break;
      }
    }
  }
Exemple #12
0
  public void downloadFile(String url, String savePath, String fileName) {

    try {
      URL theURL = new URL(url);
      InputStream input = theURL.openStream();
      OutputStream output = new FileOutputStream(new File(savePath, fileName));
      try {
        byte[] buffer = new byte[1024];
        int bytesRead = 0;
        while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
          output.write(buffer, 0, bytesRead);
        }
      } catch (Exception e) {
        debug(e.toString());
      } finally {
        output.close();
      }
    } catch (Exception e) {
      debug(e.toString());
    }
  }
Exemple #13
0
 public String getFolderName(String pageCode) {
   String usefulSection =
       pageCode.substring(
           pageCode.indexOf("<h3 id=\"breadcrumb\">"),
           pageCode.indexOf("<div id=\"list-view\" class=\"view\""));
   String folderName;
   try {
     DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
     InputSource is = new InputSource();
     is.setCharacterStream(new StringReader(usefulSection));
     Document doc = db.parse(is);
     NodeList divs = doc.getElementsByTagName("h3");
     for (int i = 0; i < divs.getLength(); i++) {
       Element div = (Element) divs.item(i);
       String a = div.getTextContent();
       folderName = a.substring(a.indexOf("/>") + 2).trim();
       return folderName;
     }
   } catch (Exception e) {
     debug(e.toString());
   }
   return "Error!";
 }
Exemple #14
0
  /**
   * If Request is MultiPartRequest type, then set MultipartEntity in the httpRequest object.
   *
   * @param httpRequest
   * @param request
   * @throws com.android.volley.AuthFailureError
   */
  private static void setMultiPartBody(
      HttpEntityEnclosingRequestBase httpRequest, Request<?> request) throws AuthFailureError {
    if (!(request instanceof MultiPartRequest)) {
      return;
    }
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    Map<String, File> fileUpload = ((MultiPartRequest) request).getFileUploads();
    for (Map.Entry<String, File> entry : fileUpload.entrySet()) {

      builder.addPart(((String) entry.getKey()), new FileBody((File) entry.getValue()));
    }
    ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
    Map<String, String> stringUpload = ((MultiPartRequest) request).getStringUploads();
    for (Map.Entry<String, String> entry : stringUpload.entrySet()) {
      try {
        builder.addPart(
            ((String) entry.getKey()), new StringBody((String) entry.getValue(), contentType));
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    httpRequest.setEntity(builder.build());
  }
  private <T> T executeRequest(final HttpUriRequest request, final ResponseHandler<T> handler)
      throws IOException {
    final CloseableHttpClient client = createClientInstance();
    try {
      final CloseableHttpResponse response = client.execute(request);
      //  Wrap the response in a buffer to facilitate error handlers re-playing the content if the
      // response
      //  size is smaller than the max allowable buffer
      if (response.getEntity().getContentLength() >= 0
          && response.getEntity().getContentLength() < config.getMaxBufferSize()) {
        EntityUtils.updateEntity(response, new BufferedHttpEntity(response.getEntity()));
      }

      //  Explicit check for the authorization status of the API key
      if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
        throw new HyppoAuthException(config);
      }

      try {
        log.debug(
            "{} - {} : {}",
            request.getMethod(),
            request.getURI().getPath(),
            response.getStatusLine().getStatusCode());
        return handler.handleResponse(response);
      } finally {
        IOUtils.closeQuietly(response);
      }
    } catch (Exception e) {
      log.error(
          "{} - {} : FAILED - {}", request.getMethod(), request.getURI().getPath(), e.toString());
      throw e;
    } finally {
      IOUtils.closeQuietly(client);
    }
  }
  /** @return {@link DefaultHttpClient} instance. */
  private HttpClient createHttpClient(CouchDbProperties props) {
    DefaultHttpClient httpclient = null;
    try {
      SchemeSocketFactory ssf = null;
      if (props.getProtocol().equals("https")) {
        TrustManager trustManager =
            new X509TrustManager() {
              public void checkClientTrusted(X509Certificate[] chain, String authType)
                  throws CertificateException {}

              public void checkServerTrusted(X509Certificate[] chain, String authType)
                  throws CertificateException {}

              public X509Certificate[] getAcceptedIssuers() {
                return null;
              }
            };
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(null, new TrustManager[] {trustManager}, null);
        ssf = new SSLSocketFactory(sslcontext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        SSLSocket socket = (SSLSocket) ssf.createSocket(null);
        socket.setEnabledCipherSuites(new String[] {"SSL_RSA_WITH_RC4_128_MD5"});
      } else {
        ssf = PlainSocketFactory.getSocketFactory();
      }
      SchemeRegistry schemeRegistry = new SchemeRegistry();
      schemeRegistry.register(new Scheme(props.getProtocol(), props.getPort(), ssf));
      PoolingClientConnectionManager ccm = new PoolingClientConnectionManager(schemeRegistry);
      httpclient = new DefaultHttpClient(ccm);
      host = new HttpHost(props.getHost(), props.getPort(), props.getProtocol());
      context = new BasicHttpContext();
      // Http params
      httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
      httpclient
          .getParams()
          .setParameter(CoreConnectionPNames.SO_TIMEOUT, props.getSocketTimeout());
      httpclient
          .getParams()
          .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, props.getConnectionTimeout());
      int maxConnections = props.getMaxConnections();
      if (maxConnections != 0) {
        ccm.setMaxTotal(maxConnections);
        ccm.setDefaultMaxPerRoute(maxConnections);
      }
      if (props.getProxyHost() != null) {
        HttpHost proxy = new HttpHost(props.getProxyHost(), props.getProxyPort());
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
      }
      // basic authentication
      if (props.getUsername() != null && props.getPassword() != null) {
        httpclient
            .getCredentialsProvider()
            .setCredentials(
                new AuthScope(props.getHost(), props.getPort()),
                new UsernamePasswordCredentials(props.getUsername(), props.getPassword()));
        props.clearPassword();
        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(host, basicAuth);
        context.setAttribute(ClientContext.AUTH_CACHE, authCache);
      }
      // request interceptor
      httpclient.addRequestInterceptor(
          new HttpRequestInterceptor() {
            public void process(final HttpRequest request, final HttpContext context)
                throws IOException {
              if (log.isInfoEnabled()) {
                RequestLine requestLine = request.getRequestLine();
                try {
                  log.info(
                      ">> "
                          + (new StringBuilder())
                              .append(">> ")
                              .append(requestLine.getMethod())
                              .append(" ")
                              .append(urlCodec.decode(requestLine.getUri()))
                              .toString());
                } catch (DecoderException e) {
                  log.error(e, e);
                }
              }
            }
          });
      // response interceptor
      httpclient.addResponseInterceptor(
          new HttpResponseInterceptor() {
            public void process(final HttpResponse response, final HttpContext context)
                throws IOException {
              validate(response);
              if (log.isInfoEnabled())
                log.info("<< Status: " + response.getStatusLine().getStatusCode());
            }
          });
    } catch (Exception e) {
      log.error("Error Creating HTTP client. " + e.getMessage());
      throw new IllegalStateException(e);
    }
    return httpclient;
  }