Java Code Examples for ucar.nc2.util.EscapeStrings

The following examples show how to use ucar.nc2.util.EscapeStrings. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * Return a variable name suitable for use in a DAP constraint expression.
 * [Original code seemed wrong because structures can be nested and hence
 * would have to use the full name just like non-structures]
 *
 * @param var The variable whose name will appear in the CE
 * @return The name in a form suitable for use in a cE
 */
public static String getDODSConstraintName(Variable var) {
  String vname = var.getDODSName();
  // The vname is backslash escaped, so we need to
  // modify to use DAP %xx escapes.
  return EscapeStrings.backslashToDAP(vname);

  /*
   * if (var instanceof DODSVariable)
   * return ((DODSVariable) var).getDODSName();
   * else if (var instanceof DODSStructure)
   * return ((DODSStructure) var).getDODSConstraintName();
   * else
   * return null;
   */
}
 
Example 2
/**
 * Given the fragment part of a url, see if it
 * parses as name=value pairs separated by '&'
 * (same as query part).
 *
 * @param fragment the fragment part of a url
 * @return a map of the name value pairs (possibly empty),
 *         or null if the fragment does not parse.
 */
private static Map<String, String> parseFragment(String fragment) {
  Map<String, String> map = new HashMap<>();
  if (fragment != null && fragment.length() >= 0) {
    if (fragment.charAt(0) == '#')
      fragment = fragment.substring(1);
    String[] pairs = fragment.split("[ \t]*[&][ \t]*");
    for (String pair : pairs) {
      String[] pieces = pair.split("[ \t]*[=][ \t]*");
      switch (pieces.length) {
        case 1:
          map.put(EscapeStrings.unescapeURL(pieces[0]).toLowerCase(), "true");
          break;
        case 2:
          map.put(EscapeStrings.unescapeURL(pieces[0]).toLowerCase(),
              EscapeStrings.unescapeURL(pieces[1]).toLowerCase());
          break;
        default:
          return null; // does not parse
      }
    }
  }
  return map;
}
 
Example 3
@Test
public void testStuff() throws IOException {
  if (!testing) {
    SocketMessage sm = new SocketMessage(9999, "startNewServer");
    sm.setRaw(true);

  } else {
    String url = "http://localhost:8080/thredds/test/it" // + EscapeStrings.escapeOGC("yabba/bad[0]/good")
        + "?" + EscapeStrings.escapeOGC("quuery[1]");
    System.out.printf("send '%s'%n", url);
    try (HTTPMethod method = HTTPFactory.Head(url)) {
      method.execute();
      int status = method.getStatusCode();
      System.out.printf("%d%n", status);
    } // close method, close method internal session
  }
}
 
Example 4
Source Project: netcdf-java   Source File: Nc4Iosp.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private StructureMembers createStructureMembers(UserType userType, String varname) {
  // Incorrect: StructureMembers sm = new StructureMembers(userType.name);
  StructureMembers.Builder sm = StructureMembers.builder().setName(varname);
  for (Field fld : userType.flds) {
    StructureMembers.MemberBuilder mb = sm.addMember(fld.name, null, null, fld.ctype.dt, fld.dims);
    mb.setDataParam(fld.offset);
    /*
     * This should already have been taken care of
     * if(fld.ctype.isVlen) {m.setShape(new int[]{-1}); }
     */

    if (fld.ctype.dt == DataType.STRUCTURE) {
      UserType nested_utype = userTypes.get(fld.fldtypeid);
      String partfqn = EscapeStrings.backslashEscapeCDMString(varname, ".") + "."
          + EscapeStrings.backslashEscapeCDMString(fld.name, ".");
      StructureMembers nested_sm = createStructureMembers(nested_utype, partfqn);
      mb.setStructureMembers(nested_sm);
    }
  }
  sm.setStructureSize(userType.size);
  return sm.build();
}
 
Example 5
Source Project: tds   Source File: OpendapServlet.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
protected ReqState getRequestState(HttpServletRequest request, HttpServletResponse response) {

    // Assume url was encoded
    String baseurl = request.getRequestURL().toString();
    baseurl = EscapeStrings.unescapeURL(baseurl);

    // Assume query was encoded
    String query = request.getQueryString();
    query = EscapeStrings.unescapeURLQuery(query);

    if (log.isDebugEnabled()) {
      log.debug(String.format("OpendapServlet: nominal url: %s?%s", baseurl, query));
    }

    String dataPath = TdsPathUtils.extractPath(request, "/dodsC");

    ReqState rs;
    try {
      rs = new ReqState(request, response, dataPath, baseurl, query);
    } catch (Exception bue) {
      rs = null;
    }

    return rs;
  }
 
Example 6
static String makeShortName(String name) {
  String unescaped = EscapeStrings.unescapeDAPIdentifier(name);
  int index = unescaped.lastIndexOf('/');
  if (index < 0)
    index = -1;
  return unescaped.substring(index + 1, unescaped.length());
}
 
Example 7
Source Project: netcdf-java   Source File: Group.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void appendGroupName(StringBuilder sbuff, Group.Builder g) {
  if (g == null || g.getParentGroup() == null) {
    return;
  }
  appendGroupName(sbuff, g.getParentGroup());
  sbuff.append(EscapeStrings.backslashEscape(g.shortName, reservedFullName));
  sbuff.append("/");
}
 
Example 8
/**
 * Given a CDMNode, create its full name with
 * appropriate backslash escaping of the specified characters.
 *
 * @param node the cdm node
 * @param reservedChars the set of characters to escape
 * @return full name
 * @deprecated use NetcdfFiles.makeFullName
 */
@Deprecated
protected static String makeFullName(CDMNode node, String reservedChars) {
  Group parent = node.getParentGroup();
  if (((parent == null) || parent.isRoot()) && !node.isMemberOfStructure()) // common case?
    return EscapeStrings.backslashEscape(node.getShortName(), reservedChars);
  StringBuilder sbuff = new StringBuilder();
  appendGroupName(sbuff, parent, reservedChars);
  appendStructureName(sbuff, node, reservedChars);
  return sbuff.toString();
}
 
Example 9
private static void appendGroupName(StringBuilder sbuff, Group g, String reserved) {
  if (g == null)
    return;
  if (g.getParentGroup() == null)
    return;
  appendGroupName(sbuff, g.getParentGroup(), reserved);
  sbuff.append(EscapeStrings.backslashEscape(g.getShortName(), reserved));
  sbuff.append("/");
}
 
Example 10
private static void appendStructureName(StringBuilder sbuff, CDMNode n, String reserved) {
  if (n.isMemberOfStructure()) {
    appendStructureName(sbuff, n.getParentStructure(), reserved);
    sbuff.append(".");
  }
  sbuff.append(EscapeStrings.backslashEscape(n.getShortName(), reserved));
}
 
Example 11
/** Create a Groups's full name with appropriate backslash escaping. */
public static String makeFullName(Group g) {
  // return makeFullName(g, reservedFullName);
  Group parent = g.getParentGroup();
  if ((parent == null) || parent.isRoot()) // common case?
    return EscapeStrings.backslashEscape(g.getShortName(), reservedFullName);
  StringBuilder sbuff = new StringBuilder();
  appendGroupName(sbuff, parent, reservedFullName);
  return sbuff.toString();
}
 
Example 12
/**
 * Given a CDMNode, create its full name with
 * appropriate backslash escaping of the specified characters.
 *
 * @param node the cdm node
 * @param reservedChars the set of characters to escape
 * @return full name
 */
private static String makeFullName(Variable node, String reservedChars) {
  Group parent = node.getParentGroup();
  if (((parent == null) || parent.isRoot()) && !node.isMemberOfStructure()) // common case?
    return EscapeStrings.backslashEscape(node.getShortName(), reservedChars);
  StringBuilder sbuff = new StringBuilder();
  appendGroupName(sbuff, parent, reservedChars);
  appendStructureName(sbuff, node, reservedChars);
  return sbuff.toString();
}
 
Example 13
private static void appendGroupName(StringBuilder sbuff, Group g, String reserved) {
  if (g == null)
    return;
  if (g.getParentGroup() == null)
    return;
  appendGroupName(sbuff, g.getParentGroup(), reserved);
  sbuff.append(EscapeStrings.backslashEscape(g.getShortName(), reserved));
  sbuff.append("/");
}
 
Example 14
private static void appendStructureName(StringBuilder sbuff, Variable n, String reserved) {
  if (n.isMemberOfStructure()) {
    appendStructureName(sbuff, n.getParentStructure(), reserved);
    sbuff.append(".");
  }
  sbuff.append(EscapeStrings.backslashEscape(n.getShortName(), reserved));
}
 
Example 15
Source Project: netcdf-java   Source File: TestMisc.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void testBackslashTokens(String escapedName) {
  System.out.printf("%s%n", escapedName);
  List<String> result = EscapeStrings.tokenizeEscapedName(escapedName);
  for (String r : result)
    System.out.printf("   %s%n", r);
  System.out.printf("%n");
}
 
Example 16
Source Project: tds   Source File: DTSServlet.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * @param request
 * @return the request state
 */
protected ReqState getRequestState(HttpServletRequest request, HttpServletResponse response) throws DAP2Exception {
  ReqState rs = null;
  // The url and query strings will come to us in encoded form
  // (see HTTPmethod.newMethod())
  String baseurl = request.getRequestURL().toString();
  baseurl = EscapeStrings.unescapeURL(baseurl);

  String query = request.getQueryString();
  query = EscapeStrings.unescapeURLQuery(query);

  rs = new ReqState(this, request, response, rootpath, baseurl, query);

  return rs;
}
 
Example 17
Source Project: tds   Source File: AbstractServlet.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * @param request
 * @return the request state
 */
protected ReqState getRequestState(HttpServletRequest request, HttpServletResponse response) throws DAP2Exception {
  ReqState rs = null;
  // The url and query strings will come to us in encoded form
  // (see HTTPmethod.newMethod())
  String baseurl = request.getRequestURL().toString();
  baseurl = EscapeStrings.unescapeURL(baseurl);

  String query = request.getQueryString();
  query = EscapeStrings.unescapeURLQuery(query);

  rs = new ReqState(this, request, response, rootpath, baseurl, query);
  return rs;
}
 
Example 18
Source Project: tds   Source File: TestMisc.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testEscapeStrings() throws Exception {
  pass = true;
  assert (esinputs.length == esoutputs.length);
  for (int i = 0; i < esinputs.length && pass; i++) {
    String result = EscapeStrings.escapeURL(esinputs[i]);
    System.err.printf("input= |%s|\n", esinputs[i]);
    System.err.printf("result=|%s|\n", result);
    System.err.printf("output=|%s|\n", esoutputs[i]);
    if (!result.equals(esoutputs[i]))
      pass = false;
    System.err.printf("input=%s output=%s pass=%s\n", esinputs[i], result, pass);
  }
  Assert.assertTrue("TestMisc.testEscapeStrings", pass);
}
 
Example 19
public void print(PrintWriter os, String pad) {

    if (_Debug)
      os.println("Entered Attribute.print()");

    if (this.attr instanceof AttributeTable) {

      if (_Debug)
        os.println("  Attribute \"" + _nameClear + "\" is a Container.");

      ((AttributeTable) this.attr).print(os, pad);

    } else {
      if (_Debug)
        os.println("    Printing Attribute \"" + _nameClear + "\".");

      os.print(pad + getTypeString() + " " + getEncodedName() + " ");

      Enumeration es = ((Vector) this.attr).elements();


      while (es.hasMoreElements()) {
        String val = (String) es.nextElement();

        /*
         * Base quoting on type
         * boolean useQuotes = false;
         * if (val.indexOf(' ') >= 0 ||
         * val.indexOf('\t') >= 0 ||
         * val.indexOf('\n') >= 0 ||
         * val.indexOf('\r') >= 0
         * ) {
         * 
         * if (val.indexOf('\"') != 0)
         * useQuotes = true;
         * }
         * 
         * if (useQuotes)
         * os.print("\"" + val + "\"");
         * else
         * os.print(val);
         */
        if (this.type == Attribute.STRING) {
          String quoted = "\"" + EscapeStrings.backslashEscapeDapString(val) + "\"";
          for (int i = 0; i < quoted.length(); i++) {
            os.print((char) ((int) quoted.charAt(i)));
          }
          // os.print(quoted);
        } else
          os.print(val);

        if (es.hasMoreElements())
          os.print(", ");
      }
      os.println(";");
    }
    if (_Debug)
      os.println("Leaving Attribute.print()");
    os.flush();
  }
 
Example 20
String dapdecode(Dap2Lex lexer, Object name) {
  return EscapeStrings.unescapeDAPIdentifier((String) name);
}
 
Example 21
static String makeDODSName(String name) {
  return EscapeStrings.unescapeDAPIdentifier(name);
}
 
Example 22
@Test
public void testOGC() {
  EscapeStrings.testOGC();
}
 
Example 23
/**
 * Parse a section specification String. These have the form:
 * 
 * <pre>
 *  section specification := selector | selector '.' selector
 *  selector := varName ['(' dims ')']
 *  varName := ESCAPED_STRING
 * <p/>
 *   dims := dim | dim, dims
 *   dim := ':' | slice | start ':' end | start ':' end ':' stride
 *   slice := INTEGER
 *   start := INTEGER
 *   stride := INTEGER
 *   end := INTEGER
 *   ESCAPED_STRING : must escape characters = ".("
 * </pre>
 * <p/>
 * Nonterminals are in lower case, terminals are in upper case, literals are in single quotes.
 * Optional components are enclosed between square braces '[' and ']'.
 *
 * @param ncfile look for variable in here
 * @param variableSection the string to parse, eg "record(12).wind(1:20,:,3)"
 * @return return ParsedSectionSpec, parsed representation of the variableSection String
 * @throws IllegalArgumentException when token is misformed, or variable name doesnt exist in ncfile
 * @throws ucar.ma2.InvalidRangeException if section does not match variable shape
 */
public static ParsedSectionSpec parseVariableSection(NetcdfFile ncfile, String variableSection)
    throws InvalidRangeException {
  List<String> tokes = EscapeStrings.tokenizeEscapedName(variableSection);
  if (tokes.isEmpty())
    throw new IllegalArgumentException("empty sectionSpec = " + variableSection);

  String selector = tokes.get(0);
  ParsedSectionSpec outerV = parseVariableSelector(ncfile, selector);

  // parse each selector, find the inner variable
  ParsedSectionSpec current = outerV;
  for (int i = 1; i < tokes.size(); i++) {
    selector = tokes.get(i);
    current.child = parseVariableSelector(current.v, selector);
    current = current.child;
  }

  return outerV;
}
 
Example 24
/**
 * Find a Variable, with the specified (escaped full) name.
 * It may possibly be nested in multiple groups and/or structures.
 * An embedded "." is interpreted as structure.member.
 * An embedded "/" is interpreted as group/variable.
 * If the name actually has a ".", you must escape it (call NetcdfFiles.makeValidPathName(varname))
 * Any other chars may also be escaped, as they are removed before testing.
 *
 * @param fullNameEscaped eg "/group/subgroup/name1.name2.name".
 * @return Variable or null if not found.
 */
@Nullable
public Variable findVariable(String fullNameEscaped) {
  if (fullNameEscaped == null || fullNameEscaped.isEmpty()) {
    return null;
  }

  Group g = rootGroup;
  String vars = fullNameEscaped;

  // break into group/group and var.var
  int pos = fullNameEscaped.lastIndexOf('/');
  if (pos >= 0) {
    String groups = fullNameEscaped.substring(0, pos);
    vars = fullNameEscaped.substring(pos + 1);
    StringTokenizer stoke = new StringTokenizer(groups, "/");
    while (stoke.hasMoreTokens()) {
      String token = NetcdfFiles.makeNameUnescaped(stoke.nextToken());
      g = g.findGroupLocal(token);
      if (g == null)
        return null;
    }
  }

  // heres var.var - tokenize respecting the possible escaped '.'
  List<String> snames = EscapeStrings.tokenizeEscapedName(vars);
  if (snames.isEmpty())
    return null;

  String varShortName = NetcdfFiles.makeNameUnescaped(snames.get(0));
  Variable v = g.findVariableLocal(varShortName);
  if (v == null)
    return null;

  int memberCount = 1;
  while (memberCount < snames.size()) {
    if (!(v instanceof Structure))
      return null;
    String name = NetcdfFiles.makeNameUnescaped(snames.get(memberCount++));
    v = ((Structure) v).findVariable(name);
    if (v == null)
      return null;
  }
  return v;
}
 
Example 25
/**
 * Find an attribute, with the specified (escaped full) name.
 * It may possibly be nested in multiple groups and/or structures.
 * An embedded "." is interpreted as structure.member.
 * An embedded "/" is interpreted as group/group or group/variable.
 * An embedded "@" is interpreted as [email protected]
 * If the name actually has a ".", you must escape it (call NetcdfFiles.makeValidPathName(varname))
 * Any other chars may also be escaped, as they are removed before testing.
 *
 * @param fullNameEscaped eg "@attName", "/group/subgroup/@attName" or "/group/subgroup/[email protected]"
 * @return Attribute or null if not found.
 */
@Nullable
public Attribute findAttribute(String fullNameEscaped) {
  if (fullNameEscaped == null || fullNameEscaped.isEmpty()) {
    return null;
  }

  int posAtt = fullNameEscaped.indexOf('@');
  if (posAtt < 0 || posAtt >= fullNameEscaped.length() - 1)
    return null;
  if (posAtt == 0) {
    return findGlobalAttribute(fullNameEscaped.substring(1));
  }

  String path = fullNameEscaped.substring(0, posAtt);
  String attName = fullNameEscaped.substring(posAtt + 1);

  // find the group
  Group g = rootGroup;
  int pos = path.lastIndexOf('/');
  String varName = (pos > 0 && pos < path.length() - 1) ? path.substring(pos + 1) : null;
  if (pos >= 0) {
    String groups = path.substring(0, pos);
    StringTokenizer stoke = new StringTokenizer(groups, "/");
    while (stoke.hasMoreTokens()) {
      String token = NetcdfFiles.makeNameUnescaped(stoke.nextToken());
      g = g.findGroupLocal(token);
      if (g == null)
        return null;
    }
  }
  if (varName == null) // group attribute
    return g.findAttribute(attName);

  // heres var.var - tokenize respecting the possible escaped '.'
  List<String> snames = EscapeStrings.tokenizeEscapedName(varName);
  if (snames.isEmpty())
    return null;

  String varShortName = NetcdfFiles.makeNameUnescaped(snames.get(0));
  Variable v = g.findVariableLocal(varShortName);
  if (v == null)
    return null;

  int memberCount = 1;
  while (memberCount < snames.size()) {
    if (!(v instanceof Structure))
      return null;
    String name = NetcdfFiles.makeNameUnescaped(snames.get(memberCount++));
    v = ((Structure) v).findVariable(name);
    if (v == null)
      return null;
  }

  return v.findAttribute(attName);
}
 
Example 26
Source Project: tds   Source File: Ceparse.java    License: BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
String unescapeDAPName(Object name) {
  return EscapeStrings.unescapeDAPIdentifier((String) name);
}
 
Example 27
Source Project: netcdf-java   Source File: DAPNode.java    License: BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
/**
 * Sets the name of the class instance.
 *
 * @param n the name of the class instance; with escapes
 */
public final void setEncodedName(String n) {
  _nameEncoded = n;
  _nameClear = EscapeStrings.unescapeDAPIdentifier(n);
}
 
Example 28
Source Project: netcdf-java   Source File: DAPNode.java    License: BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
/**
 * Sets the unencoded name of the class instance.
 *
 * @param n the unencoded name of the class instance.
 */
public void setClearName(String n) {
  _nameClear = n;
  _nameEncoded = EscapeStrings.escapeDAPIdentifier(n);
}
 
Example 29
/**
 * Escape special characters in a netcdf short name when
 * it is intended for use in CDL.
 *
 * @param vname the name
 * @return escaped version of it
 * @deprecated use NetcdfFiles.makeValidCDLName
 */
@Deprecated
public static String makeValidCDLName(String vname) {
  return EscapeStrings.backslashEscape(vname, reservedCdl);
}
 
Example 30
/**
 * Escape special characters in a netcdf short name when
 * it is intended for use in a fullname
 *
 * @param vname the name
 * @return escaped version of it
 * @deprecated use NetcdfFiles.makeValidPathName
 */
@Deprecated
public static String makeValidPathName(String vname) {
  return EscapeStrings.backslashEscape(vname, reservedFullName);
}