@NotNull
 public static String getLibraryName(@NotNull Library library) {
   final String result = library.getName();
   if (result != null) {
     return result;
   }
   String[] endingsToStrip = {"/", "!", ".jar"};
   StringBuilder buffer = new StringBuilder();
   for (OrderRootType type : OrderRootType.getAllTypes()) {
     for (String url : library.getUrls(type)) {
       buffer.setLength(0);
       buffer.append(url);
       for (String ending : endingsToStrip) {
         if (buffer.lastIndexOf(ending) == buffer.length() - ending.length()) {
           buffer.setLength(buffer.length() - ending.length());
         }
       }
       final int i = buffer.lastIndexOf(PATH_SEPARATOR);
       if (i < 0 || i >= buffer.length() - 1) {
         continue;
       }
       String candidate = buffer.substring(i + 1);
       if (!StringUtil.isEmpty(candidate)) {
         return candidate;
       }
     }
   }
   assert false;
   return "unknown-lib";
 }
예제 #2
1
 public String getPrimaryDisplay() {
   StringBuilder sb = new StringBuilder();
   sb.append("");
   sb.append(
       (user.getPrimaryDisplay().toString() == null ? " " : user.getPrimaryDisplay().toString()));
   return sb.toString();
 }
예제 #3
1
 private static String accessToString(int access) {
   StringBuilder ret = new StringBuilder();
   ret.append(((access & READ) > 0) ? "r" : "-");
   ret.append(((access & WRITE) > 0) ? "w" : "-");
   ret.append(((access & ADMIN) > 0) ? "a" : "-");
   return ret.toString();
 }
예제 #4
1
 private void readFromParcel(Parcel in) {
   // fieldToAccept = in.readInt();
   title.append(in.readString());
   date.append(in.readString());
   description.append(in.readString());
   setImageURL(in.readString());
 }
  private static void generateNameByString(
      Set<String> possibleNames,
      String value,
      NameValidator validator,
      boolean forStaticVariable,
      Project project) {
    if (!JavaPsiFacade.getInstance(project).getNameHelper().isIdentifier(value)) return;
    if (forStaticVariable) {
      StringBuilder buffer = new StringBuilder(value.length() + 10);
      char[] chars = new char[value.length()];
      value.getChars(0, value.length(), chars, 0);
      boolean wasLow = Character.isLowerCase(chars[0]);

      buffer.append(Character.toUpperCase(chars[0]));
      for (int i = 1; i < chars.length; i++) {
        if (Character.isUpperCase(chars[i])) {
          if (wasLow) {
            buffer.append('_');
            wasLow = false;
          }
        } else {
          wasLow = true;
        }

        buffer.append(Character.toUpperCase(chars[i]));
      }
      possibleNames.add(validator.validateName(buffer.toString(), true));
    } else {
      possibleNames.add(validator.validateName(value, true));
    }
  }
예제 #6
1
  public static String submitPostData(String pos, String data) throws IOException {
    Log.v("req", data);

    URL url = new URL(urlPre + pos);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    configConnection(connection);
    if (sCookie != null && sCookie.length() > 0) {
      connection.setRequestProperty("Cookie", sCookie);
    }
    connection.connect();

    // Send data
    DataOutputStream output = new DataOutputStream(connection.getOutputStream());
    output.write(data.getBytes());
    output.flush();
    output.close();

    // check Cookie
    String cookie = connection.getHeaderField("set-cookie");
    if (cookie != null && !cookie.equals(sCookie)) {
      sCookie = cookie;
    }

    // Respond
    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
      sb.append(line + "\n");
    }
    connection.disconnect();
    String res = sb.toString();
    Log.v("res", res);
    return res;
  }
  /*
   * Returns list of sensors currently loaded in the system
   * */
  public static String getListOfSensors() {
    StringBuilder s = new StringBuilder();
    Iterator iter = Mappings.getAllVSensorConfigs();

    sensors.clear();
    coordinates.clear();

    while (iter.hasNext()) {
      VSensorConfig sensorConfig = (VSensorConfig) iter.next();
      Double longitude = sensorConfig.getLongitude();
      Double latitude = sensorConfig.getLatitude();
      Double altitude = sensorConfig.getAltitude();
      String sensor = sensorConfig.getName();

      if ((latitude != null) && (longitude != null) && (altitude != null)) {
        Point point = new Point(latitude, longitude, altitude);
        coordinates.add(point);
        sensors.add(sensor);
        s.append(sensor)
            .append(" => ")
            .append(longitude)
            .append(" : ")
            .append(latitude)
            .append("\n");
      }
    }
    return s.toString();
  }
 public boolean isValidParty(PartyLovVO partyLovVO) throws Exception {
   boolean validParty = false;
   Connection connection = null;
   StringBuilder finalQry = new StringBuilder();
   PreparedStatement pstmt = null;
   ResultSet rs = null;
   QueryFields fields = null;
   String whereCond = "";
   try {
     fields = new QueryFields();
     fields.put("BP.DCS_STATUS", "1");
     fields.put("PR.DCS_CODE", partyLovVO.getPartyRole());
     fields.put("BP.DCS_CODE", partyLovVO.getPartyId());
     if (!StringUtility.isNullEmpty(partyLovVO.getRelatedParty())) {
       fields.put("BP.DCS_CODE", partyLovVO.getRelatedParty());
       fields.put("PR.DCS_CODE", partyLovVO.getRelationShipType());
     }
     whereCond = " AND " + QueryBuilderUtil.buildWhereCond(fields);
     finalQry.append(PartyLovQueries.validatePartyIdQry).append(whereCond);
     connection = getConnection();
     pstmt = connection.prepareStatement(finalQry.toString());
     rs = pstmt.executeQuery();
     if (rs.next()) {
       if (rs.getInt(1) > 0) {
         validParty = true;
       } else {
         validParty = false;
       }
     }
   } finally {
     ConnectionUtil.closeConnection(connection, pstmt, rs);
   }
   return validParty;
 }
  public static String reformatQuery(String query, String matchingSensors, String unionElement) {

    String lower_query = query.toLowerCase();

    String listSensors[] = matchingSensors.split(",");
    for (int i = 0; i < listSensors.length; i++) logger.warn(i + " : " + listSensors[i]);

    // replace "sensors"
    String ref_query =
        new StringBuilder(lower_query.replaceAll(LIST_SENSORS_RESERVED_WORD_REGEX, matchingSensors))
            .toString();

    // check for aggregates, containing reserved word $union
    if (ref_query.indexOf(UNION_RESERVED_WORD) > 0) {
      StringBuilder unionOfAll = new StringBuilder();
      if (unionElement != "") {
        System.out.println("what_to_repeat => " + unionElement);
        for (int i = 0; i < listSensors.length; i++) {
          unionOfAll.append(unionElement.replaceAll(SENSOR_RESERVED_WORD_REGEX, listSensors[i]));
          if (i < listSensors.length - 1) unionOfAll.append("\n union \n");
        }
      }
      System.out.println("unionofAll => " + unionOfAll);
      ref_query = ref_query.replaceAll(UNION_RESERVED_WORD_REGEX, unionOfAll.toString());
    }

    return ref_query;
  }
예제 #10
1
  /** Sends the current cooldown in action bar. */
  private void sendCooldownBar() {
    if (getPlayer() == null) return;

    StringBuilder stringBuilder = new StringBuilder();

    double currentCooldown = Core.getCustomPlayer(getPlayer()).canUse(type);
    double maxCooldown = type.getCountdown();

    int res = (int) (currentCooldown / maxCooldown * 10);
    ChatColor color;
    for (int i = 0; i < 10; i++) {
      color = ChatColor.RED;
      if (i < 10 - res) color = ChatColor.GREEN;
      stringBuilder.append(color + "â–�");
    }

    DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.US);
    otherSymbols.setDecimalSeparator('.');
    otherSymbols.setGroupingSeparator('.');
    otherSymbols.setPatternSeparator('.');
    final DecimalFormat decimalFormat = new DecimalFormat("0.0", otherSymbols);
    String timeLeft = decimalFormat.format(currentCooldown) + "s";

    PlayerUtils.sendInActionBar(
        getPlayer(), getName() + " §f" + stringBuilder.toString() + " §f" + timeLeft);
  }
  @LargeTest
  public void testManyRowsTxtLong() throws Exception {
    mDatabase.execSQL("CREATE TABLE test (_id INTEGER PRIMARY KEY, txt TEXT, data INT);");

    Random random = new Random(System.currentTimeMillis());
    StringBuilder randomString = new StringBuilder(1979);
    for (int i = 0; i < 1979; i++) {
      randomString.append((random.nextInt() & 0xf) % 10);
    }

    // if cursor window size changed, adjust this value too
    final int count = 600;
    for (int i = 0; i < count; i++) {
      StringBuilder sql = new StringBuilder(2100);
      sql.append("INSERT INTO test (txt, data) VALUES ('");
      sql.append(randomString);
      sql.append("','");
      sql.append(i);
      sql.append("');");
      mDatabase.execSQL(sql.toString());
    }

    Cursor c = mDatabase.query("test", new String[] {"txt", "data"}, null, null, null, null, null);
    assertNotNull(c);

    int i = 0;
    while (c.moveToNext()) {
      assertEquals(randomString.toString(), c.getString(0));
      assertEquals(i, c.getInt(1));
      i++;
    }
    assertEquals(count, i);
    assertEquals(count, c.getCount());
    c.close();
  }
예제 #12
1
  protected void writeAuditLog(ApplicationId appId) {
    RMApp app = rmContext.getRMApps().get(appId);
    String operation = "UNKONWN";
    boolean success = false;
    switch (app.getState()) {
      case FAILED:
        operation = AuditConstants.FINISH_FAILED_APP;
        break;
      case FINISHED:
        operation = AuditConstants.FINISH_SUCCESS_APP;
        success = true;
        break;
      case KILLED:
        operation = AuditConstants.FINISH_KILLED_APP;
        success = true;
        break;
      default:
    }

    if (success) {
      RMAuditLogger.logSuccess(app.getUser(), operation, "RMAppManager", app.getApplicationId());
    } else {
      StringBuilder diag = app.getDiagnostics();
      String msg = diag == null ? null : diag.toString();
      RMAuditLogger.logFailure(
          app.getUser(),
          operation,
          msg,
          "RMAppManager",
          "App failed with state: " + app.getState(),
          appId);
    }
  }
예제 #13
1
  public String oneCookie(String name) {
    Cookie found = null;
    List<Cookie> allFound = null;
    for (Cookie cookie : getCookies()) {
      if (cookie.name().equals(name)) {
        if (found == null) {
          found = cookie;
        } else if (allFound == null) {
          allFound = new ArrayList<>(2);
          allFound.add(found);
        } else {
          allFound.add(cookie);
        }
      }
    }

    if (found == null) {
      return null;
    } else if (allFound != null) {
      StringBuilder s =
          new StringBuilder("Multiple cookies with name '").append(name).append("': ");
      int i = 0;
      for (Cookie cookie : allFound) {
        s.append(cookie.toString());
        if (++i < allFound.size()) {
          s.append(", ");
        }
      }

      throw new IllegalStateException(s.toString());
    } else {
      return found.value();
    }
  }
예제 #14
1
 @Test
 public void testCreateMessageString() {
   command = new TelemetryCommand(TelemetryRadioConstants.SET_RIT);
   command.addParameter(new TelemetryParameter("RIT", 0));
   string.append("+J 0\n");
   assertEquals(string.toString(), createMessage.createMessageString(command).toString());
 }
예제 #15
0
  Result decodeRow(int rowNumber, BitArray row, int rowOffset) throws NotFoundException {

    int[] extensionStartRange =
        UPCEANReader.findGuardPattern(row, rowOffset, false, EXTENSION_START_PATTERN);

    StringBuilder result = decodeRowStringBuffer;
    result.setLength(0);
    int end = decodeMiddle(row, extensionStartRange, result);

    String resultString = result.toString();
    Map<ResultMetadataType, Object> extensionData = parseExtensionString(resultString);

    Result extensionResult =
        new Result(
            resultString,
            null,
            new ResultPoint[] {
              new ResultPoint(
                  (extensionStartRange[0] + extensionStartRange[1]) / 2.0f, (float) rowNumber),
              new ResultPoint((float) end, (float) rowNumber),
            },
            BarcodeFormat.UPC_EAN_EXTENSION);
    if (extensionData != null) {
      extensionResult.putAllMetadata(extensionData);
    }
    return extensionResult;
  }
예제 #16
0
  /**
   * 外部サービス・訪問リハ
   *
   * @param map
   * @param sysSvcCdItems
   * @return
   */
  public ArrayList<HashMap<String, String>> getSystemServiceCodeItemHomonReha(
      Map<String, String> map, ArrayList<HashMap<String, String>> sysSvcCdItems) {
    // パラメータ抽出
    // =========================================================================
    // 1330105 施設区分
    int _1330105 = getIntValue(map, "1330105");

    // 1330107 外部サービス
    int _1330107 = getIntValue(map, "1330107");

    // 1330113 訪問リハ-施設区分
    int _1330113 = getIntValue(map, "1330113");

    // 独自コード生成
    // ===========================================================================
    StringBuilder sb = new StringBuilder();

    // 施設区分
    sb.append(CODE_CHAR[_1330105]);

    // 外部サービス
    sb.append(CODE_CHAR[_1330107]);

    // 訪問リハ-施設区分
    sb.append(CODE_CHAR[_1330113]);

    putSystemServiceCodeItem(sysSvcCdItems, sb.toString());

    return sysSvcCdItems;
  }
예제 #17
0
  public static String getStat() {
    StringBuilder stat = new StringBuilder();
    stat.append("Available processors (cores): ")
        .append(Runtime.getRuntime().availableProcessors());

    /* Total amount of free memory available to the JVM */
    stat.append("\nFree memory (bytes): ").append(Runtime.getRuntime().freeMemory());

    /* This will return Long.MAX_VALUE if there is no preset limit */
    long maxMemory = Runtime.getRuntime().maxMemory();
    /* Maximum amount of memory the JVM will attempt to use */
    stat.append("\nMaximum memory (bytes): ")
        .append(maxMemory == Long.MAX_VALUE ? "no limit" : maxMemory);

    /* Total memory currently in use by the JVM */
    stat.append("\nTotal memory (bytes): ").append(Runtime.getRuntime().totalMemory());

    /* Get a list of all filesystem roots on this system */
    File[] roots = File.listRoots();

    /* For each filesystem root, print some info */
    for (File root : roots) {
      stat.append("\nFile system root: ").append(root.getAbsolutePath());
      stat.append("\nTotal space (bytes): ").append(root.getTotalSpace());
      stat.append("\nFree space (bytes): ").append(root.getFreeSpace());
      stat.append("\nUsable space (bytes): ").append(root.getUsableSpace());
    }

    return stat.toString();
  }
예제 #18
0
 @Override
 public String toString() {
   StringBuilder sb = new StringBuilder();
   sb.append("LineColor");
   sb.append(super.toString());
   return sb.toString();
 }
예제 #19
0
  /**
   * {@inheritDoc}
   *
   * <p>This implementation composes a string by iterating its entry set. If this map contains
   * itself as a key or a value, the string "(this Map)" will appear in its place.
   */
  @Override
  public String toString() {
    if (isEmpty()) {
      return "{}";
    }

    StringBuilder buffer = new StringBuilder(size() * 28);
    buffer.append('{');
    Iterator<Map.Entry<K, V>> it = entrySet().iterator();
    while (it.hasNext()) {
      Map.Entry<K, V> entry = it.next();
      Object key = entry.getKey();
      if (key != this) {
        buffer.append(key);
      } else {
        buffer.append("(this Map)");
      }
      buffer.append('=');
      Object value = entry.getValue();
      if (value != this) {
        buffer.append(value);
      } else {
        buffer.append("(this Map)");
      }
      if (it.hasNext()) {
        buffer.append(", ");
      }
    }
    buffer.append('}');
    return buffer.toString();
  }
예제 #20
0
  public String echo() {
    if (null == connectedVertexSets) {
      return "Uninitialized.\n";
    }

    final StringBuilder str = new StringBuilder();
    final Set<Integer> vid = connectedVertexSets.keySet();
    final HashSet<Integer> eid = new HashSet<Integer>(connectedEdgeSets.keySet());

    for (final Integer id : vid) {
      str.append(id + ":\n");
      str.append(" - " + connectedVertexSets.get(id) + "\n");
      final Set<DefaultWeightedEdge> es = connectedEdgeSets.get(id);
      if (es == null) {
        str.append(" - no matching edges!\n");
      } else {
        str.append(" - " + es + "\n");
      }
      eid.remove(id);
    }

    if (eid.isEmpty()) {
      str.append("No remaining edges ID.\n");
    } else {
      str.append("Found non-matching edge IDs!\n");
      for (final Integer id : eid) {
        str.append(id + ":\n");
        str.append(" - " + connectedEdgeSets.get(id) + "\n");
      }
    }

    return str.toString();
  }
예제 #21
0
 /** Add any cookies for this URI to the request headers. */
 private void loadRequestCookies() throws IOException {
   CookieHandler cookieHandler = CookieHandler.getDefault();
   if (cookieHandler != null) {
     try {
       URI uri = getURL().toURI();
       Map<String, List<String>> cookieHeaders =
           cookieHandler.get(uri, getHeaderFieldsDoNotForceResponse());
       for (Map.Entry<String, List<String>> entry : cookieHeaders.entrySet()) {
         String key = entry.getKey();
         if (("Cookie".equalsIgnoreCase(key) || "Cookie2".equalsIgnoreCase(key))
             && !entry.getValue().isEmpty()) {
           List<String> cookies = entry.getValue();
           StringBuilder sb = new StringBuilder();
           for (int i = 0, size = cookies.size(); i < size; i++) {
             if (i > 0) {
               sb.append("; ");
             }
             sb.append(cookies.get(i));
           }
           setHeader(key, sb.toString());
         }
       }
     } catch (URISyntaxException e) {
       throw new IOException(e);
     }
   }
 }
예제 #22
0
  @Override
  public CharSequence getDisplayContents() {

    CalendarParsedResult calResult = (CalendarParsedResult) getResult();
    StringBuilder result = new StringBuilder(100);

    ParsedResult.maybeAppend(calResult.getSummary(), result);

    Date start = calResult.getStart();
    ParsedResult.maybeAppend(format(calResult.isStartAllDay(), start), result);

    Date end = calResult.getEnd();
    if (end != null) {
      if (calResult.isEndAllDay() && !start.equals(end)) {
        // Show only year/month/day
        // if it's all-day and this is the end date, it's exclusive, so show the user
        // that it ends on the day before to make more intuitive sense.
        // But don't do it if the event already (incorrectly?) specifies the same start/end
        end = new Date(end.getTime() - 24 * 60 * 60 * 1000);
      }
      ParsedResult.maybeAppend(format(calResult.isEndAllDay(), end), result);
    }

    ParsedResult.maybeAppend(calResult.getLocation(), result);
    ParsedResult.maybeAppend(calResult.getOrganizer(), result);
    ParsedResult.maybeAppend(calResult.getAttendees(), result);
    ParsedResult.maybeAppend(calResult.getDescription(), result);
    return result.toString();
  }
 /**
  * Returns a string representation of this object; useful for testing and debugging.
  *
  * @return A string representation of this object.
  * @see java.lang.Object#toString()
  */
 @Override
 public String toString() {
   StringBuilder sb = new StringBuilder();
   sb.append("{");
   sb.append("}");
   return sb.toString();
 }
예제 #24
0
  /**
   * 读取文件
   *
   * @param 文件路径
   * @param 字符集名称一个受支持的名称
   * @return 如果文件不存在,返回null,否则返回文件的内容
   * @throws RuntimeException if an error occurs while operator BufferedReader
   */
  public static StringBuilder readFile(String filePath, String charsetName) {
    File file = new File(filePath);
    StringBuilder fileContent = new StringBuilder("");
    if (file == null || !file.isFile()) {
      return null;
    }

    BufferedReader reader = null;
    try {
      InputStreamReader is = new InputStreamReader(new FileInputStream(file), charsetName);
      reader = new BufferedReader(is);
      String line = null;
      while ((line = reader.readLine()) != null) {
        if (!fileContent.toString().equals("")) {
          fileContent.append("\r\n");
        }
        fileContent.append(line);
      }
      reader.close();
      return fileContent;
    } catch (IOException e) {
      throw new RuntimeException("IOException occurred. ", e);
    } finally {
      if (reader != null) {
        try {
          reader.close();
        } catch (IOException e) {
          throw new RuntimeException("IOException occurred. ", e);
        }
      }
    }
  }
  public synchronized void filter_input() {
    try {
      // grab data from shared buffer and move it the local one
      ourBuffer.append(sharedBuffer.take());
      // System.out.print(ourBuffer);
      // create a matcher to find an open tag in the buffer
      int endCloseTag;
      int startOpenTag;
      Matcher closeTagMatcher = closeTagPattern.matcher(ourBuffer);

      // look or a closing tag in our buffer
      if (closeTagMatcher.find()) {
        endCloseTag = closeTagMatcher.end();
        openTag = "<" + ourBuffer.charAt(closeTagMatcher.start() + 2) + ">";
        // find corresponding opening tag
        startOpenTag = ourBuffer.indexOf(openTag);
        // send the input string to the GUI for processing
        if (startOpenTag >= 0 && startOpenTag < endCloseTag) {
          gui.incoming(ourBuffer.substring(startOpenTag, endCloseTag));
          // clear our buffer
          ourBuffer.delete(startOpenTag, endCloseTag);
        }
      }
    } catch (Exception e) {
      System.out.print(e + "\n");
    }
  }
예제 #26
0
  private String hexDump(byte[] data, int width) {
    StringBuilder sb = new StringBuilder();
    Formatter formatter = new Formatter(sb, Locale.US);

    try {
      for (int offset = 0; offset < data.length; offset += width) {
        formatter.format("%07X:", offset);

        for (int i = 0; i < width; i++) {
          if (i % 2 == 0) formatter.out().append(' ');
          if (i + offset >= data.length) {
            formatter.out().append("  ");
            continue;
          }
          formatter.format("%02X", data[i + offset]);
        }

        formatter.out().append("  ");
        for (int i = 0; i < width; i++) {
          if (i + offset >= data.length) break;

          if (data[i + offset] >= 32 && data[i + offset] < 127) {
            formatter.out().append((char) data[i + offset]);
          } else formatter.out().append('.');
        }
        formatter.out().append('\n');
      }
    } catch (IOException e) {
      // impossible
    }

    formatter.flush();
    return sb.toString();
  }
  /**
   * Get the resource name given a full filename.
   *
   * @param fileName the full filename (which must be inside the directory)
   * @return the resource name (i.e., the filename with the directory stripped off)
   */
  String getResourceName(String fileName) {
    // FIXME: there is probably a more robust way to do this

    // Strip off the directory part.
    String dirPath = directory.getPath();
    if (!fileName.startsWith(dirPath)) {
      throw new IllegalStateException("Filename " + fileName + " not inside directory " + dirPath);
    }

    // The problem here is that we need to take the relative part of the filename
    // and break it into components that we can then reconstruct into
    // a resource name (using '/' characters to separate the components).
    // Unfortunately, the File class does not make this task particularly easy.

    String relativeFileName = fileName.substring(dirPath.length());
    File file = new File(relativeFileName);
    LinkedList<String> partList = new LinkedList<String>();
    do {
      partList.addFirst(file.getName());
    } while ((file = file.getParentFile()) != null);

    StringBuilder buf = new StringBuilder();
    for (String part : partList) {
      if (buf.length() > 0) {
        buf.append('/');
      }
      buf.append(part);
    }

    return buf.toString();
  }
 private <T> String toClassString(Collection<Class<? extends T>> providers) {
   StringBuilder sb = new StringBuilder();
   for (Class<?> provider : providers) {
     sb.append(provider.getName()).append(", ");
   }
   return sb.subSequence(0, sb.length() - 2).toString();
 }
예제 #29
0
 @Override
 public String toString() {
   StringBuilder sb = new StringBuilder();
   sb.append("live nodes:" + liveNodes);
   sb.append(" collections:" + collectionStates);
   return sb.toString();
 }
 @Override
 public List<Iteration> getAllProjectIterations(Integer projectId, IterationOptions options)
     throws PivotalTrackerException {
   StringBuilder url = new StringBuilder();
   url.append(IConstants.TRACKER_URL).append("projects/").append(projectId).append("/iterations");
   return getIterations(url, options);
 }