ucar.nc2.util.EscapeStrings Java Examples

The following examples show how to use ucar.nc2.util.EscapeStrings. 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
Source File: OpendapServlet.java    From tds with 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 #2
Source File: DODSNetcdfFile.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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 #3
Source File: Nc4Iosp.java    From netcdf-java with 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 #4
Source File: TestSocketMessage.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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 #5
Source File: DatasetUrl.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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 #6
Source File: NetcdfFile.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 #7
Source File: TestMisc.java    From tds with 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 #8
Source File: AbstractServlet.java    From tds with 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 #9
Source File: DTSServlet.java    From tds with 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 #10
Source File: TestMisc.java    From netcdf-java with 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 #11
Source File: NetcdfFiles.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 #12
Source File: NetcdfFiles.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 #13
Source File: NetcdfFiles.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * 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 #14
Source File: NetcdfFiles.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** 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 #15
Source File: NetcdfFile.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 #16
Source File: NetcdfFile.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * 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 #17
Source File: DODSNetcdfFile.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 #18
Source File: Group.java    From netcdf-java with 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 #19
Source File: NetcdfFile.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * 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 #20
Source File: Dap2Parse.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
String dapdecode(Dap2Lex lexer, Object name) {
  return EscapeStrings.unescapeDAPIdentifier((String) name);
}
 
Example #21
Source File: Ceparse.java    From tds with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
String unescapeDAPName(Object name) {
  return EscapeStrings.unescapeDAPIdentifier((String) name);
}
 
Example #22
Source File: DODSNetcdfFile.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
static String makeDODSName(String name) {
  return EscapeStrings.unescapeDAPIdentifier(name);
}
 
Example #23
Source File: TestEncode.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Test
public void testOGC() {
  EscapeStrings.testOGC();
}
 
Example #24
Source File: ParsedSectionSpec.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * 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 #25
Source File: NetcdfFile.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * 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 variable@attribute
 * 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/varname.name2.name@attName"
 * @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 File: Attribute.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
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 #27
Source File: NetcdfFile.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
/**
 * 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 #28
Source File: NetcdfFile.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
/**
 * Unescape any escaped characters in a name.
 *
 * @param vname the escaped name
 * @return unescaped version of it
 * @deprecated use NetcdfFiles.makeNameUnescaped
 */
@Deprecated
public static String makeNameUnescaped(String vname) {
  return EscapeStrings.backslashUnescape(vname);
}
 
Example #29
Source File: NetcdfFiles.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
/**
 * Unescape any escaped characters in a name.
 *
 * @param vname the escaped name
 * @return unescaped version of it
 */
static String makeNameUnescaped(String vname) {
  return EscapeStrings.backslashUnescape(vname);
}
 
Example #30
Source File: NetcdfFiles.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
/**
 * Escape special characters in a netcdf short name when
 * it is intended for use in a sectionSpec
 *
 * @param vname the name
 * @return escaped version of it
 */
static String makeValidSectionSpecName(String vname) {
  return EscapeStrings.backslashEscape(vname, reservedSectionSpec);
}