コード例 #1
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();
  }
コード例 #2
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;
 }
コード例 #3
1
ファイル: Macro.java プロジェクト: 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();
  }
コード例 #4
1
ファイル: PingTask.java プロジェクト: huangweili/crate
  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;
  }
コード例 #5
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();
  }
コード例 #6
1
ファイル: SVGApplet.java プロジェクト: ilyessou/jhotdraw
  /**
   * 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();
    }
  }
コード例 #7
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()));
    }
  }
コード例 #8
1
ファイル: Macro.java プロジェクト: 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());
   }
 }
コード例 #9
1
  /**
   * Process connection response data.
   *
   * @param conn connection to read response data from.
   * @return assembled response as string.
   * @throws IOException on I/O error
   */
  private StringBuilder readResponse(URLConnection conn) throws IOException {
    StringBuilder retval = new StringBuilder();
    HttpURLConnection http = (HttpURLConnection) conn;
    int resp = 200;
    try {
      resp = http.getResponseCode();
    } catch (Throwable ex) {
    }

    if (resp >= 200 && resp < 300) {
      BufferedReader input = null;
      try {
        input = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      } catch (Throwable ex) {
        retval.append(ex.toString());
        return retval;
      }

      String line = null;
      while ((line = input.readLine()) != null) {
        retval.append(line);
        retval.append("\n");
      }
      input.close();
    } else {
      retval.append(http.getResponseMessage());
    }

    LogContext.getLogger().finer(String.format("<-- HTTP Response: %d: %s", resp, retval));

    return retval;
  }
コード例 #10
1
ファイル: CIManagerImpl.java プロジェクト: manoj-s/framework
 private CIJobStatus deleteCI(CIJob job, List<String> builds) throws PhrescoException {
   S_LOGGER.debug("Entering Method CIManagerImpl.deleteCI(CIJob job)");
   S_LOGGER.debug("Job name " + job.getName());
   cli = getCLI(job);
   String deleteType = null;
   List<String> argList = new ArrayList<String>();
   S_LOGGER.debug("job name " + job.getName());
   S_LOGGER.debug("Builds " + builds);
   if (CollectionUtils.isEmpty(builds)) { // delete job
     S_LOGGER.debug("Job deletion started");
     S_LOGGER.debug("Command " + FrameworkConstants.CI_JOB_DELETE_COMMAND);
     deleteType = DELETE_TYPE_JOB;
     argList.add(FrameworkConstants.CI_JOB_DELETE_COMMAND);
     argList.add(job.getName());
   } else { // delete Build
     S_LOGGER.debug("Build deletion started");
     deleteType = DELETE_TYPE_BUILD;
     argList.add(FrameworkConstants.CI_BUILD_DELETE_COMMAND);
     argList.add(job.getName());
     StringBuilder result = new StringBuilder();
     for (String string : builds) {
       result.append(string);
       result.append(",");
     }
     String buildNos = result.substring(0, result.length() - 1);
     argList.add(buildNos);
     S_LOGGER.debug("Command " + FrameworkConstants.CI_BUILD_DELETE_COMMAND);
     S_LOGGER.debug("Build numbers " + buildNos);
   }
   try {
     int status = cli.execute(argList);
     String message = deleteType + " deletion started in jenkins";
     if (status == FrameworkConstants.JOB_STATUS_NOTOK) {
       deleteType = deleteType.substring(0, 1).toLowerCase() + deleteType.substring(1);
       message = "Error while deleting " + deleteType + " in jenkins";
     }
     S_LOGGER.debug("Delete CI Status " + status);
     S_LOGGER.debug("Delete CI Message " + message);
     return new CIJobStatus(status, message);
   } finally {
     if (cli != null) {
       try {
         cli.close();
       } catch (IOException e) {
         if (debugEnabled) {
           S_LOGGER.error(
               "Entered into catch block of CIManagerImpl.deleteCI(CIJob job) "
                   + e.getLocalizedMessage());
         }
       } catch (InterruptedException e) {
         if (debugEnabled) {
           S_LOGGER.error(
               "Entered into catch block of CIManagerImpl.deleteCI(CIJob job) "
                   + e.getLocalizedMessage());
         }
       }
     }
   }
 }
コード例 #11
1
ファイル: CIManagerImpl.java プロジェクト: manoj-s/framework
 private String getCIJobPath(ApplicationInfo appInfo) {
   StringBuilder builder = new StringBuilder(Utility.getProjectHome());
   builder.append(appInfo.getAppDirName());
   builder.append(File.separator);
   builder.append(FOLDER_DOT_PHRESCO);
   builder.append(File.separator);
   builder.append(CI_JOB_INFO_NAME);
   return builder.toString();
 }
コード例 #12
1
ファイル: URLUtils.java プロジェクト: krogoth/scribe-java
 public static String concatSortedPercentEncodedParams(Map<String, String> params) {
   StringBuilder target = new StringBuilder();
   for (String key : params.keySet()) {
     target.append(key);
     target.append(PAIR_SEPARATOR);
     target.append(params.get(key));
     target.append(PARAM_SEPARATOR);
   }
   return target.deleteCharAt(target.length() - 1).toString();
 }
コード例 #13
0
ファイル: JStravaV3.java プロジェクト: justinhrobbins/JStrava
  @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;
  }
コード例 #14
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();
  }
コード例 #15
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();
  }
コード例 #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();
    }
コード例 #17
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();
        }
      }
    }
  }
コード例 #18
0
 public String toString() {
   StringBuilder ret = new StringBuilder();
   ret.append("local_addr=" + local_addr).append("\n");
   ret.append("connections (" + mapper.size() + "):\n");
   ret.append(mapper.toString());
   ret.append('\n');
   return ret.toString();
 }
コード例 #19
0
ファイル: JavaMapping.java プロジェクト: phspaelti/basex
 /**
  * Returns a string representation of all found arguments.
  *
  * @param args array with arguments
  * @return string representation
  */
 static String foundArgs(final Value[] args) {
   // compose found arguments
   final StringBuilder sb = new StringBuilder();
   for (final Value v : args) {
     if (sb.length() != 0) sb.append(", ");
     sb.append(v instanceof Jav ? Util.className(((Jav) v).toJava()) : v.seqType());
   }
   return sb.toString();
 }
コード例 #20
0
  public String toString() {
    StringBuilder str = new StringBuilder();

    str.append(getHeader());
    str.append(HTTP.CRLF);
    str.append(getContentString());

    return str.toString();
  }
コード例 #21
0
 /**
  * Adds the 'cache' directory to the HD location.
  *
  * @param cacheDir the root location.
  * @return String the extended location
  */
 static String extendCacheLocation(String cacheDir) {
   StringBuilder buffer = new StringBuilder(cacheDir);
   if (!cacheDir.endsWith(File.separator)) {
     buffer.append(File.separator);
   }
   buffer.append(CACHE_ROOT_NAME);
   buffer.append(File.separator);
   return buffer.toString();
 }
コード例 #22
0
ファイル: Exporter.java プロジェクト: edina/lockss-daemon
 protected String getSoftwareVersion() {
   String releaseName = BuildInfo.getBuildProperty(BuildInfo.BUILD_RELEASENAME);
   StringBuilder sb = new StringBuilder();
   sb.append("LOCKSS Daemon ");
   if (releaseName != null) {
     sb.append(releaseName);
   }
   return sb.toString();
 }
コード例 #23
0
 /**
  * Convert byte array to hex string
  *
  * @param bytes
  * @return
  */
 public static String bytesToHex(byte[] bytes) {
   StringBuilder sbuf = new StringBuilder();
   for (int idx = 0; idx < bytes.length; idx++) {
     int intVal = bytes[idx] & 0xff;
     if (intVal < 0x10) sbuf.append("0");
     sbuf.append(Integer.toHexString(intVal).toUpperCase());
   }
   return sbuf.toString();
 }
コード例 #24
0
  public static void main(String args[]) {
    try {
      // ReceiveMessageInterface rmiclient;
      RmiServer server = new RmiServer();
      // rmiclient=(ReceiveMessageInterface)(registry.lookup("rmiclient"));
      // rmiclient.generateKeys(publicKey);
      KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
      keyGen.initialize(1024);
      KeyPair keypair = keyGen.genKeyPair();
      publicKey = keypair.getPublic();
      privateKey = keypair.getPrivate();

      BufferedImage image = ImageIO.read(new File("/home/subba/Desktop/test/iris1.bmp"));

      // write it to byte array in-memory (jpg format)
      ByteArrayOutputStream b = new ByteArrayOutputStream();
      ImageIO.write(image, "bmp", b);

      // do whatever with the array...
      byte[] jpgByteArray = b.toByteArray();

      // convert it to a String with 0s and 1s
      StringBuilder sb = new StringBuilder();
      int i = 0;
      for (byte by : jpgByteArray) {
        i++;
        if (i > 366) break;
        sb.append(Integer.toBinaryString(by & 0xFF));
      }
      sb.append("0000000000000000000000000000000000000000000");
      System.out.println(sb.toString().length());
      System.out.println(sb.toString());
      int token = 170;
      StringBuilder sb1 = new StringBuilder();
      sb1.append(Integer.toBinaryString(token));
      for (int j = 0; j < 102; j++) {
        sb1.append("00000000000000000000");
      }
      System.out.println("Binary is " + sb1.length());
      for (i = 0; i < sb.length(); i++) {
        bioTemplate.append(sb.charAt(i) ^ sb1.charAt(i));
      }

      /*MessageDigest digest = MessageDigest.getInstance("SHA-256");
      byte[] hashvalue=serviceProviderKey.getBytes();
      digest.update(hashvalue);
      Phashdigest=digest.digest();
      */

      securePassword = getSecurePassword(serviceProviderKey, "200");
      System.out.println(securePassword);
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(1);
    }
  }
コード例 #25
0
ファイル: NodeRunnerDcom.java プロジェクト: winsx/Payara
  private static String commandListToString(List<String> command) {
    StringBuilder fullCommand = new StringBuilder();

    for (String s : command) {
      fullCommand.append(" ");
      fullCommand.append(s);
    }

    return fullCommand.toString();
  }
コード例 #26
0
 /**
  * Append a query string to an URL. This adds a '?' or a '&' or nothing, as needed.
  *
  * @param urlString existing URL string
  * @param queryString query string, or null
  * @return resulting URL
  */
 public static String appendQueryString(String urlString, String queryString) {
   if (org.apache.commons.lang.StringUtils.isBlank(queryString)) {
     return urlString;
   } else {
     final StringBuilder updatedActionStringBuilder = new StringBuilder(urlString);
     updatedActionStringBuilder.append((urlString.indexOf('?') == -1) ? '?' : '&');
     updatedActionStringBuilder.append(queryString);
     return updatedActionStringBuilder.toString();
   }
 }
コード例 #27
0
  public String getHeader() {
    StringBuilder str = new StringBuilder();

    str.append(getFirstLineString());

    String headerString = getHeaderString();
    str.append(headerString);

    return str.toString();
  }
コード例 #28
0
 private String getSockAddress() {
   StringBuilder sb = new StringBuilder();
   if (sock != null) {
     sb.append(sock.getLocalAddress().getHostAddress()).append(':').append(sock.getLocalPort());
     sb.append(" - ")
         .append(sock.getInetAddress().getHostAddress())
         .append(':')
         .append(sock.getPort());
   }
   return sb.toString();
 }
コード例 #29
0
 String srvUrlStem(String host) {
   if (host == null) {
     return null;
   }
   StringBuilder sb = new StringBuilder();
   sb.append(reqURL.getProtocol());
   sb.append("://");
   sb.append(host);
   sb.append(':');
   sb.append(reqURL.getPort());
   return sb.toString();
 }
コード例 #30
0
ファイル: Macro.java プロジェクト: bramk/bnd
 @Override
 public String toString() {
   StringBuilder sb = new StringBuilder();
   String del = "[";
   for (Link r = this; r != null; r = r.previous) {
     sb.append(del);
     sb.append(r.key);
     del = ",";
   }
   sb.append("]");
   return sb.toString();
 }