Ejemplo n.º 1
4
  protected String getRallyXML(String apiUrl) throws Exception {
    String responseXML = "";

    DefaultHttpClient httpClient = new DefaultHttpClient();

    Base64 base64 = new Base64();
    String encodeString =
        new String(base64.encode((rallyApiHttpUsername + ":" + rallyApiHttpPassword).getBytes()));

    HttpGet httpGet = new HttpGet(apiUrl);
    httpGet.addHeader("Authorization", "Basic " + encodeString);
    HttpResponse response = httpClient.execute(httpGet);
    HttpEntity entity = response.getEntity();

    if (entity != null) {

      InputStreamReader reader = new InputStreamReader(entity.getContent());
      BufferedReader br = new BufferedReader(reader);

      StringBuilder sb = new StringBuilder();
      String line = "";
      while ((line = br.readLine()) != null) {
        sb.append(line);
      }

      responseXML = sb.toString();
    }

    log.debug("responseXML=" + responseXML);

    return responseXML;
  }
Ejemplo n.º 2
1
Archivo: Macro.java Proyecto: bramk/bnd
  public String _range(String args[]) {
    verifyCommand(args, _rangeHelp, _rangePattern, 2, 3);
    Version version = null;
    if (args.length >= 3) version = new Version(args[2]);
    else {
      String v = domain.getProperty("@");
      if (v == null) return null;
      version = new Version(v);
    }
    String spec = args[1];

    Matcher m = RANGE_MASK.matcher(spec);
    m.matches();
    String floor = m.group(1);
    String floorMask = m.group(2);
    String ceilingMask = m.group(3);
    String ceiling = m.group(4);

    String left = version(version, floorMask);
    String right = version(version, ceilingMask);
    StringBuilder sb = new StringBuilder();
    sb.append(floor);
    sb.append(left);
    sb.append(",");
    sb.append(right);
    sb.append(ceiling);

    String s = sb.toString();
    VersionRange vr = new VersionRange(s);
    if (!(vr.includes(vr.getHigh()) || vr.includes(vr.getLow()))) {
      domain.error(
          "${range} macro created an invalid range %s from %s and mask %s", s, version, spec);
    }
    return sb.toString();
  }
Ejemplo n.º 3
1
  private HtmlRequest readRequest(Socket socket) throws IOException {

    BufferedReader requestBufferedReader =
        new BufferedReader(new InputStreamReader(socket.getInputStream()));
    StringBuilder requestStringBuilder = new StringBuilder();
    try {
      String line = requestBufferedReader.readLine();

      while (!line.isEmpty()) {
        requestStringBuilder.append(line + NEWLINE);
        line = requestBufferedReader.readLine();
      }

    } catch (IOException e) {
      System.out.println("An error occured while reading from the socket: " + e.toString());
    }
    if (requestStringBuilder.toString().isEmpty()) {
      return null;
    }
    HtmlRequest htmlRequest = new HtmlRequest(requestStringBuilder.toString());
    if (htmlRequest.type.equals("POST") || htmlRequest.type.equals("TRACE")) {
      htmlRequest.getParametersFromBody(requestBufferedReader);
    }
    return htmlRequest;
  }
Ejemplo n.º 4
1
  private String getResult(String URL, HashMap optionalParameters) {
    StringBuilder sb = new StringBuilder();
    sb.append(URL);
    try {

      Iterator iterator = optionalParameters.keySet().iterator();

      int index = 0;
      while (iterator.hasNext()) {
        if (index == 0) {
          sb.append("?");
        } else {
          sb.append("&");
        }
        String key = (String) iterator.next();
        sb.append(key);
        sb.append("=");
        sb.append(URLEncoder.encode(optionalParameters.get(key).toString(), "UTF-8"));
        index++;
      }

      URI uri = new URI(String.format(sb.toString()));
      URL url = uri.toURL();

      HttpURLConnection conn = (HttpURLConnection) url.openConnection();

      conn.setRequestMethod("GET");
      conn.setRequestProperty("Accept", "application/json");
      conn.setRequestProperty("Authorization", "Bearer " + getAccessToken());
      if (conn.getResponseCode() != 200) {
        throw new RuntimeException(
            "Failed : HTTP error code : "
                + conn.getResponseCode()
                + " - "
                + conn.getResponseMessage());
      }

      BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

      String output;
      sb = new StringBuilder();
      while ((output = br.readLine()) != null) {
        sb.append(output);
      }

      conn.disconnect();

    } catch (IOException e) {

      e.printStackTrace();
      return null;
    } catch (URISyntaxException e) {
      e.printStackTrace();
      return null;
    }
    return sb.toString();
  }
Ejemplo n.º 5
1
  /** Takes a string and hides its extension */
  public static String hideExtension(final String str) {
    String[] arr = str.split("\\.");

    if (arr.length <= 1) return str; // there was no "." in str.

    StringBuilder sb = new StringBuilder("");
    for (int i = 0; i < arr.length - 1; ++i) {
      if (sb.length() > 0) sb.append(".");
      sb.append(arr[i]);
    }
    return sb.toString();
  }
 /** Return next string in the sequence "a", "b", ... "z", "aa", "ab", ... */
 static String getNextDirName(String old) {
   StringBuilder sb = new StringBuilder(old);
   // go through and increment the first non-'z' char
   // counts back from the last char, so 'aa'->'ab', not 'ba'
   for (int ii = sb.length() - 1; ii >= 0; ii--) {
     char curChar = sb.charAt(ii);
     if (curChar < 'z') {
       sb.setCharAt(ii, (char) (curChar + 1));
       return sb.toString();
     }
     sb.setCharAt(ii, 'a');
   }
   sb.insert(0, 'a');
   return sb.toString();
 }
Ejemplo n.º 7
1
 public static void __getNotes(String url, String token, Long[] ids)
     throws MoodleRestNotesException, MoodleRestException, UnsupportedEncodingException {
   if (MoodleCallRestWebService.isLegacy())
     throw new MoodleRestNotesException(MoodleRestException.NO_LEGACY);
   // MoodleWarning[] warnings=null;
   String functionCall = MoodleServices.CORE_NOTES_GET_NOTES.toString();
   StringBuilder data = new StringBuilder();
   data.append(URLEncoder.encode("wstoken", MoodleServices.ENCODING.toString()))
       .append("=")
       .append(URLEncoder.encode(token, MoodleServices.ENCODING.toString()));
   data.append("&")
       .append(URLEncoder.encode("wsfunction", MoodleServices.ENCODING.toString()))
       .append("=")
       .append(URLEncoder.encode(functionCall, MoodleServices.ENCODING.toString()));
   for (int i = 0; i < ids.length; i++) {
     if (ids[i] == null) throw new MoodleRestNotesException();
     else
       data.append("&")
           .append(URLEncoder.encode("notes[" + i + "]", MoodleServices.ENCODING.toString()))
           .append("=")
           .append(ids[i]);
   }
   data.trimToSize();
   NodeList elements = (new MoodleCallRestWebService()).__call(url, data.toString());
   // return warnings;
 }
Ejemplo n.º 8
1
  /**
   * Identifies WSDL documents from the {@link DOMForest}. Also identifies the root wsdl document.
   */
  private void identifyRootWsdls() {
    for (String location : rootDocuments) {
      Document doc = get(location);
      if (doc != null) {
        Element definition = doc.getDocumentElement();
        if (definition == null
            || definition.getLocalName() == null
            || definition.getNamespaceURI() == null) continue;
        if (definition.getNamespaceURI().equals(WSDLConstants.NS_WSDL)
            && definition.getLocalName().equals("definitions")) {
          rootWsdls.add(location);
          // set the root wsdl at this point. Root wsdl is one which has wsdl:service in it
          NodeList nl = definition.getElementsByTagNameNS(WSDLConstants.NS_WSDL, "service");

          // TODO:what if there are more than one wsdl with wsdl:service element. Probably such
          // cases
          // are rare and we will take any one of them, this logic should still work
          if (nl.getLength() > 0) rootWSDL = location;
        }
      }
    }
    // no wsdl with wsdl:service found, throw error
    if (rootWSDL == null) {
      StringBuilder strbuf = new StringBuilder();
      for (String str : rootWsdls) {
        strbuf.append(str);
        strbuf.append('\n');
      }
      errorReceiver.error(null, WsdlMessages.FAILED_NOSERVICE(strbuf.toString()));
    }
  }
Ejemplo n.º 9
1
  public String getHardwareAddress() {
    TransportAddress transportAddress = httpServerTransport.boundAddress().publishAddress();
    if (!(transportAddress instanceof InetSocketTransportAddress)) {
      return null;
    }

    String hardwareAddress = null;
    InetAddress inetAddress =
        ((InetSocketTransportAddress) transportAddress).address().getAddress();
    try {
      NetworkInterface networkInterface = NetworkInterface.getByInetAddress(inetAddress);
      if (networkInterface != null) {
        if (networkInterface.getName().equals("lo")) {
          hardwareAddress = "loopback device";
        } else {
          byte[] hardwareAddressBytes = networkInterface.getHardwareAddress();
          StringBuilder sb = new StringBuilder(18);
          for (byte b : hardwareAddressBytes) {
            if (sb.length() > 0) sb.append(':');
            sb.append(String.format("%02x", b));
          }
          hardwareAddress = sb.toString();
        }
      }

    } catch (SocketException e) {
      if (logger.isTraceEnabled()) {
        logger.trace("Error getting network interface", e);
      }
    }
    return hardwareAddress;
  }
Ejemplo n.º 10
1
  public String getCoordinates(RevisionRef r) {
    StringBuilder sb = new StringBuilder(r.groupId).append(":").append(r.artifactId).append(":");
    if (r.classifier != null) sb.append(r.classifier).append("@");
    sb.append(r.version);

    return sb.toString();
  }
Ejemplo n.º 11
1
  /**
   * Escapes all '<', '>' and '&' characters in a string.
   *
   * @param str A String.
   * @return HTMlEncoded String.
   */
  private static String htmlencode(String str) {
    if (str == null) {
      return "";
    } else {
      StringBuilder buf = new StringBuilder();
      for (char ch : str.toCharArray()) {
        switch (ch) {
          case '<':
            buf.append("&lt;");
            break;

          case '>':
            buf.append("&gt;");
            break;

          case '&':
            buf.append("&amp;");
            break;

          default:
            buf.append(ch);
            break;
        }
      }
      return buf.toString();
    }
  }
Ejemplo n.º 12
1
Archivo: Macro.java Proyecto: bramk/bnd
 public static void verifyCommand(
     String args[],
     @SuppressWarnings("unused") String help,
     Pattern[] patterns,
     int low,
     int high) {
   String message = "";
   if (args.length > high) {
     message = "too many arguments";
   } else if (args.length < low) {
     message = "too few arguments";
   } else {
     for (int i = 0; patterns != null && i < patterns.length && i < args.length; i++) {
       if (patterns[i] != null) {
         Matcher m = patterns[i].matcher(args[i]);
         if (!m.matches())
           message +=
               String.format(
                   "Argument %s (%s) does not match %s%n", i, args[i], patterns[i].pattern());
       }
     }
   }
   if (message.length() != 0) {
     StringBuilder sb = new StringBuilder();
     String del = "${";
     for (String arg : args) {
       sb.append(del);
       sb.append(arg);
       del = ";";
     }
     sb.append("}, is not understood. ");
     sb.append(message);
     throw new IllegalArgumentException(sb.toString());
   }
 }
Ejemplo n.º 13
1
  public String debugString() {
    StringBuilder buf = new StringBuilder("DBTCPConnector: ");
    if (_allHosts != null) buf.append("paired : ").append(_allHosts);
    else buf.append(_curAddress).append(" ").append(_curAddress._addr);

    return buf.toString();
  }
Ejemplo n.º 14
1
 // encodeURL
 public static String encodeURL(String url, String encode) throws UnsupportedEncodingException {
   StringBuilder sb = new StringBuilder();
   StringBuilder noAsciiPart = new StringBuilder();
   for (int i = 0; i < url.length(); i++) {
     char c = url.charAt(i);
     if (c > 255) {
       noAsciiPart.append(c);
     } else {
       if (noAsciiPart.length() != 0) {
         sb.append(URLEncoder.encode(noAsciiPart.toString(), encode));
         noAsciiPart.delete(0, noAsciiPart.length());
       }
       sb.append(c);
     }
   }
   return sb.toString();
 }
Ejemplo n.º 15
0
  private String prepareResultPagesSection() {

    String resultsPath;
    try {
      resultsPath = rootDirectory.getCanonicalPath() + Crawler.RESULTS_PATH_LOCAL;
    } catch (IOException e) {
      System.out.println("HTTPRequest: Error root directory" + rootDirectory.toString());
      return "";
    }

    StringBuilder result = new StringBuilder();
    result.append("<div class=\"connectedDomains\"><ul>");
    File resultsFolder = new File(resultsPath);
    if (resultsFolder.exists() && resultsFolder.isDirectory()) {
      File[] allFiles = resultsFolder.listFiles();
      SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy-HH:mm");
      for (File file : allFiles) {
        String filename = file.getName();
        String domain = Crawler.ResultsFilenameToDomain(filename);
        Date creationDate = Crawler.ResultsFilenameToDate(filename);
        String linkFormat = domain + "-" + format.format(creationDate);
        result.append("<li><a href=");
        result.append(Crawler.RESULTS_PATH_WEB);
        result.append(filename);
        result.append(">");
        result.append(linkFormat);
        result.append("</a></li>");
      }

      result.append("</ul></div>");
    }

    return result.toString();
  }
Ejemplo n.º 16
0
    public String toString() {
      StringBuilder ret = new StringBuilder();
      InetAddress local = null, remote = null;
      String local_str, remote_str;

      Socket tmp_sock = sock;
      if (tmp_sock == null) ret.append("<null socket>");
      else {
        // since the sock variable gets set to null we want to make
        // make sure we make it through here without a nullpointer exception
        local = tmp_sock.getLocalAddress();
        remote = tmp_sock.getInetAddress();
        local_str = local != null ? Util.shortName(local) : "<null>";
        remote_str = remote != null ? Util.shortName(remote) : "<null>";
        ret.append(
            '<'
                + local_str
                + ':'
                + tmp_sock.getLocalPort()
                + " --> "
                + remote_str
                + ':'
                + tmp_sock.getPort()
                + "> ("
                + ((System.currentTimeMillis() - last_access) / 1000)
                + " secs old)");
      }
      tmp_sock = null;

      return ret.toString();
    }
Ejemplo n.º 17
0
  protected Class<?> compile(String className, char[] source) {
    if (source == null) {
      source = findSource(className);
    }

    if (source != null) {
      if (compiler == null) {
        compiler =
            new Compiler(
                getNameEnvironment(),
                getErrorHandlingPolicy(),
                getCompilerOptions(),
                getCompileRequestor(),
                getProblemFactory());
      }

      ICompilationUnit[] units = new CompilationUnit[1];
      units[0] = new CompilationUnit(source, className, null);
      compiler.compile(units);
      if (hasErrors()) {
        StringBuilder sb = new StringBuilder();
        try {
          writeProblemLog(sb);
        } catch (IOException e) {
          db.p(e);
        } finally {
          clearProblems();
        }
        throw new CompileException(sb.toString());
      }
    }
    return getCachedClass(className);
  }
Ejemplo n.º 18
0
  /** Encode a query string. The input Map contains names indexing Object[]. */
  public static String encodeQueryString(Map parameters) {
    final StringBuilder sb = new StringBuilder(100);
    boolean first = true;
    try {
      for (Object o : parameters.keySet()) {
        final String name = (String) o;
        final Object[] values = (Object[]) parameters.get(name);
        for (final Object currentValue : values) {
          if (currentValue instanceof String) {
            if (!first) sb.append('&');

            sb.append(URLEncoder.encode(name, NetUtils.STANDARD_PARAMETER_ENCODING));
            sb.append('=');
            sb.append(
                URLEncoder.encode((String) currentValue, NetUtils.STANDARD_PARAMETER_ENCODING));

            first = false;
          }
        }
      }
    } catch (UnsupportedEncodingException e) {
      // Should not happen as we are using a required encoding
      throw new OXFException(e);
    }
    return sb.toString();
  }
Ejemplo n.º 19
0
    private String getAddressXY(String x, String y) {
      try {
        StringBuilder text = new StringBuilder();

        String url = properties.getProperty("geocoderUrl");
        String param1 = properties.getProperty("geocoderUrlParam1");
        String param2 = properties.getProperty("geocoderUrlParam2");
        url = url + "?" + param1 + "=" + x + "&" + param2 + "=" + y;

        URL page = new URL(url);
        HttpURLConnection urlConn = (HttpURLConnection) page.openConnection();
        urlConn.connect();
        InputStreamReader in = new InputStreamReader((InputStream) urlConn.getContent());
        BufferedReader buff = new BufferedReader(in);
        String line = buff.readLine();

        while (line != null) {
          text.append(line);
          line = buff.readLine();
        }

        String result = text.toString();
        buff.close();
        in.close();

        return result;

      } catch (MalformedURLException e) {
        windowServer.txtErrors.append(e.getMessage() + "\n");
        return "";
      } catch (Exception e) {
        windowServer.txtErrors.append(e.getMessage() + "\n");
        return "";
      }
    }
Ejemplo n.º 20
0
  public void send(byte[] buf, DatagramPacket dp) throws InterruptedException, IOException {
    StringBuilder source = new StringBuilder();
    source.append(dp.getAddress());
    String dataType = type;
    byte[] trimmedBuf = Arrays.copyOf(buf, dp.getLength());
    String rawPRI = new String(trimmedBuf, 1, 4, Charset.forName("UTF-8"));
    int i = rawPRI.indexOf(">");
    if (i <= 3 && i > -1) {
      String priorityStr = rawPRI.substring(0, i);
      int priority = 0;
      int facility = 0;
      try {
        priority = Integer.parseInt(priorityStr);
        facility = (priority >> 3) << 3;
        facility = facility / 8;
        dataType = facilityMap.get(facility);
      } catch (NumberFormatException nfe) {
        log.warn("Unsupported format detected by SyslogAdaptor:" + Arrays.toString(trimmedBuf));
      }
    }

    bytesReceived += trimmedBuf.length;
    Chunk c =
        new ChunkImpl(dataType, source.toString(), bytesReceived, trimmedBuf, SyslogAdaptor.this);
    dest.add(c);
  }
 String streamToString(InputStream in) throws IOException {
   StringBuilder out = new StringBuilder();
   BufferedReader br = new BufferedReader(new InputStreamReader(in));
   for (String line = br.readLine(); line != null; line = br.readLine()) out.append(line);
   br.close();
   return out.toString();
 }
Ejemplo n.º 22
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());
    }
  }
 public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr)
     throws BadLocationException {
   StringBuilder builder = new StringBuilder(string);
   // 过滤用户输入的所有字符
   filterInt(builder);
   super.insertString(fb, offset, builder.toString(), attr);
 }
Ejemplo n.º 24
0
  private static String expand(String str) {
    if (str == null) {
      return null;
    }

    StringBuilder result = new StringBuilder();
    Pattern re = Pattern.compile("^(.*?)\\$\\{([^}]*)\\}(.*)");
    while (true) {
      Matcher matcher = re.matcher(str);
      if (matcher.matches()) {
        result.append(matcher.group(1));
        String property = matcher.group(2);
        if (property.equals("/")) {
          property = "file.separator";
        }
        String value = System.getProperty(property);
        if (value != null) {
          result.append(value);
        }
        str = matcher.group(3);
      } else {
        result.append(str);
        break;
      }
    }
    return result.toString();
  }
Ejemplo n.º 25
0
 public static String getHex(byte[] raw) {
   if (raw == null) return null;
   final StringBuilder hex = new StringBuilder(2 * raw.length);
   for (final byte b : raw)
     hex.append(HEXES.charAt((b & 0xF0) >> 4)).append(HEXES.charAt((b & 0x0F)));
   return hex.toString();
 }
Ejemplo n.º 26
0
  // прочитать весь json в строку
  private static String readAll() throws IOException {
    StringBuilder data = new StringBuilder();
    try {
      HttpURLConnection con = (HttpURLConnection) ((new URL(PRODUCT_URL).openConnection()));
      con.setRequestMethod("GET");

      con.setDoInput(true);
      String s;
      try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
        while ((s = in.readLine()) != null) {
          data.append(s);
        }
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
      throw new MalformedURLException("Url is not valid");
    } catch (ProtocolException e) {
      e.printStackTrace();
      throw new ProtocolException("No such protocol, it must be POST,GET,PATCH,DELETE etc.");
    } catch (IOException e) {
      e.printStackTrace();
      throw new IOException("cannot read from  server");
    }
    return data.toString();
  }
Ejemplo n.º 27
0
  @Override
  public List<Stream> findSegmentStreams(
      int id, String[] types, String resolution, String series_type) {
    StringBuilder builder = new StringBuilder();

    for (int i = 0; i < types.length; i++) {
      if (i != 0) {
        builder.append(",");
      }
      builder.append(types[i]);
    }

    String URL =
        "https://www.strava.com/api/v3/segments/"
            + id
            + "/streams/"
            + builder.toString()
            + "?resolution="
            + resolution;

    if (series_type != null && !series_type.isEmpty()) {
      URL += "&series_type=" + series_type;
    }

    String result = getResult(URL);
    Gson gson = new Gson();
    Stream[] streamsArray = gson.fromJson(result, Stream[].class);
    List<Stream> streams = Arrays.asList(streamsArray);
    return streams;
  }
Ejemplo n.º 28
0
 void handleRequest(InputStream in, OutputStream out) throws IOException {
   boolean newline = false;
   StringBuilder sb = new StringBuilder();
   while (true) {
     int ch = in.read();
     if (ch < 0) {
       throw new EOFException();
     }
     sb.append((char) ch);
     if (ch == '\r') {
       // empty
     } else if (ch == '\n') {
       if (newline) {
         // 2nd newline in a row, end of request
         break;
       }
       newline = true;
     } else {
       newline = false;
     }
   }
   String request = sb.toString();
   if (request.startsWith("GET / HTTP/1.") == false) {
     throw new IOException("Invalid request: " + request);
   }
   out.write("HTTP/1.0 200 OK\r\n\r\n".getBytes());
 }
Ejemplo n.º 29
0
  private String getResult(String URL) {
    StringBuilder sb = new StringBuilder();

    try {
      URL url = new URL(URL);
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setRequestMethod("GET");
      conn.setRequestProperty("Accept", "application/json");
      conn.setRequestProperty("Authorization", "Bearer " + getAccessToken());

      if (conn.getResponseCode() != 200) {
        throw new RuntimeException(
            "Failed : HTTP error code : "
                + conn.getResponseCode()
                + " - "
                + conn.getResponseMessage());
      }

      BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

      String output;
      while ((output = br.readLine()) != null) {
        sb.append(output);
      }

      conn.disconnect();

    } catch (IOException e) {

      e.printStackTrace();
      return null;
    }

    return sb.toString();
  }
Ejemplo n.º 30
0
  /**
   * @param args arg[0] - URL of the Virtual Center Server / ESX host https://<Server host name /
   *     ip>/sdk arg[1] - User name arg[2] - Password arg[3] - One of vminfo, hostvminfo, or vmmor
   *     arg[4] - If vmmor is arg[3], then vmname argument is mandatory
   */
  public static void main(String[] args) {
    // This is to accept all SSL certifcates by default.
    System.setProperty(
        "org.apache.axis.components.net.SecureSocketFactory",
        "org.apache.axis.components.net.SunFakeTrustSocketFactory");
    if (args.length < 3) {
      printUsage();
    } else {
      try {
        /**
         * ****************************** ******************************* ** *** ** Your code goes
         * here *** ** (fill-in 1 of 1) *** ** *** *******************************
         * *******************************
         */
        VIM_HOST = args[0];
        USER_NAME = args[1];
        PASSWORD = args[2];
        initAll();
        System.out.println("***************************************************************");

        long st = System.currentTimeMillis();
        getVMInfo();
        long et = System.currentTimeMillis();
        System.out.println(
            "\nTotal time (msec) to retrieve the properties of all VMs in one call: " + (et - st));
        System.out.println("\n***************************************************************");
        System.out.println("\n***************************************************************");
        st = System.currentTimeMillis();
        initVMMorList();
        Iterator<ManagedObjectReference> iter = VM_MOR_LIST.iterator();
        StringBuilder sb = new StringBuilder();
        String name = "name";
        String powerState = "runtime.powerState";
        while (iter.hasNext()) {
          ManagedObjectReference vmMor = iter.next();
          String vmName = (String) getVMProperty(vmMor, name);
          sb.append(vmName);
          VirtualMachinePowerState vmPs =
              (VirtualMachinePowerState) getVMProperty(vmMor, powerState);
          sb.append(" : ");
          sb.append(vmPs);
          sb.append("\n");
        }
        et = System.currentTimeMillis();
        System.out.println(sb.toString());
        System.out.println(
            "\nTotal time (msec) to retrieve the properties of all VMs individually: " + (et - st));
        System.out.println("\n***************************************************************");
      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        try {
          disconnect();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
  }