Parses metric, tagk or tagv, and name to rename UID
@return as hash map of type and name
@throws JSONException if parsing failed
@throws BadRequestException if the content was missing or parsing failed
357599
public HashMap<String, String> parseUidRenameV1() {
    final String json = query.getContent();
    if (json == null || json.isEmpty()) {
      throw new BadRequestException(HttpResponseStatus.BAD_REQUEST,
          "Missing message content",
          "Supply valid JSON formatted data in the body of your request");
    }
    try {
      return JSON.parseToObject(json, TR_HASH_MAP);
    } catch (IllegalArgumentException iae) {
      throw new BadRequestException("Unable to parse the given JSON", iae);
    }
  }
24537
@Override
	public HashMap<String, Object> getRequestMap() {
		return (HashMap<String, Object>) JKThreadLocal.getValue(JKContextConstants.HTTP_REQUEST_MAP);
	}
1140570
protected SB toJavaSuper( SB sb ) {
    sb.nl();
    sb.ii(1);
    sb.i().p("public String[]   getNames() { return NAMES; } ").nl();
    sb.i().p("public String[][] getDomainValues() { return DOMAINS; }").nl();
    String uuid = this.uniqueId != null ? this.uniqueId.getId() : this._key.toString();
    sb.i().p("public String     getUUID() { return ").ps(uuid).p("; }").nl();

    return sb;
  }
1230638
private CmsSpellcheckingRequest parseJsonRequest(JSONObject jsonRequest) {

        final String id = jsonRequest.optString(JSON_ID);

        final JSONObject params = jsonRequest.optJSONObject(JSON_PARAMS);

        if (null == params) {
            LOG.debug("Invalid JSON request: No field \"params\" defined. ");
            return null;
        }
        final JSONArray words = params.optJSONArray(JSON_WORDS);
        final String lang = params.optString(JSON_LANG, LANG_DEFAULT);
        if (null == words) {
            LOG.debug("Invalid JSON request: No field \"words\" defined. ");
            return null;
        }

        // Convert JSON array to array of type String
        final List<String> wordsToCheck = new LinkedList<String>();
        for (int i = 0; i < words.length(); i++) {
            final String word = words.opt(i).toString();
            wordsToCheck.add(word);

            if (Character.isUpperCase(word.codePointAt(0))) {
                wordsToCheck.add(word.toLowerCase());
            }
        }

        return new CmsSpellcheckingRequest(wordsToCheck.toArray(new String[wordsToCheck.size()]), lang, id);
    }
52713
public static ByteMap<byte[]> getTagUids(final byte[] row) {
    final ByteMap<byte[]> uids = new ByteMap<byte[]>();
    final short name_width = TSDB.tagk_width();
    final short value_width = TSDB.tagv_width();
    final short tag_bytes = (short) (name_width + value_width);
    final short metric_ts_bytes = (short) (TSDB.metrics_width()
                                           + Const.TIMESTAMP_BYTES
                                           + Const.SALT_WIDTH());

    for (short pos = metric_ts_bytes; pos < row.length; pos += tag_bytes) {
      final byte[] tmp_name = new byte[name_width];
      final byte[] tmp_value = new byte[value_width];
      System.arraycopy(row, pos, tmp_name, 0, name_width);
      System.arraycopy(row, pos + name_width, tmp_value, 0, value_width);
      uids.put(tmp_name, tmp_value);
    }
    return uids;
  }
630305
public AnnotationBulkDelete parseAnnotationBulkDeleteV1() {
    final String json = query.getContent();
    if (json == null || json.isEmpty()) {
      throw new BadRequestException(HttpResponseStatus.BAD_REQUEST,
          "Missing message content",
          "Supply valid JSON formatted data in the body of your request");
    }
    
    return JSON.parseToObject(json, AnnotationBulkDelete.class);
  }
641284
@JsonIgnore
	public String getIdentifier() {

		String tags = "";

		Map<String, String> sortedTags = new TreeMap<>();
		sortedTags.putAll(getTags());
		if(!sortedTags.isEmpty()) {
			StringBuilder tagListBuffer = new StringBuilder("{");
			for (String tagKey : sortedTags.keySet()) {
				tagListBuffer.append(tagKey).append('=').append(sortedTags.get(tagKey)).append(',');
			}

			tags = tagListBuffer.substring(0, tagListBuffer.length() - 1).concat("}");
		}

		String namespace = getNamespace();
		Object[] params = { namespace == null ? "" : namespace + ":", getScope(), getMetric(), tags };
		String format = "{0}{1}:{2}" + "{3}";

		return MessageFormat.format(format, params);
	}
843572
@Override
  public String getTag() throws IOException {

    URLConnection urlConnection = url.openConnection();
    
    String tag = urlConnection.getHeaderField(ETAG);
    if(tag == null) {
    
      String key = url.toString() + "@" + urlConnection.getLastModified();
      
      tag = md5Cache.getIfPresent(key);

      if(tag == null) {
          
        try(InputStream urlStream = urlConnection.getInputStream()) {
      
          byte[] data = ByteStreams.toByteArray(urlConnection.getInputStream());
      
          tag = Hashing.md5().hashBytes(data).toString();
      
          md5Cache.put(key, tag);
        }
        
      }
      
    }
    
    return tag;
  }
1105515
public static Map<String, Object> convertRequestToMap(
            HttpServletRequest request) throws IOException, ServletException, JSONFormatException {

        Map<String, Object> inParams = new HashMap<String, Object>();

        //GET
        String q = request.getQueryString();
        if(!org.s1.objects.Objects.isNullOrEmpty(q)){
            String [] arr = q.split("&");
            for(String it:arr){
                String nv [] = it.split("=");
                String n = nv[0];
                String v = null;
                if(nv.length>1) {
                    v = nv[1];
                    try {
                        v = URLDecoder.decode(v, "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        throw S1SystemError.wrap(e);
                    }
                }
                if(PARAMS_PARAMETER.equals(n)){
                    inParams.putAll(Objects.fromWire(JSONFormat.evalJSON(v)));
                }else{
                    inParams.put(n,v);
                }
            }
        }
        if (request.getContentType()!=null && request.getContentType().contains("application/json")) {
            //JSON
            String s = IOUtils.toString(request.getInputStream(), "UTF-8");
            inParams = JSONFormat.evalJSON(s);
        } else if (request.getContentType()!=null
                && request.getContentType().contains("application/x-www-form-urlencoded")
                ) {
            //POST
            Iterator<Map.Entry<String, String[]>> it = request
                    .getParameterMap().entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, String[]> e = it.next();
                String v = "" + e.getValue()[0];
                inParams.put(e.getKey(), v);
            }
        } else if (request.getContentType()!=null
                && request.getContentType().contains("multipart/form-data")
                ) {
            //parts
            for(Part p : request.getParts()){
                if(p.getContentType()!=null){
                    if(p.getSize()==0)
                        continue;
                    String name = p.getName();
                    //file
                    for (String content : p.getHeader("content-disposition").split(";")) {
                        if (content.trim().startsWith("filename")) {
                            name = content.substring(
                                    content.indexOf('=') + 1).trim().replace("\"", "");
                        }
                    }
                    String ext = "";
                    int ei = name.lastIndexOf(".");
                    if(ei!=-1 && ei<name.length()-1){
                        ext = name.substring(ei+1);
                        name = name.substring(0,ei);
                    }

                    inParams.put(p.getName(), new FileParameter(p.getInputStream(),name,ext,p.getContentType(),p.getSize()));
                }else{
                    //param
                    inParams.put(p.getName(), IOUtils.toString(p.getInputStream(),"UTF-8"));
                }
            }
        }
        inParams = Objects.fromWire(inParams);
        return inParams;
    }
441322
private static JsonNode toJson(AggregatedHttpMessage res, @Nullable JsonNodeType expectedNodeType) {
        final String content = toString(res);
        final JsonNode node;
        try {
            node = Jackson.readTree(content);
        } catch (JsonParseException e) {
            throw new CentralDogmaException("failed to parse the response JSON", e);
        }

        if (expectedNodeType != null && node.getNodeType() != expectedNodeType) {
            throw new CentralDogmaException(
                    "invalid server response; expected: " + expectedNodeType +
                    ", actual: " + node.getNodeType() + ", content: " + content);
        }
        return node;
    }
1367343
private static Identity parse(final JsonObject json) {
        final String fname = "firstName";
        final String lname = "lastName";
        final String unknown = "?";
        final Map<String, String> props = new HashMap<>(json.size());
        props.put(fname, json.getString(fname, unknown));
        props.put(lname, json.getString(lname, unknown));
        return new Identity.Simple(
            String.format("urn:linkedin:%s", json.getString("id")), props
        );
    }
1305176
public static String getRowKeyTSUIDRegex(final List<String> tsuids) {
    Collections.sort(tsuids);
    
    // first, convert the tags to byte arrays and count up the total length
    // so we can allocate the string builder
    final short metric_width = TSDB.metrics_width();
    int tags_length = 0;
    final ArrayList<byte[]> uids = new ArrayList<byte[]>(tsuids.size());
    for (final String tsuid : tsuids) {
      final String tags = tsuid.substring(metric_width * 2);
      final byte[] tag_bytes = UniqueId.stringToUid(tags);
      tags_length += tag_bytes.length;
      uids.add(tag_bytes);
    }
    
    // Generate a regexp for our tags based on any metric and timestamp (since
    // those are handled by the row start/stop) and the list of TSUID tagk/v
    // pairs. The generated regex will look like: ^.{7}(tags|tags|tags)$
    // where each "tags" is similar to \\Q\000\000\001\000\000\002\\E
    final StringBuilder buf = new StringBuilder(
        13  // "(?s)^.{N}(" + ")$"
        + (tsuids.size() * 11) // "\\Q" + "\\E|"
        + tags_length); // total # of bytes in tsuids tagk/v pairs
    
    // Alright, let's build this regexp.  From the beginning...
    buf.append("(?s)"  // Ensure we use the DOTALL flag.
               + "^.{")
       // ... start by skipping the metric ID and timestamp.
       .append(Const.SALT_WIDTH() + metric_width + Const.TIMESTAMP_BYTES)
       .append("}(");
    
    for (final byte[] tags : uids) {
       // quote the bytes
      buf.append("\\Q");
      addId(buf, tags, true);
      buf.append('|');
    }
    
    // Replace the pipe of the last iteration, close and set
    buf.setCharAt(buf.length() - 1, ')');
    buf.append("$");
    return buf.toString();
  }
670647
public Map<String, Object> jsonToMap(String json) {

        /*
         * This if block treats the /v2/accounts/exists response. Currently the endpoint returns the status
         * code on its response body, breaking the JSON conversion.
         */
        if ("200".equals(json)) {
            this.responseBody.put("code", 200);
            return this.responseBody;
        }

        if ("400".equals(json)) {
            this.responseBody.put("code", 400);
            return this.responseBody;
        }

        if ("404".equals(json)) {
            this.responseBody.put("code", 404);
            return this.responseBody;
        }

        if (!json.equals("")) {
            ObjectMapper mapper = new ObjectMapper();
            try {
                this.responseBody = mapper.readValue(json, new TypeReference<Map<String, Object>>(){});
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return this.responseBody;
    }
756910
@Override
  public List<IncomingDataPoint> parsePutV1() {
    if (!query.hasContent()) {
      throw new BadRequestException("Missing request content");
    }

    // convert to a string so we can handle character encoding properly
    final String content = query.getContent().trim();
    final int firstbyte = content.charAt(0);
    try {
      if (firstbyte == '{') {
        final IncomingDataPoint dp = 
          JSON.parseToObject(content, IncomingDataPoint.class);
        final ArrayList<IncomingDataPoint> dps = 
          new ArrayList<IncomingDataPoint>(1);
        dps.add(dp);
        return dps;
      } else {
        return JSON.parseToObject(content, TR_INCOMING);
      }
    } catch (IllegalArgumentException iae) {
      throw new BadRequestException("Unable to parse the given JSON", iae);
    }
  }
1226418
public static List<byte[]> getTagsFromTSUID(final String tsuid) {
    if (tsuid == null || tsuid.isEmpty()) {
      throw new IllegalArgumentException("Missing TSUID");
    }
    if (tsuid.length() <= TSDB.metrics_width() * 2) {
      throw new IllegalArgumentException(
          "TSUID is too short, may be missing tags");
    }
     
    final List<byte[]> tags = new ArrayList<byte[]>();
    final int pair_width = (TSDB.tagk_width() * 2) + (TSDB.tagv_width() * 2);
    
    // start after the metric then iterate over each tagk/tagv pair
    for (int i = TSDB.metrics_width() * 2; i < tsuid.length(); i+= pair_width) {
      if (i + pair_width > tsuid.length()){
        throw new IllegalArgumentException(
            "The TSUID appears to be malformed, improper tag width");
      }
      String tag = tsuid.substring(i, i + (TSDB.tagk_width() * 2));
      tags.add(UniqueId.stringToUid(tag));
      tag = tsuid.substring(i + (TSDB.tagk_width() * 2), i + pair_width);
      tags.add(UniqueId.stringToUid(tag));
    }
    return tags;
  }
743100
public MetricName withTag(String key, String value) {
		return name(name).tags(tags).tag(key, value).build();
	}
708373
private String parseWithMetric(final String metric) {
    // TODO: Try to reduce code duplication with Tags.parseWithMetric().
    final int curly = metric.indexOf('{');
    if (curly < 0) {
      clearTags();
      return metric;
    }
    final int len = metric.length();
    if (metric.charAt(len - 1) != '}') {  // "foo{"
      clearTags();
      return null;  // Missing '}' at the end.
    } else if (curly == len - 2) {  // "foo{}"
      clearTags();
      return metric.substring(0, len - 2);
    }
    final int num_tags_before = getNumTags();
    
    final List<Filter> filters = new ArrayList<Filter>();
    final int close = metric.indexOf('}');
    int i = 0;
    if (close != metric.length() - 1) { // "foo{...}{tagk=filter}" 
      final int filter_bracket = metric.lastIndexOf('{');
      for (final String filter : metric.substring(filter_bracket + 1, 
          metric.length() - 1).split(",")) {
        if (filter.isEmpty()) {
          break;
        }
        final String[] kv = filter.split("=");
        if (kv.length != 2 || kv[0].isEmpty() || kv[1].isEmpty()) {
          continue;  // Invalid tag.
        }
        final Filter f = new Filter();
        f.tagk = kv[0];
        f.tagv = kv[1];
        f.is_groupby = false;
        filters.add(f);
        i++;  
      }
    }
    
    i = 0;
    for (final String tag : metric.substring(curly + 1, close).split(",")) {
      if (tag.isEmpty() && close != metric.length() - 1){
        break;
      }
      final String[] kv = tag.split("=");
      if (kv.length != 2 || kv[0].isEmpty() || kv[1].isEmpty()) {
        continue;  // Invalid tag.
      }
      final Filter f = new Filter();
      f.tagk = kv[0];
      f.tagv = kv[1];
      f.is_groupby = true;
      filters.add(f);
      i++;
    }
    if (!filters.isEmpty()) {
      Collections.sort(filters);
    }
    
    i = 0;
    for (int x = filters.size() - 1; x >= 0; x--) {
      final Filter filter = filters.get(x);
      if (i < num_tags_before) {
        setTag(i++, filter.tagk, filter.tagv, filter.is_groupby);
      } else {
        addTag(filter.tagk, filter.tagv, filter.is_groupby);
      }
    }
    
    if (i < num_tags_before) {
      setTag(i, "", "", true);
    } else {
      addTag();
    }
    // Remove extra tags.
    for (i++; i < num_tags_before; i++) {
      tagtable.removeRow(i + 1);
    }
    // Return the "foo" part of "foo{a=b,...,x=y}"
    return metric.substring(0, curly);
    
    /*
    // substring the tags out of "foo{a=b,...,x=y}" and parse them.
    int i = 0;  // Tag index.
    final int num_tags_before = getNumTags();
    for (final String tag : metric.substring(curly + 1, len - 1).split(",")) {
      final String[] kv = tag.split("=");
      if (kv.length != 2 || kv[0].isEmpty() || kv[1].isEmpty()) {
        setTag(i, "", "", true);
        continue;  // Invalid tag.
      }
      if (i < num_tags_before) {
        setTag(i, kv[0], kv[1], true);
      } else {
        addTag(kv[0], kv[1]);
      }
      i++;
    }
    // Leave an empty line at the end.
    if (i < num_tags_before) {
      setTag(i, "", "", true);
    } else {
      addTag();
    }
    // Remove extra tags.
    for (i++; i < num_tags_before; i++) {
      tagtable.removeRow(i + 1);
    }
    // Return the "foo" part of "foo{a=b,...,x=y}"
    return metric.substring(0, curly); */
  }