@Test
  public void xqueryTest()
      throws IOException, ClassNotFoundException, XQException, IllegalAccessException,
          InstantiationException, JAXBException {

    XQPreparedExpression expr;
    XQConnection conn;

    JAXBContext jaxbContext;
    Unmarshaller jaxbUnmarshaller;

    String xquery =
        "declare variable $doc  external;\n"
            + "for $r in $doc /response/body/resultat/actes/* \n"
            + "order by $r\n"
            + "return\n"
            + "<acte>\n"
            + "  <id>{$r/id/text()}</id>\n"
            + "  <name>{$r/nom/text()}</name>\n"
            + "  <init_date>{$r/data/data_inici/text()}</init_date>\n"
            + "  <start_time>{$r/data/hora_inici/text()}</start_time>\n"
            + "  <type>{$r/classificacions/nivell/text()}</type>\n"
            + "  <localization>{$r/lloc_simple/nom/text()}</localization>\n"
            + "  <street>{$r/lloc_simple/adreca_simple/carrer/text()}</street>\n"
            + "  <street_num>{$r/lloc_simple/adreca_simple/numero/text()}</street_num>\n"
            + "  <district>{$r/lloc_simple/adreca_simple/districte/text()}</district>\n"
            + "  <CP>{$r/lloc_simple/adreca_simple/codi_postal/text()}</CP>\n"
            + "  <x>{$r/lloc_simple/adreca_simple/coordenades/geocodificacio/data(@x)}</x>\n"
            + "  <y>{$r/lloc_simple/adreca_simple/coordenades/geocodificacio/data(@y)}</y>\n"
            + "</acte>";

    url = new URL("http://w10.bcn.es/APPS/asiasiacache/peticioXmlAsia?id=203");

    URLConnection urlconn = url.openConnection();
    urlconn.setReadTimeout(50000);

    XQDataSource xqds =
        (XQDataSource) Class.forName("net.sf.saxon.xqj.SaxonXQDataSource").newInstance();
    conn = xqds.getConnection();
    expr = conn.prepareExpression(xquery);
    expr.bindDocument(new javax.xml.namespace.QName("doc"), urlconn.getInputStream(), null, null);

    jaxbContext = JAXBContext.newInstance(Acte.class);
    jaxbUnmarshaller = jaxbContext.createUnmarshaller();

    OutputStream testFile = new FileOutputStream(testXmlRoute);

    List<Acte> actes = getActes(jaxbUnmarshaller, expr, conn);

    System.out.print(getActes(jaxbUnmarshaller, expr, conn));

    assertTrue(!actes.isEmpty());
  }
  // @Test
  public void staticFileTest()
      throws ClassNotFoundException, IllegalAccessException, InstantiationException, XQException,
          FileNotFoundException {

    XQPreparedExpression expr;
    XQConnection conn;
    // TODO Change local path file
    InputStream testFile = new FileInputStream(testXmlRoute);
    String xqueryString =
        " declare variable $doc external;\n" + "for $x in $doc return $x//acte/nom/text()";

    XQDataSource xqds =
        (XQDataSource) Class.forName("net.sf.saxon.xqj.SaxonXQDataSource").newInstance();
    conn = xqds.getConnection();
    expr = conn.prepareExpression(xqueryString);
    expr.bindDocument(new javax.xml.namespace.QName("doc"), testFile, null, null);

    XQResultSequence rs = expr.executeQuery();
    System.out.println("test:");
    while (rs.next()) System.out.println(rs.getItemAsString(null));
    assertNotNull(rs);
    conn.close();
  }
  /**
   * Evaluate expression and return opaque type
   *
   * @param cexp cexp
   * @param ctx ctx
   * @param type type
   * @return type
   * @throws FaultException FaultException
   * @throws EvaluationException EvaluationException
   */
  private Object evaluate(OExpression cexp, EvaluationContext ctx, QName type)
      throws FaultException, EvaluationException {
    try {
      OXQuery10ExpressionBPEL20 oxquery10 = ((OXQuery10ExpressionBPEL20) cexp);

      XQDataSource xqds = new SaxonXQDataSource();
      XQConnection xqconn = xqds.getConnection();

      Configuration configuration = ((SaxonXQConnection) xqconn).getConfiguration();
      configuration.setAllNodesUntyped(true);
      configuration.setHostLanguage(Configuration.XQUERY);

      XQStaticContext staticEnv = xqconn.getStaticContext();

      NSContext nsContext = oxquery10.getNamespaceCtx();
      Set<String> prefixes = nsContext.getPrefixes();
      for (String prefix : prefixes) {
        String uri = nsContext.getNamespaceURI(prefix);
        staticEnv.declareNamespace(prefix, uri);
      }

      configuration.setSchemaValidationMode(Validation.SKIP);
      xqconn.setStaticContext(staticEnv);

      // Prepare expression, for starters
      String xquery =
          oxquery10
              .getXquery()
              .replaceFirst(
                  Constants.XQUERY_FUNCTION_HANDLER_COMPILER,
                  Constants.XQUERY_FUNCTION_HANDLER_RUNTIME);
      XQPreparedExpression exp = xqconn.prepareExpression(xquery);

      JaxpFunctionResolver funcResolver = new JaxpFunctionResolver(ctx, oxquery10);
      JaxpVariableResolver variableResolver =
          new JaxpVariableResolver(ctx, oxquery10, configuration);
      // Bind external variables to runtime values
      for (QName variable : exp.getAllUnboundExternalVariables()) {
        // Evaluate referenced variable
        Object value = variableResolver.resolveVariable(variable);

        if (value instanceof Value) {
          SaxonXQConnection saxonConn = (SaxonXQConnection) xqconn;
          try {
            Item item = ((Value) value).asItem();
            if (item == null) {
              exp.bindSequence(variable, xqconn.createSequence(Collections.EMPTY_LIST.iterator()));
            } else {
              XQItem item2 = new SaxonXQItem(item, saxonConn);
              exp.bindItem(variable, item2);
            }
          } catch (XPathException e) {
            __log.warn("", e);
          }
        } else {

          if (value instanceof Date) {
            Date d = (Date) value;
            value = org.apache.ode.utils.ISO8601DateParser.format(d);
          }

          // Figure out type of variable
          XQSequenceType xqType = getItemType(xqconn, value);

          // Saxon doesn't like binding sequences to variables
          if (value instanceof Node) {
            // a node is a node-list, but the inverse isn't true.
            // so, if the value is truly a node, leave it alone.
          } else if (value instanceof NodeList) {
            // So extract the first item from the node list
            NodeList nodeList = (NodeList) value;
            ArrayList nodeArray = new ArrayList();
            for (int i = 0; i < nodeList.getLength(); i++) {
              nodeArray.add(nodeList.item(i));
            }
            value = xqconn.createSequence(nodeArray.iterator());
          }

          // Bind value with external variable
          if (value != null && xqType != null) {
            if (value instanceof XQSequence) {
              exp.bindSequence(variable, (XQSequence) value);
            } else {
              if (xqType instanceof XQItemType) {
                exp.bindObject(variable, value, (XQItemType) xqType);
              }
            }
          }
        }
      }

      // Set context node
      Node contextNode = (ctx.getRootNode() == null) ? DOMUtils.newDocument() : ctx.getRootNode();
      contextNode.setUserData(
          XQuery10BpelFunctions.USER_DATA_KEY_FUNCTION_RESOLVER, funcResolver, null);
      exp.bindItem(
          XQConstants.CONTEXT_ITEM,
          xqconn.createItemFromNode(contextNode, xqconn.createNodeType()));

      // Execute query
      XQResultSequence result = exp.executeQuery();

      // Cast Saxon result to Java result
      Object evalResult = getResultValue(type, result);

      if ((evalResult != null) && __log.isDebugEnabled()) {
        __log.debug(
            "Expression "
                + cexp.toString()
                + " generated result "
                + evalResult
                + " - type="
                + evalResult.getClass().getName());

        if (ctx.getRootNode() != null) {
          __log.debug("Was using context node " + DOMUtils.domToString(ctx.getRootNode()));
        }
      }

      return evalResult;
    } catch (XQException xqe) {
      // Extracting the real cause from all this wrapping isn't a simple task
      Throwable cause = (xqe.getCause() != null) ? xqe.getCause() : xqe;

      if (cause instanceof DynamicError) {
        Throwable th = ((DynamicError) cause).getException();

        if (th != null) {
          cause = th;

          if (cause.getCause() != null) {
            cause = cause.getCause();
          }
        }
      }

      throw new EvaluationException(
          "Error while executing an XQuery expression: " + cause.toString(), cause);
    } catch (WrappedResolverException wre) {
      __log.debug("Could not evaluate expression because of ", wre);
      throw (FaultException) wre.getCause();
    }
  }