/** * Tests method setRequestContent of HttpClient. * * @throws IOException I/O Exception */ @Test public void writeMultipartMessage() throws IOException { final HttpRequest req = new HttpRequest(); req.isMultipart = true; req.payloadAttrs.put("media-type", "multipart/alternative"); req.payloadAttrs.put("boundary", "boundary42"); final Part p1 = new Part(); p1.headers.put("Content-Type", "text/plain; charset=us-ascii"); p1.bodyAttrs.put("media-type", "text/plain"); final String plain = "...plain text...."; p1.bodyContent.add(Str.get(plain + '\n')); final Part p2 = new Part(); p2.headers.put("Content-Type", "text/richtext"); p2.bodyAttrs.put("media-type", "text/richtext"); final String rich = ".... richtext version..."; p2.bodyContent.add(Str.get(rich)); final Part p3 = new Part(); p3.headers.put("Content-Type", "text/x-whatever"); p3.bodyAttrs.put("media-type", "text/x-whatever"); final String fancy = ".... fanciest formatted version..."; p3.bodyContent.add(Str.get(fancy)); req.parts.add(p1); req.parts.add(p2); req.parts.add(p3); final FakeHttpConnection fakeConn = new FakeHttpConnection(new URL("http://www.test.com")); HttpClient.setRequestContent(fakeConn.getOutputStream(), req); final String expResult = "--boundary42" + CRLF + "Content-Type: text/plain; charset=us-ascii" + CRLF + CRLF + plain + Prop.NL + CRLF + "--boundary42" + CRLF + "Content-Type: text/richtext" + CRLF + CRLF + rich + CRLF + "--boundary42" + CRLF + "Content-Type: text/x-whatever" + CRLF + CRLF + fancy + CRLF + "--boundary42--" + CRLF; // Compare results assertEquals(expResult, fakeConn.getOutputStream().toString()); }
/** * Tests parsing of multipart request when the contents for each part are set from the $bodies * parameter. * * @throws IOException I/O Exception * @throws QueryException query exception */ @Test public void parseMultipartReqBodies() throws IOException, QueryException { final String multiReq = "<http:request " + "xmlns:http='http://expath.org/ns/http-client' " + "method='POST' href='" + REST_ROOT + "'>" + "<http:header name='hdr1' value='hdr1val'/>" + "<http:header name='hdr2' value='hdr2val'/>" + "<http:multipart media-type='multipart/mixed' boundary='xxxx'>" + "<http:header name='p1hdr1' value='p1hdr1val'/>" + "<http:header name='p1hdr2' value='p1hdr2val'/>" + "<http:body media-type='text/plain'/>" + "<http:header name='p2hdr1' value='p2hdr1val'/>" + "<http:body media-type='text/plain'/>" + "<http:body media-type='text/plain'/>" + "</http:multipart>" + "</http:request>"; final DBNode dbNode1 = new DBNode(new IOContent(multiReq)); final ItemList bodies = new ItemList(); bodies.add(Str.get("Part1")); bodies.add(Str.get("Part2")); bodies.add(Str.get("Part3")); final HttpRequestParser rp = new HttpRequestParser(null); final HttpRequest r = rp.parse(dbNode1.children().next(), bodies.iter()); assertEquals(2, r.attributes.size()); assertEquals(2, r.headers.size()); assertTrue(r.isMultipart); assertEquals(3, r.parts.size()); // check parts final Iterator<Part> i = r.parts.iterator(); Part part = i.next(); assertEquals(2, part.headers.size()); assertEquals(1, part.bodyContent.size()); assertEquals(1, part.bodyAttrs.size()); part = i.next(); assertEquals(1, part.headers.size()); assertEquals(1, part.bodyContent.size()); assertEquals(1, part.bodyAttrs.size()); part = i.next(); assertEquals(0, part.headers.size()); assertEquals(1, part.bodyContent.size()); assertEquals(1, part.bodyAttrs.size()); }
public static long toLong(Object obj, final long longDefault) { if (obj instanceof Long) { return (Long) obj; } if (obj instanceof Number) { return ((Number) obj).longValue(); } else if (obj instanceof CharSequence) { String str = Str.toString(obj); if (Dates.isJsonDate(str)) { return Dates.fromJsonDate(str).getTime(); } try { return StringScanner.parseLong(str); } catch (Exception ex) { return longDefault; } } else if (obj instanceof Date) { return ((Date) obj).getTime(); } else { return toInt(obj); } }
public static float toFloat(Object obj) { if (obj.getClass() == float.class) { return (Float) obj; } try { if (obj instanceof Float) { return (Float) obj; } else if (obj instanceof Number) { return ((Number) obj).floatValue(); } else if (obj instanceof CharSequence) { try { return Float.parseFloat(Str.toString(obj)); } catch (Exception ex) { die(String.format("Unable to convert %s to a float", obj.getClass())); return Float.MIN_VALUE; } } else { } } catch (Exception ex) { log.warning( String.format( "unable to convert to float and there was an exception %s", ex.getMessage())); } die(String.format("Unable to convert %s to a float", obj.getClass())); return Float.MIN_VALUE; }
public static <T extends Enum> T toEnum(Class<T> cls, String value, Enum defaultEnum) { T[] enumConstants = cls.getEnumConstants(); for (T e : enumConstants) { if (e.name().equals(value)) { return e; } } value = value.toUpperCase().replace('-', '_'); for (T e : enumConstants) { if (e.name().equals(value)) { return e; } } value = Str.underBarCase(value); for (T e : enumConstants) { if (e.name().equals(value)) { return e; } } return (T) defaultEnum; }
@Override protected Response serve() { InputStream s = null; String urlStr = _url.value(); try { // if( urlStr.startsWith("file://") ) { // urlStr = urlStr.substring("file://".length()); if (urlStr.startsWith("file:///")) { urlStr = urlStr.substring("file:///".length()); File f = new File(urlStr); // urlStr = "file://"+f.getCanonicalPath(); urlStr = "file:///" + f.getCanonicalPath(); } URL url = new URL(urlStr); Key k = _key.value(); if (k == null) k = Key.make(urlStr); s = url.openStream(); if (s == null) return Response.error("Unable to open stream to URL " + url.toString()); ValueArray.readPut(k, s); JsonObject json = new JsonObject(); json.addProperty(KEY, k.toString()); json.addProperty(URL, urlStr); Response r = Response.done(json); r.setBuilder(KEY, new KeyElementBuilder()); return r; } catch (IllegalArgumentException e) { return Response.error("Not a valid key: " + urlStr); } catch (IOException e) { return Response.error(e); } finally { Closeables.closeQuietly(s); } }
/** * Evaluates the replace function. * * @param val input value * @param ctx query context * @return function result * @throws QueryException query exception */ private Item replace(final byte[] val, final QueryContext ctx) throws QueryException { final byte[] rep = checkStr(expr[2], ctx); for (int i = 0; i < rep.length; ++i) { if (rep[i] == '\\') { if (i + 1 == rep.length || rep[i + 1] != '\\' && rep[i + 1] != '$') FUNREPBS.thrw(info); ++i; } if (rep[i] == '$' && (i == 0 || rep[i - 1] != '\\') && (i + 1 == rep.length || !digit(rep[i + 1]))) FUNREPDOL.thrw(info); } final Pattern p = pattern(expr[1], expr.length == 4 ? expr[3] : null, ctx); if (p.pattern().isEmpty()) REGROUP.thrw(info); String r = string(rep); if ((p.flags() & Pattern.LITERAL) != 0) { r = SLASH.matcher(BSLASH.matcher(r).replaceAll("\\\\\\\\")).replaceAll("\\\\\\$"); } try { return Str.get(p.matcher(string(val)).replaceAll(r)); } catch (final Exception ex) { if (ex.getMessage().contains("No group")) REGROUP.thrw(info); throw REGPAT.thrw(info, ex); } }
/** * Encrypts or decrypts the given input. * * @param in input * @param s encryption type * @param k secret key * @param a encryption algorithm * @param ec encrypt or decrypt * @return encrypted or decrypted input * @throws QueryException query exception */ Str encryption(final byte[] in, final byte[] s, final byte[] k, final byte[] a, final boolean ec) throws QueryException { final boolean symmetric = eq(lc(s), SYM) || s.length == 0; final byte[] aa = a.length == 0 ? DES : a; final byte[] tivl = ALGE.get(lc(aa)); if (!symmetric) throw CX_ENCTYP.get(info, ec); if (tivl == null) throw CX_INVALGO.get(info, s); // initialization vector length final int ivl = toInt(tivl); try { return Str.get(ec ? encrypt(in, k, aa, ivl) : decrypt(in, k, aa, ivl)); } catch (final NoSuchPaddingException e) { throw CX_NOPAD.get(info, e); } catch (final BadPaddingException e) { throw CX_BADPAD.get(info, e); } catch (final InvalidKeyException e) { throw CX_KEYINV.get(info, e); } catch (final IllegalBlockSizeException e) { throw CX_ILLBLO.get(info, e); } catch (final GeneralSecurityException e) { throw CX_INVALGO.get(info, e); } }
/** * Returns a boolean value that shows if whether relationships between the boundaries, interiors * and exteriors of two geometries match the pattern specified in intersection-matrix-pattern. * * @param node1 xml element containing gml object(s) * @param node2 xml element containing gml object(s) * @param intersectionMatrix intersection matrix for two geometries * @return boolean value * @throws QueryException query exception */ @Deterministic public Bln relate(final ANode node1, final ANode node2, final Str intersectionMatrix) throws QueryException { final Geometry geo1 = checkGeo(node1); final Geometry geo2 = checkGeo(node2); return Bln.get(geo1.relate(geo2, intersectionMatrix.toJava())); }
/** * Runs a query with an external variable declaration. * * @throws IOException I/O exception */ @Test public void queryBindSequence() throws IOException { Query query = session.query("declare variable $a external; $a"); query.bind("a", "1\u00012", "xs:integer"); assertEqual("1", query.next()); assertEqual("2", query.next()); query.close(); query = session.query("declare variable $a external; $a"); query.bind("a", "09\u0002xs:hexBinary\u00012", "xs:integer"); assertEqual("09", query.next()); assertEqual("2", query.next()); query.close(); query = session.query("declare variable $a external; $a"); query.bind("a", Seq.get(new Item[] {Int.get(1), Str.get("X")}, 2)); assertEqual("1", query.next()); assertEqual("X", query.next()); query.close(); query = session.query("declare variable $a external; $a"); query.bind("a", IntSeq.get(new long[] {1, 2}, AtomType.INT)); assertEqual("1", query.next()); assertEqual("2", query.next()); query.close(); query = session.query("declare variable $a external; $a"); query.bind("a", IntSeq.get(new long[] {1, 2}, AtomType.INT), "xs:integer"); assertEqual("1", query.next()); assertEqual("2", query.next()); query.close(); }
/** * Converts the specified result to an XQuery value. * * @param obj result object * @param qc query context * @param sc static context * @return value * @throws QueryException query exception */ public static Value toValue(final Object obj, final QueryContext qc, final StaticContext sc) throws QueryException { if (obj == null) return Empty.SEQ; if (obj instanceof Value) return (Value) obj; if (obj instanceof Iter) return ((Iter) obj).value(); // find XQuery mapping for specified type final Type type = type(obj); if (type != null) return type.cast(obj, qc, sc, null); // primitive arrays if (obj instanceof byte[]) return BytSeq.get((byte[]) obj); if (obj instanceof long[]) return IntSeq.get((long[]) obj, AtomType.ITR); if (obj instanceof char[]) return Str.get(new String((char[]) obj)); if (obj instanceof boolean[]) return BlnSeq.get((boolean[]) obj); if (obj instanceof double[]) return DblSeq.get((double[]) obj); if (obj instanceof float[]) return FltSeq.get((float[]) obj); // no array: return Java type if (!obj.getClass().isArray()) return new Jav(obj, qc); // empty array final int s = Array.getLength(obj); if (s == 0) return Empty.SEQ; // string array if (obj instanceof String[]) { final String[] r = (String[]) obj; final byte[][] b = new byte[r.length][]; for (int v = 0; v < s; v++) b[v] = token(r[v]); return StrSeq.get(b); } // character array if (obj instanceof char[][]) { final char[][] r = (char[][]) obj; final byte[][] b = new byte[r.length][]; for (int v = 0; v < s; v++) b[v] = token(new String(r[v])); return StrSeq.get(b); } // short array if (obj instanceof short[]) { final short[] r = (short[]) obj; final long[] b = new long[r.length]; for (int v = 0; v < s; v++) b[v] = r[v]; return IntSeq.get(b, AtomType.SHR); } // integer array if (obj instanceof int[]) { final int[] r = (int[]) obj; final long[] b = new long[r.length]; for (int v = 0; v < s; v++) b[v] = r[v]; return IntSeq.get(b, AtomType.INT); } // any other array (also nested ones) final Object[] objs = (Object[]) obj; final ValueBuilder vb = new ValueBuilder(objs.length); for (final Object o : objs) vb.add(toValue(o, qc, sc)); return vb.value(); }
@Override public Boolean visit(Str exp) { if (!exp.typeOf(environment).equals(new StrType())) { errorMsgs.add(String.format("Incorrect Str: %s", exp)); ; return false; } return true; }
@Test public void test2NoRoot() throws Exception { final List<URL> urls = Classpaths.classpathResources(this.getClass(), "org/node/file1.txt"); URL url = urls.get(0); boolean ok = true; ok |= Str.in("abc", IO.read(url.openStream())) || die(); }
@Override public Str item(final QueryContext qc, final InputInfo ii) throws QueryException { ANode node, par = toNode(exprs[0], qc); do { node = par; par = node.parent(); } while (par != null); final DBNode dbn = toDBNode(node); return dbn.kind() == Data.DOC ? Str.get(dbn.data().text(dbn.pre(), true)) : Str.ZERO; }
@Test public void testResourcesFromPath() throws Exception { final List<String> paths = Classpaths.resources(this.getClass(), "/org/node/file1.txt"); String path = paths.get(0); boolean ok = true; ok |= Str.in("abc", IO.read(path)) || die(); }
public static Currency toCurrency(Object obj) { if (obj instanceof Currency) { return (Currency) obj; } if (obj instanceof String) { String str = Str.toString(obj); return Currency.getInstance(str); } return null; }
public Node(char parent, Str cur, HashMap<Character, Integer> map, int loc) { if (cur.str.length() == 0) return; if (cur.str.length() == 1) { letter = cur.str.charAt(0); return; } letter = cur.str.charAt(0); cur.str = cur.str.substring(1); if (map.get(cur.str.charAt(0)) < map.get(letter)) left = new Node(letter, cur, map, 0); if (map.get(cur.str.charAt(0)) > map.get(letter) && map.get(cur.str.charAt(0)) < map.get(parent)) right = new Node(parent, cur, map, 1); }
@Override public Item item(final QueryContext qc, final InputInfo ii) throws QueryException { final Iter ir = iter(qc); final Item it = ir.next(); if (it == null || ir.size() == 1) return it; final Item n = ir.next(); if (n != null) { final ValueBuilder vb = new ValueBuilder().add(it).add(n); if (ir.next() != null) vb.add(Str.get(DOTS)); throw SEQFOUND_X.get(info, vb.value()); } return it; }
/** * Tests writing of request content with different combinations of the body attributes media-type * and method. * * @throws IOException IO exception */ @Test public void writeMessage() throws IOException { // Case 1: No method, media-type='text/xml' final HttpRequest req1 = new HttpRequest(); final FakeHttpConnection fakeConn1 = new FakeHttpConnection(new URL("http://www.test.com")); req1.payloadAttrs.put(SerializerOptions.MEDIA_TYPE.name(), "text/xml"); // Node child final FElem e1 = new FElem("a").add("a"); req1.bodyContent.add(e1); // String item child req1.bodyContent.add(Str.get("<b>b</b>")); HttpClient.setRequestContent(fakeConn1.getOutputStream(), req1); assertEquals("<a>a</a><b>b</b>", fakeConn1.out.toString(Strings.UTF8)); // Case 2: No method, media-type='text/plain' final HttpRequest req2 = new HttpRequest(); final FakeHttpConnection fakeConn2 = new FakeHttpConnection(new URL("http://www.test.com")); req2.payloadAttrs.put(SerializerOptions.MEDIA_TYPE.name(), "text/plain"); // Node child final FElem e2 = new FElem("a").add("a"); req2.bodyContent.add(e2); // String item child req2.bodyContent.add(Str.get("<b>b</b>")); HttpClient.setRequestContent(fakeConn2.getOutputStream(), req2); assertEquals("a<b>b</b>", fakeConn2.out.toString()); // Case 3: method='text', media-type='text/xml' final HttpRequest req3 = new HttpRequest(); final FakeHttpConnection fakeConn3 = new FakeHttpConnection(new URL("http://www.test.com")); req3.payloadAttrs.put(SerializerOptions.MEDIA_TYPE.name(), "text/xml"); req3.payloadAttrs.put("method", "text"); // Node child final FElem e3 = new FElem("a").add("a"); req3.bodyContent.add(e3); // String item child req3.bodyContent.add(Str.get("<b>b</b>")); HttpClient.setRequestContent(fakeConn3.getOutputStream(), req3); assertEquals("a<b>b</b>", fakeConn3.out.toString()); }
@Override public Item item(final QueryContext qc, final InputInfo ii) throws QueryException { final String form = string(toToken(exprs[0], qc)); final int es = exprs.length; final Object[] args = new Object[es - 1]; for (int e = 1; e < es; e++) { final Item it = exprs[e].item(qc, info); args[e - 1] = it == null ? null : it.type.isUntyped() ? string(it.string(info)) : it.toJava(); } try { return Str.get(String.format(form, args)); } catch (final RuntimeException ex) { throw ERRFORMAT_X_X.get(info, Util.className(ex), ex); } }
private static String _sysProp(String key, Object defaultValue) { String property = (String) systemProperties.get(key); if (property == null) { property = env.get(key); if (property == null) { String newKey = Str.underBarCase(key); property = env.get(newKey); if (property == null && defaultValue != DEFAULT_NULL_NOT_EMPTY) { property = Conversions.toString(defaultValue); } } } return property; }
public static <T extends Enum> T sysProp(Class<T> cls, String key, T defaultValue) { String property = (String) systemProperties.get(key); if (property == null) { property = env.get(key); } if (property == null) { String newKey = Str.underBarCase(key); property = env.get(newKey); } if (property == null) { return defaultValue; } return Conversions.toEnum(cls, property); }
public static BigInteger sysPropBigInteger(String key, BigInteger defaultValue) { String property = (String) systemProperties.get(key); if (property == null) { property = env.get(key); } if (property == null) { String newKey = Str.underBarCase(key); property = env.get(newKey); } if (property == null) { return defaultValue; } return Conversions.toBigInteger(property); }
public static byte sysProp(String key, byte defaultValue) { String property = (String) systemProperties.get(key); if (property == null) { property = env.get(key); } if (property == null) { String newKey = Str.underBarCase(key); property = env.get(newKey); } if (property == null) { return defaultValue; } return Conversions.toByte(property); }
public static int toInt(Object obj, int defaultValue) { if (obj.getClass() == int.class) { return int.class.cast(obj); } if (obj instanceof Number) { return ((Number) obj).intValue(); } else if (obj instanceof Boolean || obj.getClass() == Boolean.class) { boolean value = toBoolean(obj); return value ? 1 : 0; } else if (obj instanceof CharSequence) { try { return StringScanner.parseInt(Str.toString(obj)); } catch (Exception ex) { return defaultValue; } } return defaultValue; }
public static File sysProp(String key, File defaultValue) { String property = (String) systemProperties.get(key); if (property == null) { property = env.get(key); } if (property == null) { String newKey = Str.underBarCase(key); property = env.get(newKey); } if (property == null) { return defaultValue; } return new File(property); }
public static Path sysProp(String key, Path defaultValue) { String property = (String) systemProperties.get(key); if (property == null) { property = env.get(key); } if (property == null) { String newKey = Str.underBarCase(key); property = env.get(newKey); } if (property == null) { return defaultValue; } return IO.path(property); }
@Override public final Item ebv(final QueryContext qc, final InputInfo ii) throws QueryException { final Item it; if (seqType().zeroOrOne()) { it = item(qc, info); } else { final Iter ir = iter(qc); it = ir.next(); if (it != null && !(it instanceof ANode)) { final Item n = ir.next(); if (n != null) { final ValueBuilder vb = new ValueBuilder().add(it).add(n); if (ir.next() != null) vb.add(Str.get(DOTS)); throw EBV_X.get(info, vb.value()); } } } return it == null ? Bln.FALSE : it; }
public static void printArray(OutputStream out, int array[], int cols) throws IOException { // try { int maxLen = 1; for (int i = 0; i < array.length; ++i) { if (String.valueOf(array[i]).length() > maxLen) { maxLen = String.valueOf(array[i]).length(); } } for (int i = 0; i < array.length; ++i) { out.write(Str.padLeft(String.valueOf(array[i]), maxLen + 1).getBytes()); if (i % cols == cols - 1) { out.write("\n".getBytes()); } } if ((array.length - 1) % cols != cols - 1) { out.write("\n".getBytes()); } // } catch (IOException ex) { // Logger.getAnonymousLogger().log(Level.SEVERE, ex.getMessage(), ex); // } }
/** * Creates a message authentication code (MAC) for the given input. * * @param msg input * @param k secret key * @param a encryption algorithm * @param enc encoding * @return MAC * @throws QueryException query exception */ Item hmac(final byte[] msg, final byte[] k, final byte[] a, final byte[] enc) throws QueryException { // create hash value from input message final Key key = new SecretKeySpec(k, string(a)); final byte[] aa = a.length == 0 ? DEFA : a; if (!ALGHMAC.contains(lc(aa))) throw CX_INVHASH.get(info, aa); final boolean b64 = eq(lc(enc), BASE64) || enc.length == 0; if (!b64 && !eq(lc(enc), HEX)) throw CX_ENC.get(info, enc); try { final Mac mac = Mac.getInstance(string(ALGHMAC.get(lc(aa)))); mac.init(key); final byte[] hash = mac.doFinal(msg); // convert to specified encoding, base64 as a standard, else use hex return Str.get(b64 ? org.basex.util.Base64.encode(hash) : hex(hash, true)); } catch (final NoSuchAlgorithmException e) { throw CX_INVHASH.get(info, e); } catch (final InvalidKeyException e) { throw CX_KEYINV.get(info, e); } }