repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-rule/src/main/java/org/smartdata/rule/objects/FileObject.java | smart-rule/src/main/java/org/smartdata/rule/objects/FileObject.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF 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 org.smartdata.rule.objects;
import org.smartdata.rule.parser.ValueType;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Definition of rule object 'File'.
*/
public class FileObject extends SmartObject {
public static final Map<String, Property> PROPERTIES;
static {
PROPERTIES = new HashMap<>();
PROPERTIES.put("path",
new Property("path", ValueType.STRING, null, "file", "path", false));
PROPERTIES.put("accessCount",
new Property("accessCount", ValueType.LONG,
Arrays.asList(ValueType.TIMEINTVAL),
"VIRTUAL_ACCESS_COUNT_TABLE", "", false, "count"));
PROPERTIES.put("ac",
new Property("ac", ValueType.LONG,
Arrays.asList(ValueType.TIMEINTVAL),
"VIRTUAL_ACCESS_COUNT_TABLE", "", false, "count"));
PROPERTIES.put("accessCountTop",
new Property("accessCountTop", ValueType.LONG,
Arrays.asList(ValueType.TIMEINTVAL, ValueType.LONG),
"VIRTUAL_ACCESS_COUNT_TABLE", "", false, "count"));
PROPERTIES.put("acTop",
new Property("acTop", ValueType.LONG,
Arrays.asList(ValueType.TIMEINTVAL, ValueType.LONG),
"VIRTUAL_ACCESS_COUNT_TABLE", "", false, "count"));
PROPERTIES.put("accessCountBottom",
new Property("accessCountBottom", ValueType.LONG,
Arrays.asList(ValueType.TIMEINTVAL, ValueType.LONG),
"VIRTUAL_ACCESS_COUNT_TABLE", "", false, "count"));
PROPERTIES.put("acBot",
new Property("acBot", ValueType.LONG,
Arrays.asList(ValueType.TIMEINTVAL, ValueType.LONG),
"VIRTUAL_ACCESS_COUNT_TABLE", "", false, "count"));
PROPERTIES.put("accessCountTopOnStoragePolicy",
new Property("accessCountTopOnStoragePolicy", ValueType.LONG,
Arrays.asList(ValueType.TIMEINTVAL, ValueType.LONG, ValueType.STRING),
"VIRTUAL_ACCESS_COUNT_TABLE", "", false, "count"));
PROPERTIES.put("acTopSp",
new Property("acTopSp", ValueType.LONG,
Arrays.asList(ValueType.TIMEINTVAL, ValueType.LONG, ValueType.STRING),
"VIRTUAL_ACCESS_COUNT_TABLE", "", false, "count"));
PROPERTIES.put("accessCountBottomOnStoragePolicy",
new Property("accessCountBottomOnStoragePolicy", ValueType.LONG,
Arrays.asList(ValueType.TIMEINTVAL, ValueType.LONG, ValueType.STRING),
"VIRTUAL_ACCESS_COUNT_TABLE", "", false, "count"));
PROPERTIES.put("acBotSp",
new Property("acBotSp", ValueType.LONG,
Arrays.asList(ValueType.TIMEINTVAL, ValueType.LONG, ValueType.STRING),
"VIRTUAL_ACCESS_COUNT_TABLE", "", false, "count"));
PROPERTIES.put("length",
new Property("length", ValueType.LONG,
null, "file", "length", false));
PROPERTIES.put("blocksize",
new Property("blocksize", ValueType.LONG,
null, "file", "block_size", false));
PROPERTIES.put("inCache",
new Property("inCache", ValueType.BOOLEAN,
null, "cached_file", null, false));
PROPERTIES.put("age",
new Property("age", ValueType.TIMEINTVAL,
null, "file", null, false,
"($NOW - modification_time)"));
PROPERTIES.put("mtime",
new Property("mtime", ValueType.TIMEPOINT,
null, "file", "modification_time", false));
PROPERTIES.put("atime",
new Property("atime", ValueType.TIMEPOINT,
null, "file", "access_time", false));
PROPERTIES.put("storagePolicy",
new Property("storagePolicy", ValueType.STRING,
null, "file", null, false,
"(SELECT policy_name FROM storage_policy WHERE sid = file.sid)"));
PROPERTIES.put("unsynced",
new Property("unsynced", ValueType.BOOLEAN,
null, "file_diff", null, false,
"state = 0"));
PROPERTIES.put("isDir",
new Property("isDir", ValueType.BOOLEAN,
null, "file", "is_dir", false));
PROPERTIES.put("ecPolicy",
new Property("ecPolicy", ValueType.STRING,
null, "file", null, false,
"(SELECT policy_name FROM ec_policy WHERE id = file.ec_policy_id)"));
}
public FileObject() {
super(ObjectType.FILE);
}
public Map<String, Property> getProperties() {
return PROPERTIES;
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-rule/src/main/java/org/smartdata/rule/parser/OperNode.java | smart-rule/src/main/java/org/smartdata/rule/parser/OperNode.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF 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 org.smartdata.rule.parser;
import java.io.IOException;
public class OperNode extends TreeNode {
private OperatorType operatorType;
public OperNode(OperatorType type, TreeNode left, TreeNode right) {
super(left, right);
operatorType = type;
}
// return this node's return type
public ValueType getValueType() {
if (operatorType.isLogicalOperation()) {
return ValueType.BOOLEAN;
}
ValueType l = left.getValueType();
ValueType r = right.getValueType();
switch (operatorType) {
case ADD:
if ((l == ValueType.TIMEPOINT && r == ValueType.TIMEINTVAL)
|| (r == ValueType.TIMEPOINT && l == ValueType.TIMEINTVAL)) {
return ValueType.TIMEPOINT;
}
return l;
case SUB:
if (l == ValueType.TIMEPOINT) {
if (r == ValueType.TIMEINTVAL) {
return ValueType.TIMEPOINT;
} else if (r == ValueType.TIMEPOINT) {
return ValueType.TIMEINTVAL;
}
}
return l;
}
return left.getValueType();
}
public OperatorType getOperatorType() {
return operatorType;
}
// TODO: check if any miss match in the tree
public void checkValueType() throws IOException {
}
public VisitResult eval() throws IOException {
return left.eval().eval(operatorType, right == null ? null : right.eval());
}
public boolean isOperNode() {
return true;
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-rule/src/main/java/org/smartdata/rule/parser/SmartRuleVisitTranslator.java | smart-rule/src/main/java/org/smartdata/rule/parser/SmartRuleVisitTranslator.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF 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 org.smartdata.rule.parser;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.misc.Interval;
import org.smartdata.model.CmdletDescriptor;
import org.smartdata.model.rule.TimeBasedScheduleInfo;
import org.smartdata.model.rule.TranslateResult;
import org.smartdata.rule.exceptions.RuleParserException;
import org.smartdata.rule.objects.Property;
import org.smartdata.rule.objects.PropertyRealParas;
import org.smartdata.rule.objects.SmartObject;
import org.smartdata.rule.parser.SmartRuleParser.TimeintvalexprContext;
import org.smartdata.utils.StringUtil;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** Convert SSM parse tree into internal representation. */
public class SmartRuleVisitTranslator extends SmartRuleBaseVisitor<TreeNode> {
private Map<String, SmartObject> objects = new HashMap<>();
private TreeNode objFilter = null;
private TreeNode conditions = null;
private List<PropertyRealParas> realParases = new LinkedList<>();
private TimeBasedScheduleInfo timeBasedScheduleInfo = null;
private CmdletDescriptor cmdDescriptor = null;
private TranslationContext transCtx = null;
private int[] condPostion;
private long minTimeInverval = Long.MAX_VALUE;
private List<String> pathCheckGlob = new ArrayList<>();
public SmartRuleVisitTranslator() {}
public SmartRuleVisitTranslator(TranslationContext transCtx) {
this.transCtx = transCtx;
}
@Override
public TreeNode visitRuleLine(SmartRuleParser.RuleLineContext ctx) {
return visitChildren(ctx);
}
@Override
public TreeNode visitObjTypeOnly(SmartRuleParser.ObjTypeOnlyContext ctx) {
String objName = ctx.OBJECTTYPE().getText();
SmartObject obj = SmartObject.getInstance(objName);
objects.put(objName, obj);
objects.put("Default", obj);
return null;
}
@Override
public TreeNode visitObjTypeWith(SmartRuleParser.ObjTypeWithContext ctx) {
String objName = ctx.OBJECTTYPE().getText();
SmartObject obj = SmartObject.getInstance(objName);
objects.put(objName, obj);
objects.put("Default", obj);
objFilter = visit(ctx.objfilter());
return null;
}
@Override
public TreeNode visitConditions(SmartRuleParser.ConditionsContext ctx) {
// System.out.println("Condition: " + ctx.getText());
condPostion = new int[2];
condPostion[0] = ctx.getStart().getStartIndex();
condPostion[1] = ctx.getStop().getStopIndex();
conditions = visit(ctx.boolvalue());
return conditions;
}
@Override
public TreeNode visitTriOnce(SmartRuleParser.TriOnceContext ctx) {
timeBasedScheduleInfo = new TimeBasedScheduleInfo();
return null;
}
@Override
public TreeNode visitTriTimePoint(SmartRuleParser.TriTimePointContext ctx) {
timeBasedScheduleInfo = new TimeBasedScheduleInfo();
TreeNode tr = visit(ctx.timepointexpr());
try {
long tm = (Long) (tr.eval().getValue());
// "now" should not be parsed as the current time in the parsing.
// We set it to -1 and its value will be set after the rule is triggered.
if (ctx.timepointexpr().getStart().getText().equalsIgnoreCase("now")
&& ctx.timepointexpr().getStop().getText().equalsIgnoreCase("now")) {
tm = -1L;
}
timeBasedScheduleInfo.setStartTime(tm);
timeBasedScheduleInfo.setEndTime(tm);
return null;
} catch (IOException e) {
throw new RuleParserException("Evaluate 'AT' expression error");
}
}
@Override
public TreeNode visitTriCycle(SmartRuleParser.TriCycleContext ctx) {
timeBasedScheduleInfo = new TimeBasedScheduleInfo();
List<TimeintvalexprContext> timeExprs = ctx.timeintvalexpr();
long[] everys = new long[timeExprs.size() + ((timeExprs.size() + 1) % 2)];
for (int i = 0; i < timeExprs.size(); i++) {
everys[i] = getLongConstFromTreeNode(visit(timeExprs.get(i)));
}
if (timeExprs.size() % 2 == 0) {
everys[everys.length - 1] = 5000;
}
timeBasedScheduleInfo.setEvery(everys);
if (ctx.duringexpr() != null) {
visit(ctx.duringexpr());
} else {
timeBasedScheduleInfo.setStartTime(getTimeNow());
timeBasedScheduleInfo.setEndTime(TimeBasedScheduleInfo.FOR_EVER);
}
return null;
}
@Override
public TreeNode visitTriFileEvent(SmartRuleParser.TriFileEventContext ctx) {
return visitChildren(ctx);
}
// duringexpr : FROM timepointexpr (TO timepointexpr)? ;
@Override
public TreeNode visitDuringexpr(SmartRuleParser.DuringexprContext ctx) {
TreeNode trFrom = visit(ctx.timepointexpr(0));
timeBasedScheduleInfo.setStartTime(getLongConstFromTreeNode(trFrom));
if (ctx.timepointexpr().size() > 1) {
TreeNode trEnd = visit(ctx.timepointexpr(1));
timeBasedScheduleInfo.setEndTime(getLongConstFromTreeNode(trEnd));
} else {
timeBasedScheduleInfo.setEndTime(TimeBasedScheduleInfo.FOR_EVER);
}
return null;
}
private long getLongConstFromTreeNode(TreeNode tr) {
if (tr.isOperNode()) {
throw new RuleParserException("Should be a ValueNode");
}
try {
return (Long) (tr.eval().getValue());
} catch (IOException e) {
throw new RuleParserException("Evaluate ValueNode error:" + tr);
}
}
// time point
@Override
public TreeNode visitTpeCurves(SmartRuleParser.TpeCurvesContext ctx) {
return visit(ctx.getChild(1));
}
@Override
public TreeNode visitTpeNow(SmartRuleParser.TpeNowContext ctx) {
return new ValueNode(new VisitResult(ValueType.TIMEPOINT, getTimeNow()));
}
private long getTimeNow() {
if (transCtx != null) {
return transCtx.getSubmitTime();
}
return System.currentTimeMillis();
}
@Override
public TreeNode visitTpeTimeConst(SmartRuleParser.TpeTimeConstContext ctx) {
String text = ctx.getText();
String tc = text.substring(1, text.length() - 1);
return pharseConstTimePoint(tc);
}
// | timepointexpr ('+' | '-') timeintvalexpr #tpeTimeExpr
@Override
public TreeNode visitTpeTimeExpr(SmartRuleParser.TpeTimeExprContext ctx) {
return generalExprOpExpr(ctx);
// return evalLongExpr(ctx, ValueType.TIMEPOINT);
}
@Override
public TreeNode visitTpeTimeId(SmartRuleParser.TpeTimeIdContext ctx) {
TreeNode node = visitChildren(ctx);
if (!node.isOperNode()) {
if (((ValueNode) node).getValueType() == ValueType.TIMEPOINT) {
return node;
}
}
throw new RuleParserException(
"Invalid attribute type in expression for '" + ctx.getText() + "'");
}
// Time interval
@Override
public TreeNode visitTieCurves(SmartRuleParser.TieCurvesContext ctx) {
return visit(ctx.getChild(1));
}
// | timepointexpr '-' timepointexpr #tieTpExpr
@Override
public TreeNode visitTieTpExpr(SmartRuleParser.TieTpExprContext ctx) {
return generalExprOpExpr(ctx);
// return evalLongExpr(ctx, ValueType.TIMEINTVAL);
}
@Override
public TreeNode visitTieConst(SmartRuleParser.TieConstContext ctx) {
return pharseConstTimeInterval(ctx.getText());
}
// timeintvalexpr ('-' | '+') timeintvalexpr #tieTiExpr
@Override
public TreeNode visitTieTiExpr(SmartRuleParser.TieTiExprContext ctx) {
return generalExprOpExpr(ctx);
// return evalLongExpr(ctx, ValueType.TIMEINTVAL);
}
@Override
public TreeNode visitTieTiIdExpr(SmartRuleParser.TieTiIdExprContext ctx) {
TreeNode node = visitChildren(ctx);
if (!node.isOperNode()) {
if (((ValueNode) node).getValueType() == ValueType.TIMEINTVAL) {
return node;
}
}
throw new RuleParserException(
"Invalid attribute type in expression for '" + ctx.getText() + "'");
}
private SmartObject createIfNotExist(String objName) {
SmartObject obj = objects.get(objName);
if (obj == null) {
obj = SmartObject.getInstance(objName);
objects.put(objName, obj);
}
return obj;
}
// ID
@Override
public TreeNode visitIdAtt(SmartRuleParser.IdAttContext ctx) {
// System.out.println("Bare ID: " + ctx.getText());
Property p = objects.get("Default").getProperty(ctx.getText());
if (p == null) {
throw new RuleParserException(
"Object "
+ objects.get("Default").toString()
+ " does not have a attribute named '"
+ "'"
+ ctx.getText());
}
if (p.getParamsTypes() != null) {
throw new RuleParserException("Should have no parameter(s) for " + ctx.getText());
}
PropertyRealParas realParas = new PropertyRealParas(p, null);
realParases.add(realParas);
return new ValueNode(new VisitResult(p.getValueType(), null, realParas));
}
@Override
public TreeNode visitIdObjAtt(SmartRuleParser.IdObjAttContext ctx) {
SmartObject obj = createIfNotExist(ctx.OBJECTTYPE().toString());
Property p = obj.getProperty(ctx.ID().getText());
if (p == null) {
throw new RuleParserException(
"Object "
+ obj.toString()
+ " does not have a attribute named '"
+ "'"
+ ctx.ID().getText());
}
if (p.getParamsTypes() != null) {
throw new RuleParserException("Should have no parameter(s) for " + ctx.getText());
}
PropertyRealParas realParas = new PropertyRealParas(p, null);
realParases.add(realParas);
return new ValueNode(new VisitResult(p.getValueType(), null, realParas));
}
@Override
public TreeNode visitIdAttPara(SmartRuleParser.IdAttParaContext ctx) {
SmartObject obj = createIfNotExist("Default");
Property p = obj.getProperty(ctx.ID().getText());
if (p == null) {
throw new RuleParserException(
"Object "
+ obj.toString()
+ " does not have a attribute named '"
+ ctx.ID().getText()
+ "'");
}
if (p.getParamsTypes() == null) {
throw new RuleParserException(
obj.toString() + "." + ctx.ID().getText() + " does not need parameter(s)");
}
int numParameters = ctx.getChildCount() / 2 - 1;
if (p.getParamsTypes().size() != numParameters) {
throw new RuleParserException(
obj.toString()
+ "."
+ ctx.ID().getText()
+ " needs "
+ p.getParamsTypes().size()
+ " instead of "
+ numParameters);
}
return parseIdParams(ctx, p, 2);
}
@Override
public TreeNode visitIdObjAttPara(SmartRuleParser.IdObjAttParaContext ctx) {
String objName = ctx.OBJECTTYPE().getText();
String propertyName = ctx.ID().getText();
Property p = createIfNotExist(objName).getProperty(propertyName);
if (p == null) {
throw new RuleParserException(
"Object "
+ ctx.OBJECTTYPE().toString()
+ " does not have a attribute named '"
+ "'"
+ ctx.ID().getText());
}
if (p.getParamsTypes() == null) {
throw new RuleParserException(
ctx.OBJECTTYPE().toString() + "." + ctx.ID().getText() + " does not need parameter(s)");
}
int numParameters = ctx.getChildCount() / 2 - 2;
if (p.getParamsTypes().size() != numParameters) {
throw new RuleParserException(
ctx.OBJECTTYPE().toString()
+ "."
+ ctx.ID().getText()
+ " needs "
+ p.getParamsTypes().size()
+ " instead of "
+ numParameters);
}
return parseIdParams(ctx, p, 4);
}
private TreeNode parseIdParams(ParserRuleContext ctx, Property p, int start) {
int paraIndex = 0;
List<Object> paras = new ArrayList<>();
// String a = ctx.getText();
for (int i = start; i < ctx.getChildCount() - 1; i += 2) {
String c = ctx.getChild(i).getText();
TreeNode res = visit(ctx.getChild(i));
if (res.isOperNode()) {
throw new RuleParserException("Should be direct.");
}
if (res.getValueType() != p.getParamsTypes().get(paraIndex)) {
throw new RuleParserException("Unexpected parameter type: " + ctx.getChild(i).getText());
}
Object value = ((ValueNode) res).eval().getValue();
paras.add(value);
if (p.getParamsTypes().get(paraIndex) == ValueType.TIMEINTVAL) {
minTimeInverval = Math.min((long) value, minTimeInverval);
}
paraIndex++;
}
PropertyRealParas realParas = new PropertyRealParas(p, paras);
realParases.add(realParas);
return new ValueNode(new VisitResult(p.getValueType(), null, realParas));
}
// numricexpr
@Override
public TreeNode visitNumricexprId(SmartRuleParser.NumricexprIdContext ctx) {
return visit(ctx.id());
}
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling {@link #visitChildren} on {@code
* ctx}.
*/
@Override
public TreeNode visitNumricexprCurve(SmartRuleParser.NumricexprCurveContext ctx) {
return visit(ctx.numricexpr());
}
// numricexpr opr numricexpr
@Override
public TreeNode visitNumricexprAdd(SmartRuleParser.NumricexprAddContext ctx) {
return generalExprOpExpr(ctx);
}
@Override
public TreeNode visitNumricexprMul(SmartRuleParser.NumricexprMulContext ctx) {
return generalExprOpExpr(ctx);
}
@Override
public TreeNode visitNumricexprLong(SmartRuleParser.NumricexprLongContext ctx) {
return pharseConstLong(ctx.LONG().getText());
}
private TreeNode generalExprOpExpr(ParserRuleContext ctx) {
TreeNode r1 = visit(ctx.getChild(0));
TreeNode r2 = visit(ctx.getChild(2));
return generalHandleExpr(ctx.getChild(1).getText(), r1, r2);
}
private TreeNode generalHandleExpr(String operator, TreeNode left, TreeNode right) {
TreeNode ret;
try {
if (left.isOperNode() || right.isOperNode()) {
ret = new OperNode(OperatorType.fromString(operator), left, right);
} else if (left.eval().isConst() && right.eval().isConst()) {
ret = new ValueNode(left.eval().eval(OperatorType.fromString(operator), right.eval()));
} else {
ret = new OperNode(OperatorType.fromString(operator), left, right);
}
if (ret.isOperNode()) {
left.setParent(ret);
if (right != null) {
right.setParent(ret);
if (!right.isOperNode()) {
VisitResult vs = ((ValueNode) right).eval();
if (vs.isConst() && vs.getValueType() == ValueType.TIMEINTVAL) {
minTimeInverval = Math.min((long) vs.getValue(), minTimeInverval);
}
}
}
}
} catch (IOException e) {
throw new RuleParserException(e.getMessage());
}
return ret;
}
// bool value
@Override
public TreeNode visitBvAndOR(SmartRuleParser.BvAndORContext ctx) {
return generalExprOpExpr(ctx);
}
@Override
public TreeNode visitBvId(SmartRuleParser.BvIdContext ctx) {
return visit(ctx.id());
}
@Override
public TreeNode visitBvNot(SmartRuleParser.BvNotContext ctx) {
TreeNode left = visit(ctx.boolvalue());
// TODO: bypass null
TreeNode right = new ValueNode(new VisitResult(ValueType.BOOLEAN, null));
return generalHandleExpr(ctx.NOT().getText(), left, right);
}
@Override
public TreeNode visitBvCurve(SmartRuleParser.BvCurveContext ctx) {
return visit(ctx.boolvalue());
}
@Override
public TreeNode visitBvCompareexpr(SmartRuleParser.BvCompareexprContext ctx) {
return visit(ctx.compareexpr());
}
// Compare
@Override
public TreeNode visitCmpIdLong(SmartRuleParser.CmpIdLongContext ctx) {
return generalExprOpExpr(ctx);
}
@Override
public TreeNode visitCmpIdString(SmartRuleParser.CmpIdStringContext ctx) {
return generalExprOpExpr(ctx);
}
@Override
public TreeNode visitCmpIdStringMatches(SmartRuleParser.CmpIdStringMatchesContext ctx) {
return generalExprOpExpr(ctx);
}
@Override
public TreeNode visitCmpTimeintvalTimeintval(SmartRuleParser.CmpTimeintvalTimeintvalContext ctx) {
return generalExprOpExpr(ctx);
}
@Override
public TreeNode visitCmpTimepointTimePoint(SmartRuleParser.CmpTimepointTimePointContext ctx) {
return generalExprOpExpr(ctx);
}
// String
@Override
public TreeNode visitStrPlus(SmartRuleParser.StrPlusContext ctx) {
return generalExprOpExpr(ctx);
}
@Override
public TreeNode visitStrOrdString(SmartRuleParser.StrOrdStringContext ctx) {
return pharseConstString(ctx.STRING().getText());
}
@Override
public TreeNode visitStrID(SmartRuleParser.StrIDContext ctx) {
return visit(ctx.id());
}
@Override
public TreeNode visitStrCurve(SmartRuleParser.StrCurveContext ctx) {
return visit(ctx.getChild(1));
}
@Override
public TreeNode visitStrTimePointStr(SmartRuleParser.StrTimePointStrContext ctx) {
return new ValueNode(new VisitResult(ValueType.STRING, ctx.TIMEPOINTCONST().getText()));
}
@Override
public TreeNode visitConstLong(SmartRuleParser.ConstLongContext ctx) {
return pharseConstLong(ctx.getText());
}
@Override
public TreeNode visitConstString(SmartRuleParser.ConstStringContext ctx) {
return pharseConstString(ctx.getText());
}
@Override
public TreeNode visitConstTimeInverval(SmartRuleParser.ConstTimeInvervalContext ctx) {
return pharseConstTimeInterval(ctx.getText());
}
@Override
public TreeNode visitConstTimePoint(SmartRuleParser.ConstTimePointContext ctx) {
return pharseConstTimePoint(ctx.getText());
}
private TreeNode pharseConstTimeInterval(String str) {
long intval = StringUtil.pharseTimeString(str);
return new ValueNode(new VisitResult(ValueType.TIMEINTVAL, intval));
}
private TreeNode pharseConstString(String str) {
String ret = str.substring(1, str.length() - 1);
return new ValueNode(new VisitResult(ValueType.STRING, ret));
}
private TreeNode pharseConstLong(String strLong) {
String str = strLong.toUpperCase();
Long ret = 0L;
long times = 1;
try {
Pattern p = Pattern.compile("[PTGMK]?B");
Matcher m = p.matcher(str);
String unit = "";
if (m.find()) {
unit = m.group();
}
str = str.substring(0, str.length() - unit.length());
switch (unit) {
case "PB":
times *= 1024L * 1024 * 1024 * 1024 * 1024;
break;
case "TB":
times *= 1024L * 1024 * 1024 * 1024;
break;
case "GB":
times *= 1024L * 1024 * 1024;
break;
case "MB":
times *= 1024L * 1024;
break;
case "KB":
times *= 1024L;
break;
}
ret = Long.parseLong(str);
} catch (NumberFormatException e) {
// ignore, impossible
}
return new ValueNode(new VisitResult(ValueType.LONG, ret * times));
}
@Override
public TreeNode visitCmdlet(SmartRuleParser.CmdletContext ctx) {
Interval i = new Interval(ctx.getStart().getStartIndex(), ctx.getStop().getStopIndex());
String cmd = ctx.getStart().getInputStream().getText(i);
try {
cmdDescriptor = CmdletDescriptor.fromCmdletString(cmd);
} catch (ParseException e) {
throw new RuleParserException(e.getMessage());
}
return null;
}
public TreeNode pharseConstTimePoint(String str) {
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
TreeNode result;
Date date;
try {
date = ft.parse(str);
result = new ValueNode(new VisitResult(ValueType.TIMEPOINT, date.getTime()));
} catch (ParseException e) {
throw new RuleParserException("Invalid time point string '" + str + "'");
}
return result;
}
private void setDefaultTimeBasedScheduleInfo() {
if (timeBasedScheduleInfo == null) {
long intval = 5000;
if (minTimeInverval != Long.MAX_VALUE) {
intval = Math.max(intval, minTimeInverval / 20);
}
timeBasedScheduleInfo =
new TimeBasedScheduleInfo(getTimeNow(),
TimeBasedScheduleInfo.FOR_EVER, new long[] {intval});
}
}
List<String> sqlStatements = new LinkedList<>();
List<String> tempTableNames = new LinkedList<>();
Map<String, List<Object>> dynamicParameters = new HashMap<>();
public TranslateResult generateSql() throws IOException {
String ret = "";
TreeNode l = objFilter != null ? objFilter : conditions;
TreeNode r = objFilter == null ? objFilter : conditions;
switch (objects.get("Default").getType()) {
case DIRECTORY:
case FILE:
ret = "SELECT path FROM file";
break;
default:
throw new IOException(
"No operation defined for Object " + objects.get("Default").getType());
}
if (l != null) {
TreeNode actRoot = r == null ? l : new OperNode(OperatorType.AND, l, r);
if (r != null) {
l.setParent(actRoot);
r.setParent(actRoot);
}
TreeNode root = new OperNode(OperatorType.NONE, actRoot, null);
actRoot.setParent(root);
ret += " WHERE " + doGenerateSql(root, "file").getRet() + ";";
}
sqlStatements.add(ret);
setDefaultTimeBasedScheduleInfo();
return new TranslateResult(
sqlStatements,
tempTableNames,
dynamicParameters,
sqlStatements.size() - 1,
timeBasedScheduleInfo,
cmdDescriptor,
condPostion,
pathCheckGlob);
}
private class NodeTransResult {
private String tableName;
private String ret;
private boolean invert;
public NodeTransResult(String tableName, String ret) {
this.tableName = tableName;
this.ret = ret;
}
public NodeTransResult(String tableName, String ret, boolean invert) {
this.tableName = tableName;
this.ret = ret;
this.invert = invert;
}
public String getTableName() {
return tableName;
}
public String getRet() {
return ret;
}
public boolean isInvert() {
return invert;
}
}
private String connectTables(String baseTable, NodeTransResult curr) {
String[] key = TableMetaData.getJoinableKey(baseTable, curr.getTableName());
String subSql = null;
if (key == null) {
return "(SELECT COUNT(*) FROM "
+ curr.getTableName()
+ (curr.getRet() != null ? " WHERE (" + curr.getRet() + ")" : "")
+ ") <> 0";
} else {
String con = "";
if (curr.isInvert() && curr.getTableName().startsWith("VIR_ACC_CNT_TAB_")) {
con = " NOT";
}
return key[0]
+ con
+ " IN "
+ "(SELECT "
+ key[1]
+ " FROM "
+ curr.getTableName()
+ (curr.getRet() != null ? " WHERE (" + curr.getRet() + ")" : "")
+ ")";
}
}
private boolean procAcc = false;
public NodeTransResult doGenerateSql(TreeNode root, String tableName) throws IOException {
if (root == null) {
return new NodeTransResult(tableName, "");
}
if (root.isOperNode()) {
OperatorType optype = ((OperNode) root).getOperatorType();
String op = optype.getOpInSql();
NodeTransResult lop = doGenerateSql(root.getLeft(), tableName);
NodeTransResult rop = null;
if (optype != OperatorType.NOT) {
rop = doGenerateSql(root.getRight(), tableName);
}
boolean bEflag = false;
if (lop.getTableName() == null && rop.getTableName() != null) {
NodeTransResult temp = lop;
lop = rop;
rop = temp;
bEflag = true;
}
if (optype == OperatorType.AND || optype == OperatorType.OR || optype == OperatorType.NONE) {
String lopTable = lop.getTableName();
if (lopTable != null && !lopTable.equals(tableName)) {
lop = new NodeTransResult(tableName, connectTables(tableName, lop));
}
String ropTable = rop.getTableName();
if (ropTable != null && !ropTable.equals(tableName)) {
rop = new NodeTransResult(tableName, connectTables(tableName, rop));
}
}
if (optype == OperatorType.NOT) {
return new NodeTransResult(tableName, op + " " + connectTables(tableName, lop));
}
boolean procAccLt = false;
String res;
if (op.length() > 0) {
String ropStr = rop.getRet();
if (optype == OperatorType.MATCHES) {
ropStr = ropStr.replace("*", "%");
ropStr = ropStr.replace("?", "_");
}
if (bEflag && !procAcc) {
switch (optype) {
case LT:
op = ">";
break;
case LE:
op = ">=";
break;
case GT:
op = "<";
break;
case GE:
op = "<=";
break;
}
}
if (procAcc) {
switch (optype) {
case LT:
op = ">=";
procAccLt = true;
break;
case LE:
op = ">";
procAccLt = true;
break;
case EQ:
if (ropStr.equals("0")) {
ropStr = "1";
op = ">=";
procAccLt = true;
}
break;
}
procAcc = false;
}
res = "(" + lop.getRet() + " " + op + " " + ropStr + ")";
} else {
res = "(" + lop.getRet() + ")";
}
return new NodeTransResult(
lop.getTableName() != null ? lop.getTableName() : rop.getTableName(), res, procAccLt);
} else {
ValueNode vNode = (ValueNode) root;
VisitResult vr = vNode.eval();
if (vr.isConst()) {
switch (vr.getValueType()) {
case TIMEINTVAL:
case TIMEPOINT:
case LONG:
return new NodeTransResult(null, "" + ((Long) vr.getValue()));
case STRING:
return new NodeTransResult(null, "'" + ((String) vr.getValue()) + "'");
case BOOLEAN:
if ((Boolean) vr.getValue()) {
return new NodeTransResult(null, "1");
} else {
return new NodeTransResult(null, "0");
}
default:
throw new IOException("Type = " + vr.getValueType().toString());
}
} else {
PropertyRealParas realParas = vr.getRealParas();
Property p = realParas.getProperty();
// TODO: Handle not
if (p.getPropertyName().equals("path")) {
ValueNode pathStrNode = (ValueNode) (vNode.getPeer());
VisitResult pathVr = pathStrNode.eval();
String pathStr = (String) pathVr.getValue();
pathCheckGlob.add(pathStr);
}
// TODO: hard code now, abstract later
if (p.getPropertyName().equals("accessCount")
|| p.getPropertyName().equals("ac")) {
String virTab = genAccessCountTable(transCtx == null ? 0 : transCtx.getRuleId(),
(Long) realParas.getValues().get(0));
procAcc = true;
return new NodeTransResult(virTab, realParas.formatParameters());
}
if (p.getPropertyName().equals("accessCountTop")
|| p.getPropertyName().equals("accessCountBottom")
|| p.getPropertyName().equals("acTop")
|| p.getPropertyName().equals("acBot")) {
boolean topFlag = p.getPropertyName().equals("accessCountTop")
|| p.getPropertyName().equals("acTop");
String virTab = genAccessCountTable(transCtx == null ? 0 : transCtx.getRuleId(),
(Long) realParas.getValues().get(0));
String func = "$@genVirtualAccessCountTable" + (topFlag ? "Top" : "Bottom") + "Value";
String mStr = virTab + (topFlag ? "_top_" : "_bottom_")
+ realParas.getValues().get(1).toString();
String mStrValue = mStr + "_value";
if (!sqlStatements.contains(func + "(" + mStr + ")")) {
sqlStatements.add(func + "(" + mStr + ")");
dynamicParameters.put(mStr, Arrays.asList(realParas.getValues(), virTab, mStrValue));
}
procAcc = true;
return new NodeTransResult(null, "$" + mStrValue);
}
if (p.getPropertyName().equals("accessCountTopOnStoragePolicy")
|| p.getPropertyName().equals("accessCountBottomOnStoragePolicy")
|| p.getPropertyName().equals("acTopSp")
|| p.getPropertyName().equals("acBotSp")) {
boolean topFlag = p.getPropertyName().equals("accessCountTopOnStoragePolicy")
|| p.getPropertyName().equals("acTopSp");
String virTab = genAccessCountTable(transCtx == null ? 0 : transCtx.getRuleId(),
(Long) realParas.getValues().get(0));
String func = "$@genVirtualAccessCountTable" + (topFlag ? "Top" : "Bottom")
+ "ValueOnStoragePolicy";
String mStr = virTab + (topFlag ? "_top_" : "_bottom_")
+ realParas.getValues().get(1).toString() + "_on_storage_policy_"
+ realParas.getValues().get(2).toString();
String mStrValue = mStr + "_value";
if (!sqlStatements.contains(func + "(" + mStr + ")")) {
sqlStatements.add(func + "(" + mStr + ")");
dynamicParameters.put(mStr, Arrays.asList(realParas.getValues(), virTab, mStrValue));
}
procAcc = true;
return new NodeTransResult(null, "$" + mStrValue);
}
return new NodeTransResult(p.getTableName(), realParas.formatParameters());
}
}
// return new NodeTransResult(tableName, "");
}
private String genAccessCountTable(long rid, long interval) {
String virTab = "VIR_ACC_CNT_TAB_" + rid + "_" + interval;
if (!tempTableNames.contains(virTab)) {
tempTableNames.add(virTab);
sqlStatements.add("DROP TABLE IF EXISTS " + virTab + ";");
sqlStatements.add("$@genVirtualAccessCountTable(" + virTab + ")");
List<Object> args = new ArrayList<>();
args.add(Arrays.asList((Long) interval));
args.add(virTab);
dynamicParameters.put(virTab, args);
}
return virTab;
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-rule/src/main/java/org/smartdata/rule/parser/ValueType.java | smart-rule/src/main/java/org/smartdata/rule/parser/ValueType.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF 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 org.smartdata.rule.parser;
public enum ValueType {
ERROR, NONE, LONG, STRING, BOOLEAN, TIMEINTVAL, TIMEPOINT;
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-rule/src/main/java/org/smartdata/rule/parser/TranslationContext.java | smart-rule/src/main/java/org/smartdata/rule/parser/TranslationContext.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF 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 org.smartdata.rule.parser;
public class TranslationContext {
private long ruleId;
private long submitTime;
public TranslationContext(long ruleId, long submitTime) {
this.ruleId = ruleId;
this.submitTime = submitTime;
}
public long getRuleId() {
return ruleId;
}
public long getSubmitTime() {
return submitTime;
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-rule/src/main/java/org/smartdata/rule/parser/VisitResult.java | smart-rule/src/main/java/org/smartdata/rule/parser/VisitResult.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF 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 org.smartdata.rule.parser;
import org.smartdata.rule.objects.PropertyRealParas;
import java.io.IOException;
/** Represent a value or a identifier in the parser tree. */
public class VisitResult {
private ValueType type;
private Object value;
private PropertyRealParas realParas;
public void setValue(Object value) {
this.value = value;
}
public VisitResult(ValueType type, Object value) {
this.type = type;
this.value = value;
}
public VisitResult(ValueType type, Object value, PropertyRealParas realParas) {
this.type = type;
this.value = value;
this.realParas = realParas;
}
public PropertyRealParas getRealParas() {
return realParas;
}
public ValueType getValueType() {
return type;
}
public Object getValue() {
// TODO: handle identify issu
return value;
}
public VisitResult eval(OperatorType type, VisitResult dst) throws IOException {
VisitResult r;
switch (type) {
case GT:
r = new VisitResult(ValueType.BOOLEAN, this.compareTo(dst) > 0);
break;
case GE:
r = new VisitResult(ValueType.BOOLEAN, this.compareTo(dst) >= 0);
break;
case EQ:
r = new VisitResult(ValueType.BOOLEAN, this.compareTo(dst) == 0);
break;
case LT:
r = new VisitResult(ValueType.BOOLEAN, this.compareTo(dst) < 0);
break;
case LE:
r = new VisitResult(ValueType.BOOLEAN, this.compareTo(dst) <= 0);
break;
case NE:
r = new VisitResult(ValueType.BOOLEAN, this.compareTo(dst) != 0);
break;
case AND:
r = new VisitResult(ValueType.BOOLEAN, toBoolean() && dst.toBoolean());
break;
case OR:
r = new VisitResult(ValueType.BOOLEAN, toBoolean() || dst.toBoolean());
break;
case NOT:
r = new VisitResult(ValueType.BOOLEAN, !toBoolean());
break;
case ADD:
case SUB:
case MUL:
case DIV:
case MOD:
r = generateCalc(type, dst);
break;
// TODO:
default:
throw new IOException("Unknown type");
}
return r;
}
private VisitResult generateCalc(OperatorType opType, VisitResult dst) {
ValueType retType = null;
Object retValue = null;
boolean haveTimePoint =
getValueType() == ValueType.TIMEPOINT
|| (dst != null && dst.getValueType() == ValueType.TIMEPOINT);
if (haveTimePoint) {
if (opType == OperatorType.ADD) {
retType = ValueType.TIMEPOINT;
} else if (opType == OperatorType.SUB) {
retType = ValueType.TIMEINTVAL;
}
}
if (retType == null) {
retType = getValueType();
}
switch (type) {
case STRING:
switch (opType) {
case ADD:
retValue = (String) getValue() + (String) dst.getValue();
}
break;
default:
Long r1 = (Long) getValue();
Long r2 = (Long) dst.getValue();
switch (opType) {
case ADD:
retValue = r1 + r2;
break;
case SUB:
retValue = r1 - r2;
break;
case MUL:
retValue = r1 * r2;
break;
case DIV:
retValue = r1 / r2;
break;
case MOD:
retValue = r1 % r2;
break;
}
}
return new VisitResult(retType, retValue);
}
private boolean toBoolean() throws IOException {
if (type != ValueType.BOOLEAN) {
throw new IOException("Type must be boolean: " + this);
}
return (Boolean) getValue();
}
private int compareTo(VisitResult dst) throws IOException {
if (dst.getValueType() != this.type) {
throw new IOException("Type miss match for compare: [1] " + this + " [2] " + dst);
}
switch (type) {
case LONG:
case TIMEINTVAL:
case TIMEPOINT:
return (int) ((Long) getValue() - (Long) (dst.getValue()));
case STRING:
return ((String) getValue()).equals((String) (dst.getValue())) ? 0 : 1;
default:
throw new IOException("Invalid type for compare: [1] " + this + " [2] " + dst);
}
}
public boolean isConst() {
return type != ValueType.ERROR && getValue() != null;
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-rule/src/main/java/org/smartdata/rule/parser/TreeNode.java | smart-rule/src/main/java/org/smartdata/rule/parser/TreeNode.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF 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 org.smartdata.rule.parser;
import java.io.IOException;
public abstract class TreeNode {
protected TreeNode parent;
protected TreeNode left;
protected TreeNode right;
public TreeNode(TreeNode left, TreeNode right) {
this.left = left;
this.right = right;
}
public abstract VisitResult eval() throws IOException;
public abstract ValueType getValueType();
// TODO: print the tree
//public String toString();
public abstract void checkValueType() throws IOException;
public TreeNode getLeft() {
return left;
}
public TreeNode getRight() {
return right;
}
public void setParent(TreeNode parent) {
this.parent = parent;
}
public TreeNode getParent() {
return parent;
}
public TreeNode getPeer() {
if (getParent() == null) {
return null;
}
return getParent().getLeft() == this ? getParent().getRight() : getParent().getRight();
}
public abstract boolean isOperNode();
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-rule/src/main/java/org/smartdata/rule/parser/TableMetaData.java | smart-rule/src/main/java/org/smartdata/rule/parser/TableMetaData.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF 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 org.smartdata.rule.parser;
import java.util.HashMap;
import java.util.Map;
/**
* Info, constraints and relations about tables.
*/
public class TableMetaData {
private static Map<String, String[]> mapJoinableKeys = new HashMap<>();
private static Map<String, String[]> mapTableColumns = new HashMap<>();
static {
mapJoinableKeys.clear();
mapJoinableKeys.put("file-VIR_ACC_CNT_TAB",
new String[] {"fid", "fid"});
mapJoinableKeys.put("file-cached_file",
new String[] {"fid", "fid"});
mapJoinableKeys.put("file-file_diff",
new String[] {"path", "DISTINCT src"});
// TODO: others
// TODO: hard code them now
mapTableColumns.clear();
mapTableColumns.put("file", new String[] {
"path", "fid"
});
mapTableColumns.put("storage", new String[] {
"type", "capacity", "free"
});
// TODO: add other tables
}
public static String[] getJoinableKey(String tableA, String tableB) {
String keyAB = tableA + "-" + tableB;
if (mapJoinableKeys.containsKey(keyAB)) {
return mapJoinableKeys.get(keyAB).clone();
}
String keyBA = tableB + "-" + tableA;
if (mapJoinableKeys.containsKey(keyBA)) {
String[] result = mapJoinableKeys.get(keyBA);
String[] ret = new String[] {result[1], result[0]};
return ret;
}
for (String key : mapJoinableKeys.keySet()) {
if (keyAB.startsWith(key)) {
return mapJoinableKeys.get(key).clone();
}
}
return null;
}
public static String[] getTableColumns(String tableName) {
if (mapTableColumns.containsKey(tableName)) {
return mapTableColumns.get(tableName).clone();
}
return null;
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-rule/src/main/java/org/smartdata/rule/parser/SmartRuleStringParser.java | smart-rule/src/main/java/org/smartdata/rule/parser/SmartRuleStringParser.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF 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 org.smartdata.rule.parser;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.BaseErrorListener;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.Parser;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.Recognizer;
import org.antlr.v4.runtime.tree.ParseTree;
import org.smartdata.SmartConstants;
import org.smartdata.conf.SmartConf;
import org.smartdata.model.CmdletDescriptor;
import org.smartdata.model.rule.TranslateResult;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** Parser a rule string and translate it. */
public class SmartRuleStringParser {
private String rule;
private TranslationContext ctx = null;
private SmartConf conf;
private static Map<String, String> optCond = new HashMap<>();
static {
optCond.put("allssd", "storagePolicy != \"ALL_SSD\"");
optCond.put("onessd", "storagePolicy != \"ONE_SSD\"");
optCond.put("archive", "storagePolicy != \"COLD\"");
optCond.put("alldisk", "storagePolicy != \"HOT\"");
optCond.put("onedisk", "storagePolicy != \"WARM\"");
optCond.put("ramdisk", "storagePolicy != \"LAZY_PERSIST\"");
optCond.put("cache", "not inCache");
optCond.put("uncache", "inCache");
optCond.put("sync", "unsynced");
optCond.put("ec", "1");
optCond.put("unec", "1");
}
List<RecognitionException> parseErrors = new ArrayList<RecognitionException>();
String parserErrorMessage = "";
public class SSMRuleErrorListener extends BaseErrorListener {
@Override
public void syntaxError(
Recognizer<?, ?> recognizer,
Object offendingSymbol,
int line,
int charPositionInLine,
String msg,
RecognitionException e) {
List<String> stack = ((Parser) recognizer).getRuleInvocationStack();
Collections.reverse(stack);
parserErrorMessage += "Line " + line + ", Char " + charPositionInLine + " : " + msg + "\n";
parseErrors.add(e);
}
}
public SmartRuleStringParser(String rule, TranslationContext ctx, SmartConf conf) {
this.rule = rule;
this.ctx = ctx;
this.conf = conf;
}
public TranslateResult translate() throws IOException {
TranslateResult tr = doTranslate(rule);
CmdletDescriptor cmdDes = tr.getCmdDescriptor();
if (cmdDes.getActionSize() == 0) {
throw new IOException("No cmdlet specified in Rule");
}
String actName = cmdDes.getActionName(0);
if (cmdDes.getActionSize() != 1 || optCond.get(actName) == null) {
return tr;
}
String repl = optCond.get(actName);
if (cmdDes.getActionName(0).equals("ec") || cmdDes.getActionName(0).equals("unec")) {
String policy;
if (cmdDes.getActionName(0).equals("ec")) {
policy = cmdDes.getActionArgs(0).get("-policy");
if (policy == null) {
policy = conf.getTrimmed("dfs.namenode.ec.system.default.policy",
"RS-6-3-1024k");
}
} else {
policy = SmartConstants.REPLICATION_CODEC_NAME;
}
repl = "ecPolicy != \"" + policy + "\"";
}
int[] condPosition = tr.getCondPosition();
String cond = rule.substring(condPosition[0], condPosition[1] + 1);
String optRule = rule.replace(cond, repl + " and (" + cond + ")");
return doTranslate(optRule);
}
private TranslateResult doTranslate(String rule) throws IOException {
parseErrors.clear();
parserErrorMessage = "";
InputStream input = new ByteArrayInputStream(rule.getBytes());
ANTLRInputStream antlrInput = new ANTLRInputStream(input);
SmartRuleLexer lexer = new SmartRuleLexer(antlrInput);
CommonTokenStream tokens = new CommonTokenStream(lexer);
SmartRuleParser parser = new SmartRuleParser(tokens);
parser.removeErrorListeners();
parser.addErrorListener(new SSMRuleErrorListener());
ParseTree tree = parser.ssmrule();
if (parseErrors.size() > 0) {
throw new IOException(parserErrorMessage);
}
SmartRuleVisitTranslator visitor = new SmartRuleVisitTranslator(ctx);
try {
visitor.visit(tree);
} catch (RuntimeException e) {
throw new IOException(e.getMessage());
}
TranslateResult result = visitor.generateSql();
return result;
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-rule/src/main/java/org/smartdata/rule/parser/OperatorType.java | smart-rule/src/main/java/org/smartdata/rule/parser/OperatorType.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF 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 org.smartdata.rule.parser;
public enum OperatorType {
NONE("none", false, ""), // for error handling
ADD("+", false),
SUB("-", false),
MUL("*", false),
DIV("/", false),
MOD("%", false),
GT(">", true),
GE(">=", true),
LT("<", true),
LE("<=", true),
EQ("==", true),
NE("!=", true, "<>"),
MATCHES("matches", true, "LIKE"),
AND("and", true, "AND"),
OR("or", true, "OR"),
NOT("not", true, "NOT"),
;
private String name;
private boolean isLogical;
private String opInSql;
public boolean isLogicalOperation() {
return isLogical;
}
public static OperatorType fromString(String nameStr) {
for (OperatorType v : values()) {
if (v.name.equals(nameStr)) {
return v;
}
}
return NONE;
}
public String getOpInSql() {
return opInSql == null ? name : opInSql;
}
private OperatorType(String name, boolean isLogical) {
this.name = name;
this.isLogical = isLogical;
}
private OperatorType(String name, boolean isLogical, String opInSql) {
this.name = name;
this.isLogical = isLogical;
this.opInSql = opInSql;
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-rule/src/main/java/org/smartdata/rule/parser/ValueNode.java | smart-rule/src/main/java/org/smartdata/rule/parser/ValueNode.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF 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 org.smartdata.rule.parser;
import java.io.IOException;
public class ValueNode extends TreeNode {
private VisitResult value;
public ValueNode(VisitResult value) {
super(null, null);
this.value = value;
}
public void checkValueType() throws IOException {
}
public ValueType getValueType() {
return value.getValueType();
}
public VisitResult eval() {
return value;
}
public boolean isOperNode() {
return false;
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-admin/src/main/java/org/smartdata/admin/SmartAdmin.java | smart-admin/src/main/java/org/smartdata/admin/SmartAdmin.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF 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 org.smartdata.admin;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.ipc.ProtobufRpcEngine;
import org.apache.hadoop.ipc.RPC;
import org.smartdata.SmartServiceState;
import org.smartdata.conf.SmartConfKeys;
import org.smartdata.model.ActionDescriptor;
import org.smartdata.model.ActionInfo;
import org.smartdata.model.CmdletInfo;
import org.smartdata.model.CmdletState;
import org.smartdata.model.RuleInfo;
import org.smartdata.model.RuleState;
import org.smartdata.protocol.SmartAdminProtocol;
import org.smartdata.protocol.protobuffer.AdminProtocolClientSideTranslator;
import org.smartdata.protocol.protobuffer.AdminProtocolProtoBuffer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.List;
public class SmartAdmin implements java.io.Closeable, SmartAdminProtocol {
static final long VERSION = 1;
Configuration conf;
SmartAdminProtocol ssm;
volatile boolean clientRunning = true;
public SmartAdmin(Configuration conf)
throws IOException {
this.conf = conf;
String[] strings = conf.get(SmartConfKeys.SMART_SERVER_RPC_ADDRESS_KEY,
SmartConfKeys.SMART_SERVER_RPC_ADDRESS_DEFAULT).split(":");
InetSocketAddress address = new InetSocketAddress(
strings[strings.length - 2],
Integer.parseInt(strings[strings.length - 1]));
RPC.setProtocolEngine(conf, AdminProtocolProtoBuffer.class,
ProtobufRpcEngine.class);
AdminProtocolProtoBuffer proxy = RPC.getProxy(
AdminProtocolProtoBuffer.class, VERSION, address, conf);
this.ssm = new AdminProtocolClientSideTranslator(proxy);
}
@Override
public void close() {
if (clientRunning) {
RPC.stopProxy(ssm);
ssm = null;
this.clientRunning = false;
}
}
public void checkOpen() throws IOException {
if (!clientRunning) {
throw new IOException("SmartAdmin closed");
}
}
public SmartServiceState getServiceState() throws IOException {
checkOpen();
return ssm.getServiceState();
}
public void checkRule(String rule) throws IOException {
checkOpen();
ssm.checkRule(rule);
}
public long submitRule(String rule, RuleState initState)
throws IOException {
checkOpen();
return ssm.submitRule(rule, initState);
}
public RuleInfo getRuleInfo(long id) throws IOException {
checkOpen();
return ssm.getRuleInfo(id);
}
public List<RuleInfo> listRulesInfo() throws IOException {
checkOpen();
return ssm.listRulesInfo();
}
@Override
public void deleteRule(long ruleID, boolean dropPendingCmdlets)
throws IOException {
checkOpen();
ssm.deleteRule(ruleID, dropPendingCmdlets);
}
@Override
public void activateRule(long ruleID) throws IOException {
checkOpen();
ssm.activateRule(ruleID);
}
@Override
public void disableRule(long ruleID, boolean dropPendingCmdlets)
throws IOException {
checkOpen();
ssm.disableRule(ruleID, dropPendingCmdlets);
}
@Override
public CmdletInfo getCmdletInfo(long cmdletID) throws IOException {
checkOpen();
return ssm.getCmdletInfo(cmdletID);
}
@Override
public List<CmdletInfo> listCmdletInfo(long rid, CmdletState cmdletState)
throws IOException {
checkOpen();
return ssm.listCmdletInfo(rid, cmdletState);
}
@Override
public void activateCmdlet(long cmdletID) throws IOException {
checkOpen();
ssm.activateCmdlet(cmdletID);
}
@Override
public void disableCmdlet(long cmdletID) throws IOException {
checkOpen();
ssm.disableCmdlet(cmdletID);
}
@Override
public void deleteCmdlet(long cmdletID) throws IOException {
checkOpen();
ssm.deleteCmdlet(cmdletID);
}
@Override
public ActionInfo getActionInfo(long actionID) throws IOException {
checkOpen();
return ssm.getActionInfo(actionID);
}
@Override
public List<ActionInfo> listActionInfoOfLastActions(int maxNumActions) throws IOException {
checkOpen();
return ssm.listActionInfoOfLastActions(maxNumActions);
}
@Override
public long submitCmdlet(String cmd) throws IOException {
checkOpen();
return ssm.submitCmdlet(cmd);
}
@Override
public List<ActionDescriptor> listActionsSupported() throws IOException {
checkOpen();
return ssm.listActionsSupported();
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/utils/CommandLineUtils.java | smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/utils/CommandLineUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.utils;
import org.apache.zeppelin.util.Util;
import java.util.Locale;
/**
* CommandLine Support Class
*/
public class CommandLineUtils {
public static void main(String[] args) {
if (args.length == 0) {
return;
}
String usage = args[0].toLowerCase(Locale.US);
switch (usage){
case "--version":
case "-v":
System.out.println(Util.getVersion());
break;
default:
}
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/utils/InterpreterBindingUtils.java | smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/utils/InterpreterBindingUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.utils;
import org.apache.zeppelin.interpreter.InterpreterSetting;
import org.apache.zeppelin.notebook.Notebook;
import org.apache.zeppelin.types.InterpreterSettingsList;
import java.util.LinkedList;
import java.util.List;
/**
* Utils for interpreter bindings
*/
public class InterpreterBindingUtils {
public static List<InterpreterSettingsList> getInterpreterBindings(Notebook notebook,
String noteId) {
List<InterpreterSettingsList> settingList = new LinkedList<>();
List<InterpreterSetting> selectedSettings =
notebook.getBindedInterpreterSettings(noteId);
for (InterpreterSetting setting : selectedSettings) {
settingList.add(new InterpreterSettingsList(setting.getId(), setting.getName(),
setting.getInterpreterInfos(), true));
}
List<InterpreterSetting> availableSettings = notebook.getInterpreterSettingManager().get();
for (InterpreterSetting setting : availableSettings) {
boolean selected = false;
for (InterpreterSetting selectedSetting : selectedSettings) {
if (selectedSetting.getId().equals(setting.getId())) {
selected = true;
break;
}
}
if (!selected) {
settingList.add(new InterpreterSettingsList(setting.getId(), setting.getName(),
setting.getInterpreterInfos(), false));
}
}
return settingList;
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/utils/SecurityUtils.java | smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/utils/SecurityUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.utils;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ThreadContext;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.zeppelin.conf.ZeppelinConfiguration;
import org.apache.zeppelin.realm.LdapRealm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Sets;
/**
* Tools for securing Zeppelin
*/
public class SecurityUtils {
private static final String ANONYMOUS = "anonymous";
private static final HashSet<String> EMPTY_HASHSET = Sets.newHashSet();
private static boolean isEnabled = false;
private static final Logger LOG = LoggerFactory.getLogger(SecurityUtils.class);
public static void initSecurityManager(String shiroPath) {
IniSecurityManagerFactory factory = new IniSecurityManagerFactory("file:" + shiroPath);
SecurityManager securityManager = factory.getInstance();
org.apache.shiro.SecurityUtils.setSecurityManager(securityManager);
isEnabled = true;
}
public static Boolean isValidOrigin(String sourceHost, ZeppelinConfiguration conf)
throws UnknownHostException, URISyntaxException {
String sourceUriHost = "";
if (sourceHost != null && !sourceHost.isEmpty()) {
sourceUriHost = new URI(sourceHost).getHost();
sourceUriHost = (sourceUriHost == null) ? "" : sourceUriHost.toLowerCase();
}
sourceUriHost = sourceUriHost.toLowerCase();
String currentHost = InetAddress.getLocalHost().getHostName().toLowerCase();
return conf.getAllowedOrigins().contains("*") ||
currentHost.equals(sourceUriHost) ||
"localhost".equals(sourceUriHost) ||
conf.getAllowedOrigins().contains(sourceHost);
}
/**
* Return the authenticated user if any, otherwise returns "anonymous"
*
* @return shiro principal
*/
public static String getPrincipal() {
if (!isEnabled) {
return ANONYMOUS;
}
Subject subject = org.apache.shiro.SecurityUtils.getSubject();
String principal;
if (subject.isAuthenticated()) {
principal = subject.getPrincipal().toString();
} else {
principal = ANONYMOUS;
}
return principal;
}
public static Collection getRealmsList() {
if (!isEnabled) {
return Collections.emptyList();
}
DefaultWebSecurityManager defaultWebSecurityManager;
String key = ThreadContext.SECURITY_MANAGER_KEY;
defaultWebSecurityManager = (DefaultWebSecurityManager) ThreadContext.get(key);
Collection<Realm> realms = defaultWebSecurityManager.getRealms();
return realms;
}
/**
* Return the roles associated with the authenticated user if any otherwise returns empty set
* TODO(prasadwagle) Find correct way to get user roles (see SHIRO-492)
*
* @return shiro roles
*/
public static HashSet<String> getRoles() {
if (!isEnabled) {
return EMPTY_HASHSET;
}
Subject subject = org.apache.shiro.SecurityUtils.getSubject();
HashSet<String> roles = new HashSet<>();
Map allRoles = null;
if (subject.isAuthenticated()) {
Collection realmsList = SecurityUtils.getRealmsList();
for (Iterator<Realm> iterator = realmsList.iterator(); iterator.hasNext(); ) {
Realm realm = iterator.next();
String name = realm.getClass().getName();
if (name.equals("org.apache.shiro.realm.text.IniRealm")) {
allRoles = ((IniRealm) realm).getIni().get("roles");
break;
} else if (name.equals("org.apache.zeppelin.realm.LdapRealm")) {
allRoles = ((LdapRealm) realm).getListRoles();
break;
}
}
if (allRoles != null) {
Iterator it = allRoles.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
if (subject.hasRole((String) pair.getKey())) {
roles.add((String) pair.getKey());
}
}
}
}
return roles;
}
/**
* Checked if shiro enabled or not
*/
public static boolean isAuthenticated() {
if (!isEnabled) {
return false;
}
return org.apache.shiro.SecurityUtils.getSubject().isAuthenticated();
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/utils/ExceptionUtils.java | smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/utils/ExceptionUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.utils;
import javax.ws.rs.core.Response.Status;
import org.apache.zeppelin.server.JsonResponse;
/**
* Utility method for exception in rest api.
*
*/
public class ExceptionUtils {
public static javax.ws.rs.core.Response jsonResponse(Status status) {
return new JsonResponse<>(status).build();
}
public static javax.ws.rs.core.Response jsonResponseContent(Status status, String message) {
return new JsonResponse<>(status, message).build();
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/types/InterpreterSettingsList.java | smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/types/InterpreterSettingsList.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.types;
import java.util.List;
import org.apache.zeppelin.interpreter.InterpreterInfo;
/**
* InterpreterSetting information for binding
*/
public class InterpreterSettingsList {
private String id;
private String name;
private boolean selected;
private List<InterpreterInfo> interpreters;
public InterpreterSettingsList(String id, String name,
List<InterpreterInfo> interpreters, boolean selected) {
this.id = id;
this.name = name;
this.interpreters = interpreters;
this.selected = selected;
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/realm/ActiveDirectoryGroupRealm.java | smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/realm/ActiveDirectoryGroupRealm.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.realm;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.security.alias.CredentialProvider;
import org.apache.hadoop.security.alias.CredentialProviderFactory;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.realm.ldap.AbstractLdapRealm;
import org.apache.shiro.realm.ldap.DefaultLdapContextFactory;
import org.apache.shiro.realm.ldap.LdapContextFactory;
import org.apache.shiro.realm.ldap.LdapUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.LdapContext;
import java.util.*;
/**
* A {@link Realm} that authenticates with an active directory LDAP
* server to determine the roles for a particular user. This implementation
* queries for the user's groups and then maps the group names to roles using the
* {@link #groupRolesMap}.
*
* @since 0.1
*/
public class ActiveDirectoryGroupRealm extends AbstractLdapRealm {
private static final Logger log = LoggerFactory.getLogger(ActiveDirectoryGroupRealm.class);
private static final String ROLE_NAMES_DELIMETER = ",";
String KEYSTORE_PASS = "activeDirectoryRealm.systemPassword";
private String hadoopSecurityCredentialPath;
public void setHadoopSecurityCredentialPath(String hadoopSecurityCredentialPath) {
this.hadoopSecurityCredentialPath = hadoopSecurityCredentialPath;
}
/*--------------------------------------------
| I N S T A N C E V A R I A B L E S |
============================================*/
/**
* Mapping from fully qualified active directory
* group names (e.g. CN=Group,OU=Company,DC=MyDomain,DC=local)
* as returned by the active directory LDAP server to role names.
*/
private Map<String, String> groupRolesMap;
/*--------------------------------------------
| C O N S T R U C T O R S |
============================================*/
public void setGroupRolesMap(Map<String, String> groupRolesMap) {
this.groupRolesMap = groupRolesMap;
}
/*--------------------------------------------
| M E T H O D S |
============================================*/
LdapContextFactory ldapContextFactory;
protected void onInit() {
super.onInit();
this.getLdapContextFactory();
}
public LdapContextFactory getLdapContextFactory() {
if (this.ldapContextFactory == null) {
if (log.isDebugEnabled()) {
log.debug("No LdapContextFactory specified - creating a default instance.");
}
DefaultLdapContextFactory defaultFactory = new DefaultLdapContextFactory();
defaultFactory.setPrincipalSuffix(this.principalSuffix);
defaultFactory.setSearchBase(this.searchBase);
defaultFactory.setUrl(this.url);
defaultFactory.setSystemUsername(this.systemUsername);
defaultFactory.setSystemPassword(getSystemPassword());
this.ldapContextFactory = defaultFactory;
}
return this.ldapContextFactory;
}
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
throws AuthenticationException {
try {
AuthenticationInfo info = this.queryForAuthenticationInfo(token,
this.getLdapContextFactory());
return info;
} catch (javax.naming.AuthenticationException var5) {
throw new AuthenticationException("LDAP authentication failed.", var5);
} catch (NamingException var6) {
String msg = "LDAP naming error while attempting to authenticate user.";
throw new AuthenticationException(msg, var6);
}
}
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
try {
AuthorizationInfo info = this.queryForAuthorizationInfo(principals,
this.getLdapContextFactory());
return info;
} catch (NamingException var5) {
String msg = "LDAP naming error while attempting to " +
"retrieve authorization for user [" + principals + "].";
throw new AuthorizationException(msg, var5);
}
}
private String getSystemPassword() {
String password = "";
if (StringUtils.isEmpty(this.hadoopSecurityCredentialPath)) {
password = this.systemPassword;
} else {
try {
Configuration configuration = new Configuration();
configuration.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH,
this.hadoopSecurityCredentialPath);
CredentialProvider provider =
CredentialProviderFactory.getProviders(configuration).get(0);
CredentialProvider.CredentialEntry credEntry = provider.getCredentialEntry(
KEYSTORE_PASS);
if (credEntry != null) {
password = new String(credEntry.getCredential());
}
} catch (Exception e) {
}
}
return password;
}
/**
* Builds an {@link AuthenticationInfo} object by querying the active directory LDAP context for
* the specified username. This method binds to the LDAP server using the provided username
* and password - which if successful, indicates that the password is correct.
* <p/>
* This method can be overridden by subclasses to query the LDAP server in a more complex way.
*
* @param token the authentication token provided by the user.
* @param ldapContextFactory the factory used to build connections to the LDAP server.
* @return an {@link AuthenticationInfo} instance containing information retrieved from LDAP.
* @throws NamingException if any LDAP errors occur during the search.
*/
protected AuthenticationInfo queryForAuthenticationInfo(
AuthenticationToken token, LdapContextFactory ldapContextFactory) throws NamingException {
UsernamePasswordToken upToken = (UsernamePasswordToken) token;
// Binds using the username and password provided by the user.
LdapContext ctx = null;
try {
String userPrincipalName = upToken.getUsername();
if (!isValidPrincipalName(userPrincipalName)) {
return null;
}
if (this.principalSuffix != null && userPrincipalName.indexOf('@') < 0) {
userPrincipalName = upToken.getUsername() + this.principalSuffix;
}
ctx = ldapContextFactory.getLdapContext(
userPrincipalName, upToken.getPassword());
} finally {
LdapUtils.closeContext(ctx);
}
return buildAuthenticationInfo(upToken.getUsername(), upToken.getPassword());
}
private Boolean isValidPrincipalName(String userPrincipalName) {
if (userPrincipalName != null) {
if (StringUtils.isNotEmpty(userPrincipalName) && userPrincipalName.contains("@")) {
String userPrincipalWithoutDomain = userPrincipalName.split("@")[0].trim();
if (StringUtils.isNotEmpty(userPrincipalWithoutDomain)) {
return true;
}
} else if (StringUtils.isNotEmpty(userPrincipalName)) {
return true;
}
}
return false;
}
protected AuthenticationInfo buildAuthenticationInfo(String username, char[] password) {
if (this.principalSuffix != null && username.indexOf('@') > 1) {
username = username.split("@")[0];
}
return new SimpleAuthenticationInfo(username, password, getName());
}
/**
* Builds an {@link org.apache.shiro.authz.AuthorizationInfo} object by querying the active
* directory LDAP context for the groups that a user is a member of. The groups are then
* translated to role names by using the configured {@link #groupRolesMap}.
* <p/>
* This implementation expects the <tt>principal</tt> argument to be a String username.
* <p/>
* Subclasses can override this method to determine authorization data (roles, permissions, etc)
* in a more complex way. Note that this default implementation does not support permissions,
* only roles.
*
* @param principals the principal of the Subject whose account is being retrieved.
* @param ldapContextFactory the factory used to create LDAP connections.
* @return the AuthorizationInfo for the given Subject principal.
* @throws NamingException if an error occurs when searching the LDAP server.
*/
protected AuthorizationInfo queryForAuthorizationInfo(
PrincipalCollection principals,
LdapContextFactory ldapContextFactory) throws NamingException {
String username = (String) getAvailablePrincipal(principals);
// Perform context search
LdapContext ldapContext = ldapContextFactory.getSystemLdapContext();
Set<String> roleNames;
try {
roleNames = getRoleNamesForUser(username, ldapContext);
} finally {
LdapUtils.closeContext(ldapContext);
}
return buildAuthorizationInfo(roleNames);
}
protected AuthorizationInfo buildAuthorizationInfo(Set<String> roleNames) {
return new SimpleAuthorizationInfo(roleNames);
}
public List<String> searchForUserName(String containString, LdapContext ldapContext) throws
NamingException {
List<String> userNameList = new ArrayList<>();
SearchControls searchCtls = new SearchControls();
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String searchFilter = "(&(objectClass=*)(userPrincipalName=*" + containString + "*))";
Object[] searchArguments = new Object[]{containString};
NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchArguments,
searchCtls);
while (answer.hasMoreElements()) {
SearchResult sr = (SearchResult) answer.next();
if (log.isDebugEnabled()) {
log.debug("Retrieving userprincipalname names for user [" + sr.getName() + "]");
}
Attributes attrs = sr.getAttributes();
if (attrs != null) {
NamingEnumeration ae = attrs.getAll();
while (ae.hasMore()) {
Attribute attr = (Attribute) ae.next();
if (attr.getID().toLowerCase().equals("cn")) {
userNameList.addAll(LdapUtils.getAllAttributeValues(attr));
}
}
}
}
return userNameList;
}
private Set<String> getRoleNamesForUser(String username, LdapContext ldapContext)
throws NamingException {
Set<String> roleNames = new LinkedHashSet<>();
SearchControls searchCtls = new SearchControls();
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String userPrincipalName = username;
if (this.principalSuffix != null && userPrincipalName.indexOf('@') < 0) {
userPrincipalName += principalSuffix;
}
String searchFilter = "(&(objectClass=*)(userPrincipalName=" + userPrincipalName + "))";
Object[] searchArguments = new Object[]{userPrincipalName};
NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchArguments,
searchCtls);
while (answer.hasMoreElements()) {
SearchResult sr = (SearchResult) answer.next();
if (log.isDebugEnabled()) {
log.debug("Retrieving group names for user [" + sr.getName() + "]");
}
Attributes attrs = sr.getAttributes();
if (attrs != null) {
NamingEnumeration ae = attrs.getAll();
while (ae.hasMore()) {
Attribute attr = (Attribute) ae.next();
if (attr.getID().equals("memberOf")) {
Collection<String> groupNames = LdapUtils.getAllAttributeValues(attr);
if (log.isDebugEnabled()) {
log.debug("Groups found for user [" + username + "]: " + groupNames);
}
Collection<String> rolesForGroups = getRoleNamesForGroups(groupNames);
roleNames.addAll(rolesForGroups);
}
}
}
}
return roleNames;
}
/**
* This method is called by the default implementation to translate Active Directory group names
* to role names. This implementation uses the {@link #groupRolesMap} to map group names to role
* names.
*
* @param groupNames the group names that apply to the current user.
* @return a collection of roles that are implied by the given role names.
*/
protected Collection<String> getRoleNamesForGroups(Collection<String> groupNames) {
Set<String> roleNames = new HashSet<>(groupNames.size());
if (groupRolesMap != null) {
for (String groupName : groupNames) {
String strRoleNames = groupRolesMap.get(groupName);
if (strRoleNames != null) {
for (String roleName : strRoleNames.split(ROLE_NAMES_DELIMETER)) {
if (log.isDebugEnabled()) {
log.debug("User is member of group [" + groupName + "] so adding role [" +
roleName + "]");
}
roleNames.add(roleName);
}
}
}
}
return roleNames;
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/realm/UserPrincipal.java | smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/realm/UserPrincipal.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.realm;
import org.jvnet.libpam.UnixUser;
import java.security.Principal;
/**
* A {@code java.security.Principal} implememtation for use with Shiro {@code PamRealm}
*/
public class UserPrincipal implements Principal {
private final UnixUser userName;
public UserPrincipal(UnixUser userName) {
this.userName = userName;
}
@Override
public String getName() {
return userName.getUserName();
}
public UnixUser getUnixUser() {
return userName;
}
@Override
public String toString() {
return String.valueOf(userName.getUserName());
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/realm/ZeppelinHubRealm.java | smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/realm/ZeppelinHubRealm.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.realm;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashSet;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.zeppelin.notebook.repo.zeppelinhub.model.UserSessionContainer;
import org.apache.zeppelin.notebook.repo.zeppelinhub.websocket.utils.ZeppelinhubUtils;
import org.apache.zeppelin.server.SmartZeppelinServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Joiner;
import com.google.gson.Gson;
import com.google.gson.JsonParseException;
/**
* A {@code Realm} implementation that uses the ZeppelinHub to authenticate users.
*
*/
public class ZeppelinHubRealm extends AuthorizingRealm {
private static final Logger LOG = LoggerFactory.getLogger(ZeppelinHubRealm.class);
private static final String DEFAULT_ZEPPELINHUB_URL = "https://www.zeppelinhub.com";
private static final String USER_LOGIN_API_ENDPOINT = "api/v1/users/login";
private static final String JSON_CONTENT_TYPE = "application/json";
private static final String UTF_8_ENCODING = "UTF-8";
private static final String USER_SESSION_HEADER = "X-session";
private static final AtomicInteger INSTANCE_COUNT = new AtomicInteger();
private final HttpClient httpClient;
private final Gson gson;
private String zeppelinhubUrl;
private String name;
public ZeppelinHubRealm() {
super();
LOG.debug("Init ZeppelinhubRealm");
//TODO(anthonyc): think about more setting for this HTTP client.
// eg: if user uses proxy etcetc...
httpClient = new HttpClient();
gson = new Gson();
name = getClass().getName() + "_" + INSTANCE_COUNT.getAndIncrement();
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authToken)
throws AuthenticationException {
UsernamePasswordToken token = (UsernamePasswordToken) authToken;
if (StringUtils.isBlank(token.getUsername())) {
throw new AccountException("Empty usernames are not allowed by this realm.");
}
String loginPayload = createLoginPayload(token.getUsername(), token.getPassword());
User user = authenticateUser(loginPayload);
LOG.debug("{} successfully login via ZeppelinHub", user.login);
return new SimpleAuthenticationInfo(user.login, token.getPassword(), name);
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
// TODO(xxx): future work will be done here.
return null;
}
protected void onInit() {
super.onInit();
}
/**
* Setter of ZeppelinHub URL, this will be called by Shiro based on zeppelinhubUrl property
* in shiro.ini file.</p>
* It will also perform a check of ZeppelinHub url {@link #isZeppelinHubUrlValid},
* if the url is not valid, the default zeppelinhub url will be used.
*
* @param url
*/
public void setZeppelinhubUrl(String url) {
if (StringUtils.isBlank(url)) {
LOG.warn("Zeppelinhub url is empty, setting up default url {}", DEFAULT_ZEPPELINHUB_URL);
zeppelinhubUrl = DEFAULT_ZEPPELINHUB_URL;
} else {
zeppelinhubUrl = (isZeppelinHubUrlValid(url) ? url : DEFAULT_ZEPPELINHUB_URL);
LOG.info("Setting up Zeppelinhub url to {}", zeppelinhubUrl);
}
}
/**
* Send to ZeppelinHub a login request based on the request body which is a JSON that contains 2
* fields "login" and "password".
*
* @param requestBody JSON string of ZeppelinHub payload.
* @return Account object with login, name (if set in ZeppelinHub), and mail.
* @throws AuthenticationException if fail to login.
*/
protected User authenticateUser(String requestBody) {
PutMethod put = new PutMethod(Joiner.on("/").join(zeppelinhubUrl, USER_LOGIN_API_ENDPOINT));
String responseBody = StringUtils.EMPTY;
String userSession = StringUtils.EMPTY;
try {
put.setRequestEntity(new StringRequestEntity(requestBody, JSON_CONTENT_TYPE, UTF_8_ENCODING));
int statusCode = httpClient.executeMethod(put);
if (statusCode != HttpStatus.SC_OK) {
LOG.error("Cannot login user, HTTP status code is {} instead on 200 (OK)", statusCode);
put.releaseConnection();
throw new AuthenticationException("Couldnt login to ZeppelinHub. "
+ "Login or password incorrect");
}
responseBody = put.getResponseBodyAsString();
userSession = put.getResponseHeader(USER_SESSION_HEADER).getValue();
put.releaseConnection();
} catch (IOException e) {
LOG.error("Cannot login user", e);
throw new AuthenticationException(e.getMessage());
}
User account = null;
try {
account = gson.fromJson(responseBody, User.class);
} catch (JsonParseException e) {
LOG.error("Cannot deserialize ZeppelinHub response to User instance", e);
throw new AuthenticationException("Cannot login to ZeppelinHub");
}
onLoginSuccess(account.login, userSession);
return account;
}
/**
* Create a JSON String that represent login payload.</p>
* Payload will look like:
* <code>
* {
* 'login': 'userLogin',
* 'password': 'userpassword'
* }
* </code>
* @param login
* @param pwd
* @return
*/
protected String createLoginPayload(String login, char[] pwd) {
StringBuilder sb = new StringBuilder("{\"login\":\"");
return sb.append(login).append("\", \"password\":\"").append(pwd).append("\"}").toString();
}
/**
* Perform a Simple URL check by using <code>URI(url).toURL()</code>.
* If the url is not valid, the try-catch condition will catch the exceptions and return false,
* otherwise true will be returned.
*
* @param url
* @return
*/
protected boolean isZeppelinHubUrlValid(String url) {
boolean valid;
try {
new URI(url).toURL();
valid = true;
} catch (URISyntaxException | MalformedURLException e) {
LOG.error("Zeppelinhub url is not valid, default ZeppelinHub url will be used.", e);
valid = false;
}
return valid;
}
/**
* Helper class that will be use to deserialize ZeppelinHub response.
*/
protected class User {
public String login;
public String email;
public String name;
}
public void onLoginSuccess(String username, String session) {
UserSessionContainer.instance.setSession(username, session);
/* TODO(xxx): add proper roles */
HashSet<String> userAndRoles = new HashSet<String>();
userAndRoles.add(username);
ZeppelinhubUtils.userLoginRoutine(username);
}
@Override
public void onLogout(PrincipalCollection principals) {
ZeppelinhubUtils.userLogoutRoutine((String) principals.getPrimaryPrincipal());
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/realm/PamRealm.java | smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/realm/PamRealm.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.realm;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.DefaultHashService;
import org.apache.shiro.crypto.hash.Hash;
import org.apache.shiro.crypto.hash.HashRequest;
import org.apache.shiro.crypto.hash.HashService;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.jvnet.libpam.PAM;
import org.jvnet.libpam.PAMException;
import org.jvnet.libpam.UnixUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* An {@code AuthorizingRealm} base on libpam4j.
*/
public class PamRealm extends AuthorizingRealm {
private static final Logger LOG = LoggerFactory.getLogger(ZeppelinHubRealm.class);
private String service;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
Set<String> roles = new LinkedHashSet<>();
UserPrincipal user = principals.oneByType(UserPrincipal.class);
if (user != null){
roles.addAll(user.getUnixUser().getGroups());
}
return new SimpleAuthorizationInfo(roles);
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
throws AuthenticationException {
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
UnixUser user;
try {
user = (new PAM(this.getService()))
.authenticate(userToken.getUsername(), new String(userToken.getPassword()));
} catch (PAMException e) {
throw new AuthenticationException("Authentication failed for PAM.", e);
}
return new SimpleAuthenticationInfo(
new UserPrincipal(user),
userToken.getCredentials(),
getName());
}
public String getService() {
return service;
}
public void setService(String service) {
this.service = service;
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/realm/LdapRealm.java | smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/realm/LdapRealm.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF 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 org.apache.zeppelin.realm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.DefaultHashService;
import org.apache.shiro.crypto.hash.Hash;
import org.apache.shiro.crypto.hash.HashRequest;
import org.apache.shiro.crypto.hash.HashService;
import org.apache.shiro.realm.ldap.JndiLdapRealm;
import org.apache.shiro.realm.ldap.LdapContextFactory;
import org.apache.shiro.realm.ldap.LdapUtils;
import org.apache.shiro.subject.MutablePrincipalCollection;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.PartialResultException;
import javax.naming.SizeLimitExceededException;
import javax.naming.directory.Attribute;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.Control;
import javax.naming.ldap.LdapContext;
import javax.naming.ldap.LdapName;
import javax.naming.ldap.PagedResultsControl;
/**
* Implementation of {@link org.apache.shiro.realm.ldap.JndiLdapRealm} that also
* returns each user's groups. This implementation is heavily based on
* org.apache.isis.security.shiro.IsisLdapRealm.
*
* <p>This implementation saves looked up ldap groups in Shiro Session to make them
* easy to be looked up outside of this object
*
* <p>Sample config for <tt>shiro.ini</tt>:
*
* <p>[main]
* ldapRealm = org.apache.zeppelin.realm.LdapRealm
* ldapRealm.contextFactory.url = ldap://localhost:33389
* ldapRealm.contextFactory.authenticationMechanism = simple
* ldapRealm.contextFactory.systemUsername = uid=guest,ou=people,dc=hadoop,dc=
* apache,dc=org
* ldapRealm.contextFactory.systemPassword = S{ALIAS=ldcSystemPassword}
* ldapRealm.userDnTemplate = uid={0},ou=people,dc=hadoop,dc=apache,dc=org
* # Ability to set ldap paging Size if needed default is 100
* ldapRealm.pagingSize = 200
* ldapRealm.authorizationEnabled = true
* ldapRealm.searchBase = dc=hadoop,dc=apache,dc=org
* ldapRealm.userSearchBase = dc=hadoop,dc=apache,dc=org
* ldapRealm.groupSearchBase = ou=groups,dc=hadoop,dc=apache,dc=org
* ldapRealm.userObjectClass = person
* ldapRealm.groupObjectClass = groupofnames
* # Allow userSearchAttribute to be customized
* ldapRealm.userSearchAttributeName = sAMAccountName
* ldapRealm.memberAttribute = member
* # force usernames returned from ldap to lowercase useful for AD
* ldapRealm.userLowerCase = true
* # ability set searchScopes subtree (default), one, base
* ldapRealm.userSearchScope = subtree;
* ldapRealm.groupSearchScope = subtree;
* ldapRealm.memberAttributeValueTemplate=cn={0},ou=people,dc=hadoop,dc=apache,
* dc=org
* # enable support for nested groups using the LDAP_MATCHING_RULE_IN_CHAIN operator
* ldapRealm.groupSearchEnableMatchingRuleInChain = true
*
* <p># optional mapping from physical groups to logical application roles
* ldapRealm.rolesByGroup = \ LDN_USERS: user_role,\ NYK_USERS: user_role,\
* HKG_USERS: user_role,\ GLOBAL_ADMIN: admin_role,\ DEMOS: self-install_role
*
* <p># optional list of roles that are allowed to authenticate
* ldapRealm.allowedRolesForAuthentication = admin_role,user_role
*
* <p>ldapRealm.permissionsByRole=\ user_role = *:ToDoItemsJdo:*:*,\
* *:ToDoItem:*:*; \ self-install_role = *:ToDoItemsFixturesService:install:* ;
* \ admin_role = *
*
* <p>[urls]
* **=authcBasic
*
* <p>securityManager.realms = $ldapRealm
*
*/
public class LdapRealm extends JndiLdapRealm {
private static final SearchControls SUBTREE_SCOPE = new SearchControls();
private static final SearchControls ONELEVEL_SCOPE = new SearchControls();
private static final SearchControls OBJECT_SCOPE = new SearchControls();
private static final String SUBJECT_USER_ROLES = "subject.userRoles";
private static final String SUBJECT_USER_GROUPS = "subject.userGroups";
private static final String MEMBER_URL = "memberUrl";
private static final String POSIX_GROUP = "posixGroup";
// LDAP Operator '1.2.840.113556.1.4.1941'
// walks the chain of ancestry in objects all the way to the root until it finds a match
// see https://msdn.microsoft.com/en-us/library/aa746475(v=vs.85).aspx
private static final String MATCHING_RULE_IN_CHAIN_FORMAT =
"(&(objectClass=%s)(%s:1.2.840.113556.1.4.1941:=%s))";
private static Pattern TEMPLATE_PATTERN = Pattern.compile("\\{(\\d+?)\\}");
private static String DEFAULT_PRINCIPAL_REGEX = "(.*)";
private static final String MEMBER_SUBSTITUTION_TOKEN = "{0}";
private static final String HASHING_ALGORITHM = "SHA-1";
private static final Logger log = LoggerFactory.getLogger(LdapRealm.class);
static {
SUBTREE_SCOPE.setSearchScope(SearchControls.SUBTREE_SCOPE);
ONELEVEL_SCOPE.setSearchScope(SearchControls.ONELEVEL_SCOPE);
OBJECT_SCOPE.setSearchScope(SearchControls.OBJECT_SCOPE);
}
private String searchBase;
private String userSearchBase;
private int pagingSize = 100;
private boolean userLowerCase;
private String principalRegex = DEFAULT_PRINCIPAL_REGEX;
private Pattern principalPattern = Pattern.compile(DEFAULT_PRINCIPAL_REGEX);
private String userDnTemplate = "{0}";
private String userSearchFilter = null;
private String userSearchAttributeTemplate = "{0}";
private String userSearchScope = "subtree";
private String groupSearchScope = "subtree";
private boolean groupSearchEnableMatchingRuleInChain;
private String groupSearchBase;
private String groupObjectClass = "groupOfNames";
// typical value: member, uniqueMember, memberUrl
private String memberAttribute = "member";
private String groupIdAttribute = "cn";
private String memberAttributeValuePrefix = "uid={0}";
private String memberAttributeValueSuffix = "";
private final Map<String, String> rolesByGroup = new LinkedHashMap<String, String>();
private final List<String> allowedRolesForAuthentication = new ArrayList<String>();
private final Map<String, List<String>> permissionsByRole =
new LinkedHashMap<String, List<String>>();
private boolean authorizationEnabled;
private String userSearchAttributeName;
private String userObjectClass = "person";
private HashService hashService = new DefaultHashService();
public LdapRealm() {
HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher(HASHING_ALGORITHM);
setCredentialsMatcher(credentialsMatcher);
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
throws org.apache.shiro.authc.AuthenticationException {
try {
return super.doGetAuthenticationInfo(token);
} catch (org.apache.shiro.authc.AuthenticationException ae) {
throw ae;
}
}
/**
* This overrides the implementation of queryForAuthenticationInfo inside JndiLdapRealm.
* In addition to calling the super method for authentication it also tries to validate
* if this user has atleast one of the allowed roles for authentication. In case the property
* allowedRolesForAuthentication is empty this check always returns true.
*
* @param token the submitted authentication token that triggered the authentication attempt.
* @param ldapContextFactory factory used to retrieve LDAP connections.
* @return AuthenticationInfo instance representing the authenticated user's information.
* @throws NamingException if any LDAP errors occur.
*/
@Override
protected AuthenticationInfo queryForAuthenticationInfo(AuthenticationToken token,
LdapContextFactory ldapContextFactory)
throws NamingException {
AuthenticationInfo info = super.queryForAuthenticationInfo(token, ldapContextFactory);
// Credentials were verified. Verify that the principal has all allowedRulesForAuthentication
if (!hasAllowedAuthenticationRules(info.getPrincipals(), ldapContextFactory)) {
throw new NamingException("Principal does not have any of the allowedRolesForAuthentication");
}
return info;
}
/**
* Get groups from LDAP.
*
* @param principals
* the principals of the Subject whose AuthenticationInfo should
* be queried from the LDAP server.
* @param ldapContextFactory
* factory used to retrieve LDAP connections.
* @return an {@link AuthorizationInfo} instance containing information
* retrieved from the LDAP server.
* @throws NamingException
* if any LDAP errors occur during the search.
*/
@Override
protected AuthorizationInfo queryForAuthorizationInfo(final PrincipalCollection principals,
final LdapContextFactory ldapContextFactory) throws NamingException {
if (!isAuthorizationEnabled()) {
return null;
}
final Set<String> roleNames = getRoles(principals, ldapContextFactory);
if (log.isDebugEnabled()) {
log.debug("RolesNames Authorization: " + roleNames);
}
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo(roleNames);
Set<String> stringPermissions = permsFor(roleNames);
simpleAuthorizationInfo.setStringPermissions(stringPermissions);
return simpleAuthorizationInfo;
}
private boolean hasAllowedAuthenticationRules(PrincipalCollection principals,
final LdapContextFactory ldapContextFactory)
throws NamingException {
boolean allowed = allowedRolesForAuthentication.isEmpty();
if (!allowed) {
Set<String> roles = getRoles(principals, ldapContextFactory);
for (String allowedRole: allowedRolesForAuthentication) {
if (roles.contains(allowedRole)) {
log.debug("Allowed role for user [" + allowedRole + "] found.");
allowed = true;
break;
}
}
}
return allowed;
}
private Set<String> getRoles(PrincipalCollection principals,
final LdapContextFactory ldapContextFactory)
throws NamingException {
final String username = (String) getAvailablePrincipal(principals);
LdapContext systemLdapCtx = null;
try {
systemLdapCtx = ldapContextFactory.getSystemLdapContext();
return rolesFor(principals, username, systemLdapCtx, ldapContextFactory);
} catch (AuthenticationException ae) {
ae.printStackTrace();
return Collections.emptySet();
} finally {
LdapUtils.closeContext(systemLdapCtx);
}
}
private Set<String> rolesFor(PrincipalCollection principals,
String userNameIn, final LdapContext ldapCtx,
final LdapContextFactory ldapContextFactory) throws NamingException {
final Set<String> roleNames = new HashSet<>();
final Set<String> groupNames = new HashSet<>();
final String userName;
if (getUserLowerCase()) {
log.debug("userLowerCase true");
userName = userNameIn.toLowerCase();
} else {
userName = userNameIn;
}
String userDn;
if (userSearchAttributeName == null || userSearchAttributeName.isEmpty()) {
// memberAttributeValuePrefix and memberAttributeValueSuffix
// were computed from memberAttributeValueTemplate
userDn = memberAttributeValuePrefix + userName + memberAttributeValueSuffix;
} else {
userDn = getUserDn(userName);
}
// Activate paged results
int pageSize = getPagingSize();
if (log.isDebugEnabled()) {
log.debug("Ldap PagingSize: " + pageSize);
}
int numResults = 0;
byte[] cookie = null;
try {
ldapCtx.addToEnvironment(Context.REFERRAL, "ignore");
ldapCtx.setRequestControls(new Control[]{new PagedResultsControl(pageSize,
Control.NONCRITICAL)});
do {
// ldapsearch -h localhost -p 33389 -D
// uid=guest,ou=people,dc=hadoop,dc=apache,dc=org -w guest-password
// -b dc=hadoop,dc=apache,dc=org -s sub '(objectclass=*)'
NamingEnumeration<SearchResult> searchResultEnum = null;
SearchControls searchControls = getGroupSearchControls();
try {
if (groupSearchEnableMatchingRuleInChain) {
searchResultEnum = ldapCtx.search(
getGroupSearchBase(),
String.format(
MATCHING_RULE_IN_CHAIN_FORMAT, groupObjectClass, memberAttribute, userDn),
searchControls);
while (searchResultEnum != null && searchResultEnum.hasMore()) {
// searchResults contains all the groups in search scope
numResults++;
final SearchResult group = searchResultEnum.next();
Attribute attribute = group.getAttributes().get(getGroupIdAttribute());
String groupName = attribute.get().toString();
String roleName = roleNameFor(groupName);
if (roleName != null) {
roleNames.add(roleName);
} else {
roleNames.add(groupName);
}
}
} else {
searchResultEnum = ldapCtx.search(
getGroupSearchBase(),
"objectClass=" + groupObjectClass,
searchControls);
while (searchResultEnum != null && searchResultEnum.hasMore()) {
// searchResults contains all the groups in search scope
numResults++;
final SearchResult group = searchResultEnum.next();
addRoleIfMember(userDn, group, roleNames, groupNames, ldapContextFactory);
}
}
} catch (PartialResultException e) {
log.debug("Ignoring PartitalResultException");
} finally {
if (searchResultEnum != null) {
searchResultEnum.close();
}
}
// Re-activate paged results
ldapCtx.setRequestControls(new Control[]{new PagedResultsControl(pageSize,
cookie, Control.CRITICAL)});
} while (cookie != null);
} catch (SizeLimitExceededException e) {
log.info("Only retrieved first " + numResults +
" groups due to SizeLimitExceededException.");
} catch (IOException e) {
log.error("Unabled to setup paged results");
}
// save role names and group names in session so that they can be
// easily looked up outside of this object
SecurityUtils.getSubject().getSession().setAttribute(SUBJECT_USER_ROLES, roleNames);
SecurityUtils.getSubject().getSession().setAttribute(SUBJECT_USER_GROUPS, groupNames);
if (!groupNames.isEmpty() && (principals instanceof MutablePrincipalCollection)) {
((MutablePrincipalCollection) principals).addAll(groupNames, getName());
}
if (log.isDebugEnabled()) {
log.debug("User RoleNames: " + userName + "::" + roleNames);
}
return roleNames;
}
private void addRoleIfMember(final String userDn, final SearchResult group,
final Set<String> roleNames, final Set<String> groupNames,
final LdapContextFactory ldapContextFactory) throws NamingException {
NamingEnumeration<? extends Attribute> attributeEnum = null;
NamingEnumeration<?> ne = null;
try {
LdapName userLdapDn = new LdapName(userDn);
Attribute attribute = group.getAttributes().get(getGroupIdAttribute());
String groupName = attribute.get().toString();
attributeEnum = group.getAttributes().getAll();
while (attributeEnum.hasMore()) {
final Attribute attr = attributeEnum.next();
if (!memberAttribute.equalsIgnoreCase(attr.getID())) {
continue;
}
ne = attr.getAll();
while (ne.hasMore()) {
String attrValue = ne.next().toString();
if (memberAttribute.equalsIgnoreCase(MEMBER_URL)) {
boolean dynamicGroupMember = isUserMemberOfDynamicGroup(userLdapDn, attrValue,
ldapContextFactory);
if (dynamicGroupMember) {
groupNames.add(groupName);
String roleName = roleNameFor(groupName);
if (roleName != null) {
roleNames.add(roleName);
} else {
roleNames.add(groupName);
}
}
} else {
if (groupObjectClass.equalsIgnoreCase(POSIX_GROUP)) {
attrValue = memberAttributeValuePrefix + attrValue + memberAttributeValueSuffix;
}
if (userLdapDn.equals(new LdapName(attrValue))) {
groupNames.add(groupName);
String roleName = roleNameFor(groupName);
if (roleName != null) {
roleNames.add(roleName);
} else {
roleNames.add(groupName);
}
break;
}
}
}
}
} finally {
try {
if (attributeEnum != null) {
attributeEnum.close();
}
} finally {
if (ne != null) {
ne.close();
}
}
}
}
public Map<String, String> getListRoles() {
Map<String, String> groupToRoles = getRolesByGroup();
Map<String, String> roles = new HashMap<>();
for (Map.Entry<String, String> entry : groupToRoles.entrySet()){
roles.put(entry.getValue(), entry.getKey());
}
return roles;
}
private String roleNameFor(String groupName) {
return !rolesByGroup.isEmpty() ? rolesByGroup.get(groupName) : groupName;
}
private Set<String> permsFor(Set<String> roleNames) {
Set<String> perms = new LinkedHashSet<String>(); // preserve order
for (String role : roleNames) {
List<String> permsForRole = permissionsByRole.get(role);
if (log.isDebugEnabled()) {
log.debug("PermsForRole: " + role);
log.debug("PermByRole: " + permsForRole);
}
if (permsForRole != null) {
perms.addAll(permsForRole);
}
}
return perms;
}
public String getSearchBase() {
return searchBase;
}
public void setSearchBase(String searchBase) {
this.searchBase = searchBase;
}
public String getUserSearchBase() {
return (userSearchBase != null && !userSearchBase.isEmpty()) ? userSearchBase : searchBase;
}
public void setUserSearchBase(String userSearchBase) {
this.userSearchBase = userSearchBase;
}
public int getPagingSize() {
return pagingSize;
}
public void setPagingSize(int pagingSize) {
this.pagingSize = pagingSize;
}
public String getGroupSearchBase() {
return (groupSearchBase != null && !groupSearchBase.isEmpty()) ? groupSearchBase : searchBase;
}
public void setGroupSearchBase(String groupSearchBase) {
this.groupSearchBase = groupSearchBase;
}
public String getGroupObjectClass() {
return groupObjectClass;
}
public void setGroupObjectClass(String groupObjectClassAttribute) {
this.groupObjectClass = groupObjectClassAttribute;
}
public String getMemberAttribute() {
return memberAttribute;
}
public void setMemberAttribute(String memberAttribute) {
this.memberAttribute = memberAttribute;
}
public String getGroupIdAttribute() {
return groupIdAttribute;
}
public void setGroupIdAttribute(String groupIdAttribute) {
this.groupIdAttribute = groupIdAttribute;
}
/**
* Set Member Attribute Template for LDAP.
*
* @param template
* DN template to be used to query ldap.
* @throws IllegalArgumentException
* if template is empty or null.
*/
public void setMemberAttributeValueTemplate(String template) {
if (!StringUtils.hasText(template)) {
String msg = "User DN template cannot be null or empty.";
throw new IllegalArgumentException(msg);
}
int index = template.indexOf(MEMBER_SUBSTITUTION_TOKEN);
if (index < 0) {
String msg = "Member attribute value template must contain the '" + MEMBER_SUBSTITUTION_TOKEN
+ "' replacement token to understand how to " + "parse the group members.";
throw new IllegalArgumentException(msg);
}
String prefix = template.substring(0, index);
String suffix = template.substring(prefix.length() + MEMBER_SUBSTITUTION_TOKEN.length());
this.memberAttributeValuePrefix = prefix;
this.memberAttributeValueSuffix = suffix;
}
public void setAllowedRolesForAuthentication(List<String> allowedRolesForAuthencation) {
this.allowedRolesForAuthentication.addAll(allowedRolesForAuthencation);
}
public void setRolesByGroup(Map<String, String> rolesByGroup) {
this.rolesByGroup.putAll(rolesByGroup);
}
public Map<String, String> getRolesByGroup() {
return rolesByGroup;
}
public void setPermissionsByRole(String permissionsByRoleStr) {
permissionsByRole.putAll(parsePermissionByRoleString(permissionsByRoleStr));
}
public Map<String, List<String>> getPermissionsByRole() {
return permissionsByRole;
}
public boolean isAuthorizationEnabled() {
return authorizationEnabled;
}
public void setAuthorizationEnabled(boolean authorizationEnabled) {
this.authorizationEnabled = authorizationEnabled;
}
public String getUserSearchAttributeName() {
return userSearchAttributeName;
}
/**
* Set User Search Attribute Name for LDAP.
*
* @param userSearchAttributeName
* userAttribute to search ldap.
*/
public void setUserSearchAttributeName(String userSearchAttributeName) {
if (userSearchAttributeName != null) {
userSearchAttributeName = userSearchAttributeName.trim();
}
this.userSearchAttributeName = userSearchAttributeName;
}
public String getUserObjectClass() {
return userObjectClass;
}
public void setUserObjectClass(String userObjectClass) {
this.userObjectClass = userObjectClass;
}
private Map<String, List<String>> parsePermissionByRoleString(String permissionsByRoleStr) {
Map<String, List<String>> perms = new HashMap<String, List<String>>();
// split by semicolon ; then by eq = then by comma ,
StringTokenizer stSem = new StringTokenizer(permissionsByRoleStr, ";");
while (stSem.hasMoreTokens()) {
String roleAndPerm = stSem.nextToken();
StringTokenizer stEq = new StringTokenizer(roleAndPerm, "=");
if (stEq.countTokens() != 2) {
continue;
}
String role = stEq.nextToken().trim();
String perm = stEq.nextToken().trim();
StringTokenizer stCom = new StringTokenizer(perm, ",");
List<String> permList = new ArrayList<String>();
while (stCom.hasMoreTokens()) {
permList.add(stCom.nextToken().trim());
}
perms.put(role, permList);
}
return perms;
}
boolean isUserMemberOfDynamicGroup(LdapName userLdapDn, String memberUrl,
final LdapContextFactory ldapContextFactory) throws NamingException {
// ldap://host:port/dn?attributes?scope?filter?extensions
if (memberUrl == null) {
return false;
}
String[] tokens = memberUrl.split("\\?");
if (tokens.length < 4) {
return false;
}
String searchBaseString = tokens[0].substring(tokens[0].lastIndexOf("/") + 1);
String searchScope = tokens[2];
String searchFilter = tokens[3];
LdapName searchBaseDn = new LdapName(searchBaseString);
// do scope test
if (searchScope.equalsIgnoreCase("base")) {
log.debug("DynamicGroup SearchScope base");
return false;
}
if (!userLdapDn.toString().endsWith(searchBaseDn.toString())) {
return false;
}
if (searchScope.equalsIgnoreCase("one") && (userLdapDn.size() != searchBaseDn.size() - 1)) {
log.debug("DynamicGroup SearchScope one");
return false;
}
// search for the filter, substituting base with userDn
// search for base_dn=userDn, scope=base, filter=filter
LdapContext systemLdapCtx = null;
systemLdapCtx = ldapContextFactory.getSystemLdapContext();
boolean member = false;
NamingEnumeration<SearchResult> searchResultEnum = null;
try {
searchResultEnum = systemLdapCtx.search(userLdapDn, searchFilter,
searchScope.equalsIgnoreCase("sub") ? SUBTREE_SCOPE : ONELEVEL_SCOPE);
if (searchResultEnum.hasMore()) {
return true;
}
} finally {
try {
if (searchResultEnum != null) {
searchResultEnum.close();
}
} finally {
LdapUtils.closeContext(systemLdapCtx);
}
}
return member;
}
public String getPrincipalRegex() {
return principalRegex;
}
/**
* Set Regex for Principal LDAP.
*
* @param regex
* regex to use to search for principal in shiro.
*/
public void setPrincipalRegex(String regex) {
if (regex == null || regex.trim().isEmpty()) {
principalPattern = Pattern.compile(DEFAULT_PRINCIPAL_REGEX);
principalRegex = DEFAULT_PRINCIPAL_REGEX;
} else {
regex = regex.trim();
Pattern pattern = Pattern.compile(regex);
principalPattern = pattern;
principalRegex = regex;
}
}
public String getUserSearchAttributeTemplate() {
return userSearchAttributeTemplate;
}
public void setUserSearchAttributeTemplate(final String template) {
this.userSearchAttributeTemplate = (template == null ? null : template.trim());
}
public String getUserSearchFilter() {
return userSearchFilter;
}
public void setUserSearchFilter(final String filter) {
this.userSearchFilter = (filter == null ? null : filter.trim());
}
public boolean getUserLowerCase() {
return userLowerCase;
}
public void setUserLowerCase(boolean userLowerCase) {
this.userLowerCase = userLowerCase;
}
public String getUserSearchScope() {
return userSearchScope;
}
public void setUserSearchScope(final String scope) {
this.userSearchScope = (scope == null ? null : scope.trim().toLowerCase());
}
public String getGroupSearchScope() {
return groupSearchScope;
}
public void setGroupSearchScope(final String scope) {
this.groupSearchScope = (scope == null ? null : scope.trim().toLowerCase());
}
public boolean isGroupSearchEnableMatchingRuleInChain() {
return groupSearchEnableMatchingRuleInChain;
}
public void setGroupSearchEnableMatchingRuleInChain(
boolean groupSearchEnableMatchingRuleInChain) {
this.groupSearchEnableMatchingRuleInChain = groupSearchEnableMatchingRuleInChain;
}
private SearchControls getUserSearchControls() {
SearchControls searchControls = SUBTREE_SCOPE;
if ("onelevel".equalsIgnoreCase(userSearchScope)) {
searchControls = ONELEVEL_SCOPE;
} else if ("object".equalsIgnoreCase(userSearchScope)) {
searchControls = OBJECT_SCOPE;
}
return searchControls;
}
private SearchControls getGroupSearchControls() {
SearchControls searchControls = SUBTREE_SCOPE;
if ("onelevel".equalsIgnoreCase(groupSearchScope)) {
searchControls = ONELEVEL_SCOPE;
} else if ("object".equalsIgnoreCase(groupSearchScope)) {
searchControls = OBJECT_SCOPE;
}
return searchControls;
}
@Override
public void setUserDnTemplate(final String template) throws IllegalArgumentException {
userDnTemplate = template;
}
private Matcher matchPrincipal(final String principal) {
Matcher matchedPrincipal = principalPattern.matcher(principal);
if (!matchedPrincipal.matches()) {
throw new IllegalArgumentException("Principal "
+ principal + " does not match " + principalRegex);
}
return matchedPrincipal;
}
/**
* Returns the LDAP User Distinguished Name (DN) to use when acquiring an
* {@link javax.naming.ldap.LdapContext LdapContext} from the
* {@link LdapContextFactory}.
* <p/>
* If the the {@link #getUserDnTemplate() userDnTemplate} property has been
* set, this implementation will construct the User DN by substituting the
* specified {@code principal} into the configured template. If the
* {@link #getUserDnTemplate() userDnTemplate} has not been set, the method
* argument will be returned directly (indicating that the submitted
* authentication token principal <em>is</em> the User DN).
*
* @param principal
* the principal to substitute into the configured
* {@link #getUserDnTemplate() userDnTemplate}.
* @return the constructed User DN to use at runtime when acquiring an
* {@link javax.naming.ldap.LdapContext}.
* @throws IllegalArgumentException
* if the method argument is null or empty
* @throws IllegalStateException
* if the {@link #getUserDnTemplate userDnTemplate} has not been
* set.
* @see LdapContextFactory#getLdapContext(Object, Object)
*/
@Override
protected String getUserDn(final String principal) throws IllegalArgumentException,
IllegalStateException {
String userDn;
Matcher matchedPrincipal = matchPrincipal(principal);
String userSearchBase = getUserSearchBase();
String userSearchAttributeName = getUserSearchAttributeName();
// If not searching use the userDnTemplate and return.
if ((userSearchBase == null || userSearchBase.isEmpty()) || (userSearchAttributeName == null
&& userSearchFilter == null && !"object".equalsIgnoreCase(userSearchScope))) {
userDn = expandTemplate(userDnTemplate, matchedPrincipal);
if (log.isDebugEnabled()) {
log.debug("LDAP UserDN and Principal: " + userDn + "," + principal);
}
return userDn;
}
// Create the searchBase and searchFilter from config.
String searchBase = expandTemplate(getUserSearchBase(), matchedPrincipal);
String searchFilter = null;
if (userSearchFilter == null) {
if (userSearchAttributeName == null) {
searchFilter = String.format("(objectclass=%1$s)", getUserObjectClass());
} else {
searchFilter = String.format("(&(objectclass=%1$s)(%2$s=%3$s))", getUserObjectClass(),
userSearchAttributeName, expandTemplate(getUserSearchAttributeTemplate(),
matchedPrincipal));
}
} else {
searchFilter = expandTemplate(userSearchFilter, matchedPrincipal);
}
SearchControls searchControls = getUserSearchControls();
// Search for userDn and return.
LdapContext systemLdapCtx = null;
NamingEnumeration<SearchResult> searchResultEnum = null;
try {
systemLdapCtx = getContextFactory().getSystemLdapContext();
if (log.isDebugEnabled()) {
log.debug("SearchBase,SearchFilter,UserSearchScope: " + searchBase
+ "," + searchFilter + "," + userSearchScope);
}
searchResultEnum = systemLdapCtx.search(searchBase, searchFilter, searchControls);
// SearchResults contains all the entries in search scope
if (searchResultEnum.hasMore()) {
SearchResult searchResult = searchResultEnum.next();
userDn = searchResult.getNameInNamespace();
if (log.isDebugEnabled()) {
log.debug("UserDN Returned,Principal: " + userDn + "," + principal);
}
return userDn;
} else {
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | true |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/realm/LdapGroupRealm.java | smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/realm/LdapGroupRealm.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.realm;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.ldap.JndiLdapRealm;
import org.apache.shiro.realm.ldap.LdapContextFactory;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.LdapContext;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* Created for org.apache.zeppelin.server on 09/06/16.
*/
public class LdapGroupRealm extends JndiLdapRealm {
private static final Logger LOG = LoggerFactory.getLogger(LdapGroupRealm.class);
public AuthorizationInfo queryForAuthorizationInfo(
PrincipalCollection principals,
LdapContextFactory ldapContextFactory) throws NamingException {
String username = (String) getAvailablePrincipal(principals);
LdapContext ldapContext = ldapContextFactory.getSystemLdapContext();
Set<String> roleNames = getRoleNamesForUser(username, ldapContext, getUserDnTemplate());
return new SimpleAuthorizationInfo(roleNames);
}
public Set<String> getRoleNamesForUser(String username,
LdapContext ldapContext,
String userDnTemplate) throws NamingException {
try {
Set<String> roleNames = new LinkedHashSet<>();
SearchControls searchCtls = new SearchControls();
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String searchFilter = "(&(objectClass=groupOfNames)(member=" + userDnTemplate + "))";
Object[] searchArguments = new Object[]{username};
NamingEnumeration<?> answer = ldapContext.search(
String.valueOf(ldapContext.getEnvironment().get("ldap.searchBase")),
searchFilter,
searchArguments,
searchCtls);
while (answer.hasMoreElements()) {
SearchResult sr = (SearchResult) answer.next();
Attributes attrs = sr.getAttributes();
if (attrs != null) {
NamingEnumeration<?> ae = attrs.getAll();
while (ae.hasMore()) {
Attribute attr = (Attribute) ae.next();
if (attr.getID().equals("cn")) {
roleNames.add((String) attr.get());
}
}
}
}
return roleNames;
} catch (Exception e) {
LOG.error("Error", e);
}
return new HashSet<>();
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/server/CorsFilter.java | smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/server/CorsFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.server;
import org.apache.zeppelin.conf.ZeppelinConfiguration;
import org.apache.zeppelin.utils.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.URISyntaxException;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Cors filter
*
*/
public class CorsFilter implements Filter {
private static final Logger LOGGER = LoggerFactory.getLogger(CorsFilter.class);
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
String sourceHost = ((HttpServletRequest) request).getHeader("Origin");
String origin = "";
try {
if (SecurityUtils.isValidOrigin(sourceHost, ZeppelinConfiguration.create())) {
origin = sourceHost;
}
} catch (URISyntaxException e) {
LOGGER.error("Exception in WebDriverManager while getWebDriver ", e);
}
if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) {
HttpServletResponse resp = ((HttpServletResponse) response);
addCorsHeaders(resp, origin);
return;
}
if (response instanceof HttpServletResponse) {
HttpServletResponse alteredResponse = ((HttpServletResponse) response);
addCorsHeaders(alteredResponse, origin);
}
filterChain.doFilter(request, response);
}
private void addCorsHeaders(HttpServletResponse response, String origin) {
response.addHeader("Access-Control-Allow-Origin", origin);
response.addHeader("Access-Control-Allow-Credentials", "true");
response.addHeader("Access-Control-Allow-Headers", "authorization,Content-Type");
response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, HEAD, DELETE");
DateFormat fullDateFormatEN =
DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, new Locale("EN", "en"));
response.addHeader("Date", fullDateFormatEN.format(new Date()));
}
@Override
public void destroy() {}
@Override
public void init(FilterConfig filterConfig) throws ServletException {}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/server/SmartZeppelinServer.java | smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/server/SmartZeppelinServer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.server;
import com.sun.jersey.api.core.ApplicationAdapter;
import com.sun.jersey.api.core.ResourceConfig;
import com.sun.jersey.spi.container.servlet.ServletContainer;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.web.env.EnvironmentLoaderListener;
import org.apache.shiro.web.servlet.ShiroFilter;
import org.apache.zeppelin.conf.ZeppelinConfiguration;
import org.apache.zeppelin.conf.ZeppelinConfiguration.ConfVars;
import org.apache.zeppelin.dep.DependencyResolver;
import org.apache.zeppelin.helium.Helium;
import org.apache.zeppelin.helium.HeliumApplicationFactory;
import org.apache.zeppelin.helium.HeliumVisualizationFactory;
import org.apache.zeppelin.interpreter.InterpreterFactory;
import org.apache.zeppelin.interpreter.InterpreterOption;
import org.apache.zeppelin.interpreter.InterpreterOutput;
import org.apache.zeppelin.interpreter.InterpreterSettingManager;
import org.apache.zeppelin.notebook.Notebook;
import org.apache.zeppelin.notebook.NotebookAuthorization;
import org.apache.zeppelin.rest.CredentialRestApi;
import org.apache.zeppelin.rest.HeliumRestApi;
import org.apache.zeppelin.rest.LoginRestApi;
import org.apache.zeppelin.rest.SecurityRestApi;
import org.apache.zeppelin.rest.ZeppelinRestApi;
import org.apache.zeppelin.scheduler.SchedulerFactory;
import org.apache.zeppelin.search.LuceneSearch;
import org.apache.zeppelin.search.SearchService;
import org.apache.zeppelin.user.Credentials;
import org.apache.zeppelin.utils.SecurityUtils;
import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.SecureRequestCustomizer;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.SslConnectionFactory;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.server.session.SessionHandler;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.webapp.WebAppContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smartdata.conf.SmartConf;
import org.smartdata.conf.SmartConfKeys;
import org.smartdata.server.SmartEngine;
import org.smartdata.server.rest.*;
import javax.servlet.DispatcherType;
import javax.ws.rs.core.Application;
import java.io.File;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Set;
/**
* Main class of embedded Zeppelin Server.
*/
public class SmartZeppelinServer {
private static final Logger LOG = LoggerFactory.getLogger(SmartZeppelinServer.class);
private static final String SMART_PATH_SPEC = "/smart/api/v1/*";
private static final String ZEPPELIN_PATH_SPEC = "/api/*";
private static SmartEngine engine;
private SmartConf conf;
public static Notebook notebook;
private ZeppelinConfiguration zconf;
private Server jettyWebServer;
private Helium helium;
private InterpreterSettingManager interpreterSettingManager;
private SchedulerFactory schedulerFactory;
private InterpreterFactory replFactory;
private SearchService noteSearchService;
private NotebookAuthorization notebookAuthorization;
private Credentials credentials;
private DependencyResolver depResolver;
public static SmartEngine getEngine() {
return engine;
}
public SmartZeppelinServer() {}
public SmartZeppelinServer(SmartConf conf, SmartEngine engine) throws Exception {
this.conf = conf;
this.engine = engine;
this.zconf = ZeppelinConfiguration.create();
// set ZEPPELIN_ADDR and ZEPPELIN_PORT
String httpAddr = conf.get(SmartConfKeys.SMART_SERVER_HTTP_ADDRESS_KEY,
SmartConfKeys.SMART_SERVER_HTTP_ADDRESS_DEFAULT);
String[] ipport = httpAddr.split(":");
System.setProperty(ConfVars.ZEPPELIN_ADDR.getVarName(), ipport[0]);
System.setProperty(ConfVars.ZEPPELIN_PORT.getVarName(), ipport[1]);
// set zeppelin log dir
String logDir = conf.get(SmartConfKeys.SMART_LOG_DIR_KEY, SmartConfKeys.SMART_LOG_DIR_DEFAULT);
String zeppelinLogFile = logDir + "/zeppelin.log";
System.setProperty("zeppelin.log.file", zeppelinLogFile);
// set ZEPPELIN_CONF_DIR
System.setProperty(ConfVars.ZEPPELIN_CONF_DIR.getVarName(),
conf.get(SmartConfKeys.SMART_CONF_DIR_KEY, SmartConfKeys.SMART_CONF_DIR_DEFAULT));
// set ZEPPELIN_HOME
if (!isBinaryPackage(zconf)) {
System.setProperty(ConfVars.ZEPPELIN_HOME.getVarName(), "smart-zeppelin/");
}
}
private void init() throws Exception {
this.depResolver = new DependencyResolver(
zconf.getString(ConfVars.ZEPPELIN_INTERPRETER_LOCALREPO));
InterpreterOutput.limit = zconf.getInt(ConfVars.ZEPPELIN_INTERPRETER_OUTPUT_LIMIT);
HeliumApplicationFactory heliumApplicationFactory = new HeliumApplicationFactory();
HeliumVisualizationFactory heliumVisualizationFactory;
if (isBinaryPackage(zconf)) {
/* In binary package, zeppelin-web/src/app/visualization and zeppelin-web/src/app/tabledata
* are copied to lib/node_modules/zeppelin-vis, lib/node_modules/zeppelin-tabledata directory.
* Check zeppelin/zeppelin-distribution/src/assemble/distribution.xml to see how they're
* packaged into binary package.
*/
heliumVisualizationFactory = new HeliumVisualizationFactory(
zconf,
new File(zconf.getRelativeDir(ConfVars.ZEPPELIN_DEP_LOCALREPO)),
new File(zconf.getRelativeDir("lib/node_modules/zeppelin-tabledata")),
new File(zconf.getRelativeDir("lib/node_modules/zeppelin-vis")));
} else {
heliumVisualizationFactory = new HeliumVisualizationFactory(
zconf,
new File(zconf.getRelativeDir(ConfVars.ZEPPELIN_DEP_LOCALREPO)),
//new File(zconf.getRelativeDir("zeppelin-web/src/app/tabledata")),
//new File(zconf.getRelativeDir("zeppelin-web/src/app/visualization")));
new File(zconf.getRelativeDir("smart-zeppelin/zeppelin-web/src/app/tabledata")),
new File(zconf.getRelativeDir("smart-zeppelin/zeppelin-web/src/app/visualization")));
}
this.helium = new Helium(
zconf.getHeliumConfPath(),
zconf.getHeliumDefaultLocalRegistryPath(),
heliumVisualizationFactory,
heliumApplicationFactory);
// create visualization bundle
try {
heliumVisualizationFactory.bundle(helium.getVisualizationPackagesToBundle());
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
this.schedulerFactory = new SchedulerFactory();
this.interpreterSettingManager = new InterpreterSettingManager(zconf, depResolver,
new InterpreterOption(true));
this.noteSearchService = new LuceneSearch();
this.notebookAuthorization = NotebookAuthorization.init(zconf);
this.credentials = new Credentials(zconf.credentialsPersist(), zconf.getCredentialsPath());
}
private boolean isZeppelinWebEnabled() {
return conf.getBoolean(SmartConfKeys.SMART_ENABLE_ZEPPELIN_WEB,
SmartConfKeys.SMART_ENABLE_ZEPPELIN_WEB_DEFAULT);
}
public static void main(String[] args) throws Exception {
SmartZeppelinServer server = new SmartZeppelinServer(new SmartConf(), null);
server.start();
}
public void start() throws Exception {
jettyWebServer = setupJettyServer(zconf);
ContextHandlerCollection contexts = new ContextHandlerCollection();
jettyWebServer.setHandler(contexts);
// Web UI
final WebAppContext webApp = setupWebAppContext(contexts);
init();
// REST api
setupRestApiContextHandler(webApp);
LOG.info("Starting zeppelin server");
try {
jettyWebServer.start(); //Instantiates ZeppelinServer
} catch (Exception e) {
LOG.error("Error while running jettyServer", e);
//System.exit(-1);
}
LOG.info("Done, zeppelin server started");
Runtime.getRuntime().addShutdownHook(new Thread(){
@Override public void run() {
LOG.info("Shutting down Zeppelin Server ... ");
try {
if (jettyWebServer != null) {
jettyWebServer.stop();
}
if (notebook != null) {
notebook.getInterpreterSettingManager().shutdown();
notebook.close();
}
Thread.sleep(1000);
} catch (Exception e) {
LOG.error("Error while stopping servlet container", e);
}
LOG.info("Bye");
}
});
}
public void stop() {
LOG.info("Shutting down Zeppelin Server ... ");
try {
if (jettyWebServer != null) {
jettyWebServer.stop();
}
if (notebook != null) {
notebook.getInterpreterSettingManager().shutdown();
notebook.close();
}
Thread.sleep(1000);
} catch (Exception e) {
LOG.error("Error while stopping servlet container", e);
}
LOG.info("Bye");
}
private static Server setupJettyServer(ZeppelinConfiguration zconf) {
final Server server = new Server();
ServerConnector connector;
if (zconf.useSsl()) {
LOG.debug("Enabling SSL for Zeppelin Server on port " + zconf.getServerSslPort());
HttpConfiguration httpConfig = new HttpConfiguration();
httpConfig.setSecureScheme("https");
httpConfig.setSecurePort(zconf.getServerSslPort());
httpConfig.setOutputBufferSize(32768);
httpConfig.setRequestHeaderSize(8192);
httpConfig.setResponseHeaderSize(8192);
httpConfig.setSendServerVersion(true);
HttpConfiguration httpsConfig = new HttpConfiguration(httpConfig);
SecureRequestCustomizer src = new SecureRequestCustomizer();
// Only with Jetty 9.3.x
// src.setStsMaxAge(2000);
// src.setStsIncludeSubDomains(true);
httpsConfig.addCustomizer(src);
connector = new ServerConnector(
server,
new SslConnectionFactory(getSslContextFactory(zconf),
HttpVersion.HTTP_1_1.asString()),
new HttpConnectionFactory(httpsConfig));
} else {
connector = new ServerConnector(server);
}
// Set some timeout options to make debugging easier.
int timeout = 1000 * 30;
connector.setIdleTimeout(timeout);
connector.setSoLingerTime(-1);
String webUrl = "";
connector.setHost(zconf.getServerAddress());
if (zconf.useSsl()) {
connector.setPort(zconf.getServerSslPort());
webUrl = "https://" + zconf.getServerAddress() + ":" + zconf.getServerSslPort();
} else {
connector.setPort(zconf.getServerPort());
webUrl = "http://" + zconf.getServerAddress() + ":" + zconf.getServerPort();
}
LOG.info("Web address:" + webUrl);
server.addConnector(connector);
return server;
}
private static SslContextFactory getSslContextFactory(ZeppelinConfiguration zconf) {
SslContextFactory sslContextFactory = new SslContextFactory();
// Set keystore
sslContextFactory.setKeyStorePath(zconf.getKeyStorePath());
sslContextFactory.setKeyStoreType(zconf.getKeyStoreType());
sslContextFactory.setKeyStorePassword(zconf.getKeyStorePassword());
sslContextFactory.setKeyManagerPassword(zconf.getKeyManagerPassword());
if (zconf.useClientAuth()) {
sslContextFactory.setNeedClientAuth(zconf.useClientAuth());
// Set truststore
sslContextFactory.setTrustStorePath(zconf.getTrustStorePath());
sslContextFactory.setTrustStoreType(zconf.getTrustStoreType());
sslContextFactory.setTrustStorePassword(zconf.getTrustStorePassword());
}
return sslContextFactory;
}
class SmartRestApp extends Application {
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> classes = new HashSet<>();
return classes;
}
@Override
public Set<Object> getSingletons() {
Set<Object> singletons = new HashSet<>();
SystemRestApi systemApi = new SystemRestApi(engine);
singletons.add(systemApi);
ConfRestApi confApi = new ConfRestApi(engine);
singletons.add(confApi);
ActionRestApi actionApi = new ActionRestApi(engine);
singletons.add(actionApi);
ClusterRestApi clusterApi = new ClusterRestApi(engine);
singletons.add(clusterApi);
CmdletRestApi cmdletApi = new CmdletRestApi(engine);
singletons.add(cmdletApi);
RuleRestApi ruleApi = new RuleRestApi(engine);
singletons.add(ruleApi);
NoteBookRestApi notebookApi = new NoteBookRestApi(engine);
singletons.add(notebookApi);
return singletons;
}
}
class ZeppelinRestApp extends Application {
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> classes = new HashSet<>();
return classes;
}
@Override
public Set<Object> getSingletons() {
Set<Object> singletons = new HashSet<>();
/** Rest-api root endpoint */
ZeppelinRestApi root = new ZeppelinRestApi();
singletons.add(root);
HeliumRestApi heliumApi = new HeliumRestApi(helium, notebook);
singletons.add(heliumApi);
CredentialRestApi credentialApi = new CredentialRestApi(credentials);
singletons.add(credentialApi);
SecurityRestApi securityApi = new SecurityRestApi();
singletons.add(securityApi);
LoginRestApi loginRestApi = new LoginRestApi();
singletons.add(loginRestApi);
return singletons;
}
}
private void setupRestApiContextHandler(WebAppContext webApp) throws Exception {
webApp.setSessionHandler(new SessionHandler());
// There are two sets of rest api: Zeppelin's and SSM's. They have different path.
ResourceConfig smartConfig = new ApplicationAdapter(new SmartRestApp());
ServletHolder smartServletHolder = new ServletHolder(new ServletContainer(smartConfig));
webApp.addServlet(smartServletHolder, SMART_PATH_SPEC);
ResourceConfig zeppelinConfig = new ApplicationAdapter(new ZeppelinRestApp());
ServletHolder zeppelinServletHolder = new ServletHolder(new ServletContainer(zeppelinConfig));
webApp.addServlet(zeppelinServletHolder, ZEPPELIN_PATH_SPEC);
String shiroIniPath = zconf.getShiroPath();
if (!StringUtils.isBlank(shiroIniPath)) {
webApp.setInitParameter("shiroConfigLocations",
new File(shiroIniPath).toURI().toString());
SecurityUtils.initSecurityManager(shiroIniPath);
webApp.addFilter(ShiroFilter.class, ZEPPELIN_PATH_SPEC, EnumSet.allOf(DispatcherType.class));
// To make shiro configuration (authentication, etc.) take effect for smart rest api as well.
webApp.addFilter(ShiroFilter.class, SMART_PATH_SPEC, EnumSet.allOf(DispatcherType.class));
webApp.addEventListener(new EnvironmentLoaderListener());
}
}
private WebAppContext setupWebAppContext(ContextHandlerCollection contexts) {
WebAppContext webApp = new WebAppContext();
webApp.setContextPath(zconf.getServerContextPath());
if (!isZeppelinWebEnabled()) {
webApp.setResourceBase("");
contexts.addHandler(webApp);
return webApp;
}
File warPath = new File(zconf.getString(ConfVars.ZEPPELIN_WAR));
//File warPath = new File("../dist/zeppelin-web-0.7.2.war");
if (warPath.isDirectory()) {
// Development mode, read from FS
// webApp.setDescriptor(warPath+"/WEB-INF/web.xml");
webApp.setResourceBase(warPath.getPath());
webApp.setParentLoaderPriority(true);
} else {
// use packaged WAR
webApp.setWar(warPath.getAbsolutePath());
File warTempDirectory = new File(zconf.getRelativeDir(ConfVars.ZEPPELIN_WAR_TEMPDIR));
warTempDirectory.mkdir();
LOG.info("ZeppelinServer Webapp path: {}", warTempDirectory.getPath());
webApp.setTempDirectory(warTempDirectory);
}
// Explicit bind to root
webApp.addServlet(new ServletHolder(new DefaultServlet()), "/*");
contexts.addHandler(webApp);
webApp.addFilter(new FilterHolder(CorsFilter.class), "/*",
EnumSet.allOf(DispatcherType.class));
return webApp;
}
/**
* Check if it is source build or binary package
* @return
*/
private static boolean isBinaryPackage(ZeppelinConfiguration conf) {
return !new File(conf.getRelativeDir("smart-zeppelin/zeppelin-web")).isDirectory();
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/server/JsonResponse.java | smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/server/JsonResponse.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.server;
import java.util.ArrayList;
import javax.ws.rs.core.NewCookie;
import javax.ws.rs.core.Response.ResponseBuilder;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/**
* Json response builder.
*
* @param <T>
*/
public class JsonResponse<T> {
private javax.ws.rs.core.Response.Status status;
private String message;
private T body;
transient ArrayList<NewCookie> cookies;
transient boolean pretty = false;
public JsonResponse(javax.ws.rs.core.Response.Status status) {
this.status = status;
this.message = null;
this.body = null;
}
public JsonResponse(javax.ws.rs.core.Response.Status status, String message) {
this.status = status;
this.message = message;
this.body = null;
}
public JsonResponse(javax.ws.rs.core.Response.Status status, T body) {
this.status = status;
this.message = null;
this.body = body;
}
public JsonResponse(javax.ws.rs.core.Response.Status status, String message, T body) {
this.status = status;
this.message = message;
this.body = body;
}
public JsonResponse<T> setPretty(boolean pretty) {
this.pretty = pretty;
return this;
}
/**
* Add cookie for building.
*
* @param newCookie
* @return
*/
public JsonResponse<T> addCookie(NewCookie newCookie) {
if (cookies == null) {
cookies = new ArrayList<>();
}
cookies.add(newCookie);
return this;
}
/**
* Add cookie for building.
*
* @param name
* @param value
* @return
*/
public JsonResponse<?> addCookie(String name, String value) {
return addCookie(new NewCookie(name, value));
}
@Override
public String toString() {
GsonBuilder gsonBuilder = new GsonBuilder();
if (pretty) {
gsonBuilder.setPrettyPrinting();
}
gsonBuilder.setExclusionStrategies(new JsonExclusionStrategy());
Gson gson = gsonBuilder.create();
return gson.toJson(this);
}
public javax.ws.rs.core.Response.Status getCode() {
return status;
}
public void setCode(javax.ws.rs.core.Response.Status status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getBody() {
return body;
}
public void setBody(T body) {
this.body = body;
}
public javax.ws.rs.core.Response build() {
ResponseBuilder r = javax.ws.rs.core.Response.status(status).entity(this.toString());
if (cookies != null) {
for (NewCookie nc : cookies) {
r.cookie(nc);
}
}
return r.build();
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/server/JsonExclusionStrategy.java | smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/server/JsonExclusionStrategy.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.server;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import org.apache.zeppelin.interpreter.InterpreterOption;
/**
* Created by eranw on 8/30/15.
*/
public class JsonExclusionStrategy implements ExclusionStrategy {
public boolean shouldSkipClass(Class<?> arg0) {
return false;
}
public boolean shouldSkipField(FieldAttributes f) {
return false;
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/rest/ZeppelinRestApi.java | smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/rest/ZeppelinRestApi.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.rest;
import org.apache.zeppelin.annotation.ZeppelinApi;
import org.apache.zeppelin.server.JsonResponse;
import org.apache.zeppelin.util.Util;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
/**
* Zeppelin root rest api endpoint.
*
* @since 0.3.4
*/
@Path("/")
public class ZeppelinRestApi {
public ZeppelinRestApi() {
}
/**
* Get the root endpoint Return always 200.
*
* @return 200 response
*/
@GET
public Response getRoot() {
return Response.ok().build();
}
@GET
@Path("version")
@ZeppelinApi
public Response getVersion() {
return new JsonResponse<>(Response.Status.OK, "Zeppelin version", Util.getVersion()).build();
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/rest/NotebookResponse.java | smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/rest/NotebookResponse.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.rest;
import javax.xml.bind.annotation.XmlRootElement;
/**
* Response wrapper.
*/
@XmlRootElement
public class NotebookResponse {
private String msg;
public NotebookResponse() {}
public NotebookResponse(String msg) {
this.msg = msg;
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/rest/GetUserList.java | smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/rest/GetUserList.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.rest;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.realm.ldap.JndiLdapContextFactory;
import org.apache.shiro.realm.ldap.JndiLdapRealm;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.util.JdbcUtils;
import org.apache.zeppelin.realm.ActiveDirectoryGroupRealm;
import org.apache.zeppelin.realm.LdapRealm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.naming.NamingEnumeration;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.LdapContext;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* This is class which help fetching users from different realms.
* getUserList() function is overloaded and according to the realm passed to the function it
* extracts users from its respective realm
*/
public class GetUserList {
private static final Logger LOG = LoggerFactory.getLogger(GetUserList.class);
/**
* function to extract users from shiro.ini
*/
public List<String> getUserList(IniRealm r) {
List<String> userList = new ArrayList<>();
Map getIniUser = r.getIni().get("users");
if (getIniUser != null) {
Iterator it = getIniUser.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
userList.add(pair.getKey().toString().trim());
}
}
return userList;
}
/***
* Get user roles from shiro.ini
* @param r
* @return
*/
public List<String> getRolesList(IniRealm r) {
List<String> roleList = new ArrayList<>();
Map getIniRoles = r.getIni().get("roles");
if (getIniRoles != null) {
Iterator it = getIniRoles.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
roleList.add(pair.getKey().toString().trim());
}
}
return roleList;
}
/**
* function to extract users from LDAP
*/
public List<String> getUserList(JndiLdapRealm r, String searchText) {
List<String> userList = new ArrayList<>();
String userDnTemplate = r.getUserDnTemplate();
String userDn[] = userDnTemplate.split(",", 2);
String userDnPrefix = userDn[0].split("=")[0];
String userDnSuffix = userDn[1];
JndiLdapContextFactory CF = (JndiLdapContextFactory) r.getContextFactory();
try {
LdapContext ctx = CF.getSystemLdapContext();
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
String[] attrIDs = {userDnPrefix};
constraints.setReturningAttributes(attrIDs);
NamingEnumeration result = ctx.search(userDnSuffix, "(" + userDnPrefix + "=*" + searchText +
"*)", constraints);
while (result.hasMore()) {
Attributes attrs = ((SearchResult) result.next()).getAttributes();
if (attrs.get(userDnPrefix) != null) {
String currentUser = attrs.get(userDnPrefix).toString();
userList.add(currentUser.split(":")[1].trim());
}
}
} catch (Exception e) {
LOG.error("Error retrieving User list from Ldap Realm", e);
}
LOG.info("UserList: " + userList);
return userList;
}
/**
* function to extract users from Zeppelin LdapRealm
*/
public List<String> getUserList(LdapRealm r, String searchText) {
List<String> userList = new ArrayList<>();
if (LOG.isDebugEnabled()) {
LOG.debug("SearchText: " + searchText);
}
String userAttribute = r.getUserSearchAttributeName();
String userSearchRealm = r.getUserSearchBase();
String userObjectClass = r.getUserObjectClass();
JndiLdapContextFactory CF = (JndiLdapContextFactory) r.getContextFactory();
try {
LdapContext ctx = CF.getSystemLdapContext();
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
String[] attrIDs = {userAttribute};
constraints.setReturningAttributes(attrIDs);
NamingEnumeration result = ctx.search(userSearchRealm, "(&(objectclass=" +
userObjectClass + ")("
+ userAttribute + "=" + searchText + "))", constraints);
while (result.hasMore()) {
Attributes attrs = ((SearchResult) result.next()).getAttributes();
if (attrs.get(userAttribute) != null) {
String currentUser;
if (r.getUserLowerCase()) {
LOG.debug("userLowerCase true");
currentUser = ((String) attrs.get(userAttribute).get()).toLowerCase();
} else {
LOG.debug("userLowerCase false");
currentUser = (String) attrs.get(userAttribute).get();
}
if (LOG.isDebugEnabled()) {
LOG.debug("CurrentUser: " + currentUser);
}
userList.add(currentUser.trim());
}
}
} catch (Exception e) {
LOG.error("Error retrieving User list from Ldap Realm", e);
}
return userList;
}
/***
* Get user roles from shiro.ini for Zeppelin LdapRealm
* @param r
* @return
*/
public List<String> getRolesList(LdapRealm r) {
List<String> roleList = new ArrayList<>();
Map<String, String> roles = r.getListRoles();
if (roles != null) {
Iterator it = roles.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
if (LOG.isDebugEnabled()) {
LOG.debug("RoleKeyValue: " + pair.getKey() +
" = " + pair.getValue());
}
roleList.add((String) pair.getKey());
}
}
return roleList;
}
public List<String> getUserList(ActiveDirectoryGroupRealm r, String searchText) {
List<String> userList = new ArrayList<>();
try {
LdapContext ctx = r.getLdapContextFactory().getSystemLdapContext();
userList = r.searchForUserName(searchText, ctx);
} catch (Exception e) {
LOG.error("Error retrieving User list from ActiveDirectory Realm", e);
}
return userList;
}
/**
* function to extract users from JDBCs
*/
public List<String> getUserList(JdbcRealm obj) {
List<String> userlist = new ArrayList<>();
PreparedStatement ps = null;
ResultSet rs = null;
DataSource dataSource = null;
String authQuery = "";
String retval[];
String tablename = "";
String username = "";
String userquery = "";
try {
dataSource = (DataSource) FieldUtils.readField(obj, "dataSource", true);
authQuery = (String) FieldUtils.readField(obj, "DEFAULT_AUTHENTICATION_QUERY", true);
LOG.info(authQuery);
String authQueryLowerCase = authQuery.toLowerCase();
retval = authQueryLowerCase.split("from", 2);
if (retval.length >= 2) {
retval = retval[1].split("with|where", 2);
tablename = retval[0];
retval = retval[1].split("where", 2);
if (retval.length >= 2)
retval = retval[1].split("=", 2);
else
retval = retval[0].split("=", 2);
username = retval[0];
}
if (StringUtils.isBlank(username) || StringUtils.isBlank(tablename)) {
return userlist;
}
userquery = "select " + username + " from " + tablename;
} catch (IllegalAccessException e) {
LOG.error("Error while accessing dataSource for JDBC Realm", e);
return null;
}
try {
Connection con = dataSource.getConnection();
ps = con.prepareStatement(userquery);
rs = ps.executeQuery();
while (rs.next()) {
userlist.add(rs.getString(1).trim());
}
} catch (Exception e) {
LOG.error("Error retrieving User list from JDBC Realm", e);
} finally {
JdbcUtils.closeResultSet(rs);
JdbcUtils.closeStatement(ps);
}
return userlist;
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/rest/NotebookRepoRestApi.java | smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/rest/NotebookRepoRestApi.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.rest;
import java.util.Collections;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.apache.commons.lang.StringUtils;
import org.apache.zeppelin.annotation.ZeppelinApi;
import org.apache.zeppelin.notebook.repo.NotebookRepoSync;
import org.apache.zeppelin.notebook.repo.NotebookRepoWithSettings;
import org.apache.zeppelin.rest.message.NotebookRepoSettingsRequest;
import org.apache.zeppelin.server.JsonResponse;
import org.apache.zeppelin.user.AuthenticationInfo;
import org.apache.zeppelin.utils.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.ImmutableMap;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
/**
* NoteRepo rest API endpoint.
*
*/
@Path("/notebook-repositories")
@Produces("application/json")
public class NotebookRepoRestApi {
private static final Logger LOG = LoggerFactory.getLogger(NotebookRepoRestApi.class);
private Gson gson = new Gson();
private NotebookRepoSync noteRepos;
public NotebookRepoRestApi() {}
public NotebookRepoRestApi(NotebookRepoSync noteRepos) {
this.noteRepos = noteRepos;
}
/**
* List all notebook repository
*/
@GET
@ZeppelinApi
public Response listRepoSettings() {
AuthenticationInfo subject = new AuthenticationInfo(SecurityUtils.getPrincipal());
LOG.info("Getting list of NoteRepo with Settings for user {}", subject.getUser());
List<NotebookRepoWithSettings> settings = noteRepos.getNotebookRepos(subject);
return new JsonResponse<>(Status.OK, "", settings).build();
}
/**
* Reload notebook repository
*/
@GET
@Path("reload")
@ZeppelinApi
public Response refreshRepo(){
AuthenticationInfo subject = new AuthenticationInfo(SecurityUtils.getPrincipal());
LOG.info("Reloading notebook repository for user {}", subject.getUser());
return new JsonResponse<>(Status.OK, "", null).build();
}
/**
* Update a specific note repo.
*
* @return
*/
@PUT
@ZeppelinApi
public Response updateRepoSetting(String payload) {
if (StringUtils.isBlank(payload)) {
return new JsonResponse<>(Status.NOT_FOUND, "", Collections.emptyMap()).build();
}
AuthenticationInfo subject = new AuthenticationInfo(SecurityUtils.getPrincipal());
NotebookRepoSettingsRequest newSettings = NotebookRepoSettingsRequest.EMPTY;
try {
newSettings = gson.fromJson(payload, NotebookRepoSettingsRequest.class);
} catch (JsonSyntaxException e) {
LOG.error("Cannot update notebook repo settings", e);
return new JsonResponse<>(Status.NOT_ACCEPTABLE, "",
ImmutableMap.of("error", "Invalid payload structure")).build();
}
if (NotebookRepoSettingsRequest.isEmpty(newSettings)) {
LOG.error("Invalid property");
return new JsonResponse<>(Status.NOT_ACCEPTABLE, "",
ImmutableMap.of("error", "Invalid payload")).build();
}
LOG.info("User {} is going to change repo setting", subject.getUser());
NotebookRepoWithSettings updatedSettings =
noteRepos.updateNotebookRepo(newSettings.name, newSettings.settings, subject);
return new JsonResponse<>(Status.OK, "", updatedSettings).build();
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/rest/CredentialRestApi.java | smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/rest/CredentialRestApi.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.rest;
import com.google.common.base.Strings;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.zeppelin.user.Credentials;
import org.apache.zeppelin.user.UserCredentials;
import org.apache.zeppelin.user.UsernamePassword;
import org.apache.zeppelin.server.JsonResponse;
import org.apache.zeppelin.utils.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import java.io.IOException;
import java.util.Map;
/**
* Credential Rest API
*
*/
@Path("/credential")
@Produces("application/json")
public class CredentialRestApi {
Logger logger = LoggerFactory.getLogger(CredentialRestApi.class);
private Credentials credentials;
private Gson gson = new Gson();
@Context
private HttpServletRequest servReq;
public CredentialRestApi() {
}
public CredentialRestApi(Credentials credentials) {
this.credentials = credentials;
}
/**
* Put User Credentials REST API
* @param message - JSON with entity, username, password.
* @return JSON with status.OK
* @throws IOException, IllegalArgumentException
*/
@PUT
public Response putCredentials(String message) throws IOException, IllegalArgumentException {
Map<String, String> messageMap = gson.fromJson(message,
new TypeToken<Map<String, String>>(){}.getType());
String entity = messageMap.get("entity");
String username = messageMap.get("username");
String password = messageMap.get("password");
if (Strings.isNullOrEmpty(entity)
|| Strings.isNullOrEmpty(username) || Strings.isNullOrEmpty(password) ) {
return new JsonResponse(Status.BAD_REQUEST).build();
}
String user = SecurityUtils.getPrincipal();
logger.info("Update credentials for user {} entity {}", user, entity);
UserCredentials uc = credentials.getUserCredentials(user);
uc.putUsernamePassword(entity, new UsernamePassword(username, password));
credentials.putUserCredentials(user, uc);
return new JsonResponse(Status.OK).build();
}
/**
* Get User Credentials list REST API
* @param
* @return JSON with status.OK
* @throws IOException, IllegalArgumentException
*/
@GET
public Response getCredentials(String message) throws
IOException, IllegalArgumentException {
String user = SecurityUtils.getPrincipal();
logger.info("getCredentials credentials for user {} ", user);
UserCredentials uc = credentials.getUserCredentials(user);
return new JsonResponse(Status.OK, uc).build();
}
/**
* Remove User Credentials REST API
* @param
* @return JSON with status.OK
* @throws IOException, IllegalArgumentException
*/
@DELETE
public Response removeCredentials(String message) throws
IOException, IllegalArgumentException {
String user = SecurityUtils.getPrincipal();
logger.info("removeCredentials credentials for user {} ", user);
UserCredentials uc = credentials.removeUserCredentials(user);
if (uc == null) {
return new JsonResponse(Status.NOT_FOUND).build();
}
return new JsonResponse(Status.OK).build();
}
/**
* Remove Entity of User Credential entity REST API
* @param
* @return JSON with status.OK
* @throws IOException, IllegalArgumentException
*/
@DELETE
@Path("{entity}")
public Response removeCredentialEntity(@PathParam("entity") String entity) throws
IOException, IllegalArgumentException {
String user = SecurityUtils.getPrincipal();
logger.info("removeCredentialEntity for user {} entity {}", user, entity);
if (credentials.removeCredentialEntity(user, entity) == false) {
return new JsonResponse(Status.NOT_FOUND).build();
}
return new JsonResponse(Status.OK).build();
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/rest/SecurityRestApi.java | smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/rest/SecurityRestApi.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.rest;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.realm.ldap.JndiLdapRealm;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.zeppelin.annotation.ZeppelinApi;
import org.apache.zeppelin.conf.ZeppelinConfiguration;
import org.apache.zeppelin.realm.ActiveDirectoryGroupRealm;
import org.apache.zeppelin.realm.LdapRealm;
import org.apache.zeppelin.server.JsonResponse;
import org.apache.zeppelin.ticket.TicketContainer;
import org.apache.zeppelin.utils.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import java.util.*;
/**
* Zeppelin security rest api endpoint.
*/
@Path("/security")
@Produces("application/json")
public class SecurityRestApi {
private static final Logger LOG = LoggerFactory.getLogger(SecurityRestApi.class);
/**
* Required by Swagger.
*/
public SecurityRestApi() {
super();
}
/**
* Get ticket
* Returns username & ticket
* for anonymous access, username is always anonymous.
* After getting this ticket, access through websockets become safe
*
* @return 200 response
*/
@GET
@Path("ticket")
@ZeppelinApi
public Response ticket() {
ZeppelinConfiguration conf = ZeppelinConfiguration.create();
String principal = SecurityUtils.getPrincipal();
HashSet<String> roles = SecurityUtils.getRoles();
JsonResponse response;
// ticket set to anonymous for anonymous user. Simplify testing.
String ticket;
if ("anonymous".equals(principal))
ticket = "anonymous";
else
ticket = TicketContainer.instance.getTicket(principal);
Map<String, String> data = new HashMap<>();
data.put("principal", principal);
data.put("roles", roles.toString());
data.put("ticket", ticket);
response = new JsonResponse(Response.Status.OK, "", data);
LOG.debug(response.toString());
return response.build();
}
/**
* Get userlist
* Returns list of all user from available realms
*
* @return 200 response
*/
@GET
@Path("userlist/{searchText}")
public Response getUserList(@PathParam("searchText") final String searchText) {
List<String> usersList = new ArrayList<>();
List<String> rolesList = new ArrayList<>();
try {
GetUserList getUserListObj = new GetUserList();
Collection realmsList = SecurityUtils.getRealmsList();
if (realmsList != null) {
for (Iterator<Realm> iterator = realmsList.iterator(); iterator.hasNext(); ) {
Realm realm = iterator.next();
String name = realm.getClass().getName();
if (LOG.isDebugEnabled()) {
LOG.debug("RealmClass.getName: " + name);
}
if (name.equals("org.apache.shiro.realm.text.IniRealm")) {
usersList.addAll(getUserListObj.getUserList((IniRealm) realm));
rolesList.addAll(getUserListObj.getRolesList((IniRealm) realm));
} else if (name.equals("org.apache.zeppelin.realm.LdapGroupRealm")) {
usersList.addAll(getUserListObj.getUserList((JndiLdapRealm) realm, searchText));
} else if (name.equals("org.apache.zeppelin.realm.LdapRealm")) {
usersList.addAll(getUserListObj.getUserList((LdapRealm) realm, searchText));
rolesList.addAll(getUserListObj.getRolesList((LdapRealm) realm));
} else if (name.equals("org.apache.zeppelin.realm.ActiveDirectoryGroupRealm")) {
usersList.addAll(getUserListObj.getUserList((ActiveDirectoryGroupRealm) realm,
searchText));
} else if (name.equals("org.apache.shiro.realm.jdbc.JdbcRealm")) {
usersList.addAll(getUserListObj.getUserList((JdbcRealm) realm));
}
}
}
} catch (Exception e) {
LOG.error("Exception in retrieving Users from realms ", e);
}
List<String> autoSuggestUserList = new ArrayList<>();
List<String> autoSuggestRoleList = new ArrayList<>();
Collections.sort(usersList);
Collections.sort(rolesList);
Collections.sort(usersList, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
if (o1.matches(searchText + "(.*)") && o2.matches(searchText + "(.*)")) {
return 0;
} else if (o1.matches(searchText + "(.*)")) {
return -1;
}
return 0;
}
});
int maxLength = 0;
for (String user : usersList) {
if (StringUtils.containsIgnoreCase(user, searchText)) {
autoSuggestUserList.add(user);
maxLength++;
}
if (maxLength == 5) {
break;
}
}
for (String role : rolesList) {
if (StringUtils.containsIgnoreCase(role, searchText)) {
autoSuggestRoleList.add(role);
}
}
Map<String, List> returnListMap = new HashMap<>();
returnListMap.put("users", autoSuggestUserList);
returnListMap.put("roles", autoSuggestRoleList);
return new JsonResponse<>(Response.Status.OK, "", returnListMap).build();
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/rest/LoginRestApi.java | smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/rest/LoginRestApi.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.rest;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.apache.zeppelin.annotation.ZeppelinApi;
import org.apache.zeppelin.notebook.NotebookAuthorization;
import org.apache.zeppelin.server.JsonResponse;
import org.apache.zeppelin.server.SmartZeppelinServer;
import org.apache.zeppelin.ticket.TicketContainer;
import org.apache.zeppelin.utils.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smartdata.metastore.MetaStoreException;
import org.smartdata.model.UserInfo;
import org.smartdata.server.SmartEngine;
import org.smartdata.utils.StringUtil;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
/**
* Created for org.apache.zeppelin.rest.message on 17/03/16.
*/
@Path("/login")
@Produces("application/json")
public class LoginRestApi {
private SmartEngine engine = new SmartZeppelinServer().getEngine();
private static final Logger LOG = LoggerFactory.getLogger(LoginRestApi.class);
public static final String SSM_ADMIN = "admin";
/**
* Required by Swagger.
*/
public LoginRestApi() {
super();
}
private JsonResponse loginWithZeppelinCredential(Subject currentUser) {
JsonResponse response = null;
// Use the default username/password to generate a token to login.
// This username/password is consistent with the one in conf/shiro.ini.
String userName = "admin";
String password = "ssm123";
try {
UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
// token.setRememberMe(true);
currentUser.getSession().stop();
currentUser.getSession(true);
// Login will fail if username/password doesn't match with the one
// configured in conf/shiro.ini.
currentUser.login(token);
HashSet<String> roles = SecurityUtils.getRoles();
String principal = SecurityUtils.getPrincipal();
String ticket;
if ("anonymous".equals(principal))
ticket = "anonymous";
else
ticket = TicketContainer.instance.getTicket(principal);
Map<String, String> data = new HashMap<>();
data.put("principal", principal);
data.put("roles", roles.toString());
data.put("ticket", ticket);
response = new JsonResponse(Response.Status.OK, "", data);
//if no exception, that's it, we're done!
//set roles for user in NotebookAuthorization module
NotebookAuthorization.getInstance().setRoles(principal, roles);
} catch (UnknownAccountException uae) {
//username wasn't in the system, show them an error message?
LOG.error("Exception in login: ", uae);
} catch (IncorrectCredentialsException ice) {
//password didn't match, try again?
LOG.error("Exception in login: ", ice);
} catch (LockedAccountException lae) {
//account for that username is locked - can't login. Show them a message?
LOG.error("Exception in login: ", lae);
} catch (AuthenticationException ae) {
//unexpected condition - error?
LOG.error("Exception in login: ", ae);
}
return response;
}
/**
* Post Login
* Returns userName & password
* for anonymous access, username is always anonymous.
* After getting this ticket, access through websockets become safe
*
* The username/password is managed by SSM in essence, instead of being
* managed in conf/shiro.ini. SSM will keep username/password in database
* and every time of authentication, SSM will check login username/password
* with the one in database
*
* @return 200 response
*/
@POST
@ZeppelinApi
public Response postLogin(@FormParam("userName") String userName,
@FormParam("password") String password) {
JsonResponse response = null;
// ticket set to anonymous for anonymous user. Simplify testing.
Subject currentUser = org.apache.shiro.SecurityUtils.getSubject();
if (currentUser.isAuthenticated()) {
currentUser.logout();
}
boolean isCorrectCredential = false;
try {
password = StringUtil.toSHA512String(password);
isCorrectCredential =
engine.getCmdletManager().authentic(new UserInfo(userName, password));
} catch (Exception e) {
LOG.error("Exception in login: ", e);
}
if (!currentUser.isAuthenticated() && isCorrectCredential) {
response = loginWithZeppelinCredential(currentUser);
}
if (response == null) {
response = new JsonResponse(Response.Status.FORBIDDEN, "", "");
}
LOG.warn(response.toString());
return response.build();
}
@POST
@Path("logout")
@ZeppelinApi
public Response logout() {
JsonResponse response;
Subject currentUser = org.apache.shiro.SecurityUtils.getSubject();
currentUser.logout();
response = new JsonResponse(Response.Status.UNAUTHORIZED, "", "");
LOG.warn(response.toString());
return response.build();
}
@POST
@Path("newPassword")
@ZeppelinApi
public Response postPassword(@FormParam("userName") String userName,
@FormParam("oldPassword") String oldPassword,
@FormParam("newPassword1") String newPassword,
@FormParam("newPassword2") String newPassword2) {
LOG.info("Trying to change password for user: " + userName);
JsonResponse response = null;
// ticket set to anonymous for anonymous user. Simplify testing.
Subject currentUser = org.apache.shiro.SecurityUtils.getSubject();
if (currentUser.isAuthenticated()) {
currentUser.logout();
}
boolean isCorrectCredential = false;
try {
String password = StringUtil.toSHA512String(oldPassword);
isCorrectCredential =
engine.getCmdletManager().authentic(new UserInfo(userName, password));
} catch (Exception e) {
LOG.error("Exception in login: ", e);
}
if (isCorrectCredential) {
if (newPassword.equals(newPassword2)) {
try {
engine.getCmdletManager().newPassword(new UserInfo(userName, newPassword));
LOG.info("The password has been changed for user: " + userName);
} catch (Exception e) {
LOG.error("Exception in setting password: ", e);
}
} else {
LOG.warn("Unmatched password typed in two times, please do it again!");
}
}
// Re-login
if (!currentUser.isAuthenticated() && isCorrectCredential) {
response = loginWithZeppelinCredential(currentUser);
}
if (response == null) {
LOG.warn("Incorrect credential for changing password!");
response = new JsonResponse(Response.Status.FORBIDDEN, "", "");
}
return response.build();
}
/**
* Adds new user. Only admin user has the permission.
*
* @param userName the new user's name to be added
* @param password1 the new user's password
* @param password2 the new user's password for verification.
* @return
*/
@POST
@Path("adduser")
@ZeppelinApi
public Response postAddUser(
@FormParam("adminPassword") String adminPassword,
@FormParam("userName") String userName,
@FormParam("password1") String password1,
@FormParam("password2") String password2) {
Subject currentUser = org.apache.shiro.SecurityUtils.getSubject();
if (!password1.equals(password2)) {
String msg = "Unmatched password typed in two times!";
LOG.warn(msg);
return new JsonResponse(Response.Status.BAD_REQUEST, msg, "").build();
}
String password = StringUtil.toSHA512String(adminPassword);
try {
boolean hasCredential = engine.getCmdletManager().authentic(
new UserInfo(SSM_ADMIN, password));
if (hasCredential && currentUser.isAuthenticated()) {
engine.getCmdletManager().addNewUser(new UserInfo(userName, password1));
} else {
String msg = "The typed admin password is not correct!";
LOG.warn(msg + " Failed to register new user!");
return new JsonResponse(Response.Status.FORBIDDEN, msg, "").build();
}
} catch (MetaStoreException e) {
LOG.warn(e.getMessage());
return new JsonResponse(Response.Status.BAD_REQUEST,
e.getMessage(), "").build();
}
return new JsonResponse(Response.Status.OK,
"", "").build();
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/rest/HeliumRestApi.java | smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/rest/HeliumRestApi.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.rest;
import com.github.eirslett.maven.plugins.frontend.lib.TaskRunnerException;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.io.FileUtils;
import org.apache.zeppelin.helium.Helium;
import org.apache.zeppelin.helium.HeliumPackage;
import org.apache.zeppelin.notebook.Note;
import org.apache.zeppelin.notebook.Notebook;
import org.apache.zeppelin.notebook.Paragraph;
import org.apache.zeppelin.server.JsonResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import java.io.File;
import java.io.IOException;
import java.util.List;
/**
* Helium Rest Api
*/
@Path("/helium")
@Produces("application/json")
public class HeliumRestApi {
Logger logger = LoggerFactory.getLogger(HeliumRestApi.class);
private Helium helium;
private Notebook notebook;
private Gson gson = new Gson();
public HeliumRestApi() {
}
public HeliumRestApi(Helium helium, Notebook notebook) {
this.helium = helium;
this.notebook = notebook;
}
/**
* Get all packages
* @return
*/
@GET
@Path("all")
public Response getAll() {
return new JsonResponse(Response.Status.OK, "", helium.getAllPackageInfo()).build();
}
@GET
@Path("suggest/{noteId}/{paragraphId}")
public Response suggest(@PathParam("noteId") String noteId,
@PathParam("paragraphId") String paragraphId) {
Note note = notebook.getNote(noteId);
if (note == null) {
return new JsonResponse(Response.Status.NOT_FOUND, "Note " + noteId + " not found").build();
}
Paragraph paragraph = note.getParagraph(paragraphId);
if (paragraph == null) {
return new JsonResponse(Response.Status.NOT_FOUND, "Paragraph " + paragraphId + " not found")
.build();
}
return new JsonResponse(Response.Status.OK, "", helium.suggestApp(paragraph)).build();
}
@POST
@Path("load/{noteId}/{paragraphId}")
public Response suggest(@PathParam("noteId") String noteId,
@PathParam("paragraphId") String paragraphId,
String heliumPackage) {
Note note = notebook.getNote(noteId);
if (note == null) {
return new JsonResponse(Response.Status.NOT_FOUND, "Note " + noteId + " not found").build();
}
Paragraph paragraph = note.getParagraph(paragraphId);
if (paragraph == null) {
return new JsonResponse(Response.Status.NOT_FOUND, "Paragraph " + paragraphId + " not found")
.build();
}
HeliumPackage pkg = gson.fromJson(heliumPackage, HeliumPackage.class);
String appId = helium.getApplicationFactory().loadAndRun(pkg, paragraph);
return new JsonResponse(Response.Status.OK, "", appId).build();
}
@GET
@Path("visualizations/load")
@Produces("text/javascript")
public Response visualizationLoad(@QueryParam("refresh") String refresh) {
try {
File bundle;
if (refresh != null && refresh.equals("true")) {
bundle = helium.recreateVisualizationBundle();
} else {
bundle = helium.getVisualizationFactory().getCurrentBundle();
}
if (bundle == null) {
return Response.ok().build();
} else {
String visBundle = FileUtils.readFileToString(bundle);
return Response.ok(visBundle).build();
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
// returning error will prevent zeppelin front-end render any notebook.
// visualization load fail doesn't need to block notebook rendering work.
// so it's better return ok instead of any error.
return Response.ok("ERROR: " + e.getMessage()).build();
}
}
@POST
@Path("enable/{packageName}")
public Response enablePackage(@PathParam("packageName") String packageName,
String artifact) {
try {
helium.enable(packageName, artifact);
return new JsonResponse(Response.Status.OK).build();
} catch (IOException e) {
logger.error(e.getMessage(), e);
return new JsonResponse(Response.Status.INTERNAL_SERVER_ERROR, e.getMessage()).build();
}
}
@POST
@Path("disable/{packageName}")
public Response enablePackage(@PathParam("packageName") String packageName) {
try {
helium.disable(packageName);
return new JsonResponse(Response.Status.OK).build();
} catch (IOException e) {
logger.error(e.getMessage(), e);
return new JsonResponse(Response.Status.INTERNAL_SERVER_ERROR, e.getMessage()).build();
}
}
@GET
@Path("visualizationOrder")
public Response getVisualizationPackageOrder() {
List<String> order = helium.getVisualizationPackageOrder();
return new JsonResponse(Response.Status.OK, order).build();
}
@POST
@Path("visualizationOrder")
public Response setVisualizationPackageOrder(String orderedPackageNameList) {
List<String> orderedList = gson.fromJson(
orderedPackageNameList, new TypeToken<List<String>>(){}.getType());
try {
helium.setVisualizationPackageOrder(orderedList);
} catch (IOException e) {
logger.error(e.getMessage(), e);
return new JsonResponse(Response.Status.INTERNAL_SERVER_ERROR, e.getMessage()).build();
}
return new JsonResponse(Response.Status.OK).build();
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/rest/exception/BadRequestException.java | smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/rest/exception/BadRequestException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.rest.exception;
import org.apache.zeppelin.utils.ExceptionUtils;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import static javax.ws.rs.core.Response.Status.BAD_REQUEST;
/**
* BadRequestException handler for WebApplicationException.
*/
public class BadRequestException extends WebApplicationException {
public BadRequestException() {
super(ExceptionUtils.jsonResponse(BAD_REQUEST));
}
private static Response badRequestJson(String message) {
return ExceptionUtils.jsonResponseContent(BAD_REQUEST, message);
}
public BadRequestException(Throwable cause, String message) {
super(cause, badRequestJson(message));
}
public BadRequestException(String message) {
super(badRequestJson(message));
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/rest/exception/NotFoundException.java | smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/rest/exception/NotFoundException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.rest.exception;
import static javax.ws.rs.core.Response.Status.NOT_FOUND;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import org.apache.zeppelin.utils.ExceptionUtils;
/**
* Not Found handler for WebApplicationException.
*
*/
public class NotFoundException extends WebApplicationException {
private static final long serialVersionUID = 2459398393216512293L;
/**
* Create a HTTP 404 (Not Found) exception.
*/
public NotFoundException() {
super(ExceptionUtils.jsonResponse(NOT_FOUND));
}
/**
* Create a HTTP 404 (Not Found) exception.
* @param message the String that is the entity of the 404 response.
*/
public NotFoundException(String message) {
super(notFoundJson(message));
}
private static Response notFoundJson(String message) {
return ExceptionUtils.jsonResponseContent(NOT_FOUND, message);
}
public NotFoundException(Throwable cause) {
super(cause, notFoundJson(cause.getMessage()));
}
public NotFoundException(Throwable cause, String message) {
super(cause, notFoundJson(message));
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/rest/exception/ForbiddenException.java | smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/rest/exception/ForbiddenException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.rest.exception;
import static javax.ws.rs.core.Response.Status.FORBIDDEN;
import static javax.ws.rs.core.Response.Status.UNAUTHORIZED;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import org.apache.zeppelin.utils.ExceptionUtils;
/**
* UnauthorizedException handler for WebApplicationException.
*
*/
public class ForbiddenException extends WebApplicationException {
private static final long serialVersionUID = 4394749068760407567L;
private static final String FORBIDDEN_MSG = "Not allowed to access";
public ForbiddenException() {
super(forbiddenJson(FORBIDDEN_MSG));
}
private static Response forbiddenJson(String message) {
return ExceptionUtils.jsonResponseContent(FORBIDDEN, message);
}
public ForbiddenException(Throwable cause, String message) {
super(cause, forbiddenJson(message));
}
public ForbiddenException(String message) {
super(forbiddenJson(message));
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/rest/message/RestartInterpreterRequest.java | smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/rest/message/RestartInterpreterRequest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.rest.message;
/**
* RestartInterpreter rest api request message
*/
public class RestartInterpreterRequest {
String noteId;
public RestartInterpreterRequest() {
}
public String getNoteId() {
return noteId;
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/rest/message/CronRequest.java | smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/rest/message/CronRequest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.rest.message;
import java.util.Map;
import org.apache.zeppelin.interpreter.InterpreterOption;
/**
* CronRequest rest api request message
*
*/
public class CronRequest {
String cron;
public CronRequest (){
}
public String getCronString() {
return cron;
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/rest/message/NewParagraphRequest.java | smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/rest/message/NewParagraphRequest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.rest.message;
/**
* NewParagraphRequest rest api request message
*
* index field will be ignored when it's used to provide initial paragraphs
*/
public class NewParagraphRequest {
String title;
String text;
Double index;
public NewParagraphRequest() {
}
public String getTitle() {
return title;
}
public String getText() {
return text;
}
public Double getIndex() {
return index;
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/rest/message/NewNoteRequest.java | smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/rest/message/NewNoteRequest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.rest.message;
import java.util.List;
import java.util.Map;
import org.apache.zeppelin.interpreter.InterpreterOption;
/**
* NewNoteRequest rest api request message
*
*/
public class NewNoteRequest {
String name;
List<NewParagraphRequest> paragraphs;
public NewNoteRequest (){
}
public String getName() {
return name;
}
public List<NewParagraphRequest> getParagraphs() {
return paragraphs;
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/rest/message/NewInterpreterSettingRequest.java | smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/rest/message/NewInterpreterSettingRequest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.rest.message;
import java.util.List;
import java.util.Map;
import org.apache.zeppelin.dep.Dependency;
import org.apache.zeppelin.interpreter.InterpreterOption;
/**
* NewInterpreterSetting rest api request message
*/
public class NewInterpreterSettingRequest {
private String name;
private String group;
private Map<String, String> properties;
private List<Dependency> dependencies;
private InterpreterOption option;
public NewInterpreterSettingRequest() {
}
public String getName() {
return name;
}
public String getGroup() {
return group;
}
public Map<String, String> getProperties() {
return properties;
}
public List<Dependency> getDependencies() {
return dependencies;
}
public InterpreterOption getOption() {
return option;
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/rest/message/UpdateInterpreterSettingRequest.java | smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/rest/message/UpdateInterpreterSettingRequest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.rest.message;
import java.util.List;
import java.util.Properties;
import org.apache.zeppelin.dep.Dependency;
import org.apache.zeppelin.interpreter.InterpreterOption;
/**
* UpdateInterpreterSetting rest api request message
*/
public class UpdateInterpreterSettingRequest {
Properties properties;
List<Dependency> dependencies;
InterpreterOption option;
public UpdateInterpreterSettingRequest(Properties properties,
List<Dependency> dependencies, InterpreterOption option) {
this.properties = properties;
this.dependencies = dependencies;
this.option = option;
}
public Properties getProperties() {
return properties;
}
public List<Dependency> getDependencies() {
return dependencies;
}
public InterpreterOption getOption() {
return option;
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/rest/message/NotebookRepoSettingsRequest.java | smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/rest/message/NotebookRepoSettingsRequest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.rest.message;
import java.util.Collections;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
/**
* Represent payload of a notebook repo settings.
*/
public class NotebookRepoSettingsRequest {
public static final NotebookRepoSettingsRequest EMPTY = new NotebookRepoSettingsRequest();
public String name;
public Map<String, String> settings;
public NotebookRepoSettingsRequest() {
name = StringUtils.EMPTY;
settings = Collections.emptyMap();
}
public boolean isEmpty() {
return this == EMPTY;
}
public static boolean isEmpty(NotebookRepoSettingsRequest repoSetting) {
if (repoSetting == null) {
return true;
}
return repoSetting.isEmpty();
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/rest/message/RunParagraphWithParametersRequest.java | smart-zeppelin/zeppelin-server/src/main/java/org/apache/zeppelin/rest/message/RunParagraphWithParametersRequest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.rest.message;
import java.util.Map;
/**
* RunParagraphWithParametersRequest rest api request message
*/
public class RunParagraphWithParametersRequest {
Map<String, Object> params;
public RunParagraphWithParametersRequest() {
}
public Map<String, Object> getParams() {
return params;
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/smartdata/server/utils/JsonUtil.java | smart-zeppelin/zeppelin-server/src/main/java/org/smartdata/server/utils/JsonUtil.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF 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 org.smartdata.server.utils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.List;
import java.util.Map;
/**
* Json utilities for REST APIs.
*/
public class JsonUtil {
public static String toJsonString(Map<String, String> map) {
Gson gson = new Gson();
return gson.toJson(map);
}
public static String toJsonString(List<Map<String, String>> listMap) {
Gson gson = new Gson();
return gson.toJson(listMap, new TypeToken<List<Map<String, String>>>(){}.getType());
}
public static List<Map<String, String>> toArrayListMap(String jsonString) {
Gson gson = new Gson();
List<Map<String, String>> listMap = gson.fromJson(jsonString,
new TypeToken<List<Map<String, String>>>(){}.getType());
return listMap;
}
public static Map<String, String> toStringStringMap(String jsonString) {
Gson gson = new Gson();
Map<String, String> res = gson.fromJson(jsonString,
new TypeToken<Map<String, String>>(){}.getType());
return res;
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/smartdata/server/rest/ActionRestApi.java | smart-zeppelin/zeppelin-server/src/main/java/org/smartdata/server/rest/ActionRestApi.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF 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 org.smartdata.server.rest;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smartdata.action.ActionRegistry;
import org.smartdata.server.SmartEngine;
import org.smartdata.server.rest.message.JsonResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Action APIs.
*/
@Path("/actions")
@Produces("application/json")
public class ActionRestApi {
SmartEngine smartEngine;
private static final Logger logger =
LoggerFactory.getLogger(ActionRestApi.class);
public ActionRestApi(SmartEngine smartEngine) {
this.smartEngine = smartEngine;
}
@GET
@Path("/registry/list")
public Response actionTypes() {
try {
return new JsonResponse<>(Response.Status.OK,
ActionRegistry.supportedActions()).build();
} catch (Exception e) {
logger.error("Exception in ActionRestApi while listing action types", e);
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
}
@GET
@Path("/list/{pageIndex}/{numPerPage}/{orderBy}/{isDesc}")
public Response actionList(@PathParam("pageIndex") String pageIndex,
@PathParam("numPerPage") String numPerPage,
@PathParam("orderBy") String orderBy,
@PathParam("isDesc") String isDesc) {
if (logger.isDebugEnabled()) {
logger.debug("pageIndex={}, numPerPage={}, orderBy={}, isDesc={}",
pageIndex, numPerPage, orderBy, isDesc);
}
try {
List<String> orderByList = Arrays.asList(orderBy.split(","));
List<String> isDescStringList = Arrays.asList(isDesc.split(","));
List<Boolean> isDescList = new ArrayList<>();
for (int i = 0; i < isDescStringList.size(); i++) {
isDescList.add(Boolean.parseBoolean(isDescStringList.get(i)));
}
return new JsonResponse<>(Response.Status.OK,
smartEngine.getCmdletManager().listActions(Long.parseLong(pageIndex),
Long.parseLong(numPerPage), orderByList, isDescList)).build();
} catch (Exception e) {
logger.error("Exception in ActionRestApi while listing action types", e);
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
}
@GET
@Path("/search/{search}/{pageIndex}/{numPerPage}/{orderBy}/{isDesc}")
public Response searchActoin(@PathParam("search") String path,
@PathParam("pageIndex") String pageIndex,
@PathParam("numPerPage") String numPerPage, @PathParam("orderBy") String orderBy,
@PathParam("isDesc") String isDesc) {
String res = "";
for (Character i: path.toCharArray()) {
if (i == '%' || i == '_' || i == '"' || i == '/' || i == '\'') {
res += '/';
}
res += i;
}
path = res;
try {
List<String> orderByList = Arrays.asList(orderBy.split(","));
List<String> isDescStringList = Arrays.asList(isDesc.split(","));
List<Boolean> isDescList = new ArrayList<>();
for (int i = 0; i < isDescStringList.size(); i++) {
isDescList.add(Boolean.parseBoolean(isDescStringList.get(i)));
}
return new JsonResponse<>(Response.Status.OK,
smartEngine.getCmdletManager().searchAction(path, Long.parseLong(pageIndex),
Long.parseLong(numPerPage), orderByList, isDescList)).build();
} catch (Exception e) {
logger.error("Exception in ActionRestApi while listing action types", e);
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
}
@GET
@Path("/list/{listNumber}/{ruleId}")
public Response actionList(@PathParam("listNumber") String listNumber,
@PathParam("ruleId") String ruleId) {
Integer intNumber = Integer.parseInt(listNumber);
intNumber = intNumber > 0 ? intNumber : 0;
try {
return new JsonResponse<>(Response.Status.OK,
smartEngine.getCmdletManager().getActions(Long.valueOf(ruleId), intNumber)).build();
} catch (Exception e) {
logger.error("Exception in ActionRestApi while listing action types", e);
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
}
@GET
@Path("/filelist/{ruleId}/{pageIndex}/{numPerPage}")
public Response dataSyncFileList(@PathParam("ruleId") String ruleId,
@PathParam("pageIndex") String pageIndex,
@PathParam("numPerPage") String numPerPage) {
if (logger.isDebugEnabled()) {
logger.debug("ruleId={}, pageIndex={}, numPerPage={}", ruleId,
pageIndex, numPerPage);
}
try {
return new JsonResponse<>(Response.Status.OK,
smartEngine.getCmdletManager().getFileActions(Long.valueOf(ruleId),
Long.valueOf(pageIndex), Long.valueOf(numPerPage))).build();
} catch (Exception e) {
logger.error("Exception in ActionRestApi while listing file actions", e);
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
}
@GET
@Path("/filelist/{listNumber}/{ruleId}")
public Response actionFileList(@PathParam("listNumber") String listNumber,
@PathParam("ruleId") String ruleId) {
Integer intNumber = Integer.parseInt(listNumber);
intNumber = intNumber > 0 ? intNumber : 0;
try {
return new JsonResponse<>(Response.Status.OK,
smartEngine.getCmdletManager().getFileActions(Long.valueOf(ruleId), intNumber)).build();
} catch (Exception e) {
logger.error("Exception in ActionRestApi while listing file actions", e);
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
}
@GET
@Path("/type/{listNumber}/{actionName}")
public Response actionTypeList(@PathParam("listNumber") String listNumber,
@PathParam("actionName") String actionName) {
Integer intNumber = Integer.parseInt(listNumber);
intNumber = intNumber > 0 ? intNumber : 0;
try {
return new JsonResponse<>(Response.Status.OK,
smartEngine.getCmdletManager()
.listNewCreatedActions(actionName, intNumber)).build();
} catch (Exception e) {
logger.error("Exception in ActionRestApi while listing action types", e);
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
}
@GET
@Path("/{actionId}/info")
public Response info(@PathParam("actionId") String actionId) {
Long longNumber = Long.parseLong(actionId);
try {
return new JsonResponse<>(Response.Status.OK,
smartEngine.getCmdletManager().getActionInfo(longNumber)).build();
} catch (Exception e) {
logger.error("Exception in ActionRestApi while getting info", e);
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/smartdata/server/rest/RuleRestApi.java | smart-zeppelin/zeppelin-server/src/main/java/org/smartdata/server/rest/RuleRestApi.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF 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 org.smartdata.server.rest;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smartdata.model.RuleState;
import org.smartdata.server.SmartEngine;
import org.smartdata.server.rest.message.JsonResponse;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Rules APIs.
*/
@Path("/rules")
@Produces("application/json")
public class RuleRestApi {
private SmartEngine smartEngine;
private static final Logger logger =
LoggerFactory.getLogger(RuleRestApi.class);
public RuleRestApi(SmartEngine smartEngine) {
this.smartEngine = smartEngine;
}
@POST
@Path("/add")
public Response addRule(@FormParam("ruleText") String ruleText) {
String rule;
long t;
try {
logger.info("Adding rule: " + ruleText);
t = smartEngine.getRuleManager().submitRule(ruleText, RuleState.DISABLED);
} catch (Exception e) {
logger.error("Exception in RuleRestApi while adding rule: " + e.getLocalizedMessage());
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
return new JsonResponse(Response.Status.CREATED, t).build();
}
@POST
@Path("/{ruleId}/delete")
public Response deleteRule(@PathParam("ruleId") String ruleId) {
try {
Long longNumber = Long.parseLong(ruleId);
smartEngine.getRuleManager().deleteRule(longNumber, false);
return new JsonResponse<>(Response.Status.OK).build();
} catch (Exception e) {
logger.error("Exception in RuleRestApi while deleting rule ", e);
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
}
@POST
@Path("/{ruleId}/start")
public Response start(@PathParam("ruleId") String ruleId) {
logger.info("Start rule{}", ruleId);
Long intNumber = Long.parseLong(ruleId);
try {
smartEngine.getRuleManager().activateRule(intNumber);
return new JsonResponse<>(Response.Status.OK).build();
} catch (Exception e) {
logger.error("Exception in RuleRestApi while starting rule: " + e.getMessage());
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
}
@POST
@Path("/{ruleId}/stop")
public Response stop(@PathParam("ruleId") String ruleId) {
logger.info("Stop rule{}", ruleId);
Long intNumber = Long.parseLong(ruleId);
try {
smartEngine.getRuleManager().disableRule(intNumber, true);
return new JsonResponse<>(Response.Status.OK).build();
} catch (Exception e) {
logger.error("Exception in RuleRestApi while stopping rule ", e);
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
}
@GET
@Path("/{ruleId}/info")
public Response info(@PathParam("ruleId") String ruleId) {
Long intNumber = Long.parseLong(ruleId);
try {
return new JsonResponse<>(Response.Status.OK,
smartEngine.getRuleManager().getRuleInfo(intNumber)).build();
} catch (Exception e) {
logger.error("Exception in RuleRestApi while getting rule info", e);
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
}
@GET
@Path("/{ruleId}/cmdlets/{pageIndex}/{numPerPage}/{orderBy}/{isDesc}")
public Response cmdlets(@PathParam("ruleId") String ruleId,
@PathParam("pageIndex") String pageIndex,
@PathParam("numPerPage") String numPerPage,
@PathParam("orderBy") String orderBy,
@PathParam("isDesc") String isDesc) {
Long longNumber = Long.parseLong(ruleId);
if (logger.isDebugEnabled()) {
logger.debug("ruleId={}, pageIndex={}, numPerPage={}, orderBy={}, " +
"isDesc={}", longNumber, pageIndex, numPerPage, orderBy, isDesc);
}
try {
List<String> orderByList = Arrays.asList(orderBy.split(","));
List<String> isDescStringList = Arrays.asList(isDesc.split(","));
List<Boolean> isDescList = new ArrayList<>();
for (int i = 0; i < isDescStringList.size(); i++) {
isDescList.add(Boolean.parseBoolean(isDescStringList.get(i)));
}
return new JsonResponse<>(Response.Status.OK,
smartEngine.getCmdletManager().listCmdletsInfo(longNumber,
Integer.parseInt(pageIndex),
Integer.parseInt(numPerPage), orderByList, isDescList)).build();
} catch (Exception e) {
logger.error("Exception in RuleRestApi while getting cmdlets", e);
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
}
@GET
@Path("/{ruleId}/cmdlets")
public Response cmdlets(@PathParam("ruleId") String ruleId) {
Long intNumber = Long.parseLong(ruleId);
try {
return new JsonResponse<>(Response.Status.OK,
smartEngine.getCmdletManager().listCmdletsInfo(intNumber, null)).build();
} catch (Exception e) {
logger.error("Exception in RuleRestApi while getting cmdlets", e);
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
}
@GET
@Path("/list")
public Response ruleList() {
try {
return new JsonResponse<>(Response.Status.OK,
smartEngine.getRuleManager().listRulesInfo()).build();
} catch (Exception e) {
logger.error("Exception in RuleRestApi while listing rules", e);
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
}
@GET
@Path("/list/move")
public Response ruleMoveList() {
try {
return new JsonResponse<>(Response.Status.OK,
smartEngine.getRuleManager().listRulesMoveInfo()).build();
} catch (Exception e) {
logger.error("Exception in RuleRestApi while listing Move rules", e);
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
}
@GET
@Path("/list/sync")
public Response ruleSyncList() {
try {
return new JsonResponse<>(Response.Status.OK,
smartEngine.getRuleManager().listRulesSyncInfo()).build();
} catch (Exception e) {
logger.error("Exception in RuleRestApi while listing Sync rules", e);
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/smartdata/server/rest/SystemRestApi.java | smart-zeppelin/zeppelin-server/src/main/java/org/smartdata/server/rest/SystemRestApi.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF 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 org.smartdata.server.rest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smartdata.server.SmartEngine;
import org.smartdata.server.rest.message.JsonResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
/**
* System APIs.
*/
@Path("/system")
@Produces("application/json")
public class SystemRestApi {
SmartEngine smartEngine;
private static final Logger logger =
LoggerFactory.getLogger(SystemRestApi.class);
public SystemRestApi(SmartEngine smartEngine) {
this.smartEngine = smartEngine;
}
@GET
@Path("/version")
public Response version() {
return new JsonResponse<>(Response.Status.OK, "SSM version", "1.6.0-SNAPSHOT").build();
}
@GET
@Path("/servers")
public Response servers() {
// return list of SmartServers and their states
return new JsonResponse<>(Response.Status.OK, smartEngine.getStandbyServers()).build();
}
@GET
@Path("/agents")
public Response agents() {
// return list of agents and their states
return new JsonResponse<>(Response.Status.OK, smartEngine.getAgents()).build();
}
@GET
@Path("/allAgentHosts")
public Response allAgentHosts() {
return new JsonResponse<>(Response.Status.OK, smartEngine.getAgentHosts()).build();
}
@GET
@Path("/allServerHosts")
public Response allMasterHosts() {
return new JsonResponse<>(Response.Status.OK, smartEngine.getServerHosts()).build();
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/smartdata/server/rest/ClusterRestApi.java | smart-zeppelin/zeppelin-server/src/main/java/org/smartdata/server/rest/ClusterRestApi.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF 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 org.smartdata.server.rest;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smartdata.conf.SmartConfKeys;
import org.smartdata.metastore.dao.AccessCountTable;
import org.smartdata.metastore.utils.Constants;
import org.smartdata.server.SmartEngine;
import org.smartdata.server.rest.message.JsonResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import java.util.List;
/**
* Cluster APIs.
*/
@Path("/cluster")
@Produces("application/json")
public class ClusterRestApi {
SmartEngine smartEngine;
private static final Logger logger =
LoggerFactory.getLogger(ClusterRestApi.class);
public ClusterRestApi(SmartEngine smartEngine) {
this.smartEngine = smartEngine;
}
@GET
@Path("/primary")
public Response primary() {
// return NN url
try {
String namenodeUrl = smartEngine.getConf().
get(SmartConfKeys.SMART_DFS_NAMENODE_RPCSERVER_KEY);
return new JsonResponse<>(Response.Status.OK,
"Namenode URL", namenodeUrl).build();
} catch (Exception e) {
logger.error("Exception in ClusterRestApi while getting primary info", e);
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
}
@GET
@Path("/primary/cachedfiles")
public Response cachedFiles() {
try {
return new JsonResponse<>(Response.Status.OK,
smartEngine.getStatesManager().getCachedFileStatus()).build();
} catch (Exception e) {
logger.error("Exception in ClusterRestApi while listing cached files", e);
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
}
//TODO(Philo): Make topNum settable on web UI.
//Currently, topNum=0 means that SSM will use the value configured in smart-default.xml
@GET
@Path("/primary/hotfiles")
public Response hotFiles() {
try {
List<AccessCountTable> tables =
smartEngine.getStatesManager().getTablesInLast(Constants.ONE_HOUR_IN_MILLIS);
return new JsonResponse<>(Response.Status.OK,
smartEngine.getStatesManager().getHotFiles(tables, 0)).build();
} catch (Exception e) {
logger.error("Exception in ClusterRestApi while listing hot files", e);
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
}
@GET
@Path("/primary/utilization/{resourceName}")
public Response utilization(@PathParam("resourceName") String resourceName) {
try {
return new JsonResponse<>(Response.Status.OK,
smartEngine.getUtilization(resourceName)).build();
} catch (Exception e) {
logger.error("Exception in ClusterRestApi while getting [" + resourceName
+ "] utilization", e);
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
}
/**
*
* @param resourceName
* @param timeGranularity Time interval of successive data points in milliseconds
* @param beginTs Begin timestamp in milliseconds. If <=0 denotes the value related to 'endTs'
* @param endTs Like 'beginTs'. If <= 0 denotes the time related to current server time.
* @return
*/
@GET
@Path("/primary/hist_utilization/{resourceName}/{timeGranularity}/{beginTs}/{endTs}")
public Response utilization(@PathParam("resourceName") String resourceName,
@PathParam("timeGranularity") String timeGranularity,
@PathParam("beginTs") String beginTs,
@PathParam("endTs") String endTs) {
try {
long now = System.currentTimeMillis();
long granularity = Long.valueOf(timeGranularity);
if (granularity <= 0) {
return new JsonResponse<>(Status.BAD_REQUEST,
"Invalid time granularity, must larger than 0").build();
}
long tsEnd = Long.valueOf(endTs);
long tsBegin = Long.valueOf(beginTs);
if (tsEnd <= 0) {
tsEnd += now;
}
if (tsBegin <= 0) {
tsBegin += tsEnd;
}
if (tsBegin > tsEnd) {
return new JsonResponse<>(Status.BAD_REQUEST, "Invalid time range").build();
}
return new JsonResponse<>(Response.Status.OK,
smartEngine.getHistUtilization(resourceName, granularity, tsBegin, tsEnd)).build();
} catch (Exception e) {
logger.error("Exception in ClusterRestApi while getting [" + resourceName
+ "] utilization", e);
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
}
@GET
@Path("/primary/fileinfo")
public Response fileInfo(String path) {
try {
return new JsonResponse<>(Response.Status.OK,
smartEngine.getStatesManager().getFileInfo(path)).build();
} catch (Exception e) {
logger.error("Exception in ClusterRestApi while listing hot files", e);
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
}
@GET
@Path("/primary/ssmnodesinfo")
public Response ssmNodesInfo() {
try {
return new JsonResponse<>(Response.Status.OK, smartEngine.getSsmNodesInfo()).build();
} catch (Exception e) {
logger.error("Exception in ClusterRestApi while listing SSM nodes", e);
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
}
@GET
@Path("/primary/ssmnodescmdletmetrics")
public Response ssmNodesCmdletMetrics() {
try {
return new JsonResponse<>(Response.Status.OK,
smartEngine.getCmdletManager().getAllNodeCmdletMetrics()).build();
} catch (Exception e) {
logger.error("Exception in ClusterRestApi while listing metrics related with cmdlets", e);
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
}
// @GET
// @Path("/alluxio/{clusterName}")
// public void alluxio() {
// }
//
// @GET
// @Path("/hdfs/{clusterName}")
// public void hdfs() {
// }
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/smartdata/server/rest/CmdletRestApi.java | smart-zeppelin/zeppelin-server/src/main/java/org/smartdata/server/rest/CmdletRestApi.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF 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 org.smartdata.server.rest;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smartdata.server.SmartEngine;
import org.smartdata.server.rest.message.JsonResponse;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
/**
* Cmdlets APIs.
*/
@Path("/cmdlets")
@Produces("application/json")
public class CmdletRestApi {
private SmartEngine smartEngine;
private static final Logger logger =
LoggerFactory.getLogger(CmdletRestApi.class);
public CmdletRestApi(SmartEngine smartEngine) {
this.smartEngine = smartEngine;
}
@GET
@Path("/{cmdletId}/info")
public Response info(@PathParam("cmdletId") String cmdletId) {
Long longNumber = Long.parseLong(cmdletId);
try {
return new JsonResponse<>(Response.Status.OK,
smartEngine.getCmdletManager().getCmdletInfo(longNumber)).build();
} catch (Exception e) {
logger.error("Exception in CmdletRestApi while getting info", e);
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
}
@GET
@Path("/list")
public Response list() {
try {
return new JsonResponse<>(Response.Status.OK,
smartEngine.getCmdletManager()
.listCmdletsInfo(-1, null))
.build();
} catch (Exception e) {
logger.error("Exception in CmdletRestApi while listing cmdlets", e);
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
}
@POST
@Path("/submit")
public Response submitCmdlet(String args) {
try {
return new JsonResponse<>(Response.Status.CREATED, smartEngine.getCmdletManager()
.submitCmdlet(args)).build();
} catch (Exception e) {
logger.error("Exception in ActionRestApi while adding cmdlet: " + e.getLocalizedMessage());
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
}
@POST
@Path("/{cmdletId}/stop")
public Response stop(@PathParam("cmdletId") String cmdletId) {
Long longNumber = Long.parseLong(cmdletId);
try {
smartEngine.getCmdletManager().disableCmdlet(longNumber);
return new JsonResponse<>(Response.Status.OK).build();
} catch (Exception e) {
logger.error("Exception in CmdletRestApi while stop cmdlet " + longNumber, e);
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/smartdata/server/rest/NoteBookRestApi.java | smart-zeppelin/zeppelin-server/src/main/java/org/smartdata/server/rest/NoteBookRestApi.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF 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 org.smartdata.server.rest;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smartdata.server.SmartEngine;
import org.smartdata.server.rest.message.JsonResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
/**
* Notebook Api
*/
@Path("/note")
@Produces("application/json")
public class NoteBookRestApi {
SmartEngine smartEngine;
private static final Logger LOG = LoggerFactory.getLogger(NoteBookRestApi.class);
public NoteBookRestApi(SmartEngine smartEngine) {
this.smartEngine = smartEngine;
}
@GET
@Path("/info")
public Response getNotebookInfo() {
LOG.info("Request to get notebook info");
File notebookJson = new File("notebook/note.json");
BufferedReader bufferedReader = null;
StringBuilder stringBuilder = new StringBuilder();
try {
bufferedReader = new BufferedReader(new FileReader(notebookJson));
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
} catch (Exception e) {
LOG.error("Exception in NotebookRestApi while get notebook info", e);
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
return Response.status(Response.Status.OK).entity(stringBuilder.toString()).build();
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/smartdata/server/rest/ConfRestApi.java | smart-zeppelin/zeppelin-server/src/main/java/org/smartdata/server/rest/ConfRestApi.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF 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 org.smartdata.server.rest;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smartdata.server.SmartEngine;
import org.smartdata.server.rest.message.JsonResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* Conf APIs.
*/
@Path("/conf")
@Produces("application/json")
public class ConfRestApi {
SmartEngine smartEngine;
private static final Logger logger =
LoggerFactory.getLogger(ConfRestApi.class);
public ConfRestApi(SmartEngine smartEngine) {
this.smartEngine = smartEngine;
}
@GET
@Path("")
public Response conf() {
try {
Iterator<Map.Entry<String, String>> conf = smartEngine.getConf().iterator();
Map<String, String> confMap = new HashMap<>();
while (conf.hasNext()) {
Map.Entry<String, String> confEntry = conf.next();
confMap.put(confEntry.getKey(), confEntry.getValue());
}
return new JsonResponse<>(Response.Status.OK, confMap).build();
} catch (Exception e) {
logger.error("Exception while getting configuration", e);
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-server/src/main/java/org/smartdata/server/rest/message/JsonResponse.java | smart-zeppelin/zeppelin-server/src/main/java/org/smartdata/server/rest/message/JsonResponse.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.smartdata.server.rest.message;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.zeppelin.server.JsonExclusionStrategy;
import javax.ws.rs.core.NewCookie;
import javax.ws.rs.core.Response.ResponseBuilder;
import java.util.ArrayList;
/**
* Json response builder.
*
* @param <T>
*/
public class JsonResponse<T> {
private javax.ws.rs.core.Response.Status status;
private String message;
private T body;
transient ArrayList<NewCookie> cookies;
transient boolean pretty = false;
public JsonResponse(javax.ws.rs.core.Response.Status status) {
this.status = status;
this.message = null;
this.body = null;
}
public JsonResponse(javax.ws.rs.core.Response.Status status, String message) {
this.status = status;
this.message = message;
this.body = null;
}
public JsonResponse(javax.ws.rs.core.Response.Status status, T body) {
this.status = status;
this.message = null;
this.body = body;
}
public JsonResponse(javax.ws.rs.core.Response.Status status, String message, T body) {
this.status = status;
this.message = message;
this.body = body;
}
public JsonResponse<T> setPretty(boolean pretty) {
this.pretty = pretty;
return this;
}
/**
* Add cookie for building.
*
* @param newCookie
* @return
*/
public JsonResponse<T> addCookie(NewCookie newCookie) {
if (cookies == null) {
cookies = new ArrayList<>();
}
cookies.add(newCookie);
return this;
}
/**
* Add cookie for building.
*
* @param name
* @param value
* @return
*/
public JsonResponse<?> addCookie(String name, String value) {
return addCookie(new NewCookie(name, value));
}
@Override
public String toString() {
GsonBuilder gsonBuilder = new GsonBuilder();
if (pretty) {
gsonBuilder.setPrettyPrinting();
}
gsonBuilder.setExclusionStrategies(new JsonExclusionStrategy());
Gson gson = gsonBuilder.create();
return gson.toJson(this);
}
public javax.ws.rs.core.Response.Status getCode() {
return status;
}
public void setCode(javax.ws.rs.core.Response.Status status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getBody() {
return body;
}
public void setBody(T body) {
this.body = body;
}
public javax.ws.rs.core.Response build() {
ResponseBuilder r = javax.ws.rs.core.Response.status(status).entity(this.toString());
if (cookies != null) {
for (NewCookie nc : cookies) {
r.cookie(nc);
}
}
return r.build();
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/helium/HeliumTest.java | smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/helium/HeliumTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.helium;
import com.github.eirslett.maven.plugins.frontend.lib.TaskRunnerException;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class HeliumTest {
private File tmpDir;
private File localRegistryPath;
@Before
public void setUp() throws Exception {
tmpDir = new File(System.getProperty("java.io.tmpdir") + "/ZeppelinLTest_" + System.currentTimeMillis());
tmpDir.mkdirs();
localRegistryPath = new File(tmpDir, "helium");
localRegistryPath.mkdirs();
}
@After
public void tearDown() throws IOException {
FileUtils.deleteDirectory(tmpDir);
}
@Test
public void testSaveLoadConf() throws IOException, URISyntaxException, TaskRunnerException {
// given
File heliumConf = new File(tmpDir, "helium.conf");
Helium helium = new Helium(heliumConf.getAbsolutePath(), localRegistryPath.getAbsolutePath(),
null, null);
assertFalse(heliumConf.exists());
HeliumTestRegistry registry1 = new HeliumTestRegistry("r1", "r1");
helium.addRegistry(registry1);
assertEquals(2, helium.getAllRegistry().size());
assertEquals(0, helium.getAllPackageInfo().size());
// when
helium.save();
// then
assertTrue(heliumConf.exists());
// then
Helium heliumRestored = new Helium(
heliumConf.getAbsolutePath(), localRegistryPath.getAbsolutePath(), null, null);
assertEquals(2, heliumRestored.getAllRegistry().size());
}
@Test
public void testRestoreRegistryInstances() throws IOException, URISyntaxException, TaskRunnerException {
File heliumConf = new File(tmpDir, "helium.conf");
Helium helium = new Helium(
heliumConf.getAbsolutePath(), localRegistryPath.getAbsolutePath(), null, null);
HeliumTestRegistry registry1 = new HeliumTestRegistry("r1", "r1");
HeliumTestRegistry registry2 = new HeliumTestRegistry("r2", "r2");
helium.addRegistry(registry1);
helium.addRegistry(registry2);
// when
registry1.add(new HeliumPackage(
HeliumPackage.Type.APPLICATION,
"name1",
"desc1",
"artifact1",
"className1",
new String[][]{},
"",
""));
registry2.add(new HeliumPackage(
HeliumPackage.Type.APPLICATION,
"name2",
"desc2",
"artifact2",
"className2",
new String[][]{},
"",
""));
// then
assertEquals(2, helium.getAllPackageInfo().size());
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/helium/HeliumTestRegistry.java | smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/helium/HeliumTestRegistry.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.helium;
import java.io.IOException;
import java.net.URI;
import java.util.LinkedList;
import java.util.List;
public class HeliumTestRegistry extends HeliumRegistry {
List<HeliumPackage> infos = new LinkedList<>();
public HeliumTestRegistry(String name, String uri) {
super(name, uri);
}
@Override
public List<HeliumPackage> getAll() throws IOException {
return infos;
}
public void add(HeliumPackage info) {
infos.add(info);
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/helium/HeliumTestApplication.java | smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/helium/HeliumTestApplication.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.helium;
import org.apache.zeppelin.resource.ResourceSet;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
public class HeliumTestApplication extends Application {
AtomicInteger numRun = new AtomicInteger(0);
public HeliumTestApplication(ApplicationContext context) {
super(context);
}
@Override
public void run(ResourceSet args) throws ApplicationException {
try {
context().out.clear();
context().out.write("Hello world " + numRun.incrementAndGet());
context().out.flush();
} catch (IOException e) {
throw new ApplicationException(e);
}
}
@Override
public void unload() throws ApplicationException {
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/helium/HeliumLocalRegistryTest.java | smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/helium/HeliumLocalRegistryTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.helium;
import com.google.gson.Gson;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
public class HeliumLocalRegistryTest {
private File tmpDir;
@Before
public void setUp() throws Exception {
tmpDir = new File(System.getProperty("java.io.tmpdir") + "/ZeppelinLTest_" + System.currentTimeMillis());
tmpDir.mkdirs();
}
@After
public void tearDown() throws IOException {
FileUtils.deleteDirectory(tmpDir);
}
@Test
public void testGetAllPackage() throws IOException {
// given
File r1Path = new File(tmpDir, "r1");
HeliumLocalRegistry r1 = new HeliumLocalRegistry("r1", r1Path.getAbsolutePath());
assertEquals(0, r1.getAll().size());
// when
Gson gson = new Gson();
HeliumPackage pkg1 = new HeliumPackage(HeliumPackage.Type.APPLICATION,
"app1",
"desc1",
"artifact1",
"classname1",
new String[][]{},
"license",
"");
FileUtils.writeStringToFile(new File(r1Path, "pkg1.json"), gson.toJson(pkg1));
// then
assertEquals(1, r1.getAll().size());
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/helium/HeliumVisualizationFactoryTest.java | smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/helium/HeliumVisualizationFactoryTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.helium;
import com.github.eirslett.maven.plugins.frontend.lib.InstallationException;
import com.github.eirslett.maven.plugins.frontend.lib.TaskRunnerException;
import com.google.common.io.Resources;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import org.apache.zeppelin.conf.ZeppelinConfiguration;
import static org.junit.Assert.*;
public class HeliumVisualizationFactoryTest {
private File tmpDir;
private ZeppelinConfiguration conf;
private HeliumVisualizationFactory hvf;
@Before
public void setUp() throws InstallationException, TaskRunnerException {
tmpDir = new File(System.getProperty("java.io.tmpdir") + "/ZeppelinLTest_" + System.currentTimeMillis());
tmpDir.mkdirs();
// get module dir
URL res = Resources.getResource("helium/webpack.config.js");
String resDir = new File(res.getFile()).getParent();
File moduleDir = new File(resDir + "/../../../../zeppelin-web/src/app/");
conf = new ZeppelinConfiguration();
hvf = new HeliumVisualizationFactory(conf,
tmpDir,
new File(moduleDir, "tabledata"),
new File(moduleDir, "visualization"));
}
@After
public void tearDown() throws IOException {
FileUtils.deleteDirectory(tmpDir);
}
@Test
public void testInstallNpm() throws InstallationException {
assertFalse(new File(tmpDir, "vis/node/npm").isFile());
assertFalse(new File(tmpDir, "vis/node/node").isFile());
hvf.installNodeAndNpm();
assertTrue(new File(tmpDir, "vis/node/npm").isFile());
assertTrue(new File(tmpDir, "vis/node/node").isFile());
}
@Test
public void downloadPackage() throws TaskRunnerException {
HeliumPackage pkg = new HeliumPackage(
HeliumPackage.Type.VISUALIZATION,
"lodash",
"lodash",
"lodash@3.9.3",
"",
null,
"license",
"icon"
);
hvf.install(pkg);
assertTrue(new File(tmpDir, "vis/node_modules/lodash").isDirectory());
}
@Test
public void bundlePackage() throws IOException, TaskRunnerException {
HeliumPackage pkg = new HeliumPackage(
HeliumPackage.Type.VISUALIZATION,
"zeppelin-bubblechart",
"zeppelin-bubblechart",
"zeppelin-bubblechart@0.0.3",
"",
null,
"license",
"icon"
);
List<HeliumPackage> pkgs = new LinkedList<>();
pkgs.add(pkg);
File bundle = hvf.bundle(pkgs);
assertTrue(bundle.isFile());
long lastModified = bundle.lastModified();
// bundle again and check if it served from cache
bundle = hvf.bundle(pkgs);
assertEquals(lastModified, bundle.lastModified());
}
@Test
public void bundleLocalPackage() throws IOException, TaskRunnerException {
URL res = Resources.getResource("helium/webpack.config.js");
String resDir = new File(res.getFile()).getParent();
String localPkg = resDir + "/../../../src/test/resources/helium/vis1";
HeliumPackage pkg = new HeliumPackage(
HeliumPackage.Type.VISUALIZATION,
"vis1",
"vis1",
localPkg,
"",
null,
"license",
"fa fa-coffee"
);
List<HeliumPackage> pkgs = new LinkedList<>();
pkgs.add(pkg);
File bundle = hvf.bundle(pkgs);
assertTrue(bundle.isFile());
}
@Test
public void bundleErrorPropagation() throws IOException, TaskRunnerException {
URL res = Resources.getResource("helium/webpack.config.js");
String resDir = new File(res.getFile()).getParent();
String localPkg = resDir + "/../../../src/test/resources/helium/vis2";
HeliumPackage pkg = new HeliumPackage(
HeliumPackage.Type.VISUALIZATION,
"vis2",
"vis2",
localPkg,
"",
null,
"license",
"fa fa-coffee"
);
List<HeliumPackage> pkgs = new LinkedList<>();
pkgs.add(pkg);
File bundle = null;
try {
bundle = hvf.bundle(pkgs);
// should throw exception
assertTrue(false);
} catch (IOException e) {
assertTrue(e.getMessage().contains("error in the package"));
}
assertNull(bundle);
}
@Test
public void switchVersion() throws IOException, TaskRunnerException {
URL res = Resources.getResource("helium/webpack.config.js");
String resDir = new File(res.getFile()).getParent();
HeliumPackage pkgV1 = new HeliumPackage(
HeliumPackage.Type.VISUALIZATION,
"zeppelin-bubblechart",
"zeppelin-bubblechart",
"zeppelin-bubblechart@0.0.3",
"",
null,
"license",
"icon"
);
HeliumPackage pkgV2 = new HeliumPackage(
HeliumPackage.Type.VISUALIZATION,
"zeppelin-bubblechart",
"zeppelin-bubblechart",
"zeppelin-bubblechart@0.0.1",
"",
null,
"license",
"icon"
);
List<HeliumPackage> pkgsV1 = new LinkedList<>();
pkgsV1.add(pkgV1);
List<HeliumPackage> pkgsV2 = new LinkedList<>();
pkgsV2.add(pkgV2);
File bundle1 = hvf.bundle(pkgsV1);
File bundle2 = hvf.bundle(pkgsV2);
assertNotSame(bundle1.lastModified(), bundle2.lastModified());
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/display/AngularObjectBuilder.java | smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/display/AngularObjectBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.display;
public class AngularObjectBuilder {
public static <T> AngularObject<T> build(String varName, T value, String noteId,
String paragraphId) {
return new AngularObject<>(varName, value, noteId, paragraphId, null);
}
} | java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/search/LuceneSearchTest.java | smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/search/LuceneSearchTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.search;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.*;
import static org.apache.zeppelin.search.LuceneSearch.formatId;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.apache.zeppelin.interpreter.InterpreterFactory;
import org.apache.zeppelin.interpreter.InterpreterSettingManager;
import org.apache.zeppelin.notebook.Note;
import org.apache.zeppelin.notebook.Paragraph;
import org.apache.zeppelin.notebook.repo.NotebookRepo;
import org.apache.zeppelin.user.AuthenticationInfo;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.google.common.base.Splitter;
public class LuceneSearchTest {
private static NotebookRepo notebookRepoMock;
private static InterpreterFactory interpreterFactory;
private static InterpreterSettingManager interpreterSettingManager;
private SearchService noteSearchService;
private AuthenticationInfo anonymous;
@BeforeClass
public static void beforeStartUp() {
notebookRepoMock = mock(NotebookRepo.class);
interpreterFactory = mock(InterpreterFactory.class);
interpreterSettingManager = mock(InterpreterSettingManager.class);
// when(replLoaderMock.getInterpreterSettings())
// .thenReturn(ImmutableList.<InterpreterSetting>of());
}
@Before
public void startUp() {
noteSearchService = new LuceneSearch();
anonymous = new AuthenticationInfo("anonymous");
}
@After
public void shutDown() {
noteSearchService.close();
}
@Test public void canIndexNotebook() {
//give
Note note1 = newNoteWithParagraph("Notebook1", "test");
Note note2 = newNoteWithParagraph("Notebook2", "not test");
List<Note> notebook = Arrays.asList(note1, note2);
//when
noteSearchService.addIndexDocs(notebook);
}
@Test public void canIndexAndQuery() {
//given
Note note1 = newNoteWithParagraph("Notebook1", "test");
Note note2 = newNoteWithParagraphs("Notebook2", "not test", "not test at all");
noteSearchService.addIndexDocs(Arrays.asList(note1, note2));
//when
List<Map<String, String>> results = noteSearchService.query("all");
//then
assertThat(results).isNotEmpty();
assertThat(results.size()).isEqualTo(1);
assertThat(results.get(0))
.containsEntry("id", formatId(note2.getId(), note2.getLastParagraph()));
}
@Test public void canIndexAndQueryByNotebookName() {
//given
Note note1 = newNoteWithParagraph("Notebook1", "test");
Note note2 = newNoteWithParagraphs("Notebook2", "not test", "not test at all");
noteSearchService.addIndexDocs(Arrays.asList(note1, note2));
//when
List<Map<String, String>> results = noteSearchService.query("Notebook1");
//then
assertThat(results).isNotEmpty();
assertThat(results.size()).isEqualTo(1);
assertThat(results.get(0)).containsEntry("id", note1.getId());
}
@Test
public void canIndexAndQueryByParagraphTitle() {
//given
Note note1 = newNoteWithParagraph("Notebook1", "test", "testingTitleSearch");
Note note2 = newNoteWithParagraph("Notebook2", "not test", "notTestingTitleSearch");
noteSearchService.addIndexDocs(Arrays.asList(note1, note2));
//when
List<Map<String, String>> results = noteSearchService.query("testingTitleSearch");
//then
assertThat(results).isNotEmpty();
assertThat(results.size()).isAtLeast(1);
int TitleHits = 0;
for (Map<String, String> res : results) {
if (res.get("header").contains("testingTitleSearch")) {
TitleHits++;
}
}
assertThat(TitleHits).isAtLeast(1);
}
@Test public void indexKeyContract() throws IOException {
//give
Note note1 = newNoteWithParagraph("Notebook1", "test");
//when
noteSearchService.addIndexDoc(note1);
//then
String id = resultForQuery("test").get(0).get(LuceneSearch.ID_FIELD);
assertThat(Splitter.on("/").split(id)) //key structure <noteId>/paragraph/<paragraphId>
.containsAllOf(note1.getId(), LuceneSearch.PARAGRAPH, note1.getLastParagraph().getId());
}
@Test //(expected=IllegalStateException.class)
public void canNotSearchBeforeIndexing() {
//given NO noteSearchService.index() was called
//when
List<Map<String, String>> result = noteSearchService.query("anything");
//then
assertThat(result).isEmpty();
//assert logs were printed
//"ERROR org.apache.zeppelin.search.SearchService:97 - Failed to open index dir RAMDirectory"
}
@Test public void canIndexAndReIndex() throws IOException {
//given
Note note1 = newNoteWithParagraph("Notebook1", "test");
Note note2 = newNoteWithParagraphs("Notebook2", "not test", "not test at all");
noteSearchService.addIndexDocs(Arrays.asList(note1, note2));
//when
Paragraph p2 = note2.getLastParagraph();
p2.setText("test indeed");
noteSearchService.updateIndexDoc(note2);
//then
List<Map<String, String>> results = noteSearchService.query("all");
assertThat(results).isEmpty();
results = noteSearchService.query("indeed");
assertThat(results).isNotEmpty();
}
@Test public void canDeleteNull() throws IOException {
//give
// looks like a bug in web UI: it tries to delete a note twice (after it has just been deleted)
//when
noteSearchService.deleteIndexDocs(null);
}
@Test public void canDeleteFromIndex() throws IOException {
//given
Note note1 = newNoteWithParagraph("Notebook1", "test");
Note note2 = newNoteWithParagraphs("Notebook2", "not test", "not test at all");
noteSearchService.addIndexDocs(Arrays.asList(note1, note2));
assertThat(resultForQuery("Notebook2")).isNotEmpty();
//when
noteSearchService.deleteIndexDocs(note2);
//then
assertThat(noteSearchService.query("all")).isEmpty();
assertThat(resultForQuery("Notebook2")).isEmpty();
List<Map<String, String>> results = resultForQuery("test");
assertThat(results).isNotEmpty();
assertThat(results.size()).isEqualTo(1);
}
@Test public void indexParagraphUpdatedOnNoteSave() throws IOException {
//given: total 2 notebooks, 3 paragraphs
Note note1 = newNoteWithParagraph("Notebook1", "test");
Note note2 = newNoteWithParagraphs("Notebook2", "not test", "not test at all");
noteSearchService.addIndexDocs(Arrays.asList(note1, note2));
assertThat(resultForQuery("test").size()).isEqualTo(3);
//when
Paragraph p1 = note1.getLastParagraph();
p1.setText("no no no");
note1.persist(anonymous);
//then
assertThat(resultForQuery("Notebook1").size()).isEqualTo(1);
List<Map<String, String>> results = resultForQuery("test");
assertThat(results).isNotEmpty();
assertThat(results.size()).isEqualTo(2);
//does not include Notebook1's paragraph any more
for (Map<String, String> result: results) {
assertThat(result.get("id").startsWith(note1.getId())).isFalse();;
}
}
@Test public void indexNoteNameUpdatedOnNoteSave() throws IOException {
//given: total 2 notebooks, 3 paragraphs
Note note1 = newNoteWithParagraph("Notebook1", "test");
Note note2 = newNoteWithParagraphs("Notebook2", "not test", "not test at all");
noteSearchService.addIndexDocs(Arrays.asList(note1, note2));
assertThat(resultForQuery("test").size()).isEqualTo(3);
//when
note1.setName("NotebookN");
note1.persist(anonymous);
//then
assertThat(resultForQuery("Notebook1")).isEmpty();
assertThat(resultForQuery("NotebookN")).isNotEmpty();
assertThat(resultForQuery("NotebookN").size()).isEqualTo(1);
}
private List<Map<String, String>> resultForQuery(String q) {
return noteSearchService.query(q);
}
/**
* Creates a new Note \w given name,
* adds a new paragraph \w given text
*
* @param noteName name of the note
* @param parText text of the paragraph
* @return Note
*/
private Note newNoteWithParagraph(String noteName, String parText) {
Note note1 = newNote(noteName);
addParagraphWithText(note1, parText);
return note1;
}
private Note newNoteWithParagraph(String noteName, String parText,String title) {
Note note = newNote(noteName);
addParagraphWithTextAndTitle(note, parText, title);
return note;
}
/**
* Creates a new Note \w given name,
* adds N paragraphs \w given texts
*/
private Note newNoteWithParagraphs(String noteName, String... parTexts) {
Note note1 = newNote(noteName);
for (String parText : parTexts) {
addParagraphWithText(note1, parText);
}
return note1;
}
private Paragraph addParagraphWithText(Note note, String text) {
Paragraph p = note.addParagraph(AuthenticationInfo.ANONYMOUS);
p.setText(text);
return p;
}
private Paragraph addParagraphWithTextAndTitle(Note note, String text, String title) {
Paragraph p = note.addParagraph(AuthenticationInfo.ANONYMOUS);
p.setText(text);
p.setTitle(title);
return p;
}
private Note newNote(String name) {
Note note = new Note(notebookRepoMock, interpreterFactory, interpreterSettingManager, null, noteSearchService, null, null);
note.setName(name);
return note;
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/conf/ZeppelinConfigurationTest.java | smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/conf/ZeppelinConfigurationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.conf;
import junit.framework.Assert;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.zeppelin.conf.ZeppelinConfiguration.ConfVars;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import java.net.MalformedURLException;
import java.util.List;
/**
* Created by joelz on 8/19/15.
*/
public class ZeppelinConfigurationTest {
@Before
public void clearSystemVariables() {
System.clearProperty(ConfVars.ZEPPELIN_NOTEBOOK_DIR.getVarName());
}
@Test
public void getAllowedOrigins2Test() throws MalformedURLException, ConfigurationException {
ZeppelinConfiguration conf = new ZeppelinConfiguration(this.getClass().getResource("/test-zeppelin-site2.xml"));
List<String> origins = conf.getAllowedOrigins();
Assert.assertEquals(2, origins.size());
Assert.assertEquals("http://onehost:8080", origins.get(0));
Assert.assertEquals("http://otherhost.com", origins.get(1));
}
@Test
public void getAllowedOrigins1Test() throws MalformedURLException, ConfigurationException {
ZeppelinConfiguration conf = new ZeppelinConfiguration(this.getClass().getResource("/test-zeppelin-site1.xml"));
List<String> origins = conf.getAllowedOrigins();
Assert.assertEquals(1, origins.size());
Assert.assertEquals("http://onehost:8080", origins.get(0));
}
@Test
public void getAllowedOriginsNoneTest() throws MalformedURLException, ConfigurationException {
ZeppelinConfiguration conf = new ZeppelinConfiguration(this.getClass().getResource("/zeppelin-site.xml"));
List<String> origins = conf.getAllowedOrigins();
Assert.assertEquals(1, origins.size());
}
@Test
public void isWindowsPathTestTrue() throws ConfigurationException {
ZeppelinConfiguration conf = new ZeppelinConfiguration(this.getClass().getResource("/zeppelin-site.xml"));
Boolean isIt = conf.isWindowsPath("c:\\test\\file.txt");
Assert.assertTrue(isIt);
}
@Test
public void isWindowsPathTestFalse() throws ConfigurationException {
ZeppelinConfiguration conf = new ZeppelinConfiguration(this.getClass().getResource("/zeppelin-site.xml"));
Boolean isIt = conf.isWindowsPath("~/test/file.xml");
Assert.assertFalse(isIt);
}
@Test
public void getNotebookDirTest() throws ConfigurationException {
ZeppelinConfiguration conf = new ZeppelinConfiguration(this.getClass().getResource("/zeppelin-site.xml"));
String notebookLocation = conf.getNotebookDir();
Assert.assertEquals("notebook", notebookLocation);
}
@Test
public void isNotebookPublicTest() throws ConfigurationException {
ZeppelinConfiguration conf = new ZeppelinConfiguration(this.getClass().getResource("/zeppelin-site.xml"));
boolean isIt = conf.isNotebokPublic();
assertTrue(isIt);
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/notebook/FolderViewTest.java | smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/notebook/FolderViewTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.notebook;
import org.apache.zeppelin.interpreter.Interpreter;
import org.apache.zeppelin.interpreter.InterpreterFactory;
import org.apache.zeppelin.interpreter.InterpreterSettingManager;
import org.apache.zeppelin.notebook.repo.NotebookRepo;
import org.apache.zeppelin.scheduler.Scheduler;
import org.apache.zeppelin.search.SearchService;
import org.apache.zeppelin.user.Credentials;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
@RunWith(MockitoJUnitRunner.class)
public class FolderViewTest {
@Mock
NotebookRepo repo;
@Mock
JobListenerFactory jobListenerFactory;
@Mock
SearchService index;
@Mock
Credentials credentials;
@Mock
Interpreter interpreter;
@Mock
Scheduler scheduler;
@Mock
NoteEventListener noteEventListener;
@Mock
InterpreterFactory interpreterFactory;
@Mock
InterpreterSettingManager interpreterSettingManager;
FolderView folderView;
Note note1;
Note note2;
Note note3;
List<String> testNoteNames = Arrays.asList(
"note1", "/note2",
"a/note1", "/a/note2",
"a/b/note1", "/a/b/note2"
);
Folder rootFolder;
Folder aFolder;
Folder abFolder;
Note rootNote1;
Note rootNote2;
Note aNote1;
Note aNote2;
Note abNote1;
Note abNote2;
private Note createNote() {
Note note = new Note(repo, interpreterFactory, interpreterSettingManager, jobListenerFactory, index, credentials, noteEventListener);
note.setNoteNameListener(folderView);
return note;
}
@Before
public void createNotesAndFolderMap() {
folderView = new FolderView();
for (String noteName : testNoteNames) {
Note note = createNote();
note.setName(noteName);
folderView.putNote(note);
}
rootFolder = folderView.getFolder("/");
aFolder = folderView.getFolder("a");
abFolder = folderView.getFolder("a/b");
rootNote1 = rootFolder.getNotes().get(0);
rootNote2 = rootFolder.getNotes().get(1);
aNote1 = aFolder.getNotes().get(0);
aNote2 = aFolder.getNotes().get(1);
abNote1 = abFolder.getNotes().get(0);
abNote2 = abFolder.getNotes().get(1);
}
@Test
public void putNoteTest() {
assertEquals(6, folderView.countNotes());
assertEquals(3, folderView.countFolders());
assertEquals(2, rootFolder.countNotes());
assertEquals(2, aFolder.countNotes());
assertEquals(2, abFolder.countNotes());
assertEquals("note1", rootNote1.getName());
assertEquals("/note2", rootNote2.getName());
assertEquals("a/note1", aNote1.getName());
assertEquals("/a/note2", aNote2.getName());
assertEquals("a/b/note1", abNote1.getName());
assertEquals("/a/b/note2", abNote2.getName());
}
@Test
public void getTest() {
assertEquals(rootFolder, folderView.getFolder("/"));
assertEquals(aFolder, folderView.getFolder("a"));
assertEquals(aFolder, folderView.getFolder("/a"));
assertEquals(aFolder, folderView.getFolder("a/"));
assertEquals(aFolder, folderView.getFolder("/a/"));
assertEquals(abFolder, folderView.getFolder("a/b"));
assertEquals(abFolder, folderView.getFolder("/a/b"));
assertEquals(abFolder, folderView.getFolder("a/b/"));
assertEquals(abFolder, folderView.getFolder("/a/b/"));
}
@Test
public void removeNoteTest() {
Note rootNote1 = rootFolder.getNotes().get(0);
Note aNote1 = aFolder.getNotes().get(0);
Note abNote1 = abFolder.getNotes().get(0);
folderView.removeNote(rootNote1);
folderView.removeNote(aNote1);
folderView.removeNote(abNote1);
assertEquals(3, folderView.countFolders());
assertEquals(3, folderView.countNotes());
assertEquals(1, rootFolder.countNotes());
assertEquals(1, aFolder.countNotes());
assertEquals(1, abFolder.countNotes());
}
@Test
public void renameFolderOrdinaryTest() {
// "a/b" -> "a/c"
String oldName = "a/b";
String newName = "a/c";
Folder oldFolder = folderView.renameFolder(oldName, newName);
Folder newFolder = folderView.getFolder(newName);
assertNull(folderView.getFolder(oldName));
assertNotNull(newFolder);
assertEquals(3, folderView.countFolders());
assertEquals(6, folderView.countNotes());
assertEquals(abFolder, oldFolder);
assertEquals(newName, abFolder.getId());
assertEquals(newName, newFolder.getId());
assertEquals(newName + "/note1", abNote1.getName());
assertEquals(newName + "/note2", abNote2.getName());
}
@Test
public void renameFolderTargetExistsAndHasChildTest() {
// "a" -> "a/b"
String oldName = "a";
String newName = "a/b";
Folder oldFolder = folderView.renameFolder(oldName, newName);
Folder newFolder = folderView.getFolder(newName);
assertNotNull(folderView.getFolder("a"));
assertNotNull(folderView.getFolder("a/b"));
assertNotNull(folderView.getFolder("a/b/b"));
assertEquals(0, folderView.getFolder("a").countNotes());
assertEquals(2, folderView.getFolder("a/b").countNotes());
assertEquals(2, folderView.getFolder("a/b/b").countNotes());
assertEquals(4, folderView.countFolders());
assertEquals(6, folderView.countNotes());
assertEquals(newName, aFolder.getId());
assertEquals(newName, newFolder.getId());
assertEquals(newName + "/note1", aNote1.getName());
assertEquals(newName + "/note2", aNote2.getName());
assertEquals(newName + "/b" + "/note1", abNote1.getName());
assertEquals(newName + "/b" + "/note2", abNote2.getName());
}
@Test
public void renameRootFolderTest() {
String newName = "lalala";
Folder nothing = folderView.renameFolder("/", newName);
assertNull(nothing);
assertNull(folderView.getFolder(newName));
}
@Test
public void renameFolderToRootTest() {
// "a/b" -> "/"
String oldName = "a/b";
String newName = "/";
Folder oldFolder = folderView.renameFolder(oldName, newName);
Folder newFolder = folderView.getFolder(newName);
assertNull(folderView.getFolder(oldName));
assertNotNull(newFolder);
assertEquals(2, folderView.countFolders());
assertEquals(6, folderView.countNotes());
assertEquals(abFolder, oldFolder);
assertEquals(rootFolder, newFolder);
assertEquals(newName, rootFolder.getId());
assertEquals("note1", abNote1.getName());
assertEquals("note2", abNote2.getName());
}
@Test
public void renameFolderNotExistsTest() {
// "x/y/z" -> "a"
String oldName = "x/y/z";
String newName = "a";
Folder oldFolder = folderView.renameFolder(oldName, newName);
assertNull(oldFolder);
}
@Test
public void renameFolderSameNameTest() {
// "a" -> "a"
String sameName = "a";
Folder oldFolder = folderView.renameFolder(sameName, sameName);
Folder newFolder = folderView.getFolder(sameName);
assertEquals(aFolder, oldFolder);
assertEquals(aFolder, newFolder);
assertNotNull(folderView.getFolder(sameName));
assertNotNull(newFolder);
assertEquals(sameName, aFolder.getId());
}
/**
* Should rename a empty folder
*/
@Test
public void renameEmptyFolderTest() {
// Create a note of which name is "x/y/z" and rename "x" -> "u"
Note note = createNote();
note.setName("x/y/z");
folderView.putNote(note);
folderView.renameFolder("x", "u");
assertNotNull(folderView.getFolder("u"));
assertNotNull(folderView.getFolder("u/y"));
}
/**
* Should also rename child folders of the target folder
*/
@Test
public void renameFolderHasChildrenTest() {
// "a" -> "x"
// "a/b" should also be renamed to "x/b"
folderView.renameFolder("a", "x");
assertNotNull(folderView.getFolder("x/b"));
}
@Test
public void onNameChangedTest() {
Note newNote = createNote();
assert (!folderView.hasNote(newNote));
newNote.setName(" ");
assert (!folderView.hasNote(newNote));
newNote.setName("a/b/newNote");
assert (folderView.hasNote(newNote));
assertEquals(abFolder, folderView.getFolderOf(newNote));
newNote.setName("newNote");
assert (!abFolder.getNotes().contains(newNote));
assertEquals(rootFolder, folderView.getFolderOf(newNote));
}
@Test
public void renameHighDepthFolderTest() {
Note note = createNote();
note.setName("x/y/z");
Folder folder = folderView.getFolder("x");
folder.rename("d");
assertEquals("d/y/z", note.getName());
assertNull(folderView.getFolder("x"));
assertNotNull(folderView.getFolder("d"));
assertNotNull(folderView.getFolder("d/y"));
}
@Test
public void renameFolderMergingTest() {
Note xNote1 = createNote();
Note xbNote1 = createNote();
xNote1.setName("x/note1");
xbNote1.setName("x/b/note1");
folderView.getFolder("a").rename("x");
assertEquals(3, folderView.getFolder("x").countNotes());
assertEquals(3, folderView.getFolder("x/b").countNotes());
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/notebook/NoteTest.java | smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/notebook/NoteTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.notebook;
import org.apache.zeppelin.interpreter.Interpreter;
import org.apache.zeppelin.interpreter.InterpreterFactory;
import org.apache.zeppelin.interpreter.InterpreterResult;
import org.apache.zeppelin.interpreter.InterpreterSettingManager;
import org.apache.zeppelin.notebook.repo.NotebookRepo;
import org.apache.zeppelin.scheduler.Scheduler;
import org.apache.zeppelin.search.SearchService;
import org.apache.zeppelin.user.AuthenticationInfo;
import org.apache.zeppelin.user.Credentials;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
public class NoteTest {
@Mock
NotebookRepo repo;
@Mock
JobListenerFactory jobListenerFactory;
@Mock
SearchService index;
@Mock
Credentials credentials;
@Mock
Interpreter interpreter;
@Mock
Scheduler scheduler;
@Mock
NoteEventListener noteEventListener;
@Mock
InterpreterFactory interpreterFactory;
@Mock
InterpreterSettingManager interpreterSettingManager;
private AuthenticationInfo anonymous = new AuthenticationInfo("anonymous");
@Test
public void runNormalTest() {
when(interpreterFactory.getInterpreter(anyString(), anyString(), eq("spark"))).thenReturn(interpreter);
when(interpreter.getScheduler()).thenReturn(scheduler);
String pText = "%spark sc.version";
Note note = new Note(repo, interpreterFactory, interpreterSettingManager, jobListenerFactory, index, credentials, noteEventListener);
Paragraph p = note.addParagraph(AuthenticationInfo.ANONYMOUS);
p.setText(pText);
p.setAuthenticationInfo(anonymous);
note.run(p.getId());
ArgumentCaptor<Paragraph> pCaptor = ArgumentCaptor.forClass(Paragraph.class);
verify(scheduler, only()).submit(pCaptor.capture());
verify(interpreterFactory, times(2)).getInterpreter(anyString(), anyString(), eq("spark"));
assertEquals("Paragraph text", pText, pCaptor.getValue().getText());
}
@Test
public void addParagraphWithEmptyReplNameTest() {
Note note = new Note(repo, interpreterFactory, interpreterSettingManager, jobListenerFactory, index, credentials, noteEventListener);
Paragraph p = note.addParagraph(AuthenticationInfo.ANONYMOUS);
assertNull(p.getText());
}
@Test
public void addParagraphWithLastReplNameTest() {
when(interpreterFactory.getInterpreter(anyString(), anyString(), eq("spark"))).thenReturn(interpreter);
Note note = new Note(repo, interpreterFactory, interpreterSettingManager, jobListenerFactory, index, credentials, noteEventListener);
Paragraph p1 = note.addParagraph(AuthenticationInfo.ANONYMOUS);
p1.setText("%spark ");
Paragraph p2 = note.addParagraph(AuthenticationInfo.ANONYMOUS);
assertEquals("%spark\n", p2.getText());
}
@Test
public void insertParagraphWithLastReplNameTest() {
when(interpreterFactory.getInterpreter(anyString(), anyString(), eq("spark"))).thenReturn(interpreter);
Note note = new Note(repo, interpreterFactory, interpreterSettingManager, jobListenerFactory, index, credentials, noteEventListener);
Paragraph p1 = note.addParagraph(AuthenticationInfo.ANONYMOUS);
p1.setText("%spark ");
Paragraph p2 = note.insertParagraph(note.getParagraphs().size(), AuthenticationInfo.ANONYMOUS);
assertEquals("%spark\n", p2.getText());
}
@Test
public void insertParagraphWithInvalidReplNameTest() {
when(interpreterFactory.getInterpreter(anyString(), anyString(), eq("invalid"))).thenReturn(null);
Note note = new Note(repo, interpreterFactory, interpreterSettingManager, jobListenerFactory, index, credentials, noteEventListener);
Paragraph p1 = note.addParagraph(AuthenticationInfo.ANONYMOUS);
p1.setText("%invalid ");
Paragraph p2 = note.insertParagraph(note.getParagraphs().size(), AuthenticationInfo.ANONYMOUS);
assertNull(p2.getText());
}
@Test
public void insertParagraphwithUser() {
Note note = new Note(repo, interpreterFactory, interpreterSettingManager, jobListenerFactory, index, credentials, noteEventListener);
Paragraph p = note.insertParagraph(note.getParagraphs().size(), AuthenticationInfo.ANONYMOUS);
assertEquals("anonymous", p.getUser());
}
@Test
public void clearAllParagraphOutputTest() {
when(interpreterFactory.getInterpreter(anyString(), anyString(), eq("md"))).thenReturn(interpreter);
when(interpreter.getScheduler()).thenReturn(scheduler);
Note note = new Note(repo, interpreterFactory, interpreterSettingManager, jobListenerFactory, index, credentials, noteEventListener);
Paragraph p1 = note.addParagraph(AuthenticationInfo.ANONYMOUS);
InterpreterResult result = new InterpreterResult(InterpreterResult.Code.SUCCESS, InterpreterResult.Type.TEXT, "result");
p1.setResult(result);
Paragraph p2 = note.addParagraph(AuthenticationInfo.ANONYMOUS);
p2.setReturn(result, new Throwable());
note.clearAllParagraphOutput();
assertNull(p1.getReturn());
assertNull(p2.getReturn());
}
@Test
public void getFolderIdTest() {
Note note = new Note(repo, interpreterFactory, interpreterSettingManager, jobListenerFactory, index, credentials, noteEventListener);
// Ordinary case test
note.setName("this/is/a/folder/noteName");
assertEquals("this/is/a/folder", note.getFolderId());
// Normalize test
note.setName("/this/is/a/folder/noteName");
assertEquals("this/is/a/folder", note.getFolderId());
// Root folder test
note.setName("noteOnRootFolder");
assertEquals(Folder.ROOT_FOLDER_ID, note.getFolderId());
note.setName("/noteOnRootFolderStartsWithSlash");
assertEquals(Folder.ROOT_FOLDER_ID, note.getFolderId());
}
@Test
public void getNameWithoutPathTest() {
Note note = new Note(repo, interpreterFactory, interpreterSettingManager, jobListenerFactory, index, credentials, noteEventListener);
// Notes in the root folder
note.setName("noteOnRootFolder");
assertEquals("noteOnRootFolder", note.getNameWithoutPath());
note.setName("/noteOnRootFolderStartsWithSlash");
assertEquals("noteOnRootFolderStartsWithSlash", note.getNameWithoutPath());
// Notes in subdirectories
note.setName("/a/b/note");
assertEquals("note", note.getNameWithoutPath());
note.setName("a/b/note");
assertEquals("note", note.getNameWithoutPath());
}
@Test
public void isTrashTest() {
Note note = new Note(repo, interpreterFactory, interpreterSettingManager, jobListenerFactory, index, credentials, noteEventListener);
// Notes in the root folder
note.setName("noteOnRootFolder");
assertFalse(note.isTrash());
note.setName("/noteOnRootFolderStartsWithSlash");
assertFalse(note.isTrash());
// Notes in subdirectories
note.setName("/a/b/note");
assertFalse(note.isTrash());
note.setName("a/b/note");
assertFalse(note.isTrash());
// Notes in trash
note.setName(Folder.TRASH_FOLDER_ID + "/a");
assertTrue(note.isTrash());
note.setName("/" + Folder.TRASH_FOLDER_ID + "/a");
assertTrue(note.isTrash());
note.setName(Folder.TRASH_FOLDER_ID + "/a/b/c");
assertTrue(note.isTrash());
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/notebook/FolderTest.java | smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/notebook/FolderTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.notebook;
import org.apache.zeppelin.interpreter.Interpreter;
import org.apache.zeppelin.interpreter.InterpreterFactory;
import org.apache.zeppelin.interpreter.InterpreterSettingManager;
import org.apache.zeppelin.notebook.repo.NotebookRepo;
import org.apache.zeppelin.scheduler.Scheduler;
import org.apache.zeppelin.search.SearchService;
import org.apache.zeppelin.user.Credentials;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@RunWith(MockitoJUnitRunner.class)
public class FolderTest {
@Mock
NotebookRepo repo;
@Mock
JobListenerFactory jobListenerFactory;
@Mock
SearchService index;
@Mock
Credentials credentials;
@Mock
Interpreter interpreter;
@Mock
Scheduler scheduler;
@Mock
NoteEventListener noteEventListener;
@Mock
InterpreterFactory interpreterFactory;
@Mock
InterpreterSettingManager interpreterSettingManager;
Folder folder;
Note note1;
Note note2;
Note note3;
@Before
public void createFolderAndNotes() {
note1 = new Note(repo, interpreterFactory, interpreterSettingManager, jobListenerFactory, index, credentials, noteEventListener);
note1.setName("this/is/a/folder/note1");
note2 = new Note(repo, interpreterFactory, interpreterSettingManager, jobListenerFactory, index, credentials, noteEventListener);
note2.setName("this/is/a/folder/note2");
note3 = new Note(repo, interpreterFactory, interpreterSettingManager, jobListenerFactory, index, credentials, noteEventListener);
note3.setName("this/is/a/folder/note3");
folder = new Folder("this/is/a/folder");
folder.addNote(note1);
folder.addNote(note2);
folder.addNote(note3);
folder.setParent(new Folder("this/is/a"));
}
@Test
public void normalizeFolderIdTest() {
// The root folder tests
assertEquals(Folder.ROOT_FOLDER_ID, Folder.normalizeFolderId("/"));
assertEquals(Folder.ROOT_FOLDER_ID, Folder.normalizeFolderId("//"));
assertEquals(Folder.ROOT_FOLDER_ID, Folder.normalizeFolderId("///"));
assertEquals(Folder.ROOT_FOLDER_ID, Folder.normalizeFolderId("\\\\///////////"));
// Folders under the root
assertEquals("a", Folder.normalizeFolderId("a"));
assertEquals("a", Folder.normalizeFolderId("/a"));
assertEquals("a", Folder.normalizeFolderId("a/"));
assertEquals("a", Folder.normalizeFolderId("/a/"));
// Subdirectories
assertEquals("a/b/c", Folder.normalizeFolderId("a/b/c"));
assertEquals("a/b/c", Folder.normalizeFolderId("/a/b/c"));
assertEquals("a/b/c", Folder.normalizeFolderId("a/b/c/"));
assertEquals("a/b/c", Folder.normalizeFolderId("/a/b/c/"));
}
@Test
public void folderIdTest() {
assertEquals(note1.getFolderId(), folder.getId());
assertEquals(note2.getFolderId(), folder.getId());
assertEquals(note3.getFolderId(), folder.getId());
}
@Test
public void addNoteTest() {
Note note4 = new Note(repo, interpreterFactory, interpreterSettingManager, jobListenerFactory, index, credentials, noteEventListener);
note4.setName("this/is/a/folder/note4");
folder.addNote(note4);
assert (folder.getNotes().contains(note4));
}
@Test
public void removeNoteTest() {
folder.removeNote(note3);
assert (!folder.getNotes().contains(note3));
}
@Test
public void renameTest() {
// Subdirectory tests
folder.rename("renamed/folder");
assertEquals("renamed/folder", note1.getFolderId());
assertEquals("renamed/folder", note2.getFolderId());
assertEquals("renamed/folder", note3.getFolderId());
assertEquals("renamed/folder/note1", note1.getName());
assertEquals("renamed/folder/note2", note2.getName());
assertEquals("renamed/folder/note3", note3.getName());
// Folders under the root tests
folder.rename("a");
assertEquals("a", note1.getFolderId());
assertEquals("a", note2.getFolderId());
assertEquals("a", note3.getFolderId());
assertEquals("a/note1", note1.getName());
assertEquals("a/note2", note2.getName());
assertEquals("a/note3", note3.getName());
}
@Test
public void renameToRootTest() {
folder.rename(Folder.ROOT_FOLDER_ID);
assertEquals(Folder.ROOT_FOLDER_ID, note1.getFolderId());
assertEquals(Folder.ROOT_FOLDER_ID, note2.getFolderId());
assertEquals(Folder.ROOT_FOLDER_ID, note3.getFolderId());
assertEquals("note1", note1.getName());
assertEquals("note2", note2.getName());
assertEquals("note3", note3.getName());
}
@Test
public void getParentIdTest() {
Folder rootFolder = new Folder("/");
Folder aFolder = new Folder("a");
Folder abFolder = new Folder("a/b");
assertEquals("/", rootFolder.getParentFolderId());
assertEquals("/", aFolder.getParentFolderId());
assertEquals("a", abFolder.getParentFolderId());
}
@Test
public void getNameTest() {
Folder rootFolder = new Folder("/");
Folder aFolder = new Folder("a");
Folder abFolder = new Folder("a/b");
assertEquals("/", rootFolder.getName());
assertEquals("a", aFolder.getName());
assertEquals("b", abFolder.getName());
}
@Test
public void isTrashTest() {
Folder folder;
// Not trash
folder = new Folder(Folder.ROOT_FOLDER_ID);
assertFalse(folder.isTrash());
folder = new Folder("a");
assertFalse(folder.isTrash());
folder = new Folder("a/b");
assertFalse(folder.isTrash());
// trash
folder = new Folder(Folder.TRASH_FOLDER_ID);
assertTrue(folder.isTrash());
folder = new Folder(Folder.TRASH_FOLDER_ID + "/a");
assertTrue(folder.isTrash());
folder = new Folder(Folder.TRASH_FOLDER_ID + "/a/b");
assertTrue(folder.isTrash());
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/notebook/ParagraphTest.java | smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/notebook/ParagraphTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.notebook;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.google.common.collect.Lists;
import java.util.List;
import org.apache.zeppelin.display.AngularObject;
import org.apache.zeppelin.display.AngularObjectBuilder;
import org.apache.zeppelin.display.AngularObjectRegistry;
import org.apache.zeppelin.display.Input;
import org.apache.zeppelin.interpreter.Interpreter;
import org.apache.zeppelin.interpreter.Interpreter.FormType;
import org.apache.zeppelin.interpreter.InterpreterContext;
import org.apache.zeppelin.interpreter.InterpreterFactory;
import org.apache.zeppelin.interpreter.InterpreterGroup;
import org.apache.zeppelin.interpreter.InterpreterOption;
import org.apache.zeppelin.interpreter.InterpreterResult;
import org.apache.zeppelin.interpreter.InterpreterResult.Code;
import org.apache.zeppelin.interpreter.InterpreterResult.Type;
import org.apache.zeppelin.interpreter.InterpreterResultMessage;
import org.apache.zeppelin.interpreter.InterpreterSetting;
import org.apache.zeppelin.interpreter.InterpreterSetting.Status;
import org.apache.zeppelin.interpreter.InterpreterSettingManager;
import org.apache.zeppelin.resource.ResourcePool;
import org.apache.zeppelin.scheduler.JobListener;
import org.apache.zeppelin.user.AuthenticationInfo;
import org.apache.zeppelin.user.Credentials;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
public class ParagraphTest {
@Test
public void scriptBodyWithReplName() {
String text = "%spark(1234567";
assertEquals("(1234567", Paragraph.getScriptBody(text));
text = "%table 1234567";
assertEquals("1234567", Paragraph.getScriptBody(text));
}
@Test
public void scriptBodyWithoutReplName() {
String text = "12345678";
assertEquals(text, Paragraph.getScriptBody(text));
}
@Test
public void replNameAndNoBody() {
String text = "%md";
assertEquals("md", Paragraph.getRequiredReplName(text));
assertEquals("", Paragraph.getScriptBody(text));
}
@Test
public void replSingleCharName() {
String text = "%r a";
assertEquals("r", Paragraph.getRequiredReplName(text));
assertEquals("a", Paragraph.getScriptBody(text));
}
@Test
public void replNameEndsWithWhitespace() {
String text = "%md\r\n###Hello";
assertEquals("md", Paragraph.getRequiredReplName(text));
text = "%md\t###Hello";
assertEquals("md", Paragraph.getRequiredReplName(text));
text = "%md\u000b###Hello";
assertEquals("md", Paragraph.getRequiredReplName(text));
text = "%md\f###Hello";
assertEquals("md", Paragraph.getRequiredReplName(text));
text = "%md\n###Hello";
assertEquals("md", Paragraph.getRequiredReplName(text));
text = "%md ###Hello";
assertEquals("md", Paragraph.getRequiredReplName(text));
}
@Test
public void should_extract_variable_from_angular_object_registry() throws Exception {
//Given
final String noteId = "noteId";
final AngularObjectRegistry registry = mock(AngularObjectRegistry.class);
final Note note = mock(Note.class);
final Map<String, Input> inputs = new HashMap<>();
inputs.put("name", null);
inputs.put("age", null);
inputs.put("job", null);
final String scriptBody = "My name is ${name} and I am ${age=20} years old. " +
"My occupation is ${ job = engineer | developer | artists}";
final Paragraph paragraph = new Paragraph(note, null, null, null);
final String paragraphId = paragraph.getId();
final AngularObject nameAO = AngularObjectBuilder.build("name", "DuyHai DOAN", noteId,
paragraphId);
final AngularObject ageAO = AngularObjectBuilder.build("age", 34, noteId, null);
when(note.getId()).thenReturn(noteId);
when(registry.get("name", noteId, paragraphId)).thenReturn(nameAO);
when(registry.get("age", noteId, null)).thenReturn(ageAO);
final String expected = "My name is DuyHai DOAN and I am 34 years old. " +
"My occupation is ${ job = engineer | developer | artists}";
//When
final String actual = paragraph.extractVariablesFromAngularRegistry(scriptBody, inputs,
registry);
//Then
verify(registry).get("name", noteId, paragraphId);
verify(registry).get("age", noteId, null);
assertEquals(actual, expected);
}
@Test
public void returnDefaultParagraphWithNewUser() {
Paragraph p = new Paragraph("para_1", null, null, null, null);
Object defaultValue = "Default Value";
p.setResult(defaultValue);
Paragraph newUserParagraph = p.getUserParagraph("new_user");
assertNotNull(newUserParagraph);
assertEquals(defaultValue, newUserParagraph.getReturn());
}
@Test
public void returnUnchangedResultsWithDifferentUser() throws Throwable {
InterpreterSettingManager mockInterpreterSettingManager = mock(InterpreterSettingManager.class);
Note mockNote = mock(Note.class);
when(mockNote.getCredentials()).thenReturn(mock(Credentials.class));
Paragraph spyParagraph = spy(new Paragraph("para_1", mockNote, null, null, mockInterpreterSettingManager));
doReturn("spy").when(spyParagraph).getRequiredReplName();
Interpreter mockInterpreter = mock(Interpreter.class);
doReturn(mockInterpreter).when(spyParagraph).getRepl(anyString());
InterpreterGroup mockInterpreterGroup = mock(InterpreterGroup.class);
when(mockInterpreter.getInterpreterGroup()).thenReturn(mockInterpreterGroup);
when(mockInterpreterGroup.getId()).thenReturn("mock_id_1");
when(mockInterpreterGroup.getAngularObjectRegistry()).thenReturn(mock(AngularObjectRegistry.class));
when(mockInterpreterGroup.getResourcePool()).thenReturn(mock(ResourcePool.class));
List<InterpreterSetting> spyInterpreterSettingList = spy(Lists.<InterpreterSetting>newArrayList());
InterpreterSetting mockInterpreterSetting = mock(InterpreterSetting.class);
InterpreterOption mockInterpreterOption = mock(InterpreterOption.class);
when(mockInterpreterSetting.getOption()).thenReturn(mockInterpreterOption);
when(mockInterpreterOption.permissionIsSet()).thenReturn(false);
when(mockInterpreterSetting.getStatus()).thenReturn(Status.READY);
when(mockInterpreterSetting.getId()).thenReturn("mock_id_1");
when(mockInterpreterSetting.getInterpreterGroup(anyString(), anyString())).thenReturn(mockInterpreterGroup);
spyInterpreterSettingList.add(mockInterpreterSetting);
when(mockNote.getId()).thenReturn("any_id");
when(mockInterpreterSettingManager.getInterpreterSettings(anyString())).thenReturn(spyInterpreterSettingList);
doReturn("spy script body").when(spyParagraph).getScriptBody();
when(mockInterpreter.getFormType()).thenReturn(FormType.NONE);
ParagraphJobListener mockJobListener = mock(ParagraphJobListener.class);
doReturn(mockJobListener).when(spyParagraph).getListener();
doNothing().when(mockJobListener).onOutputUpdateAll(Mockito.<Paragraph>any(), Mockito.anyList());
InterpreterResult mockInterpreterResult = mock(InterpreterResult.class);
when(mockInterpreter.interpret(anyString(), Mockito.<InterpreterContext>any())).thenReturn(mockInterpreterResult);
when(mockInterpreterResult.code()).thenReturn(Code.SUCCESS);
// Actual test
List<InterpreterResultMessage> result1 = Lists.newArrayList();
result1.add(new InterpreterResultMessage(Type.TEXT, "result1"));
when(mockInterpreterResult.message()).thenReturn(result1);
AuthenticationInfo user1 = new AuthenticationInfo("user1");
spyParagraph.setAuthenticationInfo(user1);
spyParagraph.jobRun();
Paragraph p1 = spyParagraph.getUserParagraph(user1.getUser());
List<InterpreterResultMessage> result2 = Lists.newArrayList();
result2.add(new InterpreterResultMessage(Type.TEXT, "result2"));
when(mockInterpreterResult.message()).thenReturn(result2);
AuthenticationInfo user2 = new AuthenticationInfo("user2");
spyParagraph.setAuthenticationInfo(user2);
spyParagraph.jobRun();
Paragraph p2 = spyParagraph.getUserParagraph(user2.getUser());
assertNotEquals(p1.getReturn().toString(), p2.getReturn().toString());
assertEquals(p1, spyParagraph.getUserParagraph(user1.getUser()));
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/notebook/NoteInterpreterLoaderTest.java | smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/notebook/NoteInterpreterLoaderTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.notebook;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Properties;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.zeppelin.conf.ZeppelinConfiguration;
import org.apache.zeppelin.conf.ZeppelinConfiguration.ConfVars;
import org.apache.zeppelin.dep.Dependency;
import org.apache.zeppelin.dep.DependencyResolver;
import org.apache.zeppelin.interpreter.Interpreter;
import org.apache.zeppelin.interpreter.InterpreterFactory;
import org.apache.zeppelin.interpreter.InterpreterInfo;
import org.apache.zeppelin.interpreter.InterpreterOption;
import org.apache.zeppelin.interpreter.InterpreterProperty;
import org.apache.zeppelin.interpreter.InterpreterSetting;
import org.apache.zeppelin.interpreter.InterpreterSettingManager;
import org.apache.zeppelin.interpreter.LazyOpenInterpreter;
import org.apache.zeppelin.interpreter.mock.MockInterpreter1;
import org.apache.zeppelin.interpreter.mock.MockInterpreter11;
import org.apache.zeppelin.interpreter.mock.MockInterpreter2;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class NoteInterpreterLoaderTest {
private File tmpDir;
private ZeppelinConfiguration conf;
private InterpreterFactory factory;
private InterpreterSettingManager interpreterSettingManager;
private DependencyResolver depResolver;
@Before
public void setUp() throws Exception {
tmpDir = new File(System.getProperty("java.io.tmpdir")+"/ZeppelinLTest_"+System.currentTimeMillis());
tmpDir.mkdirs();
new File(tmpDir, "conf").mkdirs();
System.setProperty(ConfVars.ZEPPELIN_HOME.getVarName(), tmpDir.getAbsolutePath());
conf = ZeppelinConfiguration.create();
depResolver = new DependencyResolver(tmpDir.getAbsolutePath() + "/local-repo");
interpreterSettingManager = new InterpreterSettingManager(conf, depResolver, new InterpreterOption(false));
factory = new InterpreterFactory(conf, null, null, null, depResolver, false, interpreterSettingManager);
ArrayList<InterpreterInfo> interpreterInfos = new ArrayList<>();
interpreterInfos.add(new InterpreterInfo(MockInterpreter1.class.getName(), "mock1", true, Maps.<String, Object>newHashMap()));
interpreterInfos.add(new InterpreterInfo(MockInterpreter11.class.getName(), "mock11", false, Maps.<String, Object>newHashMap()));
ArrayList<InterpreterInfo> interpreterInfos2 = new ArrayList<>();
interpreterInfos2.add(new InterpreterInfo(MockInterpreter2.class.getName(), "mock2", true, Maps.<String, Object>newHashMap()));
interpreterSettingManager.add("group1", interpreterInfos, Lists.<Dependency>newArrayList(), new InterpreterOption(), Maps.<String, InterpreterProperty>newHashMap(), "mock", null);
interpreterSettingManager.add("group2", interpreterInfos2, Lists.<Dependency>newArrayList(), new InterpreterOption(), Maps.<String, InterpreterProperty>newHashMap(), "mock", null);
interpreterSettingManager.createNewSetting("group1", "group1", Lists.<Dependency>newArrayList(), new InterpreterOption(), new Properties());
interpreterSettingManager.createNewSetting("group2", "group2", Lists.<Dependency>newArrayList(), new InterpreterOption(), new Properties());
}
@After
public void tearDown() throws Exception {
delete(tmpDir);
Interpreter.registeredInterpreters.clear();
}
@Test
public void testGetInterpreter() throws IOException {
interpreterSettingManager.setInterpreters("user", "note", interpreterSettingManager.getDefaultInterpreterSettingList());
// when there're no interpreter selection directive
assertEquals("org.apache.zeppelin.interpreter.mock.MockInterpreter1", factory.getInterpreter("user", "note", null).getClassName());
assertEquals("org.apache.zeppelin.interpreter.mock.MockInterpreter1", factory.getInterpreter("user", "note", "").getClassName());
assertEquals("org.apache.zeppelin.interpreter.mock.MockInterpreter1", factory.getInterpreter("user", "note", " ").getClassName());
// when group name is omitted
assertEquals("org.apache.zeppelin.interpreter.mock.MockInterpreter11", factory.getInterpreter("user", "note", "mock11").getClassName());
// when 'name' is ommitted
assertEquals("org.apache.zeppelin.interpreter.mock.MockInterpreter1", factory.getInterpreter("user", "note", "group1").getClassName());
assertEquals("org.apache.zeppelin.interpreter.mock.MockInterpreter2", factory.getInterpreter("user", "note", "group2").getClassName());
// when nothing is ommitted
assertEquals("org.apache.zeppelin.interpreter.mock.MockInterpreter1", factory.getInterpreter("user", "note", "group1.mock1").getClassName());
assertEquals("org.apache.zeppelin.interpreter.mock.MockInterpreter11", factory.getInterpreter("user", "note", "group1.mock11").getClassName());
assertEquals("org.apache.zeppelin.interpreter.mock.MockInterpreter2", factory.getInterpreter("user", "note", "group2.mock2").getClassName());
interpreterSettingManager.closeNote("user", "note");
}
@Test
public void testNoteSession() throws IOException {
interpreterSettingManager.setInterpreters("user", "noteA", interpreterSettingManager.getDefaultInterpreterSettingList());
interpreterSettingManager.getInterpreterSettings("noteA").get(0).getOption().setPerNote(InterpreterOption.SCOPED);
interpreterSettingManager.setInterpreters("user", "noteB", interpreterSettingManager.getDefaultInterpreterSettingList());
interpreterSettingManager.getInterpreterSettings("noteB").get(0).getOption().setPerNote(InterpreterOption.SCOPED);
// interpreters are not created before accessing it
assertNull(interpreterSettingManager.getInterpreterSettings("noteA").get(0).getInterpreterGroup("user", "noteA").get("noteA"));
assertNull(interpreterSettingManager.getInterpreterSettings("noteB").get(0).getInterpreterGroup("user", "noteB").get("noteB"));
factory.getInterpreter("user", "noteA", null).open();
factory.getInterpreter("user", "noteB", null).open();
assertTrue(
factory.getInterpreter("user", "noteA", null).getInterpreterGroup().getId().equals(
factory.getInterpreter("user", "noteB", null).getInterpreterGroup().getId()));
// interpreters are created after accessing it
assertNotNull(interpreterSettingManager.getInterpreterSettings("noteA").get(0).getInterpreterGroup("user", "noteA").get("noteA"));
assertNotNull(interpreterSettingManager.getInterpreterSettings("noteB").get(0).getInterpreterGroup("user", "noteB").get("noteB"));
// invalid close
interpreterSettingManager.closeNote("user", "note");
assertNotNull(interpreterSettingManager.getInterpreterSettings("noteA").get(0).getInterpreterGroup("user", "shared_process").get("noteA"));
assertNotNull(interpreterSettingManager.getInterpreterSettings("noteB").get(0).getInterpreterGroup("user", "shared_process").get("noteB"));
// when
interpreterSettingManager.closeNote("user", "noteA");
interpreterSettingManager.closeNote("user", "noteB");
// interpreters are destroyed after close
assertNull(interpreterSettingManager.getInterpreterSettings("noteA").get(0).getInterpreterGroup("user", "shared_process").get("noteA"));
assertNull(interpreterSettingManager.getInterpreterSettings("noteB").get(0).getInterpreterGroup("user", "shared_process").get("noteB"));
}
@Test
public void testNotePerInterpreterProcess() throws IOException {
interpreterSettingManager.setInterpreters("user", "noteA", interpreterSettingManager.getDefaultInterpreterSettingList());
interpreterSettingManager.getInterpreterSettings("noteA").get(0).getOption().setPerNote(InterpreterOption.ISOLATED);
interpreterSettingManager.setInterpreters("user", "noteB", interpreterSettingManager.getDefaultInterpreterSettingList());
interpreterSettingManager.getInterpreterSettings("noteB").get(0).getOption().setPerNote(InterpreterOption.ISOLATED);
// interpreters are not created before accessing it
assertNull(interpreterSettingManager.getInterpreterSettings("noteA").get(0).getInterpreterGroup("user", "noteA").get("shared_session"));
assertNull(interpreterSettingManager.getInterpreterSettings("noteB").get(0).getInterpreterGroup("user", "noteB").get("shared_session"));
factory.getInterpreter("user", "noteA", null).open();
factory.getInterpreter("user", "noteB", null).open();
// per note interpreter process
assertFalse(
factory.getInterpreter("user", "noteA", null).getInterpreterGroup().getId().equals(
factory.getInterpreter("user", "noteB", null).getInterpreterGroup().getId()));
// interpreters are created after accessing it
assertNotNull(interpreterSettingManager.getInterpreterSettings("noteA").get(0).getInterpreterGroup("user", "noteA").get("shared_session"));
assertNotNull(interpreterSettingManager.getInterpreterSettings("noteB").get(0).getInterpreterGroup("user", "noteB").get("shared_session"));
// when
interpreterSettingManager.closeNote("user", "noteA");
interpreterSettingManager.closeNote("user", "noteB");
// interpreters are destroyed after close
assertNull(interpreterSettingManager.getInterpreterSettings("noteA").get(0).getInterpreterGroup("user", "noteA").get("shared_session"));
assertNull(interpreterSettingManager.getInterpreterSettings("noteB").get(0).getInterpreterGroup("user", "noteB").get("shared_session"));
}
@Test
public void testNoteInterpreterCloseForAll() throws IOException {
interpreterSettingManager.setInterpreters("user", "FitstNote", interpreterSettingManager.getDefaultInterpreterSettingList());
interpreterSettingManager.getInterpreterSettings("FitstNote").get(0).getOption().setPerNote(InterpreterOption.SCOPED);
interpreterSettingManager.setInterpreters("user", "yourFirstNote", interpreterSettingManager.getDefaultInterpreterSettingList());
interpreterSettingManager.getInterpreterSettings("yourFirstNote").get(0).getOption().setPerNote(InterpreterOption.ISOLATED);
// interpreters are not created before accessing it
assertNull(interpreterSettingManager.getInterpreterSettings("FitstNote").get(0).getInterpreterGroup("user", "FitstNote").get("FitstNote"));
assertNull(interpreterSettingManager.getInterpreterSettings("yourFirstNote").get(0).getInterpreterGroup("user", "yourFirstNote").get("yourFirstNote"));
Interpreter firstNoteIntp = factory.getInterpreter("user", "FitstNote", "group1.mock1");
Interpreter yourFirstNoteIntp = factory.getInterpreter("user", "yourFirstNote", "group1.mock1");
firstNoteIntp.open();
yourFirstNoteIntp.open();
assertTrue(((LazyOpenInterpreter)firstNoteIntp).isOpen());
assertTrue(((LazyOpenInterpreter)yourFirstNoteIntp).isOpen());
interpreterSettingManager.closeNote("user", "FitstNote");
assertFalse(((LazyOpenInterpreter)firstNoteIntp).isOpen());
assertTrue(((LazyOpenInterpreter)yourFirstNoteIntp).isOpen());
//reopen
firstNoteIntp.open();
assertTrue(((LazyOpenInterpreter)firstNoteIntp).isOpen());
assertTrue(((LazyOpenInterpreter)yourFirstNoteIntp).isOpen());
// invalid check
interpreterSettingManager.closeNote("invalid", "Note");
assertTrue(((LazyOpenInterpreter)firstNoteIntp).isOpen());
assertTrue(((LazyOpenInterpreter)yourFirstNoteIntp).isOpen());
// invalid contains value check
interpreterSettingManager.closeNote("u", "Note");
assertTrue(((LazyOpenInterpreter)firstNoteIntp).isOpen());
assertTrue(((LazyOpenInterpreter)yourFirstNoteIntp).isOpen());
}
private void delete(File file){
if(file.isFile()) file.delete();
else if(file.isDirectory()){
File [] files = file.listFiles();
if(files!=null && files.length>0){
for(File f : files){
delete(f);
}
}
file.delete();
}
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/notebook/repo/zeppelinhub/ZeppelinHubRepoTest.java | smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/notebook/repo/zeppelinhub/ZeppelinHubRepoTest.java | package org.apache.zeppelin.notebook.repo.zeppelinhub;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.apache.commons.httpclient.HttpException;
import org.apache.zeppelin.conf.ZeppelinConfiguration;
import org.apache.zeppelin.notebook.Note;
import org.apache.zeppelin.notebook.NoteInfo;
import org.apache.zeppelin.notebook.repo.zeppelinhub.rest.ZeppelinhubRestApiHandler;
import org.apache.zeppelin.user.AuthenticationInfo;
import org.junit.Before;
import org.junit.Test;
import com.google.common.io.Files;
public class ZeppelinHubRepoTest {
final String token = "AAA-BBB-CCC-00";
final String testAddr = "http://zeppelinhub.ltd";
final AuthenticationInfo auth = new AuthenticationInfo("anthony");
private ZeppelinHubRepo repo;
private File pathOfNotebooks = new File(System.getProperty("user.dir") + "/src/test/resources/list_of_notes");
private File pathOfNotebook = new File(System.getProperty("user.dir") + "/src/test/resources/note");
@Before
public void setUp() throws Exception {
System.setProperty(ZeppelinHubRepo.ZEPPELIN_CONF_PROP_NAME_SERVER, testAddr);
System.setProperty(ZeppelinHubRepo.ZEPPELIN_CONF_PROP_NAME_TOKEN, token);
ZeppelinConfiguration conf = new ZeppelinConfiguration();
repo = new ZeppelinHubRepo(conf);
repo.setZeppelinhubRestApiHandler(getMockedZeppelinHandler());
}
private ZeppelinhubRestApiHandler getMockedZeppelinHandler() throws HttpException, IOException {
ZeppelinhubRestApiHandler mockedZeppelinhubHandler = mock(ZeppelinhubRestApiHandler.class);
byte[] listOfNotesResponse = Files.toByteArray(pathOfNotebooks);
when(mockedZeppelinhubHandler.get("AAA-BBB-CCC-00", ""))
.thenReturn(new String(listOfNotesResponse));
byte[] noteResponse = Files.toByteArray(pathOfNotebook);
when(mockedZeppelinhubHandler.get("AAA-BBB-CCC-00", "AAAAA"))
.thenReturn(new String(noteResponse));
return mockedZeppelinhubHandler;
}
@Test
public void testGetZeppelinhubUrl() {
System.setProperty(ZeppelinHubRepo.ZEPPELIN_CONF_PROP_NAME_SERVER, testAddr);
ZeppelinConfiguration config = new ZeppelinConfiguration();
ZeppelinHubRepo repository = new ZeppelinHubRepo(config);
assertThat(repository.getZeppelinHubUrl(config)).isEqualTo("http://zeppelinhub.ltd");
System.setProperty(ZeppelinHubRepo.ZEPPELIN_CONF_PROP_NAME_SERVER, "yolow");
config = new ZeppelinConfiguration();
repository = new ZeppelinHubRepo(config);
assertThat(repository.getZeppelinHubUrl(config)).isEqualTo("https://www.zeppelinhub.com");
System.setProperty(ZeppelinHubRepo.ZEPPELIN_CONF_PROP_NAME_SERVER, "http://zeppelinhub.ltd:4242");
config = new ZeppelinConfiguration();
repository = new ZeppelinHubRepo(config);
assertThat(repository.getZeppelinHubUrl(config)).isEqualTo("http://zeppelinhub.ltd:4242");
System.setProperty(ZeppelinHubRepo.ZEPPELIN_CONF_PROP_NAME_SERVER, "http://zeppelinhub.ltd:0");
config = new ZeppelinConfiguration();
repository = new ZeppelinHubRepo(config);
assertThat(repository.getZeppelinHubUrl(config)).isEqualTo("http://zeppelinhub.ltd");
}
@Test
public void testGetZeppelinHubWsEndpoint() {
System.setProperty(ZeppelinHubRepo.ZEPPELIN_CONF_PROP_NAME_SERVER, testAddr);
ZeppelinConfiguration config = new ZeppelinConfiguration();
ZeppelinHubRepo repository = new ZeppelinHubRepo(config);
assertThat(repository.getZeppelinhubWebsocketUri(config)).isEqualTo("ws://zeppelinhub.ltd:80/async");
System.setProperty(ZeppelinHubRepo.ZEPPELIN_CONF_PROP_NAME_SERVER, "https://zeppelinhub.ltd");
config = new ZeppelinConfiguration();
repository = new ZeppelinHubRepo(config);
assertThat(repository.getZeppelinhubWebsocketUri(config)).isEqualTo("wss://zeppelinhub.ltd:443/async");
System.setProperty(ZeppelinHubRepo.ZEPPELIN_CONF_PROP_NAME_SERVER, "yolow");
config = new ZeppelinConfiguration();
repository = new ZeppelinHubRepo(config);
assertThat(repository.getZeppelinhubWebsocketUri(config)).isEqualTo("wss://www.zeppelinhub.com:443/async");
System.setProperty(ZeppelinHubRepo.ZEPPELIN_CONF_PROP_NAME_SERVER, "http://zeppelinhub.ltd:4242");
config = new ZeppelinConfiguration();
repository = new ZeppelinHubRepo(config);
assertThat(repository.getZeppelinhubWebsocketUri(config)).isEqualTo("ws://zeppelinhub.ltd:4242/async");
System.setProperty(ZeppelinHubRepo.ZEPPELIN_CONF_PROP_NAME_SERVER, "https://www.zeppelinhub.com");
config = new ZeppelinConfiguration();
repository = new ZeppelinHubRepo(config);
assertThat(repository.getZeppelinhubWebsocketUri(config)).isEqualTo("wss://www.zeppelinhub.com:443/async");
System.setProperty(ZeppelinHubRepo.ZEPPELIN_CONF_PROP_NAME_SERVER, "http://www.zeppelinhub.com");
config = new ZeppelinConfiguration();
repository = new ZeppelinHubRepo(config);
assertThat(repository.getZeppelinhubWebsocketUri(config)).isEqualTo("ws://www.zeppelinhub.com:80/async");
System.setProperty(ZeppelinHubRepo.ZEPPELIN_CONF_PROP_NAME_SERVER, "https://www.zeppelinhub.com:4242");
config = new ZeppelinConfiguration();
repository = new ZeppelinHubRepo(config);
assertThat(repository.getZeppelinhubWebsocketUri(config)).isEqualTo("wss://www.zeppelinhub.com:4242/async");
}
@Test
public void testGetAllNotes() throws IOException {
List<NoteInfo> notebooks = repo.list(auth);
assertThat(notebooks).isNotEmpty();
assertThat(notebooks.size()).isEqualTo(3);
}
@Test
public void testGetNote() throws IOException {
Note notebook = repo.get("AAAAA", auth);
assertThat(notebook).isNotNull();
assertThat(notebook.getId()).isEqualTo("2A94M5J1Z");
}
@Test
public void testRemoveNote() throws IOException {
// not suppose to throw
repo.remove("AAAAA", auth);
}
@Test
public void testRemoveNoteError() throws IOException {
// not suppose to throw
repo.remove("BBBBB", auth);
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/notebook/repo/zeppelinhub/websocket/ZeppelinhubClientTest.java | smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/notebook/repo/zeppelinhub/websocket/ZeppelinhubClientTest.java | package org.apache.zeppelin.notebook.repo.zeppelinhub.websocket;
import static org.junit.Assert.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.zeppelin.notebook.repo.zeppelinhub.websocket.ZeppelinhubClient;
import org.apache.zeppelin.notebook.repo.zeppelinhub.websocket.mock.MockEchoWebsocketServer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ZeppelinhubClientTest {
private Logger LOG = LoggerFactory.getLogger(ZeppelinClientTest.class);
private final int zeppelinPort = 8090;
private final String validWebsocketUrl = "ws://localhost:" + zeppelinPort + "/ws";
private ExecutorService executor;
private MockEchoWebsocketServer echoServer;
private final String runNotebookMsg =
"{\"op\":\"RUN_NOTEBOOK\"," +
"\"data\":[{\"id\":\"20150112-172845_1301897143\",\"title\":null,\"config\":{},\"params\":{},\"data\":null}," +
"{\"id\":\"20150112-172845_1301897143\",\"title\":null,\"config\":{},\"params\":{},\"data\":null}]," +
"\"meta\":{\"owner\":\"author\",\"instance\":\"my-zepp\",\"noteId\":\"2AB7SY361\"}}";
private final String invalidRunNotebookMsg = "some random string";
@Before
public void setUp() throws Exception {
startWebsocketServer();
}
@After
public void tearDown() throws Exception {
//tear down routine
echoServer.stop();
executor.shutdown();
}
private void startWebsocketServer() throws InterruptedException {
// mock zeppelin websocket server setup
executor = Executors.newFixedThreadPool(1);
echoServer = new MockEchoWebsocketServer(zeppelinPort);
executor.submit(echoServer);
}
@Test
public void zeppelinhubClientSingletonTest() {
ZeppelinhubClient client1 = ZeppelinhubClient.getInstance();
if (client1 == null) {
client1 = ZeppelinhubClient.initialize(validWebsocketUrl, "TOKEN");
}
assertNotNull(client1);
ZeppelinhubClient client2 = ZeppelinhubClient.getInstance();
assertNotNull(client2);
assertEquals(client1, client2);
}
@Test
public void runAllParagraphTest() throws Exception {
Client.initialize(validWebsocketUrl, validWebsocketUrl, "TOKEN", null);
Client.getInstance().start();
ZeppelinhubClient zeppelinhubClient = ZeppelinhubClient.getInstance();
boolean runStatus = zeppelinhubClient.runAllParagraph("2AB7SY361", runNotebookMsg);
assertTrue(runStatus);
runStatus = zeppelinhubClient.runAllParagraph("2AB7SY361", invalidRunNotebookMsg);
assertFalse(runStatus);
Client.getInstance().stop();
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/notebook/repo/zeppelinhub/websocket/ZeppelinClientTest.java | smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/notebook/repo/zeppelinhub/websocket/ZeppelinClientTest.java | package org.apache.zeppelin.notebook.repo.zeppelinhub.websocket;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.zeppelin.notebook.repo.zeppelinhub.websocket.mock.MockEchoWebsocketServer;
import org.apache.zeppelin.notebook.socket.Message;
import org.apache.zeppelin.notebook.socket.Message.OP;
import org.eclipse.jetty.websocket.api.Session;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Maps;
public class ZeppelinClientTest {
private Logger LOG = LoggerFactory.getLogger(ZeppelinClientTest.class);
private final int zeppelinPort = 8080;
private final String validWebsocketUrl = "ws://localhost:" + zeppelinPort + "/ws";
private ExecutorService executor;
private MockEchoWebsocketServer echoServer;
@Before
public void setUp() throws Exception {
startWebsocketServer();
}
@After
public void tearDown() throws Exception {
//tear down routine
echoServer.stop();
executor.shutdown();
}
private void startWebsocketServer() throws InterruptedException {
// mock zeppelin websocket server setup
executor = Executors.newFixedThreadPool(1);
echoServer = new MockEchoWebsocketServer(zeppelinPort);
executor.submit(echoServer);
}
@Test
public void zeppelinConnectionTest() {
try {
// Wait for websocket server to start
Thread.sleep(2000);
} catch (InterruptedException e) {
LOG.warn("Cannot wait for websocket server to start, returning");
return;
}
// Initialize and start Zeppelin client
ZeppelinClient client = ZeppelinClient.initialize(validWebsocketUrl, "dummy token", null);
client.start();
LOG.info("Zeppelin websocket client started");
// Connection to note AAAA
Session connectionA = client.getZeppelinConnection("AAAA", "anonymous", "anonymous");
assertNotNull(connectionA);
assertTrue(connectionA.isOpen());
assertEquals(client.countConnectedNotes(), 1);
assertEquals(connectionA, client.getZeppelinConnection("AAAA", "anonymous", "anonymous"));
// Connection to note BBBB
Session connectionB = client.getZeppelinConnection("BBBB", "anonymous", "anonymous");
assertNotNull(connectionB);
assertTrue(connectionB.isOpen());
assertEquals(client.countConnectedNotes(), 2);
assertEquals(connectionB, client.getZeppelinConnection("BBBB", "anonymous", "anonymous"));
// Remove connection to note AAAA
client.removeNoteConnection("AAAA");
assertEquals(client.countConnectedNotes(), 1);
assertNotEquals(connectionA, client.getZeppelinConnection("AAAA", "anonymous", "anonymous"));
assertEquals(client.countConnectedNotes(), 2);
client.stop();
}
@Test
public void zeppelinClientSingletonTest() {
ZeppelinClient client1 = ZeppelinClient.getInstance();
if (client1 == null) {
client1 = ZeppelinClient.initialize(validWebsocketUrl, "TOKEN", null);
}
assertNotNull(client1);
ZeppelinClient client2 = ZeppelinClient.getInstance();
assertNotNull(client2);
assertEquals(client1, client2);
}
@Test
public void zeppelinMessageSerializationTest() {
Message msg = new Message(OP.LIST_NOTES);
msg.data = Maps.newHashMap();
msg.data.put("key", "value");
ZeppelinClient client = ZeppelinClient.initialize(validWebsocketUrl, "TOKEN", null);
String serializedMsg = client.serialize(msg);
Message deserializedMsg = client.deserialize(serializedMsg);
assertEquals(msg.op, deserializedMsg.op);
assertEquals(msg.data.get("key"), deserializedMsg.data.get("key"));
String invalidMsg = "random text";
deserializedMsg =client.deserialize(invalidMsg);
assertNull(deserializedMsg);
}
@Test
public void sendToZeppelinTest() {
ZeppelinClient client = ZeppelinClient.initialize(validWebsocketUrl, "TOKEN", null);
client.start();
Message msg = new Message(OP.LIST_NOTES);
msg.data = Maps.newHashMap();
msg.data.put("key", "value");
client.send(msg, "DDDD");
client.removeNoteConnection("DDDD");
client.stop();
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/notebook/repo/zeppelinhub/websocket/mock/MockEventServlet.java | smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/notebook/repo/zeppelinhub/websocket/mock/MockEventServlet.java | package org.apache.zeppelin.notebook.repo.zeppelinhub.websocket.mock;
import org.eclipse.jetty.websocket.servlet.WebSocketServlet;
import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;
@SuppressWarnings("serial")
public class MockEventServlet extends WebSocketServlet
{
@Override
public void configure(WebSocketServletFactory factory)
{
factory.register(MockEventSocket.class);
}
} | java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/notebook/repo/zeppelinhub/websocket/mock/MockEchoWebsocketServer.java | smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/notebook/repo/zeppelinhub/websocket/mock/MockEchoWebsocketServer.java | package org.apache.zeppelin.notebook.repo.zeppelinhub.websocket.mock;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.slf4j.LoggerFactory;
public class MockEchoWebsocketServer implements Runnable {
private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(MockEchoWebsocketServer.class);
private Server server;
public MockEchoWebsocketServer(int port) {
server = new Server();
ServerConnector connector = new ServerConnector(server);
connector.setPort(port);
server.addConnector(connector);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
server.setHandler(context);
//ServletHolder holderEvents = new ServletHolder("ws-events", MockEventServlet.class);
context.addServlet(MockEventServlet.class, "/ws/*");
}
public void start() throws Exception {
LOG.info("Starting mock echo websocket server");
server.start();
server.join();
}
public void stop() throws Exception {
LOG.info("Stopping mock echo websocket server");
server.stop();
}
@Override
public void run() {
try {
this.start();
} catch (Exception e) {
LOG.error("Couldn't start mock echo websocket server", e);
}
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/notebook/repo/zeppelinhub/websocket/mock/MockEventSocket.java | smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/notebook/repo/zeppelinhub/websocket/mock/MockEventSocket.java | package org.apache.zeppelin.notebook.repo.zeppelinhub.websocket.mock;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.WebSocketAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MockEventSocket extends WebSocketAdapter {
private static final Logger LOG = LoggerFactory.getLogger(MockEventServlet.class);
private Session session;
@Override
public void onWebSocketConnect(Session session) {
super.onWebSocketConnect(session);
this.session = session;
LOG.info("Socket Connected: " + session);
}
@Override
public void onWebSocketText(String message) {
super.onWebSocketText(message);
session.getRemote().sendStringByFuture(message);
LOG.info("Received TEXT message: {}", message);
}
@Override
public void onWebSocketClose(int statusCode, String reason) {
super.onWebSocketClose(statusCode, reason);
LOG.info("Socket Closed: [{}] {}", statusCode, reason);
}
@Override
public void onWebSocketError(Throwable cause) {
super.onWebSocketError(cause);
LOG.error("Websocket error: {}", cause);
}
} | java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/notebook/repo/zeppelinhub/websocket/protocol/ZeppelinhubMessageTest.java | smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/notebook/repo/zeppelinhub/websocket/protocol/ZeppelinhubMessageTest.java | package org.apache.zeppelin.notebook.repo.zeppelinhub.websocket.protocol;
import static org.junit.Assert.assertEquals;
import java.util.Map;
import org.apache.zeppelin.notebook.socket.Message.OP;
import org.junit.Test;
import com.google.common.collect.Maps;
public class ZeppelinhubMessageTest {
private String msg = "{\"op\":\"LIST_NOTES\",\"data\":\"my data\",\"meta\":{\"key1\":\"val1\"}}";
@Test
public void testThatCanSerializeZeppelinHubMessage() {
Map<String,String> meta = Maps.newHashMap();
meta.put("key1", "val1");
String zeppelinHubMsg = ZeppelinhubMessage.newMessage(OP.LIST_NOTES, "my data", meta).serialize();
assertEquals(msg, zeppelinHubMsg);
}
@Test
public void testThastCanDeserialiseZeppelinhubMessage() {
Map<String,String> meta = Maps.newHashMap();
meta.put("key1", "val1");
ZeppelinhubMessage expected = ZeppelinhubMessage.newMessage(OP.LIST_NOTES.toString(), "my data", meta);
ZeppelinhubMessage zeppelinHubMsg = ZeppelinhubMessage.deserialize(msg);
assertEquals(expected.op, zeppelinHubMsg.op);
assertEquals(expected.data, zeppelinHubMsg.data);
assertEquals(expected.meta, zeppelinHubMsg.meta);
}
@Test
public void testThatInvalidStringReturnEmptyZeppelinhubMessage() {
assertEquals(ZeppelinhubMessage.EMPTY, ZeppelinhubMessage.deserialize(""));
assertEquals(ZeppelinhubMessage.EMPTY, ZeppelinhubMessage.deserialize("dwfewewrewr"));
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/interpreter/InterpreterSettingTest.java | smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/interpreter/InterpreterSettingTest.java | package org.apache.zeppelin.interpreter;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.junit.Test;
import org.apache.zeppelin.dep.Dependency;
import org.apache.zeppelin.interpreter.remote.RemoteInterpreter;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
public class InterpreterSettingTest {
@Test
public void sharedModeCloseandRemoveInterpreterGroupTest() {
InterpreterOption interpreterOption = new InterpreterOption();
interpreterOption.setPerUser(InterpreterOption.SHARED);
InterpreterSetting interpreterSetting = new InterpreterSetting("", "", "", new ArrayList<InterpreterInfo>(), new Properties(), new ArrayList<Dependency>(), interpreterOption, "", null);
interpreterSetting.setInterpreterGroupFactory(new InterpreterGroupFactory() {
@Override
public InterpreterGroup createInterpreterGroup(String interpreterGroupId,
InterpreterOption option) {
return new InterpreterGroup(interpreterGroupId);
}
});
Interpreter mockInterpreter1 = mock(RemoteInterpreter.class);
List<Interpreter> interpreterList1 = new ArrayList<>();
interpreterList1.add(mockInterpreter1);
InterpreterGroup interpreterGroup = interpreterSetting.getInterpreterGroup("user1", "note1");
interpreterGroup.put(interpreterSetting.getInterpreterSessionKey("user1", "note1"), interpreterList1);
// This won't effect anything
Interpreter mockInterpreter2 = mock(RemoteInterpreter.class);
List<Interpreter> interpreterList2 = new ArrayList<>();
interpreterList2.add(mockInterpreter2);
interpreterGroup = interpreterSetting.getInterpreterGroup("user2", "note1");
interpreterGroup.put(interpreterSetting.getInterpreterSessionKey("user2", "note1"), interpreterList2);
assertEquals(1, interpreterSetting.getInterpreterGroup("user1", "note1").size());
interpreterSetting.closeAndRemoveInterpreterGroup("note1", "user2");
assertEquals(0, interpreterSetting.getAllInterpreterGroups().size());
}
@Test
public void perUserScopedModeCloseAndRemoveInterpreterGroupTest() {
InterpreterOption interpreterOption = new InterpreterOption();
interpreterOption.setPerUser(InterpreterOption.SCOPED);
InterpreterSetting interpreterSetting = new InterpreterSetting("", "", "", new ArrayList<InterpreterInfo>(), new Properties(), new ArrayList<Dependency>(), interpreterOption, "", null);
interpreterSetting.setInterpreterGroupFactory(new InterpreterGroupFactory() {
@Override
public InterpreterGroup createInterpreterGroup(String interpreterGroupId,
InterpreterOption option) {
return new InterpreterGroup(interpreterGroupId);
}
});
Interpreter mockInterpreter1 = mock(RemoteInterpreter.class);
List<Interpreter> interpreterList1 = new ArrayList<>();
interpreterList1.add(mockInterpreter1);
InterpreterGroup interpreterGroup = interpreterSetting.getInterpreterGroup("user1", "note1");
interpreterGroup.put(interpreterSetting.getInterpreterSessionKey("user1", "note1"), interpreterList1);
Interpreter mockInterpreter2 = mock(RemoteInterpreter.class);
List<Interpreter> interpreterList2 = new ArrayList<>();
interpreterList2.add(mockInterpreter2);
interpreterGroup = interpreterSetting.getInterpreterGroup("user2", "note1");
interpreterGroup.put(interpreterSetting.getInterpreterSessionKey("user2", "note1"), interpreterList2);
assertEquals(1, interpreterSetting.getAllInterpreterGroups().size());
assertEquals(2, interpreterSetting.getInterpreterGroup("user1", "note1").size());
assertEquals(2, interpreterSetting.getInterpreterGroup("user2", "note1").size());
interpreterSetting.closeAndRemoveInterpreterGroup("note1", "user1");
assertEquals(1, interpreterSetting.getInterpreterGroup("user2","note1").size());
// Check if non-existed key works or not
interpreterSetting.closeAndRemoveInterpreterGroup("note1", "user1");
assertEquals(1, interpreterSetting.getInterpreterGroup("user2","note1").size());
interpreterSetting.closeAndRemoveInterpreterGroup("note1", "user2");
assertEquals(0, interpreterSetting.getAllInterpreterGroups().size());
}
@Test
public void perUserIsolatedModeCloseAndRemoveInterpreterGroupTest() {
InterpreterOption interpreterOption = new InterpreterOption();
interpreterOption.setPerUser(InterpreterOption.ISOLATED);
InterpreterSetting interpreterSetting = new InterpreterSetting("", "", "", new ArrayList<InterpreterInfo>(), new Properties(), new ArrayList<Dependency>(), interpreterOption, "", null);
interpreterSetting.setInterpreterGroupFactory(new InterpreterGroupFactory() {
@Override
public InterpreterGroup createInterpreterGroup(String interpreterGroupId,
InterpreterOption option) {
return new InterpreterGroup(interpreterGroupId);
}
});
Interpreter mockInterpreter1 = mock(RemoteInterpreter.class);
List<Interpreter> interpreterList1 = new ArrayList<>();
interpreterList1.add(mockInterpreter1);
InterpreterGroup interpreterGroup = interpreterSetting.getInterpreterGroup("user1", "note1");
interpreterGroup.put(interpreterSetting.getInterpreterSessionKey("user1", "note1"), interpreterList1);
Interpreter mockInterpreter2 = mock(RemoteInterpreter.class);
List<Interpreter> interpreterList2 = new ArrayList<>();
interpreterList2.add(mockInterpreter2);
interpreterGroup = interpreterSetting.getInterpreterGroup("user2", "note1");
interpreterGroup.put(interpreterSetting.getInterpreterSessionKey("user2", "note1"), interpreterList2);
assertEquals(2, interpreterSetting.getAllInterpreterGroups().size());
assertEquals(1, interpreterSetting.getInterpreterGroup("user1", "note1").size());
assertEquals(1, interpreterSetting.getInterpreterGroup("user2", "note1").size());
interpreterSetting.closeAndRemoveInterpreterGroup("note1", "user1");
assertEquals(1, interpreterSetting.getInterpreterGroup("user2","note1").size());
assertEquals(1, interpreterSetting.getAllInterpreterGroups().size());
interpreterSetting.closeAndRemoveInterpreterGroup("note1", "user2");
assertEquals(0, interpreterSetting.getAllInterpreterGroups().size());
}
@Test
public void perNoteScopedModeCloseAndRemoveInterpreterGroupTest() {
InterpreterOption interpreterOption = new InterpreterOption();
interpreterOption.setPerNote(InterpreterOption.SCOPED);
InterpreterSetting interpreterSetting = new InterpreterSetting("", "", "", new ArrayList<InterpreterInfo>(), new Properties(), new ArrayList<Dependency>(), interpreterOption, "", null);
interpreterSetting.setInterpreterGroupFactory(new InterpreterGroupFactory() {
@Override
public InterpreterGroup createInterpreterGroup(String interpreterGroupId,
InterpreterOption option) {
return new InterpreterGroup(interpreterGroupId);
}
});
Interpreter mockInterpreter1 = mock(RemoteInterpreter.class);
List<Interpreter> interpreterList1 = new ArrayList<>();
interpreterList1.add(mockInterpreter1);
InterpreterGroup interpreterGroup = interpreterSetting.getInterpreterGroup("user1", "note1");
interpreterGroup.put(interpreterSetting.getInterpreterSessionKey("user1", "note1"), interpreterList1);
Interpreter mockInterpreter2 = mock(RemoteInterpreter.class);
List<Interpreter> interpreterList2 = new ArrayList<>();
interpreterList2.add(mockInterpreter2);
interpreterGroup = interpreterSetting.getInterpreterGroup("user1", "note2");
interpreterGroup.put(interpreterSetting.getInterpreterSessionKey("user1", "note2"), interpreterList2);
assertEquals(1, interpreterSetting.getAllInterpreterGroups().size());
assertEquals(2, interpreterSetting.getInterpreterGroup("user1", "note1").size());
assertEquals(2, interpreterSetting.getInterpreterGroup("user1", "note2").size());
interpreterSetting.closeAndRemoveInterpreterGroup("note1", "user1");
assertEquals(1, interpreterSetting.getInterpreterGroup("user1","note2").size());
// Check if non-existed key works or not
interpreterSetting.closeAndRemoveInterpreterGroup("note1", "user1");
assertEquals(1, interpreterSetting.getInterpreterGroup("user1","note2").size());
interpreterSetting.closeAndRemoveInterpreterGroup("note2", "user1");
assertEquals(0, interpreterSetting.getAllInterpreterGroups().size());
}
@Test
public void perNoteIsolatedModeCloseAndRemoveInterpreterGroupTest() {
InterpreterOption interpreterOption = new InterpreterOption();
interpreterOption.setPerNote(InterpreterOption.ISOLATED);
InterpreterSetting interpreterSetting = new InterpreterSetting("", "", "", new ArrayList<InterpreterInfo>(), new Properties(), new ArrayList<Dependency>(), interpreterOption, "", null);
interpreterSetting.setInterpreterGroupFactory(new InterpreterGroupFactory() {
@Override
public InterpreterGroup createInterpreterGroup(String interpreterGroupId,
InterpreterOption option) {
return new InterpreterGroup(interpreterGroupId);
}
});
Interpreter mockInterpreter1 = mock(RemoteInterpreter.class);
List<Interpreter> interpreterList1 = new ArrayList<>();
interpreterList1.add(mockInterpreter1);
InterpreterGroup interpreterGroup = interpreterSetting.getInterpreterGroup("user1", "note1");
interpreterGroup.put(interpreterSetting.getInterpreterSessionKey("user1", "note1"), interpreterList1);
Interpreter mockInterpreter2 = mock(RemoteInterpreter.class);
List<Interpreter> interpreterList2 = new ArrayList<>();
interpreterList2.add(mockInterpreter2);
interpreterGroup = interpreterSetting.getInterpreterGroup("user1", "note2");
interpreterGroup.put(interpreterSetting.getInterpreterSessionKey("user1", "note2"), interpreterList2);
assertEquals(2, interpreterSetting.getAllInterpreterGroups().size());
assertEquals(1, interpreterSetting.getInterpreterGroup("user1", "note1").size());
assertEquals(1, interpreterSetting.getInterpreterGroup("user1", "note2").size());
interpreterSetting.closeAndRemoveInterpreterGroup("note1", "user1");
assertEquals(1, interpreterSetting.getInterpreterGroup("user1","note2").size());
assertEquals(1, interpreterSetting.getAllInterpreterGroups().size());
interpreterSetting.closeAndRemoveInterpreterGroup("note2", "user1");
assertEquals(0, interpreterSetting.getAllInterpreterGroups().size());
}
@Test
public void perNoteScopedModeRemoveInterpreterGroupWhenNoteIsRemoved() {
InterpreterOption interpreterOption = new InterpreterOption();
interpreterOption.setPerNote(InterpreterOption.SCOPED);
InterpreterSetting interpreterSetting = new InterpreterSetting("", "", "", new ArrayList<InterpreterInfo>(), new Properties(), new ArrayList<Dependency>(), interpreterOption, "", null);
interpreterSetting.setInterpreterGroupFactory(new InterpreterGroupFactory() {
@Override
public InterpreterGroup createInterpreterGroup(String interpreterGroupId,
InterpreterOption option) {
return new InterpreterGroup(interpreterGroupId);
}
});
Interpreter mockInterpreter1 = mock(RemoteInterpreter.class);
List<Interpreter> interpreterList1 = new ArrayList<>();
interpreterList1.add(mockInterpreter1);
InterpreterGroup interpreterGroup = interpreterSetting.getInterpreterGroup("user1", "note1");
interpreterGroup.put(interpreterSetting.getInterpreterSessionKey("user1", "note1"), interpreterList1);
assertEquals(1, interpreterSetting.getAllInterpreterGroups().size());
assertEquals(1, interpreterSetting.getInterpreterGroup("user1", "note1").size());
// This method will be called when remove note
interpreterSetting.closeAndRemoveInterpreterGroup("note1","");
assertEquals(0, interpreterSetting.getAllInterpreterGroups().size());
// Be careful that getInterpreterGroup makes interpreterGroup if it doesn't exist
assertEquals(0, interpreterSetting.getInterpreterGroup("user1","note1").size());
}
@Test
public void perNoteIsolatedModeRemoveInterpreterGroupWhenNoteIsRemoved() {
InterpreterOption interpreterOption = new InterpreterOption();
interpreterOption.setPerNote(InterpreterOption.ISOLATED);
InterpreterSetting interpreterSetting = new InterpreterSetting("", "", "", new ArrayList<InterpreterInfo>(), new Properties(), new ArrayList<Dependency>(), interpreterOption, "", null);
interpreterSetting.setInterpreterGroupFactory(new InterpreterGroupFactory() {
@Override
public InterpreterGroup createInterpreterGroup(String interpreterGroupId,
InterpreterOption option) {
return new InterpreterGroup(interpreterGroupId);
}
});
Interpreter mockInterpreter1 = mock(RemoteInterpreter.class);
List<Interpreter> interpreterList1 = new ArrayList<>();
interpreterList1.add(mockInterpreter1);
InterpreterGroup interpreterGroup = interpreterSetting.getInterpreterGroup("user1", "note1");
interpreterGroup.put(interpreterSetting.getInterpreterSessionKey("user1", "note1"), interpreterList1);
assertEquals(1, interpreterSetting.getAllInterpreterGroups().size());
assertEquals(1, interpreterSetting.getInterpreterGroup("user1", "note1").size());
// This method will be called when remove note
interpreterSetting.closeAndRemoveInterpreterGroup("note1","");
assertEquals(0, interpreterSetting.getAllInterpreterGroups().size());
// Be careful that getInterpreterGroup makes interpreterGroup if it doesn't exist
assertEquals(0, interpreterSetting.getInterpreterGroup("user1","note1").size());
}
@Test
public void perUserScopedModeNeverRemoveInterpreterGroupWhenNoteIsRemoved() {
InterpreterOption interpreterOption = new InterpreterOption();
interpreterOption.setPerUser(InterpreterOption.SCOPED);
InterpreterSetting interpreterSetting = new InterpreterSetting("", "", "", new ArrayList<InterpreterInfo>(), new Properties(), new ArrayList<Dependency>(), interpreterOption, "", null);
interpreterSetting.setInterpreterGroupFactory(new InterpreterGroupFactory() {
@Override
public InterpreterGroup createInterpreterGroup(String interpreterGroupId,
InterpreterOption option) {
return new InterpreterGroup(interpreterGroupId);
}
});
Interpreter mockInterpreter1 = mock(RemoteInterpreter.class);
List<Interpreter> interpreterList1 = new ArrayList<>();
interpreterList1.add(mockInterpreter1);
InterpreterGroup interpreterGroup = interpreterSetting.getInterpreterGroup("user1", "note1");
interpreterGroup.put(interpreterSetting.getInterpreterSessionKey("user1", "note1"), interpreterList1);
assertEquals(1, interpreterSetting.getAllInterpreterGroups().size());
assertEquals(1, interpreterSetting.getInterpreterGroup("user1", "note1").size());
// This method will be called when remove note
interpreterSetting.closeAndRemoveInterpreterGroup("note1","");
assertEquals(1, interpreterSetting.getAllInterpreterGroups().size());
// Be careful that getInterpreterGroup makes interpreterGroup if it doesn't exist
assertEquals(1, interpreterSetting.getInterpreterGroup("user1","note1").size());
}
@Test
public void perUserIsolatedModeNeverRemoveInterpreterGroupWhenNoteIsRemoved() {
InterpreterOption interpreterOption = new InterpreterOption();
interpreterOption.setPerUser(InterpreterOption.ISOLATED);
InterpreterSetting interpreterSetting = new InterpreterSetting("", "", "", new ArrayList<InterpreterInfo>(), new Properties(), new ArrayList<Dependency>(), interpreterOption, "", null);
interpreterSetting.setInterpreterGroupFactory(new InterpreterGroupFactory() {
@Override
public InterpreterGroup createInterpreterGroup(String interpreterGroupId,
InterpreterOption option) {
return new InterpreterGroup(interpreterGroupId);
}
});
Interpreter mockInterpreter1 = mock(RemoteInterpreter.class);
List<Interpreter> interpreterList1 = new ArrayList<>();
interpreterList1.add(mockInterpreter1);
InterpreterGroup interpreterGroup = interpreterSetting.getInterpreterGroup("user1", "note1");
interpreterGroup.put(interpreterSetting.getInterpreterSessionKey("user1", "note1"), interpreterList1);
assertEquals(1, interpreterSetting.getAllInterpreterGroups().size());
assertEquals(1, interpreterSetting.getInterpreterGroup("user1", "note1").size());
// This method will be called when remove note
interpreterSetting.closeAndRemoveInterpreterGroup("note1","");
assertEquals(1, interpreterSetting.getAllInterpreterGroups().size());
// Be careful that getInterpreterGroup makes interpreterGroup if it doesn't exist
assertEquals(1, interpreterSetting.getInterpreterGroup("user1","note1").size());
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/interpreter/mock/MockInterpreter1.java | smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/interpreter/mock/MockInterpreter1.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.interpreter.mock;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.zeppelin.interpreter.Interpreter;
import org.apache.zeppelin.interpreter.InterpreterContext;
import org.apache.zeppelin.interpreter.InterpreterResult;
import org.apache.zeppelin.interpreter.thrift.InterpreterCompletion;
import org.apache.zeppelin.scheduler.Scheduler;
import org.apache.zeppelin.scheduler.SchedulerFactory;
public class MockInterpreter1 extends Interpreter{
Map<String, Object> vars = new HashMap<>();
public MockInterpreter1(Properties property) {
super(property);
}
boolean open;
@Override
public void open() {
open = true;
}
@Override
public void close() {
open = false;
}
public boolean isOpen() {
return open;
}
@Override
public InterpreterResult interpret(String st, InterpreterContext context) {
InterpreterResult result;
if ("getId".equals(st)) {
// get unique id of this interpreter instance
result = new InterpreterResult(InterpreterResult.Code.SUCCESS, "" + this.hashCode());
} else if (st.startsWith("sleep")) {
try {
Thread.sleep(Integer.parseInt(st.split(" ")[1]));
} catch (InterruptedException e) {
// nothing to do
}
result = new InterpreterResult(InterpreterResult.Code.SUCCESS, "repl1: " + st);
} else {
result = new InterpreterResult(InterpreterResult.Code.SUCCESS, "repl1: " + st);
}
if (context.getResourcePool() != null) {
context.getResourcePool().put(context.getNoteId(), context.getParagraphId(), "result", result);
}
return result;
}
@Override
public void cancel(InterpreterContext context) {
}
@Override
public FormType getFormType() {
return FormType.SIMPLE;
}
@Override
public int getProgress(InterpreterContext context) {
return 0;
}
@Override
public Scheduler getScheduler() {
return SchedulerFactory.singleton().createOrGetFIFOScheduler("test_"+this.hashCode());
}
@Override
public List<InterpreterCompletion> completion(String buf, int cursor) {
return null;
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/interpreter/mock/MockInterpreter11.java | smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/interpreter/mock/MockInterpreter11.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.interpreter.mock;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.zeppelin.interpreter.Interpreter;
import org.apache.zeppelin.interpreter.InterpreterContext;
import org.apache.zeppelin.interpreter.InterpreterResult;
import org.apache.zeppelin.interpreter.thrift.InterpreterCompletion;
import org.apache.zeppelin.scheduler.Scheduler;
import org.apache.zeppelin.scheduler.SchedulerFactory;
public class MockInterpreter11 extends Interpreter{
Map<String, Object> vars = new HashMap<>();
public MockInterpreter11(Properties property) {
super(property);
}
boolean open;
@Override
public void open() {
open = true;
}
@Override
public void close() {
open = false;
}
public boolean isOpen() {
return open;
}
@Override
public InterpreterResult interpret(String st, InterpreterContext context) {
return new InterpreterResult(InterpreterResult.Code.SUCCESS, "repl11: "+st);
}
@Override
public void cancel(InterpreterContext context) {
}
@Override
public FormType getFormType() {
return FormType.SIMPLE;
}
@Override
public int getProgress(InterpreterContext context) {
return 0;
}
@Override
public Scheduler getScheduler() {
return SchedulerFactory.singleton().createOrGetFIFOScheduler("test_"+this.hashCode());
}
@Override
public List<InterpreterCompletion> completion(String buf, int cursor) {
return null;
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/interpreter/mock/MockInterpreter2.java | smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/interpreter/mock/MockInterpreter2.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.interpreter.mock;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.zeppelin.interpreter.Interpreter;
import org.apache.zeppelin.interpreter.InterpreterContext;
import org.apache.zeppelin.interpreter.InterpreterResult;
import org.apache.zeppelin.interpreter.thrift.InterpreterCompletion;
import org.apache.zeppelin.scheduler.Scheduler;
import org.apache.zeppelin.scheduler.SchedulerFactory;
public class MockInterpreter2 extends Interpreter{
Map<String, Object> vars = new HashMap<>();
public MockInterpreter2(Properties property) {
super(property);
}
boolean open;
@Override
public void open() {
open = true;
}
@Override
public void close() {
open = false;
}
public boolean isOpen() {
return open;
}
@Override
public InterpreterResult interpret(String st, InterpreterContext context) {
InterpreterResult result;
if ("getId".equals(st)) {
// get unique id of this interpreter instance
result = new InterpreterResult(InterpreterResult.Code.SUCCESS, "" + this.hashCode());
} else if (st.startsWith("sleep")) {
try {
Thread.sleep(Integer.parseInt(st.split(" ")[1]));
} catch (InterruptedException e) {
// nothing to do
}
result = new InterpreterResult(InterpreterResult.Code.SUCCESS, "repl2: " + st);
} else {
result = new InterpreterResult(InterpreterResult.Code.SUCCESS, "repl2: " + st);
}
if (context.getResourcePool() != null) {
context.getResourcePool().put(context.getNoteId(), context.getParagraphId(), "result", result);
}
return result;
}
@Override
public void cancel(InterpreterContext context) {
}
@Override
public FormType getFormType() {
return FormType.SIMPLE;
}
@Override
public int getProgress(InterpreterContext context) {
return 0;
}
@Override
public Scheduler getScheduler() {
return SchedulerFactory.singleton().createOrGetFIFOScheduler("test_"+this.hashCode());
}
@Override
public List<InterpreterCompletion> completion(String buf, int cursor) {
return null;
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/interpreter/install/InstallInterpreterTest.java | smart-zeppelin/zeppelin-zengine/src/test/java/org/apache/zeppelin/interpreter/install/InstallInterpreterTest.java | package org.apache.zeppelin.interpreter.install;
import org.apache.commons.io.FileUtils;
import org.apache.zeppelin.conf.ZeppelinConfiguration;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.
*/
public class InstallInterpreterTest {
private File tmpDir;
private InstallInterpreter installer;
private File interpreterBaseDir;
@Before
public void setUp() throws IOException {
tmpDir = new File(System.getProperty("java.io.tmpdir")+"/ZeppelinLTest_"+System.currentTimeMillis());
new File(tmpDir, "conf").mkdirs();
interpreterBaseDir = new File(tmpDir, "interpreter");
File localRepoDir = new File(tmpDir, "local-repo");
interpreterBaseDir.mkdir();
localRepoDir.mkdir();
File interpreterListFile = new File(tmpDir, "conf/interpreter-list");
// create interpreter list file
System.setProperty(ZeppelinConfiguration.ConfVars.ZEPPELIN_HOME.getVarName(), tmpDir.getAbsolutePath());
String interpreterList = "";
interpreterList += "intp1 org.apache.commons:commons-csv:1.1 test interpreter 1\n";
interpreterList += "intp2 org.apache.commons:commons-math3:3.6.1 test interpreter 2\n";
FileUtils.writeStringToFile(new File(tmpDir, "conf/interpreter-list"), interpreterList);
installer = new InstallInterpreter(interpreterListFile, interpreterBaseDir, localRepoDir
.getAbsolutePath());
}
@After
public void tearDown() throws IOException {
FileUtils.deleteDirectory(tmpDir);
}
@Test
public void testList() {
assertEquals(2, installer.list().size());
}
@Test
public void install() {
assertEquals(0, interpreterBaseDir.listFiles().length);
installer.install("intp1");
assertTrue(new File(interpreterBaseDir, "intp1").isDirectory());
}
@Test
public void installAll() {
installer.installAll();
assertTrue(new File(interpreterBaseDir, "intp1").isDirectory());
assertTrue(new File(interpreterBaseDir, "intp2").isDirectory());
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/util/WatcherSecurityKey.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/util/WatcherSecurityKey.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.util;
import java.util.UUID;
/**
* Simple implementation of a auto-generated key for websocket watcher.
* This is a LAZY implementation, we might want to update this later on :)
*/
public class WatcherSecurityKey {
public static final String HTTP_HEADER = "X-Watcher-Key";
private static final String KEY = UUID.randomUUID().toString();
protected WatcherSecurityKey() {}
public static String getKey() {
return KEY;
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/util/Util.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/util/Util.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.util;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
import java.util.Properties;
/**
* TODO(moon) : add description.
*/
public class Util {
private static final String PROJECT_PROPERTIES_VERSION_KEY = "version";
private static Properties projectProperties;
static {
projectProperties = new Properties();
try {
projectProperties.load(Util.class.getResourceAsStream("/project.properties"));
} catch (IOException e) {
//Fail to read project.properties
}
}
/**
* Get Zeppelin version
*
* @return Current Zeppelin version
*/
public static String getVersion() {
return StringUtils.defaultIfEmpty(projectProperties.getProperty(PROJECT_PROPERTIES_VERSION_KEY),
StringUtils.EMPTY);
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/helium/HeliumLocalRegistry.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/helium/HeliumLocalRegistry.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.helium;
import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.net.URI;
import java.util.LinkedList;
import java.util.List;
/**
* Simple Helium registry on local filesystem
*/
public class HeliumLocalRegistry extends HeliumRegistry {
Logger logger = LoggerFactory.getLogger(HeliumLocalRegistry.class);
private final Gson gson;
public HeliumLocalRegistry(String name, String uri) {
super(name, uri);
gson = new Gson();
}
@Override
public synchronized List<HeliumPackage> getAll() throws IOException {
List<HeliumPackage> result = new LinkedList<>();
File file = new File(uri());
File [] files = file.listFiles();
if (files == null) {
return result;
}
for (File f : files) {
if (f.getName().startsWith(".")) {
continue;
}
HeliumPackage pkgInfo = readPackageInfo(f);
if (pkgInfo != null) {
result.add(pkgInfo);
}
}
return result;
}
private HeliumPackage readPackageInfo(File f) {
try {
JsonReader reader = new JsonReader(new StringReader(FileUtils.readFileToString(f)));
reader.setLenient(true);
return gson.fromJson(reader, HeliumPackage.class);
} catch (IOException e) {
logger.error(e.getMessage(), e);
return null;
}
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/helium/HeliumConf.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/helium/HeliumConf.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.helium;
import java.util.*;
/**
* Helium config. This object will be persisted to conf/heliumc.conf
*/
public class HeliumConf {
List<HeliumRegistry> registry = new LinkedList<>();
// enabled packages {name, version}
Map<String, String> enabled = Collections.synchronizedMap(new HashMap<String, String>());
// enabled visualization package display order
List<String> visualizationDisplayOrder = new LinkedList<>();
public List<HeliumRegistry> getRegistry() {
return registry;
}
public void setRegistry(List<HeliumRegistry> registry) {
this.registry = registry;
}
public Map<String, String> getEnabledPackages() {
return new HashMap<>(enabled);
}
public void enablePackage(HeliumPackage pkg) {
enablePackage(pkg.getName(), pkg.getArtifact());
}
public void enablePackage(String name, String artifact) {
enabled.put(name, artifact);
}
public void disablePackage(HeliumPackage pkg) {
disablePackage(pkg.getName());
}
public void disablePackage(String name) {
enabled.remove(name);
}
public List<String> getVisualizationDisplayOrder() {
if (visualizationDisplayOrder == null) {
return new LinkedList<String>();
} else {
return visualizationDisplayOrder;
}
}
public void setVisualizationDisplayOrder(List<String> orderedPackageList) {
visualizationDisplayOrder = orderedPackageList;
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/helium/HeliumPackageSearchResult.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/helium/HeliumPackageSearchResult.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.helium;
/**
* search result
*/
public class HeliumPackageSearchResult {
private final String registry;
private final HeliumPackage pkg;
private final boolean enabled;
/**
* Create search result item
* @param registry registry name
* @param pkg package information
*/
public HeliumPackageSearchResult(String registry, HeliumPackage pkg, boolean enabled) {
this.registry = registry;
this.pkg = pkg;
this.enabled = enabled;
}
public String getRegistry() {
return registry;
}
public HeliumPackage getPkg() {
return pkg;
}
public boolean isEnabled() {
return enabled;
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/helium/WebpackResult.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/helium/WebpackResult.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.helium;
/**
* Represetns webpack json format result
*/
public class WebpackResult {
public final String [] errors = new String[0];
public final String [] warnings = new String[0];
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/helium/HeliumVisualizationFactory.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/helium/HeliumVisualizationFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.helium;
import com.github.eirslett.maven.plugins.frontend.lib.*;
import com.google.common.base.Charsets;
import com.google.common.io.Resources;
import com.google.gson.Gson;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Appender;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.WriterAppender;
import org.apache.log4j.spi.Filter;
import org.apache.log4j.spi.LoggingEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.URI;
import java.net.URL;
import java.util.*;
import org.apache.zeppelin.conf.ZeppelinConfiguration;
/**
* Load helium visualization
*/
public class HeliumVisualizationFactory {
Logger logger = LoggerFactory.getLogger(HeliumVisualizationFactory.class);
private final String NODE_VERSION = "v6.9.1";
private final String NPM_VERSION = "3.10.8";
private final int FETCH_RETRY_COUNT = 2;
private final int FETCH_RETRY_FACTOR_COUNT = 1;
// Milliseconds
private final int FETCH_RETRY_MIN_TIMEOUT = 5000;
private final FrontendPluginFactory frontEndPluginFactory;
private final File workingDirectory;
private ZeppelinConfiguration conf;
private File tabledataModulePath;
private File visualizationModulePath;
private String defaultNodeRegistryUrl;
private String defaultNpmRegistryUrl;
private Gson gson;
private boolean nodeAndNpmInstalled = false;
String bundleCacheKey = "";
File currentBundle;
ByteArrayOutputStream out = new ByteArrayOutputStream();
public HeliumVisualizationFactory(
ZeppelinConfiguration conf,
File moduleDownloadPath,
File tabledataModulePath,
File visualizationModulePath) throws TaskRunnerException {
this(conf, moduleDownloadPath);
this.tabledataModulePath = tabledataModulePath;
this.visualizationModulePath = visualizationModulePath;
}
public HeliumVisualizationFactory(
ZeppelinConfiguration conf,
File moduleDownloadPath) throws TaskRunnerException {
this.workingDirectory = new File(moduleDownloadPath, "vis");
this.conf = conf;
this.defaultNodeRegistryUrl = "https://nodejs.org/dist/";
this.defaultNpmRegistryUrl = conf.getHeliumNpmRegistry();
File installDirectory = workingDirectory;
frontEndPluginFactory = new FrontendPluginFactory(
workingDirectory, installDirectory);
currentBundle = new File(workingDirectory, "vis.bundle.cache.js");
gson = new Gson();
}
void installNodeAndNpm() {
if (nodeAndNpmInstalled) {
return;
}
try {
NPMInstaller npmInstaller = frontEndPluginFactory
.getNPMInstaller(getProxyConfig(isSecure(defaultNpmRegistryUrl)));
npmInstaller.setNpmVersion(NPM_VERSION);
npmInstaller.install();
NodeInstaller nodeInstaller = frontEndPluginFactory
.getNodeInstaller(getProxyConfig(isSecure(defaultNodeRegistryUrl)));
nodeInstaller.setNodeVersion(NODE_VERSION);
nodeInstaller.install();
configureLogger();
nodeAndNpmInstalled = true;
} catch (InstallationException e) {
logger.error(e.getMessage(), e);
}
}
private ProxyConfig getProxyConfig(boolean isSecure) {
List<ProxyConfig.Proxy> proxies = new LinkedList<>();
String httpProxy = StringUtils.isBlank(System.getenv("http_proxy")) ?
System.getenv("HTTP_PROXY") : System.getenv("http_proxy");
String httpsProxy = StringUtils.isBlank(System.getenv("https_proxy")) ?
System.getenv("HTTPS_PROXY") : System.getenv("https_proxy");
try {
if (isSecure && StringUtils.isNotBlank(httpsProxy))
proxies.add(generateProxy("secure", new URI(httpsProxy)));
else if (!isSecure && StringUtils.isNotBlank(httpsProxy))
proxies.add(generateProxy("insecure", new URI(httpProxy)));
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
}
return new ProxyConfig(proxies);
}
private ProxyConfig.Proxy generateProxy(String proxyId, URI uri) {
String protocol = uri.getScheme();
String host = uri.getHost();
int port = uri.getPort() <= 0 ? 80 : uri.getPort();
String username = null, password = null;
if (uri.getUserInfo() != null) {
String[] authority = uri.getUserInfo().split(":");
if (authority.length == 2) {
username = authority[0];
password = authority[1];
} else if (authority.length == 1) {
username = authority[0];
}
}
String nonProxyHosts = StringUtils.isBlank(System.getenv("no_proxy")) ?
System.getenv("NO_PROXY") : System.getenv("no_proxy");
return new ProxyConfig.Proxy(proxyId, protocol, host, port, username, password, nonProxyHosts);
}
private boolean isSecure(String url) {
return url.toLowerCase().startsWith("https");
}
public File bundle(List<HeliumPackage> pkgs) throws IOException {
return bundle(pkgs, false);
}
public synchronized File bundle(List<HeliumPackage> pkgs, boolean forceRefresh)
throws IOException {
if (pkgs == null || pkgs.size() == 0) {
// when no package is selected, simply return an empty file instead of try bundle package
synchronized (this) {
currentBundle.getParentFile().mkdirs();
currentBundle.delete();
currentBundle.createNewFile();
bundleCacheKey = "";
return currentBundle;
}
}
installNodeAndNpm();
// package.json
URL pkgUrl = Resources.getResource("helium/package.json");
String pkgJson = Resources.toString(pkgUrl, Charsets.UTF_8);
StringBuilder dependencies = new StringBuilder();
StringBuilder cacheKeyBuilder = new StringBuilder();
FileFilter npmPackageCopyFilter = new FileFilter() {
@Override
public boolean accept(File pathname) {
String fileName = pathname.getName();
if (fileName.startsWith(".") || fileName.startsWith("#") || fileName.startsWith("~")) {
return false;
} else {
return true;
}
}
};
for (HeliumPackage pkg : pkgs) {
String[] moduleNameVersion = getNpmModuleNameAndVersion(pkg);
if (moduleNameVersion == null) {
logger.error("Can't get module name and version of package " + pkg.getName());
continue;
}
if (dependencies.length() > 0) {
dependencies.append(",\n");
}
dependencies.append("\"" + moduleNameVersion[0] + "\": \"" + moduleNameVersion[1] + "\"");
cacheKeyBuilder.append(pkg.getName() + pkg.getArtifact());
File pkgInstallDir = new File(workingDirectory, "node_modules/" + pkg.getName());
if (pkgInstallDir.exists()) {
FileUtils.deleteDirectory(pkgInstallDir);
}
if (isLocalPackage(pkg)) {
FileUtils.copyDirectory(
new File(pkg.getArtifact()),
pkgInstallDir,
npmPackageCopyFilter);
}
}
pkgJson = pkgJson.replaceFirst("DEPENDENCIES", dependencies.toString());
// check if we can use previous bundle or not
if (cacheKeyBuilder.toString().equals(bundleCacheKey)
&& currentBundle.isFile() && !forceRefresh) {
return currentBundle;
}
// webpack.config.js
URL webpackConfigUrl = Resources.getResource("helium/webpack.config.js");
String webpackConfig = Resources.toString(webpackConfigUrl, Charsets.UTF_8);
// generate load.js
StringBuilder loadJsImport = new StringBuilder();
StringBuilder loadJsRegister = new StringBuilder();
long idx = 0;
for (HeliumPackage pkg : pkgs) {
String[] moduleNameVersion = getNpmModuleNameAndVersion(pkg);
if (moduleNameVersion == null) {
continue;
}
String className = "vis" + idx++;
loadJsImport.append(
"import " + className + " from \"" + moduleNameVersion[0] + "\"\n");
loadJsRegister.append("visualizations.push({\n");
loadJsRegister.append("id: \"" + moduleNameVersion[0] + "\",\n");
loadJsRegister.append("name: \"" + pkg.getName() + "\",\n");
loadJsRegister.append("icon: " + gson.toJson(pkg.getIcon()) + ",\n");
loadJsRegister.append("class: " + className + "\n");
loadJsRegister.append("})\n");
}
FileUtils.write(new File(workingDirectory, "package.json"), pkgJson);
FileUtils.write(new File(workingDirectory, "webpack.config.js"), webpackConfig);
FileUtils.write(new File(workingDirectory, "load.js"),
loadJsImport.append(loadJsRegister).toString());
// install tabledata module
File tabledataModuleInstallPath = new File(workingDirectory,
"node_modules/zeppelin-tabledata");
if (tabledataModulePath != null) {
if (tabledataModuleInstallPath.exists()) {
FileUtils.deleteDirectory(tabledataModuleInstallPath);
}
FileUtils.copyDirectory(
tabledataModulePath,
tabledataModuleInstallPath,
npmPackageCopyFilter);
}
// install visualization module
File visModuleInstallPath = new File(workingDirectory,
"node_modules/zeppelin-vis");
if (visualizationModulePath != null) {
if (visModuleInstallPath.exists()) {
// when zeppelin-vis and zeppelin-table package is published to npm repository
// we don't need to remove module because npm install cmdlet will take care
// dependency version change. However, when two dependencies are copied manually
// into node_modules directory, changing vis package version results inconsistent npm
// install behavior.
//
// Remote vis package everytime and let npm download every time bundle as a workaround
FileUtils.deleteDirectory(visModuleInstallPath);
}
FileUtils.copyDirectory(visualizationModulePath, visModuleInstallPath, npmPackageCopyFilter);
}
out.reset();
try {
String commandForNpmInstall =
String.format("install --fetch-retries=%d --fetch-retry-factor=%d " +
"--fetch-retry-mintimeout=%d",
FETCH_RETRY_COUNT, FETCH_RETRY_FACTOR_COUNT, FETCH_RETRY_MIN_TIMEOUT);
npmCommand(commandForNpmInstall);
npmCommand("run bundle");
} catch (TaskRunnerException e) {
throw new IOException(new String(out.toByteArray()));
}
File visBundleJs = new File(workingDirectory, "vis.bundle.js");
if (!visBundleJs.isFile()) {
throw new IOException(
"Can't create visualization bundle : \n" + new String(out.toByteArray()));
}
WebpackResult result = getWebpackResultFromOutput(new String(out.toByteArray()));
if (result.errors.length > 0) {
visBundleJs.delete();
throw new IOException(result.errors[0]);
}
synchronized (this) {
currentBundle.delete();
FileUtils.moveFile(visBundleJs, currentBundle);
bundleCacheKey = cacheKeyBuilder.toString();
}
return currentBundle;
}
private WebpackResult getWebpackResultFromOutput(String output) {
BufferedReader reader = new BufferedReader(new StringReader(output));
String line;
boolean webpackRunDetected = false;
boolean resultJsonDetected = false;
StringBuffer sb = new StringBuffer();
try {
while ((line = reader.readLine()) != null) {
if (!webpackRunDetected) {
if (line.contains("webpack.js") && line.endsWith("--json")) {
webpackRunDetected = true;
}
continue;
}
if (!resultJsonDetected) {
if (line.equals("{")) {
sb.append(line);
resultJsonDetected = true;
}
continue;
}
if (resultJsonDetected && webpackRunDetected) {
sb.append(line);
}
}
Gson gson = new Gson();
return gson.fromJson(sb.toString(), WebpackResult.class);
} catch (IOException e) {
logger.error(e.getMessage(), e);
return new WebpackResult();
}
}
public File getCurrentBundle() {
synchronized (this) {
if (currentBundle.isFile()) {
return currentBundle;
} else {
return null;
}
}
}
private boolean isLocalPackage(HeliumPackage pkg) {
return (pkg.getArtifact().startsWith(".") || pkg.getArtifact().startsWith("/"));
}
private String[] getNpmModuleNameAndVersion(HeliumPackage pkg) {
String artifact = pkg.getArtifact();
if (isLocalPackage(pkg)) {
File packageJson = new File(artifact, "package.json");
if (!packageJson.isFile()) {
return null;
}
Gson gson = new Gson();
try {
NpmPackage npmPackage = gson.fromJson(
FileUtils.readFileToString(packageJson),
NpmPackage.class);
String[] nameVersion = new String[2];
nameVersion[0] = npmPackage.name;
nameVersion[1] = npmPackage.version;
return nameVersion;
} catch (IOException e) {
logger.error(e.getMessage(), e);
return null;
}
} else {
String[] nameVersion = new String[2];
int pos;
if ((pos = artifact.indexOf('@')) > 0) {
nameVersion[0] = artifact.substring(0, pos);
nameVersion[1] = artifact.substring(pos + 1);
} else if (
(pos = artifact.indexOf('^')) > 0 ||
(pos = artifact.indexOf('~')) > 0) {
nameVersion[0] = artifact.substring(0, pos);
nameVersion[1] = artifact.substring(pos);
} else {
nameVersion[0] = artifact;
nameVersion[1] = "";
}
return nameVersion;
}
}
synchronized void install(HeliumPackage pkg) throws TaskRunnerException {
String commandForNpmInstallArtifact =
String.format("install %s --fetch-retries=%d --fetch-retry-factor=%d " +
"--fetch-retry-mintimeout=%d", pkg.getArtifact(),
FETCH_RETRY_COUNT, FETCH_RETRY_FACTOR_COUNT, FETCH_RETRY_MIN_TIMEOUT);
npmCommand(commandForNpmInstallArtifact);
}
private void npmCommand(String args) throws TaskRunnerException {
npmCommand(args, new HashMap<String, String>());
}
private void npmCommand(String args, Map<String, String> env) throws TaskRunnerException {
installNodeAndNpm();
NpmRunner npm = frontEndPluginFactory.getNpmRunner(
getProxyConfig(isSecure(defaultNpmRegistryUrl)), defaultNpmRegistryUrl);
npm.execute(args, env);
}
private void configureLogger() {
org.apache.log4j.Logger npmLogger = org.apache.log4j.Logger.getLogger(
"com.github.eirslett.maven.plugins.frontend.lib.DefaultNpmRunner");
Enumeration appenders = org.apache.log4j.Logger.getRootLogger().getAllAppenders();
if (appenders != null) {
while (appenders.hasMoreElements()) {
Appender appender = (Appender) appenders.nextElement();
appender.addFilter(new Filter() {
@Override
public int decide(LoggingEvent loggingEvent) {
if (loggingEvent.getLoggerName().contains("DefaultNpmRunner")) {
return DENY;
} else {
return NEUTRAL;
}
}
});
}
}
npmLogger.addAppender(new WriterAppender(
new PatternLayout("%m%n"),
out
));
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/helium/HeliumApplicationFactory.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/helium/HeliumApplicationFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.helium;
import com.google.gson.Gson;
import org.apache.thrift.TException;
import org.apache.zeppelin.interpreter.*;
import org.apache.zeppelin.interpreter.remote.RemoteAngularObjectRegistry;
import org.apache.zeppelin.interpreter.remote.RemoteInterpreterProcess;
import org.apache.zeppelin.interpreter.thrift.RemoteApplicationResult;
import org.apache.zeppelin.interpreter.thrift.RemoteInterpreterService;
import org.apache.zeppelin.notebook.*;
import org.apache.zeppelin.scheduler.ExecutorFactory;
import org.apache.zeppelin.scheduler.Job;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.concurrent.ExecutorService;
/**
* HeliumApplicationFactory
*/
public class HeliumApplicationFactory implements ApplicationEventListener, NotebookEventListener {
private final Logger logger = LoggerFactory.getLogger(HeliumApplicationFactory.class);
private final ExecutorService executor;
private final Gson gson = new Gson();
private Notebook notebook;
private ApplicationEventListener applicationEventListener;
public HeliumApplicationFactory() {
executor = ExecutorFactory.singleton().createOrGet(
HeliumApplicationFactory.class.getName(), 10);
}
private boolean isRemote(InterpreterGroup group) {
return group.getAngularObjectRegistry() instanceof RemoteAngularObjectRegistry;
}
/**
* Load pkg and run task
*/
public String loadAndRun(HeliumPackage pkg, Paragraph paragraph) {
ApplicationState appState = paragraph.createOrGetApplicationState(pkg);
onLoad(paragraph.getNote().getId(), paragraph.getId(), appState.getId(),
appState.getHeliumPackage());
executor.submit(new LoadApplication(appState, pkg, paragraph));
return appState.getId();
}
/**
* Load application and run in the remote process
*/
private class LoadApplication implements Runnable {
private final HeliumPackage pkg;
private final Paragraph paragraph;
private final ApplicationState appState;
public LoadApplication(ApplicationState appState, HeliumPackage pkg, Paragraph paragraph) {
this.appState = appState;
this.pkg = pkg;
this.paragraph = paragraph;
}
@Override
public void run() {
try {
// get interpreter process
Interpreter intp = paragraph.getRepl(paragraph.getRequiredReplName());
InterpreterGroup intpGroup = intp.getInterpreterGroup();
RemoteInterpreterProcess intpProcess = intpGroup.getRemoteInterpreterProcess();
if (intpProcess == null) {
throw new ApplicationException("Target interpreter process is not running");
}
// load application
load(intpProcess, appState);
// run application
RunApplication runTask = new RunApplication(paragraph, appState.getId());
runTask.run();
} catch (Exception e) {
logger.error(e.getMessage(), e);
if (appState != null) {
appStatusChange(paragraph, appState.getId(), ApplicationState.Status.ERROR);
appState.setOutput(e.getMessage());
}
}
}
private void load(RemoteInterpreterProcess intpProcess, ApplicationState appState)
throws Exception {
RemoteInterpreterService.Client client = null;
synchronized (appState) {
if (appState.getStatus() == ApplicationState.Status.LOADED) {
// already loaded
return;
}
try {
appStatusChange(paragraph, appState.getId(), ApplicationState.Status.LOADING);
String pkgInfo = gson.toJson(pkg);
String appId = appState.getId();
client = intpProcess.getClient();
RemoteApplicationResult ret = client.loadApplication(
appId,
pkgInfo,
paragraph.getNote().getId(),
paragraph.getId());
if (ret.isSuccess()) {
appStatusChange(paragraph, appState.getId(), ApplicationState.Status.LOADED);
} else {
throw new ApplicationException(ret.getMsg());
}
} catch (TException e) {
intpProcess.releaseBrokenClient(client);
throw e;
} finally {
if (client != null) {
intpProcess.releaseClient(client);
}
}
}
}
}
/**
* Get ApplicationState
* @param paragraph
* @param appId
* @return
*/
public ApplicationState get(Paragraph paragraph, String appId) {
return paragraph.getApplicationState(appId);
}
/**
* Unload application
* It does not remove ApplicationState
*
* @param paragraph
* @param appId
*/
public void unload(Paragraph paragraph, String appId) {
executor.execute(new UnloadApplication(paragraph, appId));
}
/**
* Unload application task
*/
private class UnloadApplication implements Runnable {
private final Paragraph paragraph;
private final String appId;
public UnloadApplication(Paragraph paragraph, String appId) {
this.paragraph = paragraph;
this.appId = appId;
}
@Override
public void run() {
ApplicationState appState = null;
try {
appState = paragraph.getApplicationState(appId);
if (appState == null) {
logger.warn("Can not find {} to unload from {}", appId, paragraph.getId());
return;
}
if (appState.getStatus() == ApplicationState.Status.UNLOADED) {
// not loaded
return;
}
unload(appState);
} catch (Exception e) {
logger.error(e.getMessage(), e);
if (appState != null) {
appStatusChange(paragraph, appId, ApplicationState.Status.ERROR);
appState.setOutput(e.getMessage());
}
}
}
private void unload(ApplicationState appsToUnload) throws ApplicationException {
synchronized (appsToUnload) {
if (appsToUnload.getStatus() != ApplicationState.Status.LOADED) {
throw new ApplicationException(
"Can't unload application status " + appsToUnload.getStatus());
}
appStatusChange(paragraph, appsToUnload.getId(), ApplicationState.Status.UNLOADING);
Interpreter intp = paragraph.getCurrentRepl();
if (intp == null) {
throw new ApplicationException("No interpreter found");
}
RemoteInterpreterProcess intpProcess =
intp.getInterpreterGroup().getRemoteInterpreterProcess();
if (intpProcess == null) {
throw new ApplicationException("Target interpreter process is not running");
}
RemoteInterpreterService.Client client;
try {
client = intpProcess.getClient();
} catch (Exception e) {
throw new ApplicationException(e);
}
try {
RemoteApplicationResult ret = client.unloadApplication(appsToUnload.getId());
if (ret.isSuccess()) {
appStatusChange(paragraph, appsToUnload.getId(), ApplicationState.Status.UNLOADED);
} else {
throw new ApplicationException(ret.getMsg());
}
} catch (TException e) {
intpProcess.releaseBrokenClient(client);
throw new ApplicationException(e);
} finally {
intpProcess.releaseClient(client);
}
}
}
}
/**
* Run application
* It does not remove ApplicationState
*
* @param paragraph
* @param appId
*/
public void run(Paragraph paragraph, String appId) {
executor.execute(new RunApplication(paragraph, appId));
}
/**
* Run application task
*/
private class RunApplication implements Runnable {
private final Paragraph paragraph;
private final String appId;
public RunApplication(Paragraph paragraph, String appId) {
this.paragraph = paragraph;
this.appId = appId;
}
@Override
public void run() {
ApplicationState appState = null;
try {
appState = paragraph.getApplicationState(appId);
if (appState == null) {
logger.warn("Can not find {} to unload from {}", appId, paragraph.getId());
return;
}
run(appState);
} catch (Exception e) {
logger.error(e.getMessage(), e);
if (appState != null) {
appStatusChange(paragraph, appId, ApplicationState.Status.UNLOADED);
appState.setOutput(e.getMessage());
}
}
}
private void run(ApplicationState app) throws ApplicationException {
synchronized (app) {
if (app.getStatus() != ApplicationState.Status.LOADED) {
throw new ApplicationException(
"Can't run application status " + app.getStatus());
}
Interpreter intp = paragraph.getCurrentRepl();
if (intp == null) {
throw new ApplicationException("No interpreter found");
}
RemoteInterpreterProcess intpProcess =
intp.getInterpreterGroup().getRemoteInterpreterProcess();
if (intpProcess == null) {
throw new ApplicationException("Target interpreter process is not running");
}
RemoteInterpreterService.Client client = null;
try {
client = intpProcess.getClient();
} catch (Exception e) {
throw new ApplicationException(e);
}
try {
RemoteApplicationResult ret = client.runApplication(app.getId());
if (ret.isSuccess()) {
// success
} else {
throw new ApplicationException(ret.getMsg());
}
} catch (TException e) {
intpProcess.releaseBrokenClient(client);
client = null;
throw new ApplicationException(e);
} finally {
if (client != null) {
intpProcess.releaseClient(client);
}
}
}
}
}
@Override
public void onOutputAppend(
String noteId, String paragraphId, int index, String appId, String output) {
ApplicationState appToUpdate = getAppState(noteId, paragraphId, appId);
if (appToUpdate != null) {
appToUpdate.appendOutput(output);
} else {
logger.error("Can't find app {}", appId);
}
if (applicationEventListener != null) {
applicationEventListener.onOutputAppend(noteId, paragraphId, index, appId, output);
}
}
@Override
public void onOutputUpdated(
String noteId, String paragraphId, int index, String appId,
InterpreterResult.Type type, String output) {
ApplicationState appToUpdate = getAppState(noteId, paragraphId, appId);
if (appToUpdate != null) {
appToUpdate.setOutput(output);
} else {
logger.error("Can't find app {}", appId);
}
if (applicationEventListener != null) {
applicationEventListener.onOutputUpdated(noteId, paragraphId, index, appId, type, output);
}
}
@Override
public void onLoad(String noteId, String paragraphId, String appId, HeliumPackage pkg) {
if (applicationEventListener != null) {
applicationEventListener.onLoad(noteId, paragraphId, appId, pkg);
}
}
@Override
public void onStatusChange(String noteId, String paragraphId, String appId, String status) {
ApplicationState appToUpdate = getAppState(noteId, paragraphId, appId);
if (appToUpdate != null) {
appToUpdate.setStatus(ApplicationState.Status.valueOf(status));
}
if (applicationEventListener != null) {
applicationEventListener.onStatusChange(noteId, paragraphId, appId, status);
}
}
private void appStatusChange(Paragraph paragraph,
String appId,
ApplicationState.Status status) {
ApplicationState app = paragraph.getApplicationState(appId);
app.setStatus(status);
onStatusChange(paragraph.getNote().getId(), paragraph.getId(), appId, status.toString());
}
private ApplicationState getAppState(String noteId, String paragraphId, String appId) {
if (notebook == null) {
return null;
}
Note note = notebook.getNote(noteId);
if (note == null) {
logger.error("Can't get note {}", noteId);
return null;
}
Paragraph paragraph = note.getParagraph(paragraphId);
if (paragraph == null) {
logger.error("Can't get paragraph {}", paragraphId);
return null;
}
ApplicationState appFound = paragraph.getApplicationState(appId);
return appFound;
}
public Notebook getNotebook() {
return notebook;
}
public void setNotebook(Notebook notebook) {
this.notebook = notebook;
}
public ApplicationEventListener getApplicationEventListener() {
return applicationEventListener;
}
public void setApplicationEventListener(ApplicationEventListener applicationEventListener) {
this.applicationEventListener = applicationEventListener;
}
@Override
public void onNoteRemove(Note note) {
}
@Override
public void onNoteCreate(Note note) {
}
@Override
public void onUnbindInterpreter(Note note, InterpreterSetting setting) {
for (Paragraph p : note.getParagraphs()) {
Interpreter currentInterpreter = p.getCurrentRepl();
List<InterpreterInfo> infos = setting.getInterpreterInfos();
for (InterpreterInfo info : infos) {
if (currentInterpreter != null &&
info.getClassName().equals(currentInterpreter.getClassName())) {
onParagraphRemove(p);
break;
}
}
}
}
@Override
public void onParagraphRemove(Paragraph paragraph) {
List<ApplicationState> appStates = paragraph.getAllApplicationStates();
for (ApplicationState app : appStates) {
UnloadApplication unloadJob = new UnloadApplication(paragraph, app.getId());
unloadJob.run();
}
}
@Override
public void onParagraphCreate(Paragraph p) {
}
@Override
public void onParagraphStatusChange(Paragraph p, Job.Status status) {
if (status == Job.Status.FINISHED) {
// refresh application
List<ApplicationState> appStates = p.getAllApplicationStates();
for (ApplicationState app : appStates) {
loadAndRun(app.getHeliumPackage(), p);
}
}
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/helium/Helium.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/helium/Helium.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.helium;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.commons.io.FileUtils;
import org.apache.zeppelin.interpreter.Interpreter;
import org.apache.zeppelin.notebook.Paragraph;
import org.apache.zeppelin.resource.DistributedResourcePool;
import org.apache.zeppelin.resource.ResourcePool;
import org.apache.zeppelin.resource.ResourcePoolUtils;
import org.apache.zeppelin.resource.ResourceSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.util.*;
/**
* Manages helium packages
*/
public class Helium {
Logger logger = LoggerFactory.getLogger(Helium.class);
private List<HeliumRegistry> registry = new LinkedList<>();
private final HeliumConf heliumConf;
private final String heliumConfPath;
private final String defaultLocalRegistryPath;
private final Gson gson;
private final HeliumVisualizationFactory visualizationFactory;
private final HeliumApplicationFactory applicationFactory;
public Helium(
String heliumConfPath,
String defaultLocalRegistryPath,
HeliumVisualizationFactory visualizationFactory,
HeliumApplicationFactory applicationFactory)
throws IOException {
this.heliumConfPath = heliumConfPath;
this.defaultLocalRegistryPath = defaultLocalRegistryPath;
this.visualizationFactory = visualizationFactory;
this.applicationFactory = applicationFactory;
GsonBuilder builder = new GsonBuilder();
builder.setPrettyPrinting();
builder.registerTypeAdapter(
HeliumRegistry.class, new HeliumRegistrySerializer());
gson = builder.create();
heliumConf = loadConf(heliumConfPath);
}
/**
* Add HeliumRegistry
*
* @param registry
*/
public void addRegistry(HeliumRegistry registry) {
synchronized (this.registry) {
this.registry.add(registry);
}
}
public List<HeliumRegistry> getAllRegistry() {
synchronized (this.registry) {
List list = new LinkedList<>();
for (HeliumRegistry r : registry) {
list.add(r);
}
return list;
}
}
public HeliumApplicationFactory getApplicationFactory() {
return applicationFactory;
}
public HeliumVisualizationFactory getVisualizationFactory() {
return visualizationFactory;
}
private synchronized HeliumConf loadConf(String path) throws IOException {
File heliumConfFile = new File(path);
if (!heliumConfFile.isFile()) {
logger.warn("{} does not exists", path);
HeliumConf conf = new HeliumConf();
LinkedList<HeliumRegistry> defaultRegistry = new LinkedList<>();
defaultRegistry.add(new HeliumLocalRegistry("local", defaultLocalRegistryPath));
conf.setRegistry(defaultRegistry);
this.registry = conf.getRegistry();
return conf;
} else {
String jsonString = FileUtils.readFileToString(heliumConfFile);
HeliumConf conf = gson.fromJson(jsonString, HeliumConf.class);
this.registry = conf.getRegistry();
return conf;
}
}
public synchronized void save() throws IOException {
String jsonString;
synchronized (registry) {
clearNotExistsPackages();
heliumConf.setRegistry(registry);
jsonString = gson.toJson(heliumConf);
}
File heliumConfFile = new File(heliumConfPath);
if (!heliumConfFile.exists()) {
heliumConfFile.createNewFile();
}
FileUtils.writeStringToFile(heliumConfFile, jsonString);
}
private void clearNotExistsPackages() {
Map<String, List<HeliumPackageSearchResult>> all = getAllPackageInfo();
// clear visualization display order
List<String> packageOrder = heliumConf.getVisualizationDisplayOrder();
List<String> clearedOrder = new LinkedList<>();
for (String pkgName : packageOrder) {
if (all.containsKey(pkgName)) {
clearedOrder.add(pkgName);
}
}
heliumConf.setVisualizationDisplayOrder(clearedOrder);
// clear enabled package
Map<String, String> enabledPackages = heliumConf.getEnabledPackages();
for (String pkgName : enabledPackages.keySet()) {
if (!all.containsKey(pkgName)) {
heliumConf.disablePackage(pkgName);
}
}
}
public Map<String, List<HeliumPackageSearchResult>> getAllPackageInfo() {
Map<String, String> enabledPackageInfo = heliumConf.getEnabledPackages();
Map<String, List<HeliumPackageSearchResult>> map = new HashMap<>();
synchronized (registry) {
for (HeliumRegistry r : registry) {
try {
for (HeliumPackage pkg : r.getAll()) {
String name = pkg.getName();
String artifact = enabledPackageInfo.get(name);
boolean enabled = (artifact != null && artifact.equals(pkg.getArtifact()));
if (!map.containsKey(name)) {
map.put(name, new LinkedList<HeliumPackageSearchResult>());
}
map.get(name).add(new HeliumPackageSearchResult(r.name(), pkg, enabled));
}
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
}
// sort version (artifact)
for (String name : map.keySet()) {
List<HeliumPackageSearchResult> packages = map.get(name);
Collections.sort(packages, new Comparator<HeliumPackageSearchResult>() {
@Override
public int compare(HeliumPackageSearchResult o1, HeliumPackageSearchResult o2) {
return o2.getPkg().getArtifact().compareTo(o1.getPkg().getArtifact());
}
});
}
return map;
}
public HeliumPackageSearchResult getPackageInfo(String name, String artifact) {
Map<String, List<HeliumPackageSearchResult>> infos = getAllPackageInfo();
List<HeliumPackageSearchResult> packages = infos.get(name);
if (artifact == null) {
return packages.get(0);
} else {
for (HeliumPackageSearchResult pkg : packages) {
if (pkg.getPkg().getArtifact().equals(artifact)) {
return pkg;
}
}
}
return null;
}
public File recreateVisualizationBundle() throws IOException {
return visualizationFactory.bundle(getVisualizationPackagesToBundle(), true);
}
public void enable(String name, String artifact) throws IOException {
HeliumPackageSearchResult pkgInfo = getPackageInfo(name, artifact);
// no package found.
if (pkgInfo == null) {
return;
}
// enable package
heliumConf.enablePackage(name, artifact);
// if package is visualization, rebuild bundle
if (pkgInfo.getPkg().getType() == HeliumPackage.Type.VISUALIZATION) {
visualizationFactory.bundle(getVisualizationPackagesToBundle());
}
save();
}
public void disable(String name) throws IOException {
String artifact = heliumConf.getEnabledPackages().get(name);
if (artifact == null) {
return;
}
heliumConf.disablePackage(name);
HeliumPackageSearchResult pkg = getPackageInfo(name, artifact);
if (pkg == null || pkg.getPkg().getType() == HeliumPackage.Type.VISUALIZATION) {
visualizationFactory.bundle(getVisualizationPackagesToBundle());
}
save();
}
public HeliumPackageSuggestion suggestApp(Paragraph paragraph) {
HeliumPackageSuggestion suggestion = new HeliumPackageSuggestion();
Interpreter intp = paragraph.getCurrentRepl();
if (intp == null) {
return suggestion;
}
ResourcePool resourcePool = intp.getInterpreterGroup().getResourcePool();
ResourceSet allResources;
if (resourcePool != null) {
if (resourcePool instanceof DistributedResourcePool) {
allResources = ((DistributedResourcePool) resourcePool).getAll(true);
} else {
allResources = resourcePool.getAll();
}
} else {
allResources = ResourcePoolUtils.getAllResources();
}
for (List<HeliumPackageSearchResult> pkgs : getAllPackageInfo().values()) {
for (HeliumPackageSearchResult pkg : pkgs) {
if (pkg.getPkg().getType() == HeliumPackage.Type.APPLICATION && pkg.isEnabled()) {
ResourceSet resources = ApplicationLoader.findRequiredResourceSet(
pkg.getPkg().getResources(),
paragraph.getNote().getId(),
paragraph.getId(),
allResources);
if (resources == null) {
continue;
} else {
suggestion.addAvailablePackage(pkg);
}
break;
}
}
}
suggestion.sort();
return suggestion;
}
/**
* Get enabled visualization packages
*
* @return ordered list of enabled visualization package
*/
public List<HeliumPackage> getVisualizationPackagesToBundle() {
Map<String, List<HeliumPackageSearchResult>> allPackages = getAllPackageInfo();
List<String> visOrder = heliumConf.getVisualizationDisplayOrder();
List<HeliumPackage> orderedVisualizationPackages = new LinkedList<>();
// add enabled packages in visOrder
for (String name : visOrder) {
List<HeliumPackageSearchResult> versions = allPackages.get(name);
if (versions == null) {
continue;
}
for (HeliumPackageSearchResult pkgInfo : versions) {
if (pkgInfo.getPkg().getType() == HeliumPackage.Type.VISUALIZATION && pkgInfo.isEnabled()) {
orderedVisualizationPackages.add(pkgInfo.getPkg());
allPackages.remove(name);
break;
}
}
}
// add enabled packages not in visOrder
for (List<HeliumPackageSearchResult> pkgs : allPackages.values()) {
for (HeliumPackageSearchResult pkg : pkgs) {
if (pkg.getPkg().getType() == HeliumPackage.Type.VISUALIZATION && pkg.isEnabled()) {
orderedVisualizationPackages.add(pkg.getPkg());
break;
}
}
}
return orderedVisualizationPackages;
}
/**
* Get enabled package list in order
* @return
*/
public List<String> getVisualizationPackageOrder() {
List orderedPackageList = new LinkedList<>();
List<HeliumPackage> packages = getVisualizationPackagesToBundle();
for (HeliumPackage pkg : packages) {
orderedPackageList.add(pkg.getName());
}
return orderedPackageList;
}
public void setVisualizationPackageOrder(List<String> orderedPackageList)
throws IOException {
heliumConf.setVisualizationDisplayOrder(orderedPackageList);
// if package is visualization, rebuild bundle
visualizationFactory.bundle(getVisualizationPackagesToBundle());
save();
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/helium/HeliumRegistrySerializer.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/helium/HeliumRegistrySerializer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.helium;
import com.google.gson.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Type;
import java.net.URI;
import java.net.URISyntaxException;
/**
* HeliumRegistrySerializer (and deserializer) for gson
*/
public class HeliumRegistrySerializer
implements JsonSerializer<HeliumRegistry>, JsonDeserializer<HeliumRegistry> {
Logger logger = LoggerFactory.getLogger(HeliumRegistrySerializer.class);
@Override
public HeliumRegistry deserialize(JsonElement json,
Type type,
JsonDeserializationContext jsonDeserializationContext)
throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
String className = jsonObject.get("class").getAsString();
String uri = jsonObject.get("uri").getAsString();
String name = jsonObject.get("name").getAsString();
try {
logger.info("Restore helium registry {} {} {}", name, className, uri);
Class<HeliumRegistry> cls =
(Class<HeliumRegistry>) getClass().getClassLoader().loadClass(className);
Constructor<HeliumRegistry> constructor = cls.getConstructor(String.class, String.class);
HeliumRegistry registry = constructor.newInstance(name, uri);
return registry;
} catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException |
InstantiationException | InvocationTargetException e) {
logger.error(e.getMessage(), e);
return null;
}
}
@Override
public JsonElement serialize(HeliumRegistry heliumRegistry,
Type type,
JsonSerializationContext jsonSerializationContext) {
JsonObject json = new JsonObject();
json.addProperty("class", heliumRegistry.getClass().getName());
json.addProperty("uri", heliumRegistry.uri());
json.addProperty("name", heliumRegistry.name());
return json;
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/helium/NpmPackage.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/helium/NpmPackage.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.helium;
import java.util.Map;
/**
* To read package.json
*/
public class NpmPackage {
public String name;
public String version;
public Map<String, String> dependencies;
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/helium/HeliumRegistry.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/helium/HeliumRegistry.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.helium;
import java.io.IOException;
import java.net.URI;
import java.util.List;
/**
* Helium package registry
*/
public abstract class HeliumRegistry {
private final String name;
private final String uri;
public HeliumRegistry(String name, String uri) {
this.name = name;
this.uri = uri;
}
public String name() {
return name;
}
public String uri() {
return uri;
}
public abstract List<HeliumPackage> getAll() throws IOException;
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/helium/HeliumPackageSuggestion.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/helium/HeliumPackageSuggestion.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.helium;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
/**
* Suggested apps
*/
public class HeliumPackageSuggestion {
private final List<HeliumPackageSearchResult> available = new LinkedList<>();
/*
* possible future improvement
* provides n - 'favorite' list, based on occurrence of apps in notebook
*/
public HeliumPackageSuggestion() {
}
public void addAvailablePackage(HeliumPackageSearchResult r) {
available.add(r);
}
public void sort() {
Collections.sort(available, new Comparator<HeliumPackageSearchResult>() {
@Override
public int compare(HeliumPackageSearchResult o1, HeliumPackageSearchResult o2) {
return o1.getPkg().getName().compareTo(o2.getPkg().getName());
}
});
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/ticket/TicketContainer.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/ticket/TicketContainer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.ticket;
import java.util.Calendar;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* Very simple ticket container
* No cleanup is done, since the same user accross different devices share the same ticket
* The Map size is at most the number of different user names having access to a Zeppelin instance
*/
public class TicketContainer {
private static class Entry {
public final String ticket;
// lastAccessTime still unused
public final long lastAccessTime;
Entry(String ticket) {
this.ticket = ticket;
this.lastAccessTime = Calendar.getInstance().getTimeInMillis();
}
}
private Map<String, Entry> sessions = new ConcurrentHashMap<>();
public static final TicketContainer instance = new TicketContainer();
/**
* For test use
* @param principal
* @param ticket
* @return true if ticket assigned to principal.
*/
public boolean isValid(String principal, String ticket) {
if ("anonymous".equals(principal) && "anonymous".equals(ticket))
return true;
Entry entry = sessions.get(principal);
return entry != null && entry.ticket.equals(ticket);
}
/**
* get or create ticket for Websocket authentication assigned to authenticated shiro user
* For unathenticated user (anonymous), always return ticket value "anonymous"
* @param principal
* @return
*/
public synchronized String getTicket(String principal) {
Entry entry = sessions.get(principal);
String ticket;
if (entry == null) {
if (principal.equals("anonymous"))
ticket = "anonymous";
else
ticket = UUID.randomUUID().toString();
} else {
ticket = entry.ticket;
}
entry = new Entry(ticket);
sessions.put(principal, entry);
return ticket;
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/search/LuceneSearch.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/search/LuceneSearch.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.search;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.LongField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.WildcardQuery;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.search.highlight.TextFragment;
import org.apache.lucene.search.highlight.TokenSources;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
import org.apache.zeppelin.notebook.Note;
import org.apache.zeppelin.notebook.Paragraph;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
/**
* Search (both, indexing and query) the notebooks using Lucene.
*
* Query is thread-safe, as creates new IndexReader every time.
* Index is thread-safe, as re-uses single IndexWriter, which is thread-safe.
*/
public class LuceneSearch implements SearchService {
private static final Logger LOG = LoggerFactory.getLogger(LuceneSearch.class);
private static final String SEARCH_FIELD_TEXT = "contents";
private static final String SEARCH_FIELD_TITLE = "header";
static final String PARAGRAPH = "paragraph";
static final String ID_FIELD = "id";
Directory ramDirectory;
Analyzer analyzer;
IndexWriterConfig iwc;
IndexWriter writer;
public LuceneSearch() {
ramDirectory = new RAMDirectory();
analyzer = new StandardAnalyzer();
iwc = new IndexWriterConfig(analyzer);
try {
writer = new IndexWriter(ramDirectory, iwc);
} catch (IOException e) {
LOG.error("Failed to create new IndexWriter", e);
}
}
/* (non-Javadoc)
* @see org.apache.zeppelin.search.Search#query(java.lang.String)
*/
@Override
public List<Map<String, String>> query(String queryStr) {
if (null == ramDirectory) {
throw new IllegalStateException(
"Something went wrong on instance creation time, index dir is null");
}
List<Map<String, String>> result = Collections.emptyList();
try (IndexReader indexReader = DirectoryReader.open(ramDirectory)) {
IndexSearcher indexSearcher = new IndexSearcher(indexReader);
Analyzer analyzer = new StandardAnalyzer();
MultiFieldQueryParser parser = new MultiFieldQueryParser(
new String[] {SEARCH_FIELD_TEXT, SEARCH_FIELD_TITLE},
analyzer);
Query query = parser.parse(queryStr);
LOG.debug("Searching for: " + query.toString(SEARCH_FIELD_TEXT));
SimpleHTMLFormatter htmlFormatter = new SimpleHTMLFormatter();
Highlighter highlighter = new Highlighter(htmlFormatter, new QueryScorer(query));
result = doSearch(indexSearcher, query, analyzer, highlighter);
indexReader.close();
} catch (IOException e) {
LOG.error("Failed to open index dir {}, make sure indexing finished OK", ramDirectory, e);
} catch (ParseException e) {
LOG.error("Failed to parse query " + queryStr, e);
}
return result;
}
private List<Map<String, String>> doSearch(IndexSearcher searcher, Query query,
Analyzer analyzer, Highlighter highlighter) {
List<Map<String, String>> matchingParagraphs = Lists.newArrayList();
ScoreDoc[] hits;
try {
hits = searcher.search(query, 20).scoreDocs;
for (int i = 0; i < hits.length; i++) {
LOG.debug("doc={} score={}", hits[i].doc, hits[i].score);
int id = hits[i].doc;
Document doc = searcher.doc(id);
String path = doc.get(ID_FIELD);
if (path != null) {
LOG.debug((i + 1) + ". " + path);
String title = doc.get("title");
if (title != null) {
LOG.debug(" Title: {}", doc.get("title"));
}
String text = doc.get(SEARCH_FIELD_TEXT);
String header = doc.get(SEARCH_FIELD_TITLE);
String fragment = "";
if (text != null) {
TokenStream tokenStream = TokenSources.getTokenStream(searcher.getIndexReader(), id,
SEARCH_FIELD_TEXT, analyzer);
TextFragment[] frag = highlighter.getBestTextFragments(tokenStream, text, true, 3);
LOG.debug(" {} fragments found for query '{}'", frag.length, query);
for (int j = 0; j < frag.length; j++) {
if ((frag[j] != null) && (frag[j].getScore() > 0)) {
LOG.debug(" Fragment: {}", frag[j].toString());
}
}
fragment = (frag != null && frag.length > 0) ? frag[0].toString() : "";
}
if (header != null) {
TokenStream tokenTitle = TokenSources.getTokenStream(searcher.getIndexReader(), id,
SEARCH_FIELD_TITLE, analyzer);
TextFragment[] frgTitle = highlighter.getBestTextFragments(tokenTitle, header, true, 3);
header = (frgTitle != null && frgTitle.length > 0) ? frgTitle[0].toString() : "";
} else {
header = "";
}
matchingParagraphs.add(ImmutableMap.of("id", path, // <noteId>/paragraph/<paragraphId>
"name", title, "snippet", fragment, "text", text, "header", header));
} else {
LOG.info("{}. No {} for this document", i + 1, ID_FIELD);
}
}
} catch (IOException | InvalidTokenOffsetsException e) {
LOG.error("Exception on searching for {}", query, e);
}
return matchingParagraphs;
}
/* (non-Javadoc)
* @see org.apache.zeppelin.search.Search#updateIndexDoc(org.apache.zeppelin.notebook.Note)
*/
@Override
public void updateIndexDoc(Note note) throws IOException {
updateIndexNoteName(note);
for (Paragraph p: note.getParagraphs()) {
updateIndexParagraph(note, p);
}
}
private void updateIndexNoteName(Note note) throws IOException {
String noteName = note.getName();
String noteId = note.getId();
LOG.debug("Indexing Notebook {}, '{}'", noteId, noteName);
if (null == noteName || noteName.isEmpty()) {
LOG.debug("Skipping empty notebook name");
return;
}
updateDoc(noteId, noteName, null);
}
private void updateIndexParagraph(Note note, Paragraph p) throws IOException {
if (p.getText() == null) {
LOG.debug("Skipping empty paragraph");
return;
}
updateDoc(note.getId(), note.getName(), p);
}
/**
* Updates index for the given note: either note.name or a paragraph If
* paragraph is <code>null</code> - updates only for the note.name
*
* @param noteId
* @param noteName
* @param p
* @throws IOException
*/
private void updateDoc(String noteId, String noteName, Paragraph p) throws IOException {
String id = formatId(noteId, p);
Document doc = newDocument(id, noteName, p);
try {
writer.updateDocument(new Term(ID_FIELD, id), doc);
writer.commit();
} catch (IOException e) {
LOG.error("Failed to updaet index of notebook {}", noteId, e);
}
}
/**
* If paragraph is not null, id is <noteId>/paragraphs/<paragraphId>,
* otherwise it's just <noteId>.
*/
static String formatId(String noteId, Paragraph p) {
String id = noteId;
if (null != p) {
id = Joiner.on('/').join(id, PARAGRAPH, p.getId());
}
return id;
}
static String formatDeleteId(String noteId, Paragraph p) {
String id = noteId;
if (null != p) {
id = Joiner.on('/').join(id, PARAGRAPH, p.getId());
} else {
id = id + "*";
}
return id;
}
/**
* If paragraph is not null, indexes code in the paragraph, otherwise indexes
* the notebook name.
*
* @param id id of the document, different for Note name and paragraph
* @param noteName name of the note
* @param p paragraph
* @return
*/
private Document newDocument(String id, String noteName, Paragraph p) {
Document doc = new Document();
Field pathField = new StringField(ID_FIELD, id, Field.Store.YES);
doc.add(pathField);
doc.add(new StringField("title", noteName, Field.Store.YES));
if (null != p) {
doc.add(new TextField(SEARCH_FIELD_TEXT, p.getText(), Field.Store.YES));
if (p.getTitle() != null) {
doc.add(new TextField(SEARCH_FIELD_TITLE, p.getTitle(), Field.Store.YES));
}
Date date = p.getDateStarted() != null ? p.getDateStarted() : p.getDateCreated();
doc.add(new LongField("modified", date.getTime(), Field.Store.NO));
} else {
doc.add(new TextField(SEARCH_FIELD_TEXT, noteName, Field.Store.YES));
}
return doc;
}
/* (non-Javadoc)
* @see org.apache.zeppelin.search.Search#addIndexDocs(java.util.Collection)
*/
@Override
public void addIndexDocs(Collection<Note> collection) {
int docsIndexed = 0;
long start = System.nanoTime();
try {
for (Note note : collection) {
addIndexDocAsync(note);
docsIndexed++;
}
} catch (IOException e) {
LOG.error("Failed to index all Notebooks", e);
} finally {
try { // save what's been indexed, even if not full collection
writer.commit();
} catch (IOException e) {
LOG.error("Failed to save index", e);
}
long end = System.nanoTime();
LOG.info("Indexing {} notebooks took {}ms", docsIndexed,
TimeUnit.NANOSECONDS.toMillis(end - start));
}
}
/* (non-Javadoc)
* @see org.apache.zeppelin.search.Search#addIndexDoc(org.apache.zeppelin.notebook.Note)
*/
@Override
public void addIndexDoc(Note note) {
try {
addIndexDocAsync(note);
writer.commit();
} catch (IOException e) {
LOG.error("Failed to add note {} to index", note, e);
}
}
/**
* Indexes the given notebook, but does not commit changes.
*
* @param note
* @throws IOException
*/
private void addIndexDocAsync(Note note) throws IOException {
indexNoteName(writer, note.getId(), note.getName());
for (Paragraph doc : note.getParagraphs()) {
if (doc.getText() == null) {
LOG.debug("Skipping empty paragraph");
continue;
}
indexDoc(writer, note.getId(), note.getName(), doc);
}
}
/* (non-Javadoc)
* @see org.apache.zeppelin.search.Search#deleteIndexDocs(org.apache.zeppelin.notebook.Note)
*/
@Override
public void deleteIndexDocs(Note note) {
deleteDoc(note, null);
}
/* (non-Javadoc)
* @see org.apache.zeppelin.search.Search
* #deleteIndexDoc(org.apache.zeppelin.notebook.Note, org.apache.zeppelin.notebook.Paragraph)
*/
@Override
public void deleteIndexDoc(Note note, Paragraph p) {
deleteDoc(note, p);
}
private void deleteDoc(Note note, Paragraph p) {
if (null == note) {
LOG.error("Trying to delete note by reference to NULL");
return;
}
String fullNoteOrJustParagraph = formatDeleteId(note.getId(), p);
LOG.debug("Deleting note {}, out of: {}", note.getId(), writer.numDocs());
try {
writer.deleteDocuments(new WildcardQuery(new Term(ID_FIELD, fullNoteOrJustParagraph)));
writer.commit();
} catch (IOException e) {
LOG.error("Failed to delete {} from index by '{}'", note, fullNoteOrJustParagraph, e);
}
LOG.debug("Done, index contains {} docs now" + writer.numDocs());
}
/* (non-Javadoc)
* @see org.apache.zeppelin.search.Search#close()
*/
@Override
public void close() {
try {
writer.close();
} catch (IOException e) {
LOG.error("Failed to .close() the notebook index", e);
}
}
/**
* Indexes a notebook name
*
* @throws IOException
*/
private void indexNoteName(IndexWriter w, String noteId, String noteName) throws IOException {
LOG.debug("Indexing Notebook {}, '{}'", noteId, noteName);
if (null == noteName || noteName.isEmpty()) {
LOG.debug("Skipping empty notebook name");
return;
}
indexDoc(w, noteId, noteName, null);
}
/**
* Indexes a single document:
* - code of the paragraph (if non-null)
* - or just a note name
*/
private void indexDoc(IndexWriter w, String noteId, String noteName, Paragraph p)
throws IOException {
String id = formatId(noteId, p);
Document doc = newDocument(id, noteName, p);
w.addDocument(doc);
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/search/SearchService.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/search/SearchService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.search;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.apache.zeppelin.notebook.Note;
import org.apache.zeppelin.notebook.Paragraph;
/**
* Search (both, indexing and query) the notes.
*
* Intended to have multiple implementation, i.e:
* - local Lucene (in-memory, on-disk)
* - remote Elasticsearch
*/
public interface SearchService {
/**
* Full-text search in all the notes
*
* @param queryStr a query
* @return A list of matching paragraphs (id, text, snippet w/ highlight)
*/
public List<Map<String, String>> query(String queryStr);
/**
* Updates all documents in index for the given note:
* - name
* - all paragraphs
*
* @param note a Note to update index for
* @throws IOException
*/
public void updateIndexDoc(Note note) throws IOException;
/**
* Indexes full collection of notes: all the paragraphs + Note names
*
* @param collection of Notes
*/
public void addIndexDocs(Collection<Note> collection);
/**
* Indexes the given note.
*
* @throws IOException If there is a low-level I/O error
*/
public void addIndexDoc(Note note);
/**
* Deletes all docs on given Note from index
*/
public void deleteIndexDocs(Note note);
/**
* Deletes doc for a given
*
* @param note
* @param p
* @throws IOException
*/
public void deleteIndexDoc(Note note, Paragraph p);
/**
* Frees the recourses used by index
*/
public void close();
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/conf/ZeppelinConfiguration.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/conf/ZeppelinConfiguration.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.conf;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.commons.configuration.tree.ConfigurationNode;
import org.apache.commons.lang.StringUtils;
import org.apache.zeppelin.util.Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Zeppelin configuration.
*
*/
public class ZeppelinConfiguration extends XMLConfiguration {
private static final String ZEPPELIN_SITE_XML = "zeppelin-site.xml";
private static final long serialVersionUID = 4749305895693848035L;
private static final Logger LOG = LoggerFactory.getLogger(ZeppelinConfiguration.class);
private static ZeppelinConfiguration conf;
public ZeppelinConfiguration(URL url) throws ConfigurationException {
setDelimiterParsingDisabled(true);
load(url);
}
public ZeppelinConfiguration() {
ConfVars[] vars = ConfVars.values();
for (ConfVars v : vars) {
if (v.getType() == ConfVars.VarType.BOOLEAN) {
this.setProperty(v.getVarName(), v.getBooleanValue());
} else if (v.getType() == ConfVars.VarType.LONG) {
this.setProperty(v.getVarName(), v.getLongValue());
} else if (v.getType() == ConfVars.VarType.INT) {
this.setProperty(v.getVarName(), v.getIntValue());
} else if (v.getType() == ConfVars.VarType.FLOAT) {
this.setProperty(v.getVarName(), v.getFloatValue());
} else if (v.getType() == ConfVars.VarType.STRING) {
this.setProperty(v.getVarName(), v.getStringValue());
} else {
throw new RuntimeException("Unsupported VarType");
}
}
}
/**
* Load from resource.
*url = ZeppelinConfiguration.class.getResource(ZEPPELIN_SITE_XML);
* @throws ConfigurationException
*/
public static synchronized ZeppelinConfiguration create() {
if (conf != null) {
return conf;
}
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL url;
url = ZeppelinConfiguration.class.getResource(ZEPPELIN_SITE_XML);
if (url == null) {
ClassLoader cl = ZeppelinConfiguration.class.getClassLoader();
if (cl != null) {
url = cl.getResource(ZEPPELIN_SITE_XML);
}
}
if (url == null) {
url = classLoader.getResource(ZEPPELIN_SITE_XML);
}
if (url == null) {
LOG.warn("Failed to load configuration, proceeding with a default");
conf = new ZeppelinConfiguration();
} else {
try {
LOG.info("Load configuration from " + url);
conf = new ZeppelinConfiguration(url);
} catch (ConfigurationException e) {
LOG.warn("Failed to load configuration from " + url + " proceeding with a default", e);
conf = new ZeppelinConfiguration();
}
}
LOG.info("Server Host: " + conf.getServerAddress());
if (conf.useSsl() == false) {
LOG.info("Server Port: " + conf.getServerPort());
} else {
LOG.info("Server SSL Port: " + conf.getServerSslPort());
}
LOG.info("Context Path: " + conf.getServerContextPath());
LOG.info("Zeppelin Version: " + Util.getVersion());
return conf;
}
private String getStringValue(String name, String d) {
List<ConfigurationNode> properties = getRootNode().getChildren();
if (properties == null || properties.isEmpty()) {
return d;
}
for (ConfigurationNode p : properties) {
if (p.getChildren("name") != null && !p.getChildren("name").isEmpty()
&& name.equals(p.getChildren("name").get(0).getValue())) {
return (String) p.getChildren("value").get(0).getValue();
}
}
return d;
}
private int getIntValue(String name, int d) {
List<ConfigurationNode> properties = getRootNode().getChildren();
if (properties == null || properties.isEmpty()) {
return d;
}
for (ConfigurationNode p : properties) {
if (p.getChildren("name") != null && !p.getChildren("name").isEmpty()
&& name.equals(p.getChildren("name").get(0).getValue())) {
return Integer.parseInt((String) p.getChildren("value").get(0).getValue());
}
}
return d;
}
private long getLongValue(String name, long d) {
List<ConfigurationNode> properties = getRootNode().getChildren();
if (properties == null || properties.isEmpty()) {
return d;
}
for (ConfigurationNode p : properties) {
if (p.getChildren("name") != null && !p.getChildren("name").isEmpty()
&& name.equals(p.getChildren("name").get(0).getValue())) {
return Long.parseLong((String) p.getChildren("value").get(0).getValue());
}
}
return d;
}
private float getFloatValue(String name, float d) {
List<ConfigurationNode> properties = getRootNode().getChildren();
if (properties == null || properties.isEmpty()) {
return d;
}
for (ConfigurationNode p : properties) {
if (p.getChildren("name") != null && !p.getChildren("name").isEmpty()
&& name.equals(p.getChildren("name").get(0).getValue())) {
return Float.parseFloat((String) p.getChildren("value").get(0).getValue());
}
}
return d;
}
private boolean getBooleanValue(String name, boolean d) {
List<ConfigurationNode> properties = getRootNode().getChildren();
if (properties == null || properties.isEmpty()) {
return d;
}
for (ConfigurationNode p : properties) {
if (p.getChildren("name") != null && !p.getChildren("name").isEmpty()
&& name.equals(p.getChildren("name").get(0).getValue())) {
return Boolean.parseBoolean((String) p.getChildren("value").get(0).getValue());
}
}
return d;
}
public String getString(ConfVars c) {
return getString(c.name(), c.getVarName(), c.getStringValue());
}
public String getString(String envName, String propertyName, String defaultValue) {
if (System.getenv(envName) != null) {
return System.getenv(envName);
}
if (System.getProperty(propertyName) != null) {
return System.getProperty(propertyName);
}
return getStringValue(propertyName, defaultValue);
}
public int getInt(ConfVars c) {
return getInt(c.name(), c.getVarName(), c.getIntValue());
}
public int getInt(String envName, String propertyName, int defaultValue) {
if (System.getenv(envName) != null) {
return Integer.parseInt(System.getenv(envName));
}
if (System.getProperty(propertyName) != null) {
return Integer.parseInt(System.getProperty(propertyName));
}
return getIntValue(propertyName, defaultValue);
}
public long getLong(ConfVars c) {
return getLong(c.name(), c.getVarName(), c.getLongValue());
}
public long getLong(String envName, String propertyName, long defaultValue) {
if (System.getenv(envName) != null) {
return Long.parseLong(System.getenv(envName));
}
if (System.getProperty(propertyName) != null) {
return Long.parseLong(System.getProperty(propertyName));
}
return getLongValue(propertyName, defaultValue);
}
public float getFloat(ConfVars c) {
return getFloat(c.name(), c.getVarName(), c.getFloatValue());
}
public float getFloat(String envName, String propertyName, float defaultValue) {
if (System.getenv(envName) != null) {
return Float.parseFloat(System.getenv(envName));
}
if (System.getProperty(propertyName) != null) {
return Float.parseFloat(System.getProperty(propertyName));
}
return getFloatValue(propertyName, defaultValue);
}
public boolean getBoolean(ConfVars c) {
return getBoolean(c.name(), c.getVarName(), c.getBooleanValue());
}
public boolean getBoolean(String envName, String propertyName, boolean defaultValue) {
if (System.getenv(envName) != null) {
return Boolean.parseBoolean(System.getenv(envName));
}
if (System.getProperty(propertyName) != null) {
return Boolean.parseBoolean(System.getProperty(propertyName));
}
return getBooleanValue(propertyName, defaultValue);
}
public boolean useSsl() {
return getBoolean(ConfVars.ZEPPELIN_SSL);
}
public int getServerSslPort() {
return getInt(ConfVars.ZEPPELIN_SSL_PORT);
}
public boolean useClientAuth() {
return getBoolean(ConfVars.ZEPPELIN_SSL_CLIENT_AUTH);
}
public String getServerAddress() {
return getString(ConfVars.ZEPPELIN_ADDR);
}
public int getServerPort() {
return getInt(ConfVars.ZEPPELIN_PORT);
}
public String getServerContextPath() {
return getString(ConfVars.ZEPPELIN_SERVER_CONTEXT_PATH);
}
public String getKeyStorePath() {
String path = getString(ConfVars.ZEPPELIN_SSL_KEYSTORE_PATH);
if (path != null && path.startsWith("/") || isWindowsPath(path)) {
return path;
} else {
return getRelativeDir(
String.format("%s/%s",
getConfDir(),
path));
}
}
public String getKeyStoreType() {
return getString(ConfVars.ZEPPELIN_SSL_KEYSTORE_TYPE);
}
public String getKeyStorePassword() {
return getString(ConfVars.ZEPPELIN_SSL_KEYSTORE_PASSWORD);
}
public String getKeyManagerPassword() {
String password = getString(ConfVars.ZEPPELIN_SSL_KEY_MANAGER_PASSWORD);
if (password == null) {
return getKeyStorePassword();
} else {
return password;
}
}
public String getTrustStorePath() {
String path = getString(ConfVars.ZEPPELIN_SSL_TRUSTSTORE_PATH);
if (path == null) {
path = getKeyStorePath();
}
if (path != null && path.startsWith("/") || isWindowsPath(path)) {
return path;
} else {
return getRelativeDir(
String.format("%s/%s",
getConfDir(),
path));
}
}
public String getTrustStoreType() {
String type = getString(ConfVars.ZEPPELIN_SSL_TRUSTSTORE_TYPE);
if (type == null) {
return getKeyStoreType();
} else {
return type;
}
}
public String getTrustStorePassword() {
String password = getString(ConfVars.ZEPPELIN_SSL_TRUSTSTORE_PASSWORD);
if (password == null) {
return getKeyStorePassword();
} else {
return password;
}
}
public String getNotebookDir() {
return getString(ConfVars.ZEPPELIN_NOTEBOOK_DIR);
}
public String getUser() {
return getString(ConfVars.ZEPPELIN_NOTEBOOK_S3_USER);
}
public String getBucketName() {
return getString(ConfVars.ZEPPELIN_NOTEBOOK_S3_BUCKET);
}
public String getEndpoint() {
return getString(ConfVars.ZEPPELIN_NOTEBOOK_S3_ENDPOINT);
}
public String getS3KMSKeyID() {
return getString(ConfVars.ZEPPELIN_NOTEBOOK_S3_KMS_KEY_ID);
}
public String getS3KMSKeyRegion() {
return getString(ConfVars.ZEPPELIN_NOTEBOOK_S3_KMS_KEY_REGION);
}
public String getS3EncryptionMaterialsProviderClass() {
return getString(ConfVars.ZEPPELIN_NOTEBOOK_S3_EMP);
}
public String getInterpreterListPath() {
return getRelativeDir(String.format("%s/interpreter-list", getConfDir()));
}
public String getInterpreterDir() {
return getRelativeDir(ConfVars.ZEPPELIN_INTERPRETER_DIR);
}
public String getInterpreterJson() {
return getString(ConfVars.ZEPPELIN_INTERPRETER_JSON);
}
public String getInterpreterSettingPath() {
return getRelativeDir(String.format("%s/interpreter.json", getConfDir()));
}
public String getHeliumConfPath() {
return getRelativeDir(String.format("%s/helium.json", getConfDir()));
}
public String getHeliumDefaultLocalRegistryPath() {
return getRelativeDir(ConfVars.ZEPPELIN_HELIUM_LOCALREGISTRY_DEFAULT);
}
public String getHeliumNpmRegistry() {
return getString(ConfVars.ZEPPELIN_HELIUM_NPM_REGISTRY);
}
public String getNotebookAuthorizationPath() {
return getRelativeDir(String.format("%s/notebook-authorization.json", getConfDir()));
}
public Boolean credentialsPersist() {
return getBoolean(ConfVars.ZEPPELIN_CREDENTIALS_PERSIST);
}
public String getCredentialsPath() {
return getRelativeDir(String.format("%s/credentials.json", getConfDir()));
}
public String getShiroPath() {
String shiroPath = getRelativeDir(String.format("%s/shiro.ini", getConfDir()));
return new File(shiroPath).exists() ? shiroPath : StringUtils.EMPTY;
}
public String getInterpreterRemoteRunnerPath() {
return getRelativeDir(ConfVars.ZEPPELIN_INTERPRETER_REMOTE_RUNNER);
}
public String getInterpreterLocalRepoPath() {
return getRelativeDir(ConfVars.ZEPPELIN_INTERPRETER_LOCALREPO);
}
public String getInterpreterMvnRepoPath() {
return getString(ConfVars.ZEPPELIN_INTERPRETER_DEP_MVNREPO);
}
public String getRelativeDir(ConfVars c) {
return getRelativeDir(getString(c));
}
public String getRelativeDir(String path) {
if (path != null && path.startsWith("/") || isWindowsPath(path)) {
return path;
} else {
return getString(ConfVars.ZEPPELIN_HOME) + "/" + path;
}
}
public boolean isWindowsPath(String path){
return path.matches("^[A-Za-z]:\\\\.*");
}
public boolean isAnonymousAllowed() {
return getBoolean(ConfVars.ZEPPELIN_ANONYMOUS_ALLOWED);
}
public boolean isNotebokPublic() {
return getBoolean(ConfVars.ZEPPELIN_NOTEBOOK_PUBLIC);
}
public String getConfDir() {
return getString(ConfVars.ZEPPELIN_CONF_DIR);
}
public List<String> getAllowedOrigins()
{
if (getString(ConfVars.ZEPPELIN_ALLOWED_ORIGINS).isEmpty()) {
return Arrays.asList(new String[0]);
}
return Arrays.asList(getString(ConfVars.ZEPPELIN_ALLOWED_ORIGINS).toLowerCase().split(","));
}
public String getWebsocketMaxTextMessageSize() {
return getString(ConfVars.ZEPPELIN_WEBSOCKET_MAX_TEXT_MESSAGE_SIZE);
}
public Map<String, String> dumpConfigurations(ZeppelinConfiguration conf,
ConfigurationKeyPredicate predicate) {
Map<String, String> configurations = new HashMap<>();
for (ZeppelinConfiguration.ConfVars v : ZeppelinConfiguration.ConfVars.values()) {
String key = v.getVarName();
if (!predicate.apply(key)) {
continue;
}
ConfVars.VarType type = v.getType();
Object value = null;
if (type == ConfVars.VarType.BOOLEAN) {
value = conf.getBoolean(v);
} else if (type == ConfVars.VarType.LONG) {
value = conf.getLong(v);
} else if (type == ConfVars.VarType.INT) {
value = conf.getInt(v);
} else if (type == ConfVars.VarType.FLOAT) {
value = conf.getFloat(v);
} else if (type == ConfVars.VarType.STRING) {
value = conf.getString(v);
}
if (value != null) {
configurations.put(key, value.toString());
}
}
return configurations;
}
/**
* Predication whether key/value pair should be included or not
*/
public interface ConfigurationKeyPredicate {
boolean apply(String key);
}
/**
* Wrapper class.
*/
public static enum ConfVars {
ZEPPELIN_HOME("zeppelin.home", "./"),
ZEPPELIN_ADDR("zeppelin.server.addr", "0.0.0.0"),
ZEPPELIN_PORT("zeppelin.server.port", 7045),
ZEPPELIN_SERVER_CONTEXT_PATH("zeppelin.server.context.path", "/"),
ZEPPELIN_SSL("zeppelin.ssl", false),
ZEPPELIN_SSL_PORT("zeppelin.server.ssl.port", 8443),
ZEPPELIN_SSL_CLIENT_AUTH("zeppelin.ssl.client.auth", false),
ZEPPELIN_SSL_KEYSTORE_PATH("zeppelin.ssl.keystore.path", "keystore"),
ZEPPELIN_SSL_KEYSTORE_TYPE("zeppelin.ssl.keystore.type", "JKS"),
ZEPPELIN_SSL_KEYSTORE_PASSWORD("zeppelin.ssl.keystore.password", ""),
ZEPPELIN_SSL_KEY_MANAGER_PASSWORD("zeppelin.ssl.key.manager.password", null),
ZEPPELIN_SSL_TRUSTSTORE_PATH("zeppelin.ssl.truststore.path", null),
ZEPPELIN_SSL_TRUSTSTORE_TYPE("zeppelin.ssl.truststore.type", null),
ZEPPELIN_SSL_TRUSTSTORE_PASSWORD("zeppelin.ssl.truststore.password", null),
ZEPPELIN_WAR("zeppelin.war", "dist"),
ZEPPELIN_WAR_TEMPDIR("zeppelin.war.tempdir", "webapps"),
ZEPPELIN_INTERPRETERS("zeppelin.interpreters", "org.apache.zeppelin.spark.SparkInterpreter,"
+ "org.apache.zeppelin.spark.PySparkInterpreter,"
+ "org.apache.zeppelin.rinterpreter.RRepl,"
+ "org.apache.zeppelin.rinterpreter.KnitR,"
+ "org.apache.zeppelin.spark.SparkRInterpreter,"
+ "org.apache.zeppelin.spark.SparkSqlInterpreter,"
+ "org.apache.zeppelin.spark.DepInterpreter,"
+ "org.apache.zeppelin.markdown.Markdown,"
+ "org.apache.zeppelin.angular.AngularInterpreter,"
+ "org.apache.zeppelin.shell.ShellInterpreter,"
+ "org.apache.zeppelin.livy.LivySparkInterpreter,"
+ "org.apache.zeppelin.livy.LivySparkSQLInterpreter,"
+ "org.apache.zeppelin.livy.LivyPySparkInterpreter,"
+ "org.apache.zeppelin.livy.LivyPySpark3Interpreter,"
+ "org.apache.zeppelin.livy.LivySparkRInterpreter,"
+ "org.apache.zeppelin.alluxio.AlluxioInterpreter,"
+ "org.apache.zeppelin.file.HDFSFileInterpreter,"
+ "org.apache.zeppelin.postgresql.PostgreSqlInterpreter,"
+ "org.apache.zeppelin.pig.PigInterpreter,"
+ "org.apache.zeppelin.pig.PigQueryInterpreter,"
+ "org.apache.zeppelin.flink.FlinkInterpreter,"
+ "org.apache.zeppelin.python.PythonInterpreter,"
+ "org.apache.zeppelin.python.PythonInterpreterPandasSql,"
+ "org.apache.zeppelin.python.PythonCondaInterpreter,"
+ "org.apache.zeppelin.python.PythonDockerInterpreter,"
+ "org.apache.zeppelin.ignite.IgniteInterpreter,"
+ "org.apache.zeppelin.ignite.IgniteSqlInterpreter,"
+ "org.apache.zeppelin.lens.LensInterpreter,"
+ "org.apache.zeppelin.cassandra.CassandraInterpreter,"
+ "org.apache.zeppelin.geode.GeodeOqlInterpreter,"
+ "org.apache.zeppelin.kylin.KylinInterpreter,"
+ "org.apache.zeppelin.elasticsearch.ElasticsearchInterpreter,"
+ "org.apache.zeppelin.scalding.ScaldingInterpreter,"
+ "org.apache.zeppelin.jdbc.JDBCInterpreter,"
+ "org.apache.zeppelin.hbase.HbaseInterpreter,"
+ "org.apache.zeppelin.bigquery.BigQueryInterpreter,"
+ "org.apache.zeppelin.beam.BeamInterpreter,"
+ "org.apache.zeppelin.scio.ScioInterpreter"),
ZEPPELIN_INTERPRETER_JSON("zeppelin.interpreter.setting", "interpreter-setting.json"),
ZEPPELIN_INTERPRETER_DIR("zeppelin.interpreter.dir", "interpreter"),
ZEPPELIN_INTERPRETER_LOCALREPO("zeppelin.interpreter.localRepo", "local-repo"),
ZEPPELIN_INTERPRETER_DEP_MVNREPO("zeppelin.interpreter.dep.mvnRepo",
"http://repo1.maven.org/maven2/"),
ZEPPELIN_INTERPRETER_CONNECT_TIMEOUT("zeppelin.interpreter.connect.timeout", 30000),
ZEPPELIN_INTERPRETER_MAX_POOL_SIZE("zeppelin.interpreter.max.poolsize", 10),
ZEPPELIN_INTERPRETER_GROUP_ORDER("zeppelin.interpreter.group.order", "spark,md,angular,sh,"
+ "livy,alluxio,file,psql,flink,python,ignite,lens,cassandra,geode,kylin,elasticsearch,"
+ "scalding,jdbc,hbase,bigquery,beam,pig,scio"),
ZEPPELIN_INTERPRETER_OUTPUT_LIMIT("zeppelin.interpreter.output.limit", 1024 * 100),
ZEPPELIN_ENCODING("zeppelin.encoding", "UTF-8"),
ZEPPELIN_NOTEBOOK_DIR("zeppelin.notebook.dir", "notebook"),
// use specified notebook (id) as homescreen
ZEPPELIN_NOTEBOOK_HOMESCREEN("zeppelin.notebook.homescreen", null),
// whether homescreen notebook will be hidden from notebook list or not
ZEPPELIN_NOTEBOOK_HOMESCREEN_HIDE("zeppelin.notebook.homescreen.hide", false),
ZEPPELIN_NOTEBOOK_S3_BUCKET("zeppelin.notebook.s3.bucket", "zeppelin"),
ZEPPELIN_NOTEBOOK_S3_ENDPOINT("zeppelin.notebook.s3.endpoint", "s3.amazonaws.com"),
ZEPPELIN_NOTEBOOK_S3_USER("zeppelin.notebook.s3.user", "user"),
ZEPPELIN_NOTEBOOK_S3_EMP("zeppelin.notebook.s3.encryptionMaterialsProvider", null),
ZEPPELIN_NOTEBOOK_S3_KMS_KEY_ID("zeppelin.notebook.s3.kmsKeyID", null),
ZEPPELIN_NOTEBOOK_S3_KMS_KEY_REGION("zeppelin.notebook.s3.kmsKeyRegion", null),
ZEPPELIN_NOTEBOOK_AZURE_CONNECTION_STRING("zeppelin.notebook.azure.connectionString", null),
ZEPPELIN_NOTEBOOK_AZURE_SHARE("zeppelin.notebook.azure.share", "zeppelin"),
ZEPPELIN_NOTEBOOK_AZURE_USER("zeppelin.notebook.azure.user", "user"),
ZEPPELIN_NOTEBOOK_STORAGE("zeppelin.notebook.storage", ""),
ZEPPELIN_NOTEBOOK_ONE_WAY_SYNC("zeppelin.notebook.one.way.sync", false),
// whether by default note is public or private
ZEPPELIN_NOTEBOOK_PUBLIC("zeppelin.notebook.public", true),
ZEPPELIN_INTERPRETER_REMOTE_RUNNER("zeppelin.interpreter.remoterunner",
System.getProperty("os.name")
.startsWith("Windows") ? "bin/interpreter.cmd" : "bin/interpreter.sh"),
// Decide when new note is created, interpreter settings will be binded automatically or not.
ZEPPELIN_NOTEBOOK_AUTO_INTERPRETER_BINDING("zeppelin.notebook.autoInterpreterBinding", true),
ZEPPELIN_CONF_DIR("zeppelin.conf.dir", "conf"),
ZEPPELIN_DEP_LOCALREPO("zeppelin.dep.localrepo", "local-repo"),
ZEPPELIN_HELIUM_LOCALREGISTRY_DEFAULT("zeppelin.helium.localregistry.default", "helium"),
ZEPPELIN_HELIUM_NPM_REGISTRY("zeppelin.helium.npm.registry", "http://registry.npmjs.org/"),
// Allows a way to specify a ',' separated list of allowed origins for rest and websockets
// i.e. http://localhost:8080
ZEPPELIN_ALLOWED_ORIGINS("zeppelin.server.allowed.origins", "*"),
ZEPPELIN_ANONYMOUS_ALLOWED("zeppelin.anonymous.allowed", true),
ZEPPELIN_CREDENTIALS_PERSIST("zeppelin.credentials.persist", true),
ZEPPELIN_WEBSOCKET_MAX_TEXT_MESSAGE_SIZE("zeppelin.websocket.max.text.message.size", "1024000");
private String varName;
@SuppressWarnings("rawtypes")
private Class varClass;
private String stringValue;
private VarType type;
private int intValue;
private float floatValue;
private boolean booleanValue;
private long longValue;
ConfVars(String varName, String varValue) {
this.varName = varName;
this.varClass = String.class;
this.stringValue = varValue;
this.intValue = -1;
this.floatValue = -1;
this.longValue = -1;
this.booleanValue = false;
this.type = VarType.STRING;
}
ConfVars(String varName, int intValue) {
this.varName = varName;
this.varClass = Integer.class;
this.stringValue = null;
this.intValue = intValue;
this.floatValue = -1;
this.longValue = -1;
this.booleanValue = false;
this.type = VarType.INT;
}
ConfVars(String varName, long longValue) {
this.varName = varName;
this.varClass = Integer.class;
this.stringValue = null;
this.intValue = -1;
this.floatValue = -1;
this.longValue = longValue;
this.booleanValue = false;
this.type = VarType.LONG;
}
ConfVars(String varName, float floatValue) {
this.varName = varName;
this.varClass = Float.class;
this.stringValue = null;
this.intValue = -1;
this.longValue = -1;
this.floatValue = floatValue;
this.booleanValue = false;
this.type = VarType.FLOAT;
}
ConfVars(String varName, boolean booleanValue) {
this.varName = varName;
this.varClass = Boolean.class;
this.stringValue = null;
this.intValue = -1;
this.longValue = -1;
this.floatValue = -1;
this.booleanValue = booleanValue;
this.type = VarType.BOOLEAN;
}
public String getVarName() {
return varName;
}
@SuppressWarnings("rawtypes")
public Class getVarClass() {
return varClass;
}
public int getIntValue() {
return intValue;
}
public long getLongValue() {
return longValue;
}
public float getFloatValue() {
return floatValue;
}
public String getStringValue() {
return stringValue;
}
public boolean getBooleanValue() {
return booleanValue;
}
public VarType getType() {
return type;
}
enum VarType {
STRING {
@Override
void checkType(String value) throws Exception {}
},
INT {
@Override
void checkType(String value) throws Exception {
Integer.valueOf(value);
}
},
LONG {
@Override
void checkType(String value) throws Exception {
Long.valueOf(value);
}
},
FLOAT {
@Override
void checkType(String value) throws Exception {
Float.valueOf(value);
}
},
BOOLEAN {
@Override
void checkType(String value) throws Exception {
Boolean.valueOf(value);
}
};
boolean isType(String value) {
try {
checkType(value);
} catch (Exception e) {
LOG.error("Exception in ZeppelinConfiguration while isType", e);
return false;
}
return true;
}
String typeString() {
return name().toUpperCase();
}
abstract void checkType(String value) throws Exception;
}
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/Notebook.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/Notebook.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.notebook;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Sets;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.stream.JsonReader;
import org.apache.zeppelin.interpreter.*;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.zeppelin.conf.ZeppelinConfiguration;
import org.apache.zeppelin.conf.ZeppelinConfiguration.ConfVars;
import org.apache.zeppelin.display.AngularObject;
import org.apache.zeppelin.display.AngularObjectRegistry;
import org.apache.zeppelin.interpreter.remote.RemoteAngularObjectRegistry;
import org.apache.zeppelin.notebook.repo.NotebookRepo;
import org.apache.zeppelin.notebook.repo.NotebookRepo.Revision;
import org.apache.zeppelin.notebook.repo.NotebookRepoSync;
import org.apache.zeppelin.resource.ResourcePoolUtils;
import org.apache.zeppelin.scheduler.Job;
import org.apache.zeppelin.scheduler.SchedulerFactory;
import org.apache.zeppelin.search.SearchService;
import org.apache.zeppelin.user.AuthenticationInfo;
import org.apache.zeppelin.user.Credentials;
/**
* Collection of Notes.
*/
public class Notebook implements NoteEventListener {
private static final Logger logger = LoggerFactory.getLogger(Notebook.class);
@SuppressWarnings("unused") @Deprecated //TODO(bzz): remove unused
private SchedulerFactory schedulerFactory;
private InterpreterFactory replFactory;
private InterpreterSettingManager interpreterSettingManager;
/**
* Keep the order.
*/
private final Map<String, Note> notes = new LinkedHashMap<>();
private final FolderView folders = new FolderView();
private ZeppelinConfiguration conf;
private StdSchedulerFactory quertzSchedFact;
private org.quartz.Scheduler quartzSched;
private JobListenerFactory jobListenerFactory;
private NotebookRepo notebookRepo;
private SearchService noteSearchService;
private NotebookAuthorization notebookAuthorization;
private final List<NotebookEventListener> notebookEventListeners =
Collections.synchronizedList(new LinkedList<NotebookEventListener>());
private Credentials credentials;
/**
* Main constructor \w manual Dependency Injection
*
* @param noteSearchService - (nullable) for indexing all notebooks on creating.
* @throws IOException
* @throws SchedulerException
*/
public Notebook(ZeppelinConfiguration conf, NotebookRepo notebookRepo,
SchedulerFactory schedulerFactory, InterpreterFactory replFactory,
InterpreterSettingManager interpreterSettingManager, JobListenerFactory jobListenerFactory,
SearchService noteSearchService, NotebookAuthorization notebookAuthorization,
Credentials credentials) throws IOException, SchedulerException {
this.conf = conf;
this.notebookRepo = notebookRepo;
this.schedulerFactory = schedulerFactory;
this.replFactory = replFactory;
this.interpreterSettingManager = interpreterSettingManager;
this.jobListenerFactory = jobListenerFactory;
this.noteSearchService = noteSearchService;
this.notebookAuthorization = notebookAuthorization;
this.credentials = credentials;
quertzSchedFact = new org.quartz.impl.StdSchedulerFactory();
quartzSched = quertzSchedFact.getScheduler();
quartzSched.start();
CronJob.notebook = this;
AuthenticationInfo anonymous = AuthenticationInfo.ANONYMOUS;
loadAllNotes(anonymous);
if (this.noteSearchService != null) {
long start = System.nanoTime();
logger.info("Notebook indexing started...");
noteSearchService.addIndexDocs(notes.values());
logger.info("Notebook indexing finished: {} indexed in {}s", notes.size(),
TimeUnit.NANOSECONDS.toSeconds(start - System.nanoTime()));
}
}
/**
* Create new note.
*
* @throws IOException
*/
public Note createNote(AuthenticationInfo subject) throws IOException {
Preconditions.checkNotNull(subject, "AuthenticationInfo should not be null");
Note note;
if (conf.getBoolean(ConfVars.ZEPPELIN_NOTEBOOK_AUTO_INTERPRETER_BINDING)) {
note = createNote(interpreterSettingManager.getDefaultInterpreterSettingList(), subject);
} else {
note = createNote(null, subject);
}
noteSearchService.addIndexDoc(note);
return note;
}
/**
* Create new note.
*
* @throws IOException
*/
public Note createNote(List<String> interpreterIds, AuthenticationInfo subject)
throws IOException {
Note note =
new Note(notebookRepo, replFactory, interpreterSettingManager, jobListenerFactory,
noteSearchService, credentials, this);
note.setNoteNameListener(folders);
synchronized (notes) {
notes.put(note.getId(), note);
}
if (interpreterIds != null) {
bindInterpretersToNote(subject.getUser(), note.getId(), interpreterIds);
}
notebookAuthorization.setNewNotePermissions(note.getId(), subject);
noteSearchService.addIndexDoc(note);
note.persist(subject);
fireNoteCreateEvent(note);
return note;
}
/**
* Export existing note.
*
* @param noteId - the note ID to clone
* @return Note JSON
* @throws IOException, IllegalArgumentException
*/
public String exportNote(String noteId) throws IOException, IllegalArgumentException {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setPrettyPrinting();
Gson gson = gsonBuilder.create();
Note note = getNote(noteId);
if (note == null) {
throw new IllegalArgumentException(noteId + " not found");
}
return gson.toJson(note);
}
/**
* import JSON as a new note.
*
* @param sourceJson - the note JSON to import
* @param noteName - the name of the new note
* @return note ID
* @throws IOException
*/
public Note importNote(String sourceJson, String noteName, AuthenticationInfo subject)
throws IOException {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setPrettyPrinting();
Gson gson =
gsonBuilder.registerTypeAdapter(Date.class, new NotebookImportDeserializer()).create();
JsonReader reader = new JsonReader(new StringReader(sourceJson));
reader.setLenient(true);
Note newNote;
try {
Note oldNote = gson.fromJson(reader, Note.class);
convertFromSingleResultToMultipleResultsFormat(oldNote);
newNote = createNote(subject);
if (noteName != null)
newNote.setName(noteName);
else
newNote.setName(oldNote.getName());
List<Paragraph> paragraphs = oldNote.getParagraphs();
for (Paragraph p : paragraphs) {
newNote.addCloneParagraph(p);
}
notebookAuthorization.setNewNotePermissions(newNote.getId(), subject);
newNote.persist(subject);
} catch (IOException e) {
logger.error(e.toString(), e);
throw e;
}
return newNote;
}
/**
* Clone existing note.
*
* @param sourceNoteId - the note ID to clone
* @param newNoteName - the name of the new note
* @return noteId
* @throws IOException, CloneNotSupportedException, IllegalArgumentException
*/
public Note cloneNote(String sourceNoteId, String newNoteName, AuthenticationInfo subject)
throws IOException, CloneNotSupportedException, IllegalArgumentException {
Note sourceNote = getNote(sourceNoteId);
if (sourceNote == null) {
throw new IllegalArgumentException(sourceNoteId + "not found");
}
Note newNote = createNote(subject);
if (newNoteName != null) {
newNote.setName(newNoteName);
} else {
newNote.setName("Note " + newNote.getId());
}
// Copy the interpreter bindings
List<String> boundInterpreterSettingsIds = getBindedInterpreterSettingsIds(sourceNote.getId());
bindInterpretersToNote(subject.getUser(), newNote.getId(), boundInterpreterSettingsIds);
List<Paragraph> paragraphs = sourceNote.getParagraphs();
for (Paragraph p : paragraphs) {
newNote.addCloneParagraph(p);
}
noteSearchService.addIndexDoc(newNote);
newNote.persist(subject);
return newNote;
}
public void bindInterpretersToNote(String user, String id, List<String> interpreterSettingIds)
throws IOException {
Note note = getNote(id);
if (note != null) {
List<InterpreterSetting> currentBindings =
interpreterSettingManager.getInterpreterSettings(id);
for (InterpreterSetting setting : currentBindings) {
if (!interpreterSettingIds.contains(setting.getId())) {
fireUnbindInterpreter(note, setting);
}
}
interpreterSettingManager.setInterpreters(user, note.getId(), interpreterSettingIds);
// comment out while note.getNoteReplLoader().setInterpreters(...) do the same
// replFactory.putNoteInterpreterSettingBinding(id, interpreterSettingIds);
}
}
List<String> getBindedInterpreterSettingsIds(String id) {
Note note = getNote(id);
if (note != null) {
return interpreterSettingManager.getInterpreters(note.getId());
} else {
return new LinkedList<>();
}
}
public List<InterpreterSetting> getBindedInterpreterSettings(String id) {
Note note = getNote(id);
if (note != null) {
return interpreterSettingManager.getInterpreterSettings(note.getId());
} else {
return new LinkedList<>();
}
}
public Note getNote(String id) {
synchronized (notes) {
return notes.get(id);
}
}
public Folder getFolder(String folderId) {
synchronized (folders) {
return folders.getFolder(folderId);
}
}
public boolean hasFolder(String folderId) {
synchronized (folders) {
return folders.hasFolder(folderId);
}
}
public void moveNoteToTrash(String noteId) {
for (InterpreterSetting interpreterSetting : interpreterSettingManager
.getInterpreterSettings(noteId)) {
interpreterSettingManager.removeInterpretersForNote(interpreterSetting, "", noteId);
}
}
public void removeNote(String id, AuthenticationInfo subject) {
Preconditions.checkNotNull(subject, "AuthenticationInfo should not be null");
Note note;
synchronized (notes) {
note = notes.remove(id);
folders.removeNote(note);
}
try {
interpreterSettingManager.removeNoteInterpreterSettingBinding(subject.getUser(), id);
} catch (IOException e) {
logger.error(e.toString(), e);
}
noteSearchService.deleteIndexDocs(note);
notebookAuthorization.removeNote(id);
// remove from all interpreter instance's angular object registry
for (InterpreterSetting settings : interpreterSettingManager.get()) {
AngularObjectRegistry registry =
settings.getInterpreterGroup(subject.getUser(), id).getAngularObjectRegistry();
if (registry instanceof RemoteAngularObjectRegistry) {
// remove paragraph scope object
for (Paragraph p : note.getParagraphs()) {
((RemoteAngularObjectRegistry) registry).removeAllAndNotifyRemoteProcess(id, p.getId());
// remove app scope object
List<ApplicationState> appStates = p.getAllApplicationStates();
if (appStates != null) {
for (ApplicationState app : appStates) {
((RemoteAngularObjectRegistry) registry)
.removeAllAndNotifyRemoteProcess(id, app.getId());
}
}
}
// remove note scope object
((RemoteAngularObjectRegistry) registry).removeAllAndNotifyRemoteProcess(id, null);
} else {
// remove paragraph scope object
for (Paragraph p : note.getParagraphs()) {
registry.removeAll(id, p.getId());
// remove app scope object
List<ApplicationState> appStates = p.getAllApplicationStates();
if (appStates != null) {
for (ApplicationState app : appStates) {
registry.removeAll(id, app.getId());
}
}
}
// remove note scope object
registry.removeAll(id, null);
}
}
ResourcePoolUtils.removeResourcesBelongsToNote(id);
fireNoteRemoveEvent(note);
try {
note.unpersist(subject);
} catch (IOException e) {
logger.error(e.toString(), e);
}
}
public Revision checkpointNote(String noteId, String checkpointMessage,
AuthenticationInfo subject) throws IOException {
return notebookRepo.checkpoint(noteId, checkpointMessage, subject);
}
public List<Revision> listRevisionHistory(String noteId,
AuthenticationInfo subject) {
return notebookRepo.revisionHistory(noteId, subject);
}
public Note setNoteRevision(String noteId, String revisionId, AuthenticationInfo subject)
throws IOException {
return notebookRepo.setNoteRevision(noteId, revisionId, subject);
}
public Note getNoteByRevision(String noteId, String revisionId, AuthenticationInfo subject)
throws IOException {
return notebookRepo.get(noteId, revisionId, subject);
}
public void convertFromSingleResultToMultipleResultsFormat(Note note) {
for (Paragraph p : note.paragraphs) {
Object ret = p.getPreviousResultFormat();
if (ret != null && p.results != null) {
continue; // already converted
}
try {
if (ret != null && ret instanceof Map) {
Map r = ((Map) ret);
if (r.containsKey("code") &&
r.containsKey("msg") &&
r.containsKey("type")) { // all three fields exists in sinle result format
InterpreterResult.Code code = InterpreterResult.Code.valueOf((String) r.get("code"));
InterpreterResult.Type type = InterpreterResult.Type.valueOf((String) r.get("type"));
String msg = (String) r.get("msg");
InterpreterResult result = new InterpreterResult(code, msg);
if (result.message().size() == 1) {
result = new InterpreterResult(code);
result.add(type, msg);
}
p.setResult(result);
// convert config
Map<String, Object> config = p.getConfig();
Object graph = config.remove("graph");
Object apps = config.remove("apps");
Object helium = config.remove("helium");
List<Object> results = new LinkedList<>();
for (int i = 0; i < result.message().size(); i++) {
if (i == result.message().size() - 1) {
HashMap<Object, Object> res = new HashMap<>();
res.put("graph", graph);
res.put("apps", apps);
res.put("helium", helium);
results.add(res);
} else {
results.add(new HashMap<>());
}
}
config.put("results", results);
}
}
} catch (Exception e) {
logger.error("Conversion failure", e);
}
}
}
@SuppressWarnings("rawtypes")
public Note loadNoteFromRepo(String id, AuthenticationInfo subject) {
Note note = null;
try {
note = notebookRepo.get(id, subject);
} catch (IOException e) {
logger.error("Failed to load " + id, e);
}
if (note == null) {
return null;
}
convertFromSingleResultToMultipleResultsFormat(note);
//Manually inject ALL dependencies, as DI constructor was NOT used
note.setIndex(this.noteSearchService);
note.setCredentials(this.credentials);
note.setInterpreterFactory(replFactory);
note.setInterpreterSettingManager(interpreterSettingManager);
note.setJobListenerFactory(jobListenerFactory);
note.setNotebookRepo(notebookRepo);
Map<String, SnapshotAngularObject> angularObjectSnapshot = new HashMap<>();
// restore angular object --------------
Date lastUpdatedDate = new Date(0);
for (Paragraph p : note.getParagraphs()) {
p.setNote(note);
if (p.getDateFinished() != null && lastUpdatedDate.before(p.getDateFinished())) {
lastUpdatedDate = p.getDateFinished();
}
}
Map<String, List<AngularObject>> savedObjects = note.getAngularObjects();
if (savedObjects != null) {
for (String intpGroupName : savedObjects.keySet()) {
List<AngularObject> objectList = savedObjects.get(intpGroupName);
for (AngularObject object : objectList) {
SnapshotAngularObject snapshot = angularObjectSnapshot.get(object.getName());
if (snapshot == null || snapshot.getLastUpdate().before(lastUpdatedDate)) {
angularObjectSnapshot.put(object.getName(),
new SnapshotAngularObject(intpGroupName, object, lastUpdatedDate));
}
}
}
}
note.setNoteEventListener(this);
note.setNoteNameListener(folders);
synchronized (notes) {
notes.put(note.getId(), note);
folders.putNote(note);
refreshCron(note.getId());
}
for (String name : angularObjectSnapshot.keySet()) {
SnapshotAngularObject snapshot = angularObjectSnapshot.get(name);
List<InterpreterSetting> settings = interpreterSettingManager.get();
for (InterpreterSetting setting : settings) {
InterpreterGroup intpGroup = setting.getInterpreterGroup(subject.getUser(), note.getId());
if (intpGroup.getId().equals(snapshot.getIntpGroupId())) {
AngularObjectRegistry registry = intpGroup.getAngularObjectRegistry();
String noteId = snapshot.getAngularObject().getNoteId();
String paragraphId = snapshot.getAngularObject().getParagraphId();
// at this point, remote interpreter process is not created.
// so does not make sense add it to the remote.
//
// therefore instead of addAndNotifyRemoteProcess(), need to use add()
// that results add angularObject only in ZeppelinServer side not remoteProcessSide
registry.add(name, snapshot.getAngularObject().get(), noteId, paragraphId);
}
}
}
return note;
}
void loadAllNotes(AuthenticationInfo subject) throws IOException {
List<NoteInfo> noteInfos = notebookRepo.list(subject);
for (NoteInfo info : noteInfos) {
loadNoteFromRepo(info.getId(), subject);
}
}
/**
* Reload all notes from repository after clearing `notes` and `folders`
* to reflect the changes of added/deleted/modified notes on file system level.
*
* @throws IOException
*/
public void reloadAllNotes(AuthenticationInfo subject) throws IOException {
synchronized (notes) {
notes.clear();
}
synchronized (folders) {
folders.clear();
}
if (notebookRepo instanceof NotebookRepoSync) {
NotebookRepoSync mainRepo = (NotebookRepoSync) notebookRepo;
if (mainRepo.getRepoCount() > 1) {
mainRepo.sync(subject);
}
}
List<NoteInfo> noteInfos = notebookRepo.list(subject);
for (NoteInfo info : noteInfos) {
loadNoteFromRepo(info.getId(), subject);
}
}
private class SnapshotAngularObject {
String intpGroupId;
AngularObject angularObject;
Date lastUpdate;
SnapshotAngularObject(String intpGroupId, AngularObject angularObject, Date lastUpdate) {
super();
this.intpGroupId = intpGroupId;
this.angularObject = angularObject;
this.lastUpdate = lastUpdate;
}
String getIntpGroupId() {
return intpGroupId;
}
AngularObject getAngularObject() {
return angularObject;
}
Date getLastUpdate() {
return lastUpdate;
}
}
public Folder renameFolder(String oldFolderId, String newFolderId) {
return folders.renameFolder(oldFolderId, newFolderId);
}
public List<Note> getNotesUnderFolder(String folderId) {
return folders.getFolder(folderId).getNotesRecursively();
}
public List<Note> getAllNotes() {
synchronized (notes) {
List<Note> noteList = new ArrayList<>(notes.values());
Collections.sort(noteList, new Comparator<Note>() {
@Override
public int compare(Note note1, Note note2) {
String name1 = note1.getId();
if (note1.getName() != null) {
name1 = note1.getName();
}
String name2 = note2.getId();
if (note2.getName() != null) {
name2 = note2.getName();
}
return name1.compareTo(name2);
}
});
return noteList;
}
}
public List<Note> getAllNotes(Set<String> userAndRoles) {
final Set<String> entities = Sets.newHashSet();
if (userAndRoles != null) {
entities.addAll(userAndRoles);
}
synchronized (notes) {
return FluentIterable.from(notes.values()).filter(new Predicate<Note>() {
@Override
public boolean apply(Note input) {
return input != null && notebookAuthorization.isReader(input.getId(), entities);
}
}).toSortedList(new Comparator<Note>() {
@Override
public int compare(Note note1, Note note2) {
String name1 = note1.getId();
if (note1.getName() != null) {
name1 = note1.getName();
}
String name2 = note2.getId();
if (note2.getName() != null) {
name2 = note2.getName();
}
return name1.compareTo(name2);
}
});
}
}
private Map<String, Object> getParagraphForJobManagerItem(Paragraph paragraph) {
Map<String, Object> paragraphItem = new HashMap<>();
// set paragraph id
paragraphItem.put("id", paragraph.getId());
// set paragraph name
String paragraphName = paragraph.getTitle();
if (paragraphName != null) {
paragraphItem.put("name", paragraphName);
} else {
paragraphItem.put("name", paragraph.getId());
}
// set status for paragraph.
paragraphItem.put("status", paragraph.getStatus().toString());
return paragraphItem;
}
private long getUnixTimeLastRunParagraph(Paragraph paragraph) {
Date lastRunningDate;
long lastRunningUnixTime;
Date paragaraphDate = paragraph.getDateStarted();
// diff started time <-> finishied time
if (paragaraphDate == null) {
paragaraphDate = paragraph.getDateFinished();
} else {
if (paragraph.getDateFinished() != null && paragraph.getDateFinished()
.after(paragaraphDate)) {
paragaraphDate = paragraph.getDateFinished();
}
}
// finished time and started time is not exists.
if (paragaraphDate == null) {
paragaraphDate = paragraph.getDateCreated();
}
// set last update unixtime(ms).
lastRunningDate = paragaraphDate;
lastRunningUnixTime = lastRunningDate.getTime();
return lastRunningUnixTime;
}
public List<Map<String, Object>> getJobListByParagraphId(String paragraphId) {
String gotNoteId = null;
List<Note> notes = getAllNotes();
for (Note note : notes) {
Paragraph p = note.getParagraph(paragraphId);
if (p != null) {
gotNoteId = note.getId();
}
}
return getJobListByNoteId(gotNoteId);
}
public List<Map<String, Object>> getJobListByNoteId(String noteId) {
final String CRON_TYPE_NOTE_KEYWORD = "cron";
long lastRunningUnixTime = 0;
boolean isNoteRunning = false;
Note jobNote = getNote(noteId);
List<Map<String, Object>> notesInfo = new LinkedList<>();
if (jobNote == null) {
return notesInfo;
}
Map<String, Object> info = new HashMap<>();
info.put("noteId", jobNote.getId());
String noteName = jobNote.getName();
if (noteName != null && !noteName.equals("")) {
info.put("noteName", jobNote.getName());
} else {
info.put("noteName", "Note " + jobNote.getId());
}
// set note type ( cron or normal )
if (jobNote.getConfig().containsKey(CRON_TYPE_NOTE_KEYWORD) && !jobNote.getConfig()
.get(CRON_TYPE_NOTE_KEYWORD).equals("")) {
info.put("noteType", "cron");
} else {
info.put("noteType", "normal");
}
// set paragraphs
List<Map<String, Object>> paragraphsInfo = new LinkedList<>();
for (Paragraph paragraph : jobNote.getParagraphs()) {
// check paragraph's status.
if (paragraph.getStatus().isRunning()) {
isNoteRunning = true;
}
// get data for the job manager.
Map<String, Object> paragraphItem = getParagraphForJobManagerItem(paragraph);
lastRunningUnixTime = getUnixTimeLastRunParagraph(paragraph);
paragraphsInfo.add(paragraphItem);
}
// set interpreter bind type
String interpreterGroupName = null;
if (interpreterSettingManager.getInterpreterSettings(jobNote.getId()) != null
&& interpreterSettingManager.getInterpreterSettings(jobNote.getId()).size() >= 1) {
interpreterGroupName =
interpreterSettingManager.getInterpreterSettings(jobNote.getId()).get(0).getName();
}
// note json object root information.
info.put("interpreter", interpreterGroupName);
info.put("isRunningJob", isNoteRunning);
info.put("unixTimeLastRun", lastRunningUnixTime);
info.put("paragraphs", paragraphsInfo);
notesInfo.add(info);
return notesInfo;
};
public List<Map<String, Object>> getJobListByUnixTime(boolean needsReload,
long lastUpdateServerUnixTime, AuthenticationInfo subject) {
final String CRON_TYPE_NOTE_KEYWORD = "cron";
if (needsReload) {
try {
reloadAllNotes(subject);
} catch (IOException e) {
logger.error("Fail to reload notes from repository");
}
}
List<Note> notes = getAllNotes();
List<Map<String, Object>> notesInfo = new LinkedList<>();
for (Note note : notes) {
boolean isNoteRunning = false;
boolean isUpdateNote = false;
long lastRunningUnixTime = 0;
Map<String, Object> info = new HashMap<>();
// set note ID
info.put("noteId", note.getId());
// set note Name
String noteName = note.getName();
if (noteName != null && !noteName.equals("")) {
info.put("noteName", note.getName());
} else {
info.put("noteName", "Note " + note.getId());
}
// set note type ( cron or normal )
if (note.getConfig().containsKey(CRON_TYPE_NOTE_KEYWORD) && !note.getConfig()
.get(CRON_TYPE_NOTE_KEYWORD).equals("")) {
info.put("noteType", "cron");
} else {
info.put("noteType", "normal");
}
// set paragraphs
List<Map<String, Object>> paragraphsInfo = new LinkedList<>();
for (Paragraph paragraph : note.getParagraphs()) {
// check paragraph's status.
if (paragraph.getStatus().isRunning()) {
isNoteRunning = true;
isUpdateNote = true;
}
// get data for the job manager.
Map<String, Object> paragraphItem = getParagraphForJobManagerItem(paragraph);
lastRunningUnixTime = getUnixTimeLastRunParagraph(paragraph);
// is update note for last server update time.
if (lastRunningUnixTime > lastUpdateServerUnixTime) {
isUpdateNote = true;
}
paragraphsInfo.add(paragraphItem);
}
// set interpreter bind type
String interpreterGroupName = null;
if (interpreterSettingManager.getInterpreterSettings(note.getId()) != null
&& interpreterSettingManager.getInterpreterSettings(note.getId()).size() >= 1) {
interpreterGroupName =
interpreterSettingManager.getInterpreterSettings(note.getId()).get(0).getName();
}
// not update and not running -> pass
if (!isUpdateNote && !isNoteRunning) {
continue;
}
// note json object root information.
info.put("interpreter", interpreterGroupName);
info.put("isRunningJob", isNoteRunning);
info.put("unixTimeLastRun", lastRunningUnixTime);
info.put("paragraphs", paragraphsInfo);
notesInfo.add(info);
}
return notesInfo;
}
/**
* Cron task for the note.
*/
public static class CronJob implements org.quartz.Job {
public static Notebook notebook;
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
String noteId = context.getJobDetail().getJobDataMap().getString("noteId");
Note note = notebook.getNote(noteId);
note.runAll();
while (!note.isTerminated()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
logger.error(e.toString(), e);
}
}
boolean releaseResource = false;
try {
Map<String, Object> config = note.getConfig();
if (config != null && config.containsKey("releaseresource")) {
releaseResource = (boolean) note.getConfig().get("releaseresource");
}
} catch (ClassCastException e) {
logger.error(e.getMessage(), e);
}
if (releaseResource) {
for (InterpreterSetting setting : notebook.getInterpreterSettingManager()
.getInterpreterSettings(note.getId())) {
notebook.getInterpreterSettingManager().restart(setting.getId());
}
}
}
}
public void refreshCron(String id) {
removeCron(id);
synchronized (notes) {
Note note = notes.get(id);
if (note == null) {
return;
}
Map<String, Object> config = note.getConfig();
if (config == null) {
return;
}
String cronExpr = (String) note.getConfig().get("cron");
if (cronExpr == null || cronExpr.trim().length() == 0) {
return;
}
JobDetail newJob =
JobBuilder.newJob(CronJob.class).withIdentity(id, "note").usingJobData("noteId", id)
.build();
Map<String, Object> info = note.getInfo();
info.put("cron", null);
CronTrigger trigger = null;
try {
trigger = TriggerBuilder.newTrigger().withIdentity("trigger_" + id, "note")
.withSchedule(CronScheduleBuilder.cronSchedule(cronExpr)).forJob(id, "note").build();
} catch (Exception e) {
logger.error("Error", e);
info.put("cron", e.getMessage());
}
try {
if (trigger != null) {
quartzSched.scheduleJob(newJob, trigger);
}
} catch (SchedulerException e) {
logger.error("Error", e);
info.put("cron", "Scheduler Exception");
}
}
}
private void removeCron(String id) {
try {
quartzSched.deleteJob(new JobKey(id, "note"));
} catch (SchedulerException e) {
logger.error("Can't remove quertz " + id, e);
}
}
public InterpreterFactory getInterpreterFactory() {
return replFactory;
}
public InterpreterSettingManager getInterpreterSettingManager() {
return interpreterSettingManager;
}
public NotebookAuthorization getNotebookAuthorization() {
return notebookAuthorization;
}
public ZeppelinConfiguration getConf() {
return conf;
}
public void close() {
this.notebookRepo.close();
this.noteSearchService.close();
}
public void addNotebookEventListener(NotebookEventListener listener) {
notebookEventListeners.add(listener);
}
private void fireNoteCreateEvent(Note note) {
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | true |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/NoteInfo.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/NoteInfo.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.notebook;
import java.util.HashMap;
import java.util.Map;
/**
*
*/
public class NoteInfo {
String id;
String name;
private Map<String, Object> config = new HashMap<>();
public NoteInfo(String id, String name, Map<String, Object> config) {
super();
this.id = id;
this.name = name;
this.config = config;
}
public NoteInfo(Note note) {
id = note.getId();
name = note.getName();
config = note.getConfig();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map<String, Object> getConfig() {
return config;
}
public void setConfig(Map<String, Object> config) {
this.config = config;
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/JobListenerFactory.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/JobListenerFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 org.apache.zeppelin.notebook;
/**
* TODO(moon): provide description.
*/
public interface JobListenerFactory {
public ParagraphJobListener getParagraphJobListener(Note note);
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.