-
Notifications
You must be signed in to change notification settings - Fork 44
Add javascript and regex parsers #36
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,102 @@ | ||
| /* | ||
| * Licensed to Metamarkets Group Inc. (Metamarkets) under one | ||
| * or more contributor license agreements. See the NOTICE file | ||
| * distributed with this work for additional information | ||
| * regarding copyright ownership. Metamarkets licenses this file | ||
| * to you under the Apache License, Version 2.0 (the | ||
| * "License"); you may not use this file except in compliance | ||
| * with the License. You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, | ||
| * software distributed under the License is distributed on an | ||
| * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| * KIND, either express or implied. See the License for the | ||
| * specific language governing permissions and limitations | ||
| * under the License. | ||
| */ | ||
|
|
||
| package com.metamx.common.parsers; | ||
|
|
||
| import com.google.common.base.Function; | ||
| import org.mozilla.javascript.Context; | ||
| import org.mozilla.javascript.ContextFactory; | ||
| import org.mozilla.javascript.ScriptableObject; | ||
|
|
||
| import java.util.List; | ||
| import java.util.Map; | ||
|
|
||
| /** | ||
| */ | ||
| public class JavaScriptParser implements Parser<String, Object> | ||
| { | ||
| private static Function<Object, Object> compile(String function) | ||
| { | ||
| final ContextFactory contextFactory = ContextFactory.getGlobal(); | ||
| final Context context = contextFactory.enterContext(); | ||
| context.setOptimizationLevel(9); | ||
|
|
||
| final ScriptableObject scope = context.initStandardObjects(); | ||
|
|
||
| final org.mozilla.javascript.Function fn = context.compileFunction(scope, function, "fn", 1, null); | ||
| Context.exit(); | ||
|
|
||
| return new Function<Object, Object>() | ||
| { | ||
| public Object apply(Object input) | ||
| { | ||
| // ideally we need a close() function to discard the context once it is not used anymore | ||
| Context cx = Context.getCurrentContext(); | ||
| if (cx == null) { | ||
| cx = contextFactory.enterContext(); | ||
| } | ||
|
|
||
| final Object res = fn.call(cx, scope, scope, new Object[]{input}); | ||
| return res != null ? Context.toObject(res, scope) : null; | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. You can use Context.jsToJava(res, Map.class) to avoid having to cast things later on I think |
||
| } | ||
| }; | ||
| } | ||
|
|
||
| private final Function<Object, Object> fn; | ||
|
|
||
| public JavaScriptParser( | ||
| final String function | ||
| ) | ||
| { | ||
| this.fn = compile(function); | ||
| } | ||
|
|
||
| public Function<Object, Object> getFn() | ||
| { | ||
| return fn; | ||
| } | ||
|
|
||
| @Override | ||
| public Map<String, Object> parse(String input) | ||
| { | ||
| try { | ||
| final Object compiled = fn.apply(input); | ||
| if (!(compiled instanceof Map)) { | ||
| throw new ParseException("JavaScript parsed value must be in {key: value} format!"); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. minor nit, but this will not throw a meaningful error message if one of the values in map is also a map. It will probably throw a weird error message about something being a Scriptable object and not a list downstream somewhere. |
||
| } | ||
|
|
||
| return (Map) compiled; | ||
| } | ||
| catch (Exception e) { | ||
| throw new ParseException(e, "Unable to parse row [%s]", input); | ||
| } | ||
| } | ||
|
|
||
| @Override | ||
| public void setFieldNames(Iterable<String> fieldNames) | ||
| { | ||
| throw new UnsupportedOperationException(); | ||
| } | ||
|
|
||
| @Override | ||
| public List<String> getFieldNames() | ||
| { | ||
| throw new UnsupportedOperationException(); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,125 @@ | ||
| /* | ||
| * Licensed to Metamarkets Group Inc. (Metamarkets) under one | ||
| * or more contributor license agreements. See the NOTICE file | ||
| * distributed with this work for additional information | ||
| * regarding copyright ownership. Metamarkets licenses this file | ||
| * to you under the Apache License, Version 2.0 (the | ||
| * "License"); you may not use this file except in compliance | ||
| * with the License. You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, | ||
| * software distributed under the License is distributed on an | ||
| * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| * KIND, either express or implied. See the License for the | ||
| * specific language governing permissions and limitations | ||
| * under the License. | ||
| */ | ||
|
|
||
| package com.metamx.common.parsers; | ||
|
|
||
| import com.google.common.base.Function; | ||
| import com.google.common.base.Optional; | ||
| import com.google.common.base.Splitter; | ||
| import com.google.common.collect.Iterables; | ||
| import com.google.common.collect.Lists; | ||
| import com.metamx.common.collect.Utils; | ||
|
|
||
| import java.util.List; | ||
| import java.util.Map; | ||
| import java.util.regex.Matcher; | ||
| import java.util.regex.Pattern; | ||
|
|
||
| /** | ||
| */ | ||
| public class RegexParser implements Parser<String, Object> | ||
| { | ||
| private final String pattern; | ||
| private final Splitter listSplitter; | ||
| private final Function<String, Object> valueFunction; | ||
| private final Pattern compiled; | ||
|
|
||
| private List<String> fieldNames = null; | ||
|
|
||
| public RegexParser( | ||
| final String pattern, | ||
| final Optional<String> listDelimiter | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. how about making the delimiter a regex as well?
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| ) | ||
| { | ||
| this.pattern = pattern; | ||
| this.listSplitter = Splitter.onPattern(listDelimiter.isPresent() | ||
| ? listDelimiter.get() | ||
| : Parsers.DEFAULT_LIST_DELIMITER); | ||
| this.valueFunction = new Function<String, Object>() | ||
| { | ||
| @Override | ||
| public Object apply(String input) | ||
| { | ||
| final List retVal = Lists.newArrayList( | ||
| Iterables.transform( | ||
| listSplitter.split(input), | ||
| ParserUtils.nullEmptyStringFunction | ||
| ) | ||
| ); | ||
| if (retVal.size() == 1) { | ||
| return retVal.get(0); | ||
| } else { | ||
| return retVal; | ||
| } | ||
| } | ||
| }; | ||
| this.compiled = Pattern.compile(pattern); | ||
| } | ||
|
|
||
| public RegexParser( | ||
| final String pattern, | ||
| final Optional<String> listDelimiter, | ||
| final Iterable<String> fieldNames | ||
| ) | ||
| { | ||
| this(pattern, listDelimiter); | ||
|
|
||
| setFieldNames(fieldNames); | ||
| } | ||
|
|
||
| @Override | ||
| public Map<String, Object> parse(String input) | ||
| { | ||
| try { | ||
| final Matcher matcher = compiled.matcher(input); | ||
|
|
||
| if (!matcher.matches()) { | ||
| throw new ParseException("Incorrect Regex: %s . No match found.", pattern); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Is "Incorrect regex" the correct message here? the regex might be fine, but the input simply has no match? |
||
| } | ||
|
|
||
| List<String> values = Lists.newArrayList(); | ||
| for (int i = 1; i <= matcher.groupCount(); i++) { | ||
| values.add(matcher.group(i)); | ||
| } | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. personally speaking :) , I would have done |
||
|
|
||
| if (fieldNames == null) { | ||
| setFieldNames(ParserUtils.generateFieldNames(values.size())); | ||
| } | ||
|
|
||
| return Utils.zipMapPartial(fieldNames, Iterables.transform(values, valueFunction)); | ||
| } | ||
| catch (Exception e) { | ||
| throw new ParseException(e, "Unable to parse row [%s]", input); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. probably not a big issue, but if matching fails then user would get nested ParseException, one from line 92 then that will get wrapped inside another here, should we catch specific exceptions instead of Exception ? or may be add another catch for ParseException that simple throws that?
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. the two levels of parseexceptions will tell you exactly what is wrong and where it is wrong. I tested this
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ok |
||
| } | ||
| } | ||
|
|
||
| @Override | ||
| public void setFieldNames(Iterable<String> fieldNames) | ||
| { | ||
| ParserUtils.validateFields(fieldNames); | ||
| this.fieldNames = Lists.newArrayList(fieldNames); | ||
| } | ||
|
|
||
| @Override | ||
|
|
||
| public List<String> getFieldNames() | ||
| { | ||
| return fieldNames; | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,81 @@ | ||
| /* | ||
| * Licensed to Metamarkets Group Inc. (Metamarkets) under one | ||
| * or more contributor license agreements. See the NOTICE file | ||
| * distributed with this work for additional information | ||
| * regarding copyright ownership. Metamarkets licenses this file | ||
| * to you under the Apache License, Version 2.0 (the | ||
| * "License"); you may not use this file except in compliance | ||
| * with the License. You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, | ||
| * software distributed under the License is distributed on an | ||
| * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| * KIND, either express or implied. See the License for the | ||
| * specific language governing permissions and limitations | ||
| * under the License. | ||
| */ | ||
|
|
||
| package com.metamx.common.parsers; | ||
|
|
||
| import com.google.common.collect.ImmutableMap; | ||
| import com.google.common.collect.Lists; | ||
| import junit.framework.Assert; | ||
| import org.junit.Test; | ||
|
|
||
| import java.util.Map; | ||
|
|
||
| /** | ||
| */ | ||
| public class JavaScriptParserTest | ||
| { | ||
| @Test | ||
| public void testParse() | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. add a test for returning an array, like for a multi-valued dim? or just add |
||
| { | ||
| final String function = "function(str) { var parts = str.split(\"-\"); return { one: parts[0], two: parts[1] } }"; | ||
|
|
||
| final Parser<String, Object> parser = new JavaScriptParser( | ||
| function | ||
| ); | ||
| String data = "foo-val1"; | ||
|
|
||
| final Map<String, Object> parsed = parser.parse(data); | ||
| ImmutableMap.Builder builder = ImmutableMap.builder(); | ||
| builder.put("one", "foo"); | ||
| builder.put("two", "val1"); | ||
| Assert.assertEquals( | ||
| "result", | ||
| builder.build(), | ||
| parsed | ||
| ); | ||
| } | ||
|
|
||
| @Test | ||
| public void testParseWithMultiVal() | ||
| { | ||
| final String function = "function(str) { var parts = str.split(\"-\"); return { one: [parts[0], parts[1]] } }"; | ||
|
|
||
| final Parser<String, Object> parser = new JavaScriptParser( | ||
| function | ||
| ); | ||
| String data = "val1-val2"; | ||
|
|
||
| final Map<String, Object> parsed = parser.parse(data); | ||
| ImmutableMap.Builder builder = ImmutableMap.builder(); | ||
| builder.put("one", Lists.newArrayList("val1", "val2")); | ||
| Assert.assertEquals( | ||
| "result", | ||
| builder.build(), | ||
| parsed | ||
| ); | ||
| } | ||
|
|
||
| @Test(expected = org.mozilla.javascript.EvaluatorException.class) | ||
| public void testFailure() | ||
| { | ||
| final String function = "i am bad javascript"; | ||
|
|
||
| new JavaScriptParser(function); | ||
| } | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This seems to use ThreadLocal variables, which is interesting.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this is what we do for all the javascript aggregators, filters, etc.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
can we move the context.exit to finally, to make sure any error does not leaves the thread local set ?