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-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/FolderView.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/FolderView.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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Folder view of notes of Notebook.
* FolderView allows you to see notes from perspective of folders.
*/
public class FolderView implements NoteNameListener, FolderListener {
// key: folderId
private final Map<String, Folder> folders = new LinkedHashMap<>();
// key: a note, value: a folder where the note belongs to
private final Map<Note, Folder> index = new LinkedHashMap<>();
private static final Logger logger = LoggerFactory.getLogger(FolderView.class);
public Folder getFolder(String folderId) {
String normalizedFolderId = Folder.normalizeFolderId(folderId);
return folders.get(normalizedFolderId);
}
/**
* Rename folder of which id is folderId to newFolderId
*
* @param oldFolderId folderId to rename
* @param newFolderId newFolderId
* @return `null` if folder not exists, else old Folder
* in order to know which notes and child folders are renamed
*/
public Folder renameFolder(String oldFolderId, String newFolderId) {
String normOldFolderId = Folder.normalizeFolderId(oldFolderId);
String normNewFolderId = Folder.normalizeFolderId(newFolderId);
if (!hasFolder(normOldFolderId))
return null;
if (oldFolderId.equals(Folder.ROOT_FOLDER_ID)) // cannot rename the root folder
return null;
// check whether oldFolderId and newFolderId are same or not
if (normOldFolderId.equals(normNewFolderId))
return getFolder(normOldFolderId);
logger.info("Rename {} to {}", normOldFolderId, normNewFolderId);
Folder oldFolder = getFolder(normOldFolderId);
removeFolder(oldFolderId);
oldFolder.rename(normNewFolderId);
return oldFolder;
}
public Folder getFolderOf(Note note) {
return index.get(note);
}
public void putNote(Note note) {
if (note.isNameEmpty()) {
return;
}
String folderId = note.getFolderId();
Folder folder = getOrCreateFolder(folderId);
folder.addNote(note);
synchronized (index) {
index.put(note, folder);
}
}
private Folder getOrCreateFolder(String folderId) {
if (folders.containsKey(folderId))
return folders.get(folderId);
return createFolder(folderId);
}
private Folder createFolder(String folderId) {
folderId = Folder.normalizeFolderId(folderId);
Folder newFolder = new Folder(folderId);
newFolder.addFolderListener(this);
logger.info("Create folder {}", folderId);
synchronized (folders) {
folders.put(folderId, newFolder);
}
Folder parentFolder = getOrCreateFolder(newFolder.getParentFolderId());
newFolder.setParent(parentFolder);
parentFolder.addChild(newFolder);
return newFolder;
}
private void removeFolder(String folderId) {
Folder removedFolder;
synchronized (folders) {
removedFolder = folders.remove(folderId);
}
if (removedFolder != null) {
logger.info("Remove folder {}", folderId);
Folder parent = removedFolder.getParent();
parent.removeChild(folderId);
removeFolderIfEmpty(parent.getId());
}
}
private void removeFolderIfEmpty(String folderId) {
if (!hasFolder(folderId))
return;
Folder folder = getFolder(folderId);
if (folder.countNotes() == 0 && !folder.hasChild()) {
logger.info("Folder {} is empty", folder.getId());
removeFolder(folderId);
}
}
public void removeNote(Note note) {
if (!index.containsKey(note)) {
return;
}
Folder folder = index.get(note);
folder.removeNote(note);
removeFolderIfEmpty(folder.getId());
synchronized (index) {
index.remove(note);
}
}
public void clear() {
synchronized (folders) {
folders.clear();
}
synchronized (index) {
index.clear();
}
}
public boolean hasFolder(String folderId) {
return getFolder(folderId) != null;
}
public boolean hasNote(Note note) {
return index.containsKey(note);
}
public int countFolders() {
return folders.size();
}
public int countNotes() {
int count = 0;
for (Folder folder : folders.values()) {
count += folder.countNotes();
}
return count;
}
/**
* Fired after a note's setName() run.
* When the note's name changed, FolderView should check if the note is in the right folder.
*
* @param note
* @param oldName
*/
@Override
public void onNoteNameChanged(Note note, String oldName) {
if (note.isNameEmpty()) {
return;
}
logger.info("Note name changed: {} -> {}", oldName, note.getName());
// New note
if (!index.containsKey(note)) {
putNote(note);
}
// Existing note
else {
// If the note is in the right place, just return
Folder folder = index.get(note);
if (folder.getId().equals(note.getFolderId())) {
return;
}
// The note's folder is changed!
removeNote(note);
putNote(note);
}
}
@Override
public void onFolderRenamed(Folder folder, String oldFolderId) {
if (getFolder(folder.getId()) == folder) // the folder is at the right place
return;
logger.info("folder renamed: {} -> {}", oldFolderId, folder.getId());
if (getFolder(oldFolderId) == folder)
folders.remove(oldFolderId);
Folder newFolder = getOrCreateFolder(folder.getId());
newFolder.merge(folder);
for (Note note : folder.getNotes()) {
index.put(note, newFolder);
}
}
}
| 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/NoteEventListener.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/NoteEventListener.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.scheduler.Job;
/**
* NoteEventListener
*/
public interface NoteEventListener {
public void onParagraphRemove(Paragraph p);
public void onParagraphCreate(Paragraph p);
public void onParagraphStatusChange(Paragraph p, Job.Status status);
}
| 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/FolderListener.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/FolderListener.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;
/**
* Folder listener used by FolderView
*/
public interface FolderListener {
void onFolderRenamed(Folder folder, String oldFolderId);
}
| 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/ParagraphJobListener.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/ParagraphJobListener.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.InterpreterOutput;
import org.apache.zeppelin.interpreter.InterpreterResultMessage;
import org.apache.zeppelin.interpreter.InterpreterResultMessageOutput;
import org.apache.zeppelin.scheduler.JobListener;
import java.util.List;
/**
* Listen paragraph update
*/
public interface ParagraphJobListener extends JobListener {
public void onOutputAppend(Paragraph paragraph, int idx, String output);
public void onOutputUpdate(Paragraph paragraph, int idx, InterpreterResultMessage msg);
public void onOutputUpdateAll(Paragraph paragraph, List<InterpreterResultMessage> msgs);
}
| 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/Note.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/Note.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 java.lang.String.format;
import java.io.IOException;
import java.io.Serializable;
import java.util.*;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang.StringUtils;
import org.apache.zeppelin.conf.ZeppelinConfiguration;
import org.apache.zeppelin.display.AngularObject;
import org.apache.zeppelin.display.AngularObjectRegistry;
import org.apache.zeppelin.display.Input;
import org.apache.zeppelin.interpreter.*;
import org.apache.zeppelin.interpreter.remote.RemoteAngularObjectRegistry;
import org.apache.zeppelin.interpreter.thrift.InterpreterCompletion;
import org.apache.zeppelin.notebook.repo.NotebookRepo;
import org.apache.zeppelin.notebook.utility.IdHashes;
import org.apache.zeppelin.resource.ResourcePoolUtils;
import org.apache.zeppelin.scheduler.Job;
import org.apache.zeppelin.scheduler.Job.Status;
import org.apache.zeppelin.search.SearchService;
import org.apache.zeppelin.user.AuthenticationInfo;
import org.apache.zeppelin.user.Credentials;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
import com.google.gson.Gson;
/**
* Binded interpreters for a note
*/
public class Note implements Serializable, ParagraphJobListener {
private static final Logger logger = LoggerFactory.getLogger(Note.class);
private static final long serialVersionUID = 7920699076577612429L;
// threadpool for delayed persist of note
private static final ScheduledThreadPoolExecutor delayedPersistThreadPool =
new ScheduledThreadPoolExecutor(0);
static {
delayedPersistThreadPool.setRemoveOnCancelPolicy(true);
}
final List<Paragraph> paragraphs = new LinkedList<>();
private String name = "";
private String id;
private transient ZeppelinConfiguration conf = ZeppelinConfiguration.create();
private Map<String, List<AngularObject>> angularObjects = new HashMap<>();
private transient InterpreterFactory factory;
private transient InterpreterSettingManager interpreterSettingManager;
private transient JobListenerFactory jobListenerFactory;
private transient NotebookRepo repo;
private transient SearchService index;
private transient ScheduledFuture delayedPersist;
private transient NoteEventListener noteEventListener;
private transient Credentials credentials;
private transient NoteNameListener noteNameListener;
/*
* note configurations.
* - looknfeel - cron
*/
private Map<String, Object> config = new HashMap<>();
/*
* note information.
* - cron : cron expression validity.
*/
private Map<String, Object> info = new HashMap<>();
public Note() {
}
public Note(NotebookRepo repo, InterpreterFactory factory,
InterpreterSettingManager interpreterSettingManager, JobListenerFactory jlFactory,
SearchService noteIndex, Credentials credentials, NoteEventListener noteEventListener) {
this.repo = repo;
this.factory = factory;
this.interpreterSettingManager = interpreterSettingManager;
this.jobListenerFactory = jlFactory;
this.index = noteIndex;
this.noteEventListener = noteEventListener;
this.credentials = credentials;
generateId();
}
private void generateId() {
id = IdHashes.generateId();
}
private String getDefaultInterpreterName() {
InterpreterSetting setting = interpreterSettingManager.getDefaultInterpreterSetting(getId());
return null != setting ? setting.getName() : StringUtils.EMPTY;
}
public boolean isPersonalizedMode() {
Object v = getConfig().get("personalizedMode");
return null != v && "true".equals(v);
}
public void setPersonalizedMode(Boolean value) {
String valueString = StringUtils.EMPTY;
if (value) {
valueString = "true";
} else {
valueString = "false";
}
getConfig().put("personalizedMode", valueString);
clearUserParagraphs(value);
}
private void clearUserParagraphs(boolean isPersonalized) {
if (!isPersonalized) {
for (Paragraph p : paragraphs) {
p.clearUserParagraphs();
}
}
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getNameWithoutPath() {
String notePath = getName();
int lastSlashIndex = notePath.lastIndexOf("/");
// The note is in the root folder
if (lastSlashIndex < 0) {
return notePath;
}
return notePath.substring(lastSlashIndex + 1);
}
/**
* @return normalized folder path, which is folderId
*/
public String getFolderId() {
String notePath = getName();
// Ignore first '/'
if (notePath.charAt(0) == '/')
notePath = notePath.substring(1);
int lastSlashIndex = notePath.lastIndexOf("/");
// The root folder
if (lastSlashIndex < 0) {
return Folder.ROOT_FOLDER_ID;
}
String folderId = notePath.substring(0, lastSlashIndex);
return folderId;
}
public boolean isNameEmpty() {
return getName().trim().isEmpty();
}
private String normalizeNoteName(String name) {
name = name.trim();
name = name.replace("\\", "/");
while (name.contains("///")) {
name = name.replaceAll("///", "/");
}
name = name.replaceAll("//", "/");
if (name.length() == 0) {
name = "/";
}
return name;
}
public void setName(String name) {
String oldName = this.name;
if (name.indexOf('/') >= 0 || name.indexOf('\\') >= 0) {
name = normalizeNoteName(name);
}
this.name = name;
if (this.noteNameListener != null && !oldName.equals(name)) {
noteNameListener.onNoteNameChanged(this, oldName);
}
}
public void setNoteNameListener(NoteNameListener listener) {
this.noteNameListener = listener;
}
void setInterpreterFactory(InterpreterFactory factory) {
this.factory = factory;
synchronized (paragraphs) {
for (Paragraph p : paragraphs) {
p.setInterpreterFactory(factory);
}
}
}
void setInterpreterSettingManager(InterpreterSettingManager interpreterSettingManager) {
this.interpreterSettingManager = interpreterSettingManager;
synchronized (paragraphs) {
for (Paragraph p : paragraphs) {
p.setInterpreterSettingManager(interpreterSettingManager);
}
}
}
public void initializeJobListenerForParagraph(Paragraph paragraph) {
final Note paragraphNote = paragraph.getNote();
if (!paragraphNote.getId().equals(this.getId())) {
throw new IllegalArgumentException(
format("The paragraph %s from note %s " + "does not belong to note %s", paragraph.getId(),
paragraphNote.getId(), this.getId()));
}
boolean foundParagraph = false;
for (Paragraph ownParagraph : paragraphs) {
if (paragraph.getId().equals(ownParagraph.getId())) {
paragraph.setListener(this.jobListenerFactory.getParagraphJobListener(this));
foundParagraph = true;
}
}
if (!foundParagraph) {
throw new IllegalArgumentException(
format("Cannot find paragraph %s " + "from note %s", paragraph.getId(),
paragraphNote.getId()));
}
}
void setJobListenerFactory(JobListenerFactory jobListenerFactory) {
this.jobListenerFactory = jobListenerFactory;
}
void setNotebookRepo(NotebookRepo repo) {
this.repo = repo;
}
public void setIndex(SearchService index) {
this.index = index;
}
public Credentials getCredentials() {
return credentials;
}
public void setCredentials(Credentials credentials) {
this.credentials = credentials;
}
Map<String, List<AngularObject>> getAngularObjects() {
return angularObjects;
}
/**
* Add paragraph last.
*/
public Paragraph addParagraph(AuthenticationInfo authenticationInfo) {
Paragraph p = new Paragraph(this, this, factory, interpreterSettingManager);
p.setAuthenticationInfo(authenticationInfo);
setParagraphMagic(p, paragraphs.size());
synchronized (paragraphs) {
paragraphs.add(p);
}
if (noteEventListener != null) {
noteEventListener.onParagraphCreate(p);
}
return p;
}
/**
* Clone paragraph and add it to note.
*
* @param srcParagraph source paragraph
*/
void addCloneParagraph(Paragraph srcParagraph) {
// Keep paragraph original ID
final Paragraph newParagraph = new Paragraph(srcParagraph.getId(), this, this, factory,
interpreterSettingManager);
Map<String, Object> config = new HashMap<>(srcParagraph.getConfig());
Map<String, Object> param = srcParagraph.settings.getParams();
LinkedHashMap<String, Input> form = srcParagraph.settings.getForms();
newParagraph.setConfig(config);
newParagraph.settings.setParams(param);
newParagraph.settings.setForms(form);
newParagraph.setText(srcParagraph.getText());
newParagraph.setTitle(srcParagraph.getTitle());
try {
Gson gson = new Gson();
String resultJson = gson.toJson(srcParagraph.getReturn());
InterpreterResult result = gson.fromJson(resultJson, InterpreterResult.class);
newParagraph.setReturn(result, null);
} catch (Exception e) {
// 'result' part of Note consists of exception, instead of actual interpreter results
logger.warn(
"Paragraph " + srcParagraph.getId() + " has a result with exception. " + e.getMessage());
}
synchronized (paragraphs) {
paragraphs.add(newParagraph);
}
if (noteEventListener != null) {
noteEventListener.onParagraphCreate(newParagraph);
}
}
/**
* Insert paragraph in given index.
*
* @param index index of paragraphs
*/
public Paragraph insertParagraph(int index, AuthenticationInfo authenticationInfo) {
Paragraph p = new Paragraph(this, this, factory, interpreterSettingManager);
p.setAuthenticationInfo(authenticationInfo);
setParagraphMagic(p, index);
synchronized (paragraphs) {
paragraphs.add(index, p);
}
p.addUser(p, p.getUser());
if (noteEventListener != null) {
noteEventListener.onParagraphCreate(p);
}
return p;
}
/**
* Remove paragraph by id.
*
* @param paragraphId ID of paragraph
* @return a paragraph that was deleted, or <code>null</code> otherwise
*/
public Paragraph removeParagraph(String user, String paragraphId) {
removeAllAngularObjectInParagraph(user, paragraphId);
ResourcePoolUtils.removeResourcesBelongsToParagraph(getId(), paragraphId);
synchronized (paragraphs) {
Iterator<Paragraph> i = paragraphs.iterator();
while (i.hasNext()) {
Paragraph p = i.next();
if (p.getId().equals(paragraphId)) {
index.deleteIndexDoc(this, p);
i.remove();
if (noteEventListener != null) {
noteEventListener.onParagraphRemove(p);
}
return p;
}
}
}
return null;
}
/**
* Clear paragraph output by id.
*
* @param paragraphId ID of paragraph
* @param user not null if personalized mode is enabled
* @return Paragraph
*/
public Paragraph clearParagraphOutput(String paragraphId, String user) {
synchronized (paragraphs) {
for (Paragraph p : paragraphs) {
if (!p.getId().equals(paragraphId)) {
continue;
}
/** `broadcastParagraph` requires original paragraph */
Paragraph originParagraph = p;
if (user != null) {
p = p.getUserParagraphMap().get(user);
}
p.setReturn(null, null);
return originParagraph;
}
}
return null;
}
/**
* Clear all paragraph output of note
*/
public void clearAllParagraphOutput() {
synchronized (paragraphs) {
for (Paragraph p : paragraphs) {
p.setReturn(null, null);
}
}
}
/**
* Move paragraph into the new index (order from 0 ~ n-1).
*
* @param paragraphId ID of paragraph
* @param index new index
*/
public void moveParagraph(String paragraphId, int index) {
moveParagraph(paragraphId, index, false);
}
/**
* Move paragraph into the new index (order from 0 ~ n-1).
*
* @param paragraphId ID of paragraph
* @param index new index
* @param throwWhenIndexIsOutOfBound whether throw IndexOutOfBoundException
* when index is out of bound
*/
public void moveParagraph(String paragraphId, int index, boolean throwWhenIndexIsOutOfBound) {
synchronized (paragraphs) {
int oldIndex;
Paragraph p = null;
if (index < 0 || index >= paragraphs.size()) {
if (throwWhenIndexIsOutOfBound) {
throw new IndexOutOfBoundsException(
"paragraph size is " + paragraphs.size() + " , index is " + index);
} else {
return;
}
}
for (int i = 0; i < paragraphs.size(); i++) {
if (paragraphs.get(i).getId().equals(paragraphId)) {
oldIndex = i;
if (oldIndex == index) {
return;
}
p = paragraphs.remove(i);
}
}
if (p != null) {
paragraphs.add(index, p);
}
}
}
public boolean isLastParagraph(String paragraphId) {
if (!paragraphs.isEmpty()) {
synchronized (paragraphs) {
if (paragraphId.equals(paragraphs.get(paragraphs.size() - 1).getId())) {
return true;
}
}
return false;
}
/** because empty list, cannot remove nothing right? */
return true;
}
public Paragraph getParagraph(String paragraphId) {
synchronized (paragraphs) {
for (Paragraph p : paragraphs) {
if (p.getId().equals(paragraphId)) {
return p;
}
}
}
return null;
}
public Paragraph getLastParagraph() {
synchronized (paragraphs) {
return paragraphs.get(paragraphs.size() - 1);
}
}
public List<Map<String, String>> generateParagraphsInfo() {
List<Map<String, String>> paragraphsInfo = new LinkedList<>();
synchronized (paragraphs) {
for (Paragraph p : paragraphs) {
Map<String, String> info = populateParagraphInfo(p);
paragraphsInfo.add(info);
}
}
return paragraphsInfo;
}
public Map<String, String> generateSingleParagraphInfo(String paragraphId) {
synchronized (paragraphs) {
for (Paragraph p : paragraphs) {
if (p.getId().equals(paragraphId)) {
return populateParagraphInfo(p);
}
}
return new HashMap<>();
}
}
private Map<String, String> populateParagraphInfo(Paragraph p) {
Map<String, String> info = new HashMap<>();
info.put("id", p.getId());
info.put("status", p.getStatus().toString());
if (p.getDateStarted() != null) {
info.put("started", p.getDateStarted().toString());
}
if (p.getDateFinished() != null) {
info.put("finished", p.getDateFinished().toString());
}
if (p.getStatus().isRunning()) {
info.put("progress", String.valueOf(p.progress()));
} else {
info.put("progress", String.valueOf(100));
}
return info;
}
private void setParagraphMagic(Paragraph p, int index) {
if (paragraphs.size() > 0) {
String magic;
if (index == 0) {
magic = paragraphs.get(0).getMagic();
} else {
magic = paragraphs.get(index - 1).getMagic();
}
if (StringUtils.isNotEmpty(magic)) {
p.setText(magic + "\n");
}
}
}
/**
* Run all paragraphs sequentially.
*/
public synchronized void runAll() {
String cronExecutingUser = (String) getConfig().get("cronExecutingUser");
if (null == cronExecutingUser) {
cronExecutingUser = "anonymous";
}
AuthenticationInfo authenticationInfo = new AuthenticationInfo();
authenticationInfo.setUser(cronExecutingUser);
runAll(authenticationInfo);
}
public void runAll(AuthenticationInfo authenticationInfo) {
for (Paragraph p : getParagraphs()) {
if (!p.isEnabled()) {
continue;
}
p.setAuthenticationInfo(authenticationInfo);
run(p.getId());
}
}
/**
* Run a single paragraph.
*
* @param paragraphId ID of paragraph
*/
public void run(String paragraphId) {
Paragraph p = getParagraph(paragraphId);
p.setListener(jobListenerFactory.getParagraphJobListener(this));
if (p.isBlankParagraph()) {
logger.info("skip to run blank paragraph. {}", p.getId());
p.setStatus(Job.Status.FINISHED);
return;
}
String requiredReplName = p.getRequiredReplName();
Interpreter intp = factory.getInterpreter(p.getUser(), getId(), requiredReplName);
if (intp == null) {
String intpExceptionMsg =
p.getJobName() + "'s Interpreter " + requiredReplName + " not found";
InterpreterException intpException = new InterpreterException(intpExceptionMsg);
InterpreterResult intpResult =
new InterpreterResult(InterpreterResult.Code.ERROR, intpException.getMessage());
p.setReturn(intpResult, intpException);
p.setStatus(Job.Status.ERROR);
throw intpException;
}
if (p.getConfig().get("enabled") == null || (Boolean) p.getConfig().get("enabled")) {
p.setAuthenticationInfo(p.getAuthenticationInfo());
intp.getScheduler().submit(p);
}
}
/**
* Check whether all paragraphs belongs to this note has terminated
*/
boolean isTerminated() {
synchronized (paragraphs) {
for (Paragraph p : paragraphs) {
if (!p.isTerminated()) {
return false;
}
}
}
return true;
}
public boolean isTrash() {
String path = getName();
if (path.charAt(0) == '/') {
path = path.substring(1);
}
return path.split("/")[0].equals(Folder.TRASH_FOLDER_ID);
}
public List<InterpreterCompletion> completion(String paragraphId, String buffer, int cursor) {
Paragraph p = getParagraph(paragraphId);
p.setListener(jobListenerFactory.getParagraphJobListener(this));
return p.completion(buffer, cursor);
}
public List<Paragraph> getParagraphs() {
synchronized (paragraphs) {
return new LinkedList<>(paragraphs);
}
}
private void snapshotAngularObjectRegistry(String user) {
angularObjects = new HashMap<>();
List<InterpreterSetting> settings = interpreterSettingManager.getInterpreterSettings(getId());
if (settings == null || settings.size() == 0) {
return;
}
for (InterpreterSetting setting : settings) {
InterpreterGroup intpGroup = setting.getInterpreterGroup(user, id);
AngularObjectRegistry registry = intpGroup.getAngularObjectRegistry();
angularObjects.put(intpGroup.getId(), registry.getAllWithGlobal(id));
}
}
private void removeAllAngularObjectInParagraph(String user, String paragraphId) {
angularObjects = new HashMap<>();
List<InterpreterSetting> settings = interpreterSettingManager.getInterpreterSettings(getId());
if (settings == null || settings.size() == 0) {
return;
}
for (InterpreterSetting setting : settings) {
InterpreterGroup intpGroup = setting.getInterpreterGroup(user, id);
AngularObjectRegistry registry = intpGroup.getAngularObjectRegistry();
if (registry instanceof RemoteAngularObjectRegistry) {
// remove paragraph scope object
((RemoteAngularObjectRegistry) registry).removeAllAndNotifyRemoteProcess(id, paragraphId);
// remove app scope object
List<ApplicationState> appStates = getParagraph(paragraphId).getAllApplicationStates();
if (appStates != null) {
for (ApplicationState app : appStates) {
((RemoteAngularObjectRegistry) registry)
.removeAllAndNotifyRemoteProcess(id, app.getId());
}
}
} else {
registry.removeAll(id, paragraphId);
// remove app scope object
List<ApplicationState> appStates = getParagraph(paragraphId).getAllApplicationStates();
if (appStates != null) {
for (ApplicationState app : appStates) {
registry.removeAll(id, app.getId());
}
}
}
}
}
public void persist(AuthenticationInfo subject) throws IOException {
Preconditions.checkNotNull(subject, "AuthenticationInfo should not be null");
stopDelayedPersistTimer();
snapshotAngularObjectRegistry(subject.getUser());
index.updateIndexDoc(this);
repo.save(this, subject);
}
/**
* Persist this note with maximum delay.
*/
public void persist(int maxDelaySec, AuthenticationInfo subject) {
startDelayedPersistTimer(maxDelaySec, subject);
}
void unpersist(AuthenticationInfo subject) throws IOException {
repo.remove(getId(), subject);
}
/**
* Return new note for specific user. this inserts and replaces user paragraph which doesn't
* exists in original paragraph
*
* @param user specific user
* @return new Note for the user
*/
public Note getUserNote(String user) {
Note newNote = new Note();
newNote.id = getId();
newNote.config = getConfig();
newNote.angularObjects = getAngularObjects();
Paragraph newParagraph;
for (Paragraph p : paragraphs) {
newParagraph = p.getUserParagraph(user);
if (null == newParagraph) {
newParagraph = p.cloneParagraphForUser(user);
}
newNote.paragraphs.add(newParagraph);
}
return newNote;
}
private void startDelayedPersistTimer(int maxDelaySec, final AuthenticationInfo subject) {
synchronized (this) {
if (delayedPersist != null) {
return;
}
delayedPersist = delayedPersistThreadPool.schedule(new Runnable() {
@Override
public void run() {
try {
persist(subject);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
}, maxDelaySec, TimeUnit.SECONDS);
}
}
private void stopDelayedPersistTimer() {
synchronized (this) {
if (delayedPersist == null) {
return;
}
delayedPersist.cancel(false);
}
}
public Map<String, Object> getConfig() {
if (config == null) {
config = new HashMap<>();
}
return config;
}
public void setConfig(Map<String, Object> config) {
this.config = config;
}
public Map<String, Object> getInfo() {
if (info == null) {
info = new HashMap<>();
}
return info;
}
public void setInfo(Map<String, Object> info) {
this.info = info;
}
@Override
public void beforeStatusChange(Job job, Status before, Status after) {
if (jobListenerFactory != null) {
ParagraphJobListener listener = jobListenerFactory.getParagraphJobListener(this);
if (listener != null) {
listener.beforeStatusChange(job, before, after);
}
}
}
@Override
public void afterStatusChange(Job job, Status before, Status after) {
if (jobListenerFactory != null) {
ParagraphJobListener listener = jobListenerFactory.getParagraphJobListener(this);
if (listener != null) {
listener.afterStatusChange(job, before, after);
}
}
if (noteEventListener != null) {
noteEventListener.onParagraphStatusChange((Paragraph) job, after);
}
}
@Override
public void onProgressUpdate(Job job, int progress) {
if (jobListenerFactory != null) {
ParagraphJobListener listener = jobListenerFactory.getParagraphJobListener(this);
if (listener != null) {
listener.onProgressUpdate(job, progress);
}
}
}
@Override
public void onOutputAppend(Paragraph paragraph, int idx, String output) {
if (jobListenerFactory != null) {
ParagraphJobListener listener = jobListenerFactory.getParagraphJobListener(this);
if (listener != null) {
listener.onOutputAppend(paragraph, idx, output);
}
}
}
@Override
public void onOutputUpdate(Paragraph paragraph, int idx, InterpreterResultMessage msg) {
if (jobListenerFactory != null) {
ParagraphJobListener listener = jobListenerFactory.getParagraphJobListener(this);
if (listener != null) {
listener.onOutputUpdate(paragraph, idx, msg);
}
}
}
@Override
public void onOutputUpdateAll(Paragraph paragraph, List<InterpreterResultMessage> msgs) {
if (jobListenerFactory != null) {
ParagraphJobListener listener = jobListenerFactory.getParagraphJobListener(this);
if (listener != null) {
listener.onOutputUpdateAll(paragraph, msgs);
}
}
}
void setNoteEventListener(NoteEventListener noteEventListener) {
this.noteEventListener = noteEventListener;
}
}
| 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/NotebookEventListener.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/NotebookEventListener.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.InterpreterSetting;
/**
* Notebook event
*/
public interface NotebookEventListener extends NoteEventListener {
public void onNoteRemove(Note note);
public void onNoteCreate(Note note);
public void onUnbindInterpreter(Note note, InterpreterSetting setting);
}
| 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/NoteNameListener.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/NoteNameListener.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;
/**
* NoteNameListener. It's used by FolderView.
*/
public interface NoteNameListener {
/**
* Fired after note name changed
* @param note
* @param oldName
*/
void onNoteNameChanged(Note note, String oldName);
}
| 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/NotebookAuthorization.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/NotebookAuthorization.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.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
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 org.apache.commons.lang.StringUtils;
import org.apache.zeppelin.conf.ZeppelinConfiguration;
import org.apache.zeppelin.user.AuthenticationInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;
/**
* Contains authorization information for notes
*/
public class NotebookAuthorization {
private static final Logger LOG = LoggerFactory.getLogger(NotebookAuthorization.class);
private static NotebookAuthorization instance = null;
/*
* { "note1": { "owners": ["u1"], "readers": ["u1", "u2"], "writers": ["u1"] }, "note2": ... } }
*/
private static Map<String, Map<String, Set<String>>> authInfo = new HashMap<>();
/*
* contains roles for each user
*/
private static Map<String, Set<String>> userRoles = new HashMap<>();
private static ZeppelinConfiguration conf;
private static Gson gson;
private static String filePath;
private NotebookAuthorization() {}
public static NotebookAuthorization init(ZeppelinConfiguration config) {
if (instance == null) {
instance = new NotebookAuthorization();
conf = config;
filePath = conf.getNotebookAuthorizationPath();
GsonBuilder builder = new GsonBuilder();
builder.setPrettyPrinting();
gson = builder.create();
try {
loadFromFile();
} catch (IOException e) {
LOG.error("Error loading NotebookAuthorization", e);
}
}
return instance;
}
public static NotebookAuthorization getInstance() {
if (instance == null) {
LOG.warn("Notebook authorization module was called without initialization,"
+ " initializing with default configuration");
init(ZeppelinConfiguration.create());
}
return instance;
}
private static void loadFromFile() throws IOException {
File settingFile = new File(filePath);
LOG.info(settingFile.getAbsolutePath());
if (!settingFile.exists()) {
// nothing to read
return;
}
FileInputStream fis = new FileInputStream(settingFile);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
isr.close();
fis.close();
String json = sb.toString();
NotebookAuthorizationInfoSaving info = gson.fromJson(json,
NotebookAuthorizationInfoSaving.class);
authInfo = info.authInfo;
}
public void setRoles(String user, Set<String> roles) {
if (StringUtils.isBlank(user)) {
LOG.warn("Setting roles for empty user");
return;
}
roles = validateUser(roles);
userRoles.put(user, roles);
}
public Set<String> getRoles(String user) {
Set<String> roles = Sets.newHashSet();
if (userRoles.containsKey(user)) {
roles.addAll(userRoles.get(user));
}
return roles;
}
private void saveToFile() {
String jsonString;
synchronized (authInfo) {
NotebookAuthorizationInfoSaving info = new NotebookAuthorizationInfoSaving();
info.authInfo = authInfo;
jsonString = gson.toJson(info);
}
try {
File settingFile = new File(filePath);
if (!settingFile.exists()) {
settingFile.createNewFile();
}
FileOutputStream fos = new FileOutputStream(settingFile, false);
OutputStreamWriter out = new OutputStreamWriter(fos);
out.append(jsonString);
out.close();
fos.close();
} catch (IOException e) {
LOG.error("Error saving notebook authorization file: " + e.getMessage());
}
}
public boolean isPublic() {
return conf.isNotebokPublic();
}
private Set<String> validateUser(Set<String> users) {
Set<String> returnUser = new HashSet<>();
for (String user : users) {
if (!user.trim().isEmpty()) {
returnUser.add(user.trim());
}
}
return returnUser;
}
public void setOwners(String noteId, Set<String> entities) {
Map<String, Set<String>> noteAuthInfo = authInfo.get(noteId);
entities = validateUser(entities);
if (noteAuthInfo == null) {
noteAuthInfo = new LinkedHashMap();
noteAuthInfo.put("owners", new LinkedHashSet(entities));
noteAuthInfo.put("readers", new LinkedHashSet());
noteAuthInfo.put("writers", new LinkedHashSet());
} else {
noteAuthInfo.put("owners", new LinkedHashSet(entities));
}
authInfo.put(noteId, noteAuthInfo);
saveToFile();
}
public void setReaders(String noteId, Set<String> entities) {
Map<String, Set<String>> noteAuthInfo = authInfo.get(noteId);
entities = validateUser(entities);
if (noteAuthInfo == null) {
noteAuthInfo = new LinkedHashMap();
noteAuthInfo.put("owners", new LinkedHashSet());
noteAuthInfo.put("readers", new LinkedHashSet(entities));
noteAuthInfo.put("writers", new LinkedHashSet());
} else {
noteAuthInfo.put("readers", new LinkedHashSet(entities));
}
authInfo.put(noteId, noteAuthInfo);
saveToFile();
}
public void setWriters(String noteId, Set<String> entities) {
Map<String, Set<String>> noteAuthInfo = authInfo.get(noteId);
entities = validateUser(entities);
if (noteAuthInfo == null) {
noteAuthInfo = new LinkedHashMap();
noteAuthInfo.put("owners", new LinkedHashSet());
noteAuthInfo.put("readers", new LinkedHashSet());
noteAuthInfo.put("writers", new LinkedHashSet(entities));
} else {
noteAuthInfo.put("writers", new LinkedHashSet(entities));
}
authInfo.put(noteId, noteAuthInfo);
saveToFile();
}
public Set<String> getOwners(String noteId) {
Map<String, Set<String>> noteAuthInfo = authInfo.get(noteId);
Set<String> entities = null;
if (noteAuthInfo == null) {
entities = new HashSet<>();
} else {
entities = noteAuthInfo.get("owners");
if (entities == null) {
entities = new HashSet<>();
}
}
return entities;
}
public Set<String> getReaders(String noteId) {
Map<String, Set<String>> noteAuthInfo = authInfo.get(noteId);
Set<String> entities = null;
if (noteAuthInfo == null) {
entities = new HashSet<>();
} else {
entities = noteAuthInfo.get("readers");
if (entities == null) {
entities = new HashSet<>();
}
}
return entities;
}
public Set<String> getWriters(String noteId) {
Map<String, Set<String>> noteAuthInfo = authInfo.get(noteId);
Set<String> entities = null;
if (noteAuthInfo == null) {
entities = new HashSet<>();
} else {
entities = noteAuthInfo.get("writers");
if (entities == null) {
entities = new HashSet<>();
}
}
return entities;
}
public boolean isOwner(String noteId, Set<String> entities) {
return isMember(entities, getOwners(noteId));
}
public boolean isWriter(String noteId, Set<String> entities) {
return isMember(entities, getWriters(noteId)) || isMember(entities, getOwners(noteId));
}
public boolean isReader(String noteId, Set<String> entities) {
return isMember(entities, getReaders(noteId)) ||
isMember(entities, getOwners(noteId)) ||
isMember(entities, getWriters(noteId));
}
// return true if b is empty or if (a intersection b) is non-empty
private boolean isMember(Set<String> a, Set<String> b) {
Set<String> intersection = new HashSet<>(b);
intersection.retainAll(a);
return (b.isEmpty() || (intersection.size() > 0));
}
public boolean isOwner(Set<String> userAndRoles, String noteId) {
if (conf.isAnonymousAllowed()) {
LOG.debug("Zeppelin runs in anonymous mode, everybody is owner");
return true;
}
if (userAndRoles == null) {
return false;
}
return isOwner(noteId, userAndRoles);
}
public boolean hasWriteAuthorization(Set<String> userAndRoles, String noteId) {
if (conf.isAnonymousAllowed()) {
LOG.debug("Zeppelin runs in anonymous mode, everybody is writer");
return true;
}
if (userAndRoles == null) {
return false;
}
return isWriter(noteId, userAndRoles);
}
public boolean hasReadAuthorization(Set<String> userAndRoles, String noteId) {
if (conf.isAnonymousAllowed()) {
LOG.debug("Zeppelin runs in anonymous mode, everybody is reader");
return true;
}
if (userAndRoles == null) {
return false;
}
return isReader(noteId, userAndRoles);
}
public void removeNote(String noteId) {
authInfo.remove(noteId);
saveToFile();
}
public List<NoteInfo> filterByUser(List<NoteInfo> notes, AuthenticationInfo subject) {
final Set<String> entities = Sets.newHashSet();
if (subject != null) {
entities.add(subject.getUser());
}
return FluentIterable.from(notes).filter(new Predicate<NoteInfo>() {
@Override
public boolean apply(NoteInfo input) {
return input != null && isReader(input.getId(), entities);
}
}).toList();
}
public void setNewNotePermissions(String noteId, AuthenticationInfo subject) {
if (!AuthenticationInfo.isAnonymous(subject)) {
if (isPublic()) {
// add current user to owners - can be public
Set<String> owners = getOwners(noteId);
owners.add(subject.getUser());
setOwners(noteId, owners);
} else {
// add current user to owners, readers, writers - private note
Set<String> entities = getOwners(noteId);
entities.add(subject.getUser());
setOwners(noteId, entities);
entities = getReaders(noteId);
entities.add(subject.getUser());
setReaders(noteId, entities);
entities = getWriters(noteId);
entities.add(subject.getUser());
setWriters(noteId, entities);
}
}
}
}
| 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/ApplicationState.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/ApplicationState.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.helium.HeliumPackage;
import org.apache.zeppelin.interpreter.InterpreterGroup;
/**
* Current state of application
*/
public class ApplicationState {
/**
* Status of Application
*/
public static enum Status {
LOADING,
LOADED,
UNLOADING,
UNLOADED,
ERROR
};
Status status = Status.UNLOADED;
String id; // unique id for this instance. Similar to note id or paragraph id
HeliumPackage pkg;
String output;
public ApplicationState(String id, HeliumPackage pkg) {
this.id = id;
this.pkg = pkg;
}
/**
* After ApplicationState is restored from NotebookRepo,
* such as after Zeppelin daemon starts or Notebook import,
* Application status need to be reset.
*/
public void resetStatus() {
if (status != Status.ERROR) {
status = Status.UNLOADED;
}
}
@Override
public boolean equals(Object o) {
String compareName;
if (o instanceof ApplicationState) {
return pkg.equals(((ApplicationState) o).getHeliumPackage());
} else if (o instanceof HeliumPackage) {
return pkg.equals((HeliumPackage) o);
} else {
return false;
}
}
@Override
public int hashCode() {
return pkg.hashCode();
}
public String getId() {
return id;
}
public void setStatus(Status status) {
this.status = status;
}
public Status getStatus() {
return status;
}
public String getOutput() {
return output;
}
public void setOutput(String output) {
this.output = output;
}
public synchronized void appendOutput(String output) {
if (this.output == null) {
this.output = output;
} else {
this.output += output;
}
}
public HeliumPackage getHeliumPackage() {
return pkg;
}
}
| 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/NotebookImportDeserializer.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/NotebookImportDeserializer.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 com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;
/**
* importNote date format deserializer
*/
public class NotebookImportDeserializer implements JsonDeserializer<Date> {
private static final String[] DATE_FORMATS = new String[] {
"yyyy-MM-dd'T'HH:mm:ssZ",
"MMM d, yyyy h:mm:ss a",
"MMM dd, yyyy HH:mm:ss"
};
@Override
public Date deserialize(JsonElement jsonElement, Type typeOF,
JsonDeserializationContext context) throws JsonParseException {
for (String format : DATE_FORMATS) {
try {
return new SimpleDateFormat(format, Locale.US).parse(jsonElement.getAsString());
} catch (ParseException e) {
}
}
throw new JsonParseException("Unparsable date: \"" + jsonElement.getAsString()
+ "\". Supported formats: " + Arrays.toString(DATE_FORMATS));
}
}
| 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/Paragraph.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/Paragraph.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 com.google.common.collect.Maps;
import com.google.common.base.Strings;
import org.apache.commons.lang.StringUtils;
import org.apache.zeppelin.display.AngularObject;
import org.apache.zeppelin.display.AngularObjectRegistry;
import org.apache.zeppelin.helium.HeliumPackage;
import org.apache.zeppelin.interpreter.thrift.InterpreterCompletion;
import org.apache.zeppelin.user.AuthenticationInfo;
import org.apache.zeppelin.user.Credentials;
import org.apache.zeppelin.user.UserCredentials;
import org.apache.zeppelin.display.GUI;
import org.apache.zeppelin.display.Input;
import org.apache.zeppelin.interpreter.*;
import org.apache.zeppelin.interpreter.Interpreter.FormType;
import org.apache.zeppelin.interpreter.InterpreterResult.Code;
import org.apache.zeppelin.resource.ResourcePool;
import org.apache.zeppelin.scheduler.Job;
import org.apache.zeppelin.scheduler.JobListener;
import org.apache.zeppelin.scheduler.Scheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.Serializable;
import java.util.*;
import com.google.common.annotations.VisibleForTesting;
/**
* Paragraph is a representation of an execution unit.
*/
public class Paragraph extends Job implements Serializable, Cloneable {
private static final long serialVersionUID = -6328572073497992016L;
private static Logger logger = LoggerFactory.getLogger(Paragraph.class);
private transient InterpreterFactory factory;
private transient InterpreterSettingManager interpreterSettingManager;
private transient Note note;
private transient AuthenticationInfo authenticationInfo;
private transient Map<String, Paragraph> userParagraphMap = Maps.newHashMap(); // personalized
String title;
String text;
String user;
Date dateUpdated;
private Map<String, Object> config; // paragraph configs like isOpen, colWidth, etc
public GUI settings; // form and parameter settings
// since zeppelin-0.7.0, zeppelin stores multiple results of the paragraph
// see ZEPPELIN-212
Object results;
// For backward compatibility of note.json format after ZEPPELIN-212
Object result;
/**
* Applicaiton states in this paragraph
*/
private final List<ApplicationState> apps = new LinkedList<>();
@VisibleForTesting
Paragraph() {
super(generateId(), null);
config = new HashMap<>();
settings = new GUI();
}
public Paragraph(String paragraphId, Note note, JobListener listener,
InterpreterFactory factory, InterpreterSettingManager interpreterSettingManager) {
super(paragraphId, generateId(), listener);
this.note = note;
this.factory = factory;
this.interpreterSettingManager = interpreterSettingManager;
title = null;
text = null;
authenticationInfo = null;
user = null;
dateUpdated = null;
settings = new GUI();
config = new HashMap<>();
}
public Paragraph(Note note, JobListener listener, InterpreterFactory factory,
InterpreterSettingManager interpreterSettingManager) {
super(generateId(), listener);
this.note = note;
this.factory = factory;
this.interpreterSettingManager = interpreterSettingManager;
title = null;
text = null;
authenticationInfo = null;
dateUpdated = null;
settings = new GUI();
config = new HashMap<>();
}
private static String generateId() {
return "paragraph_" + System.currentTimeMillis() + "_" + new Random(System.currentTimeMillis())
.nextInt();
}
public Map<String, Paragraph> getUserParagraphMap() {
return userParagraphMap;
}
public Paragraph getUserParagraph(String user) {
if (!userParagraphMap.containsKey(user)) {
cloneParagraphForUser(user);
}
return userParagraphMap.get(user);
}
@Override
public void setResult(Object results) {
this.results = results;
}
public Paragraph cloneParagraphForUser(String user) {
Paragraph p = new Paragraph();
p.settings.setParams(Maps.newHashMap(settings.getParams()));
p.settings.setForms(Maps.newLinkedHashMap(settings.getForms()));
p.setConfig(Maps.newHashMap(config));
p.setTitle(getTitle());
p.setText(getText());
p.setResult(getReturn());
p.setStatus(Status.READY);
p.setId(getId());
addUser(p, user);
return p;
}
public void clearUserParagraphs() {
userParagraphMap.clear();
}
public void addUser(Paragraph p, String user) {
userParagraphMap.put(user, p);
}
public String getUser() {
return user;
}
public String getText() {
return text;
}
public void setText(String newText) {
this.text = newText;
this.dateUpdated = new Date();
}
public AuthenticationInfo getAuthenticationInfo() {
return authenticationInfo;
}
public void setAuthenticationInfo(AuthenticationInfo authenticationInfo) {
this.authenticationInfo = authenticationInfo;
this.user = authenticationInfo.getUser();
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public void setNote(Note note) {
this.note = note;
}
public Note getNote() {
return note;
}
public boolean isEnabled() {
Boolean enabled = (Boolean) config.get("enabled");
return enabled == null || enabled.booleanValue();
}
public String getRequiredReplName() {
return getRequiredReplName(text);
}
public static String getRequiredReplName(String text) {
if (text == null) {
return null;
}
String trimmed = text.trim();
if (!trimmed.startsWith("%")) {
return null;
}
// get script head
int scriptHeadIndex = 0;
for (int i = 0; i < trimmed.length(); i++) {
char ch = trimmed.charAt(i);
if (Character.isWhitespace(ch) || ch == '(' || ch == '\n') {
break;
}
scriptHeadIndex = i;
}
if (scriptHeadIndex < 1) {
return null;
}
String head = text.substring(1, scriptHeadIndex + 1);
return head;
}
public String getScriptBody() {
return getScriptBody(text);
}
public static String getScriptBody(String text) {
if (text == null) {
return null;
}
String magic = getRequiredReplName(text);
if (magic == null) {
return text;
}
String trimmed = text.trim();
if (magic.length() + 1 >= trimmed.length()) {
return "";
}
return trimmed.substring(magic.length() + 1).trim();
}
public Interpreter getRepl(String name) {
return factory.getInterpreter(user, note.getId(), name);
}
public Interpreter getCurrentRepl() {
return getRepl(getRequiredReplName());
}
public List<InterpreterCompletion> getInterpreterCompletion() {
List<InterpreterCompletion> completion = new LinkedList();
for (InterpreterSetting intp : interpreterSettingManager.getInterpreterSettings(note.getId())) {
List<InterpreterInfo> intInfo = intp.getInterpreterInfos();
if (intInfo.size() > 1) {
for (InterpreterInfo info : intInfo) {
String name = intp.getName() + "." + info.getName();
completion.add(new InterpreterCompletion(name, name));
}
} else {
completion.add(new InterpreterCompletion(intp.getName(), intp.getName()));
}
}
return completion;
}
public List<InterpreterCompletion> completion(String buffer, int cursor) {
String lines[] = buffer.split(System.getProperty("line.separator"));
if (lines.length > 0 && lines[0].startsWith("%") && cursor <= lines[0].trim().length()) {
int idx = lines[0].indexOf(' ');
if (idx < 0 || (idx > 0 && cursor <= idx)) {
return getInterpreterCompletion();
}
}
String replName = getRequiredReplName(buffer);
if (replName != null && cursor > replName.length()) {
cursor -= replName.length() + 1;
}
String body = getScriptBody(buffer);
Interpreter repl = getRepl(replName);
if (repl == null) {
return null;
}
List completion = repl.completion(body, cursor);
return completion;
}
public void setInterpreterFactory(InterpreterFactory factory) {
this.factory = factory;
}
public void setInterpreterSettingManager(InterpreterSettingManager interpreterSettingManager) {
this.interpreterSettingManager = interpreterSettingManager;
}
public InterpreterResult getResult() {
return (InterpreterResult) getReturn();
}
@Override
public Object getReturn() {
return results;
}
public Object getPreviousResultFormat() {
return result;
}
@Override
public int progress() {
String replName = getRequiredReplName();
Interpreter repl = getRepl(replName);
if (repl != null) {
return repl.getProgress(getInterpreterContext(null));
} else {
return 0;
}
}
@Override
public Map<String, Object> info() {
return null;
}
private boolean hasPermission(String user, List<String> intpUsers) {
if (1 > intpUsers.size()) {
return true;
}
for (String u : intpUsers) {
if (user.trim().equals(u.trim())) {
return true;
}
}
return false;
}
public boolean isBlankParagraph() {
return Strings.isNullOrEmpty(getText()) || getText().trim().equals(getMagic());
}
@Override
protected Object jobRun() throws Throwable {
String replName = getRequiredReplName();
Interpreter repl = getRepl(replName);
logger.info("run paragraph {} using {} " + repl, getId(), replName);
if (repl == null) {
logger.error("Can not find interpreter name " + repl);
throw new RuntimeException("Can not find interpreter for " + getRequiredReplName());
}
InterpreterSetting intp = getInterpreterSettingById(repl.getInterpreterGroup().getId());
while (intp.getStatus().equals(
org.apache.zeppelin.interpreter.InterpreterSetting.Status.DOWNLOADING_DEPENDENCIES)) {
Thread.sleep(200);
}
if (this.noteHasUser() && this.noteHasInterpreters()) {
if (intp != null && interpreterHasUser(intp)
&& isUserAuthorizedToAccessInterpreter(intp.getOption()) == false) {
logger.error("{} has no permission for {} ", authenticationInfo.getUser(), repl);
return new InterpreterResult(Code.ERROR,
authenticationInfo.getUser() + " has no permission for " + getRequiredReplName());
}
}
for (Paragraph p : userParagraphMap.values()) {
p.setText(getText());
}
String script = getScriptBody();
// inject form
if (repl.getFormType() == FormType.NATIVE) {
settings.clear();
} else if (repl.getFormType() == FormType.SIMPLE) {
String scriptBody = getScriptBody();
// inputs will be built from script body
LinkedHashMap<String, Input> inputs = Input.extractSimpleQueryForm(scriptBody);
final AngularObjectRegistry angularRegistry =
repl.getInterpreterGroup().getAngularObjectRegistry();
scriptBody = extractVariablesFromAngularRegistry(scriptBody, inputs, angularRegistry);
settings.setForms(inputs);
script = Input.getSimpleQuery(settings.getParams(), scriptBody);
}
logger.debug("RUN : " + script);
try {
InterpreterContext context = getInterpreterContext();
InterpreterContext.set(context);
InterpreterResult ret = repl.interpret(script, context);
if (Code.KEEP_PREVIOUS_RESULT == ret.code()) {
return getReturn();
}
context.out.flush();
List<InterpreterResultMessage> resultMessages = context.out.toInterpreterResultMessage();
resultMessages.addAll(ret.message());
InterpreterResult res = new InterpreterResult(ret.code(), resultMessages);
Paragraph p = getUserParagraph(getUser());
if (null != p) {
p.setResult(res);
p.settings.setParams(settings.getParams());
}
return res;
} finally {
InterpreterContext.remove();
}
}
private boolean noteHasUser() {
return this.user != null;
}
private boolean noteHasInterpreters() {
return !interpreterSettingManager.getInterpreterSettings(note.getId()).isEmpty();
}
private boolean interpreterHasUser(InterpreterSetting intp) {
return intp.getOption().permissionIsSet() && intp.getOption().getUsers() != null;
}
private boolean isUserAuthorizedToAccessInterpreter(InterpreterOption intpOpt) {
return intpOpt.permissionIsSet() && hasPermission(authenticationInfo.getUser(),
intpOpt.getUsers());
}
private InterpreterSetting getInterpreterSettingById(String id) {
InterpreterSetting setting = null;
for (InterpreterSetting i : interpreterSettingManager.getInterpreterSettings(note.getId())) {
if (id.startsWith(i.getId())) {
setting = i;
break;
}
}
return setting;
}
@Override
protected boolean jobAbort() {
Interpreter repl = getRepl(getRequiredReplName());
if (repl == null) {
// when interpreters are already destroyed
return true;
}
Scheduler scheduler = repl.getScheduler();
if (scheduler == null) {
return true;
}
Job job = scheduler.removeFromWaitingQueue(getId());
if (job != null) {
job.setStatus(Status.ABORT);
} else {
repl.cancel(getInterpreterContextWithoutRunner(null));
}
return true;
}
private InterpreterContext getInterpreterContext() {
final Paragraph self = this;
return getInterpreterContext(new InterpreterOutput(new InterpreterOutputListener() {
@Override
public void onAppend(int index, InterpreterResultMessageOutput out, byte[] line) {
((ParagraphJobListener) getListener()).onOutputAppend(self, index, new String(line));
}
@Override
public void onUpdate(int index, InterpreterResultMessageOutput out) {
try {
((ParagraphJobListener) getListener())
.onOutputUpdate(self, index, out.toInterpreterResultMessage());
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
@Override
public void onUpdateAll(InterpreterOutput out) {
try {
List<InterpreterResultMessage> messages = out.toInterpreterResultMessage();
((ParagraphJobListener) getListener()).onOutputUpdateAll(self, messages);
updateParagraphResult(messages);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
private void updateParagraphResult(List<InterpreterResultMessage> msgs) {
// update paragraph result
InterpreterResult result = new InterpreterResult(Code.SUCCESS, msgs);
setReturn(result, null);
}
}));
}
private InterpreterContext getInterpreterContextWithoutRunner(InterpreterOutput output) {
AngularObjectRegistry registry = null;
ResourcePool resourcePool = null;
if (!interpreterSettingManager.getInterpreterSettings(note.getId()).isEmpty()) {
InterpreterSetting intpGroup =
interpreterSettingManager.getInterpreterSettings(note.getId()).get(0);
registry = intpGroup.getInterpreterGroup(getUser(), note.getId()).getAngularObjectRegistry();
resourcePool = intpGroup.getInterpreterGroup(getUser(), note.getId()).getResourcePool();
}
List<InterpreterContextRunner> runners = new LinkedList<>();
final Paragraph self = this;
Credentials credentials = note.getCredentials();
if (authenticationInfo != null) {
UserCredentials userCredentials =
credentials.getUserCredentials(authenticationInfo.getUser());
authenticationInfo.setUserCredentials(userCredentials);
}
InterpreterContext interpreterContext =
new InterpreterContext(note.getId(), getId(), getRequiredReplName(), this.getTitle(),
this.getText(), this.getAuthenticationInfo(), this.getConfig(), this.settings, registry,
resourcePool, runners, output);
return interpreterContext;
}
private InterpreterContext getInterpreterContext(InterpreterOutput output) {
AngularObjectRegistry registry = null;
ResourcePool resourcePool = null;
if (!interpreterSettingManager.getInterpreterSettings(note.getId()).isEmpty()) {
InterpreterSetting intpGroup =
interpreterSettingManager.getInterpreterSettings(note.getId()).get(0);
registry = intpGroup.getInterpreterGroup(getUser(), note.getId()).getAngularObjectRegistry();
resourcePool = intpGroup.getInterpreterGroup(getUser(), note.getId()).getResourcePool();
}
List<InterpreterContextRunner> runners = new LinkedList<>();
for (Paragraph p : note.getParagraphs()) {
runners.add(new ParagraphRunner(note, note.getId(), p.getId()));
}
final Paragraph self = this;
Credentials credentials = note.getCredentials();
if (authenticationInfo != null) {
UserCredentials userCredentials =
credentials.getUserCredentials(authenticationInfo.getUser());
authenticationInfo.setUserCredentials(userCredentials);
}
InterpreterContext interpreterContext =
new InterpreterContext(note.getId(), getId(), getRequiredReplName(), this.getTitle(),
this.getText(), this.getAuthenticationInfo(), this.getConfig(), this.settings, registry,
resourcePool, runners, output);
return interpreterContext;
}
public InterpreterContextRunner getInterpreterContextRunner() {
return new ParagraphRunner(note, note.getId(), getId());
}
public void setStatusToUserParagraph(Status status) {
String user = getUser();
if (null != user) {
getUserParagraph(getUser()).setStatus(status);
}
}
static class ParagraphRunner extends InterpreterContextRunner {
private transient Note note;
public ParagraphRunner(Note note, String noteId, String paragraphId) {
super(noteId, paragraphId);
this.note = note;
}
@Override
public void run() {
note.run(getParagraphId());
}
}
public Map<String, Object> getConfig() {
return config;
}
public void setConfig(Map<String, Object> config) {
this.config = config;
}
public void setReturn(InterpreterResult value, Throwable t) {
setResult(value);
setException(t);
}
@Override
public Object clone() throws CloneNotSupportedException {
Paragraph paraClone = (Paragraph) this.clone();
return paraClone;
}
private String getApplicationId(HeliumPackage pkg) {
return "app_" + getNote().getId() + "-" + getId() + pkg.getName().replaceAll("\\.", "_");
}
public ApplicationState createOrGetApplicationState(HeliumPackage pkg) {
synchronized (apps) {
for (ApplicationState as : apps) {
if (as.equals(pkg)) {
return as;
}
}
String appId = getApplicationId(pkg);
ApplicationState appState = new ApplicationState(appId, pkg);
apps.add(appState);
return appState;
}
}
public ApplicationState getApplicationState(String appId) {
synchronized (apps) {
for (ApplicationState as : apps) {
if (as.getId().equals(appId)) {
return as;
}
}
}
return null;
}
public List<ApplicationState> getAllApplicationStates() {
synchronized (apps) {
return new LinkedList<>(apps);
}
}
String extractVariablesFromAngularRegistry(String scriptBody, Map<String, Input> inputs,
AngularObjectRegistry angularRegistry) {
final String noteId = this.getNote().getId();
final String paragraphId = this.getId();
final Set<String> keys = new HashSet<>(inputs.keySet());
for (String varName : keys) {
final AngularObject paragraphScoped = angularRegistry.get(varName, noteId, paragraphId);
final AngularObject noteScoped = angularRegistry.get(varName, noteId, null);
final AngularObject angularObject = paragraphScoped != null ? paragraphScoped : noteScoped;
if (angularObject != null) {
inputs.remove(varName);
final String pattern = "[$][{]\\s*" + varName + "\\s*(?:=[^}]+)?[}]";
scriptBody = scriptBody.replaceAll(pattern, angularObject.get().toString());
}
}
return scriptBody;
}
public String getMagic() {
String magic = StringUtils.EMPTY;
String text = getText();
if (text != null && text.startsWith("%")) {
magic = text.split("\\s+")[0];
if (isValidInterpreter(magic.substring(1))) {
return magic;
} else {
return StringUtils.EMPTY;
}
}
return magic;
}
private boolean isValidInterpreter(String replName) {
try {
return factory.getInterpreter(user, note.getId(), replName) != null;
} catch (InterpreterException e) {
// ignore this exception, it would be recaught when running paragraph.
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-zengine/src/main/java/org/apache/zeppelin/notebook/Folder.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/Folder.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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
/**
* Represents a folder of Notebook. ID of the folder is a normalized path of it.
* 'normalized path' means the path that removed '/' from the beginning and the end of the path.
* e.g. "a/b/c", but not "/a/b/c", "a/b/c/" or "/a/b/c/".
* One exception can be the root folder, which is '/'.
*/
public class Folder {
public static final String ROOT_FOLDER_ID = "/";
public static final String TRASH_FOLDER_ID = "~Trash";
public static final String TRASH_FOLDER_CONFLICT_INFIX = " ";
private String id;
private Folder parent;
private Map<String, Folder> children = new LinkedHashMap<>();
// key: noteId
private final Map<String, Note> notes = new LinkedHashMap<>();
private List<FolderListener> listeners = new LinkedList<>();
private static final Logger logger = LoggerFactory.getLogger(Folder.class);
public Folder(String id) {
this.id = id;
}
public String getId() {
return id;
}
public String getName() {
if (isRoot())
return ROOT_FOLDER_ID;
String path = getId();
int lastSlashIndex = path.lastIndexOf("/");
if (lastSlashIndex < 0) { // This folder is under the root
return path;
}
return path.substring(lastSlashIndex + 1);
}
public String getParentFolderId() {
if (isRoot())
return ROOT_FOLDER_ID;
int lastSlashIndex = getId().lastIndexOf("/");
// The root folder
if (lastSlashIndex < 0) {
return Folder.ROOT_FOLDER_ID;
}
return getId().substring(0, lastSlashIndex);
}
public static String normalizeFolderId(String id) {
id = id.trim();
id = id.replace("\\", "/");
while (id.contains("///")) {
id = id.replaceAll("///", "/");
}
id = id.replaceAll("//", "/");
if (id.equals(ROOT_FOLDER_ID)) {
return ROOT_FOLDER_ID;
}
if (id.charAt(0) == '/') {
id = id.substring(1);
}
if (id.charAt(id.length() - 1) == '/') {
id = id.substring(0, id.length() - 1);
}
return id;
}
/**
* Rename this folder as well as the notes and the children belong to it
*
* @param newId
*/
public void rename(String newId) {
if (isRoot()) // root folder cannot be renamed
return;
String oldId = getId();
id = normalizeFolderId(newId);
logger.info("Rename {} to {}", oldId, getId());
synchronized (notes) {
for (Note note : notes.values()) {
String noteName = note.getNameWithoutPath();
String newNotePath;
if (newId.equals(ROOT_FOLDER_ID)) {
newNotePath = noteName;
} else {
newNotePath = newId + "/" + noteName;
}
note.setName(newNotePath);
}
}
for (Folder child : children.values()) {
child.rename(getId() + "/" + child.getName());
}
notifyRenamed(oldId);
}
/**
* Merge folder's notes and child folders
*
* @param folder
*/
public void merge(Folder folder) {
logger.info("Merge {} into {}", folder.getId(), getId());
addNotes(folder.getNotes());
}
public void addFolderListener(FolderListener listener) {
listeners.add(listener);
}
public void notifyRenamed(String oldFolderId) {
for (FolderListener listener : listeners) {
listener.onFolderRenamed(this, oldFolderId);
}
}
public Folder getParent() {
return parent;
}
public Map<String, Folder> getChildren() {
return children;
}
public void setParent(Folder parent) {
logger.info("Set parent of {} to {}", getId(), parent.getId());
this.parent = parent;
}
public void addChild(Folder child) {
if (child == this) // prevent the root folder from setting itself as child
return;
children.put(child.getId(), child);
}
public void removeChild(String folderId) {
logger.info("Remove child {} from {}", folderId, getId());
children.remove(folderId);
}
public void addNote(Note note) {
logger.info("Add note {} to folder {}", note.getId(), getId());
synchronized (notes) {
notes.put(note.getId(), note);
}
}
public void addNotes(List<Note> newNotes) {
synchronized (notes) {
for (Note note : newNotes) {
notes.put(note.getId(), note);
}
}
}
public void removeNote(Note note) {
logger.info("Remove note {} from folder {}", note.getId(), getId());
synchronized (notes) {
notes.remove(note.getId());
}
}
public List<Note> getNotes() {
return new LinkedList<>(notes.values());
}
public List<Note> getNotesRecursively() {
List<Note> notes = getNotes();
for (Folder child : children.values()) {
notes.addAll(child.getNotesRecursively());
}
return notes;
}
public int countNotes() {
return notes.size();
}
public boolean hasChild() {
return children.size() > 0;
}
boolean isRoot() {
return getId().equals(ROOT_FOLDER_ID);
}
public boolean isTrash() {
if (isRoot())
return false;
return getId().split("/")[0].equals(TRASH_FOLDER_ID);
}
}
| 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/NotebookAuthorizationInfoSaving.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/NotebookAuthorizationInfoSaving.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.Map;
import java.util.Set;
/**
* Only used for saving NotebookAuthorization info
*/
public class NotebookAuthorizationInfoSaving {
public Map<String, Map<String, Set<String>>> authInfo;
}
| 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/repo/NotebookRepoSettingsInfo.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/repo/NotebookRepoSettingsInfo.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.repo;
import java.util.List;
import java.util.Map;
/**
* Notebook repo settings. This represent a structure of a notebook repo settings that will mostly
* used in the frontend.
*
*/
public class NotebookRepoSettingsInfo {
/**
* Type of value, It can be text or list.
*/
public enum Type {
INPUT, DROPDOWN
}
public static NotebookRepoSettingsInfo newInstance() {
return new NotebookRepoSettingsInfo();
}
public Type type;
public List<Map<String, String>> value;
public String selected;
public String name;
}
| 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/repo/NotebookRepo.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/repo/NotebookRepo.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.repo;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.zeppelin.annotation.ZeppelinApi;
import org.apache.zeppelin.notebook.Note;
import org.apache.zeppelin.notebook.NoteInfo;
import org.apache.zeppelin.user.AuthenticationInfo;
/**
* Notebook repository (persistence layer) abstraction
*/
public interface NotebookRepo {
/**
* Lists notebook information about all notebooks in storage.
* @param subject contains user information.
* @return
* @throws IOException
*/
@ZeppelinApi public List<NoteInfo> list(AuthenticationInfo subject) throws IOException;
/**
* Get the notebook with the given id.
* @param noteId is note id.
* @param subject contains user information.
* @return
* @throws IOException
*/
@ZeppelinApi public Note get(String noteId, AuthenticationInfo subject) throws IOException;
/**
* Save given note in storage
* @param note is the note itself.
* @param subject contains user information.
* @throws IOException
*/
@ZeppelinApi public void save(Note note, AuthenticationInfo subject) throws IOException;
/**
* Remove note with given id.
* @param noteId is the note id.
* @param subject contains user information.
* @throws IOException
*/
@ZeppelinApi public void remove(String noteId, AuthenticationInfo subject) throws IOException;
/**
* Release any underlying resources
*/
@ZeppelinApi public void close();
/**
* Versioning API (optional, preferred to have).
*/
/**
* chekpoint (set revision) for notebook.
* @param noteId Id of the Notebook
* @param checkpointMsg message description of the checkpoint
* @return Rev
* @throws IOException
*/
@ZeppelinApi public Revision checkpoint(String noteId, String checkpointMsg,
AuthenticationInfo subject) throws IOException;
/**
* Get particular revision of the Notebook.
*
* @param noteId Id of the Notebook
* @param rev revision of the Notebook
* @return a Notebook
* @throws IOException
*/
@ZeppelinApi public Note get(String noteId, String revId, AuthenticationInfo subject)
throws IOException;
/**
* List of revisions of the given Notebook.
*
* @param noteId id of the Notebook
* @return list of revisions
*/
@ZeppelinApi public List<Revision> revisionHistory(String noteId, AuthenticationInfo subject);
/**
* Set note to particular revision.
*
* @param noteId Id of the Notebook
* @param rev revision of the Notebook
* @return a Notebook
* @throws IOException
*/
@ZeppelinApi
public Note setNoteRevision(String noteId, String revId, AuthenticationInfo subject)
throws IOException;
/**
* Get NotebookRepo settings got the given user.
*
* @param subject
* @return
*/
@ZeppelinApi public List<NotebookRepoSettingsInfo> getSettings(AuthenticationInfo subject);
/**
* update notebook repo settings.
*
* @param settings
* @param subject
*/
@ZeppelinApi public void updateSettings(Map<String, String> settings, AuthenticationInfo subject);
/**
* Represents the 'Revision' a point in life of the notebook
*/
static class Revision {
public static final Revision EMPTY = new Revision(StringUtils.EMPTY, StringUtils.EMPTY, 0);
public String id;
public String message;
public int time;
public Revision(String revId, String message, int time) {
this.id = revId;
this.message = message;
this.time = time;
}
public static boolean isEmpty(Revision revision) {
return revision == null || EMPTY.equals(revision);
}
}
}
| 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/repo/NotebookRepoSync.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/repo/NotebookRepoSync.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.repo;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.zeppelin.conf.ZeppelinConfiguration;
import org.apache.zeppelin.conf.ZeppelinConfiguration.ConfVars;
import org.apache.zeppelin.notebook.Note;
import org.apache.zeppelin.notebook.NoteInfo;
import org.apache.zeppelin.notebook.NotebookAuthorization;
import org.apache.zeppelin.notebook.Paragraph;
import org.apache.zeppelin.user.AuthenticationInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Lists;
/**
* Notebook repository sync with remote storage
*/
public class NotebookRepoSync implements NotebookRepo {
private static final Logger LOG = LoggerFactory.getLogger(NotebookRepoSync.class);
private static final int maxRepoNum = 2;
private static final String pushKey = "pushNoteIds";
private static final String pullKey = "pullNoteIds";
private static final String delDstKey = "delDstNoteIds";
private static ZeppelinConfiguration config;
private static final String defaultStorage = "org.apache.zeppelin.notebook.repo.GitNotebookRepo";
private List<NotebookRepo> repos = new ArrayList<>();
private final boolean oneWaySync;
/**
* @param conf
*/
@SuppressWarnings("static-access")
public NotebookRepoSync(ZeppelinConfiguration conf) {
config = conf;
oneWaySync = conf.getBoolean(ConfVars.ZEPPELIN_NOTEBOOK_ONE_WAY_SYNC);
String allStorageClassNames = conf.getString(ConfVars.ZEPPELIN_NOTEBOOK_STORAGE).trim();
if (allStorageClassNames.isEmpty()) {
allStorageClassNames = defaultStorage;
LOG.warn("Empty ZEPPELIN_NOTEBOOK_STORAGE conf parameter, using default {}", defaultStorage);
}
String[] storageClassNames = allStorageClassNames.split(",");
if (storageClassNames.length > getMaxRepoNum()) {
LOG.warn("Unsupported number {} of storage classes in ZEPPELIN_NOTEBOOK_STORAGE : {}\n" +
"first {} will be used", storageClassNames.length, allStorageClassNames, getMaxRepoNum());
}
for (int i = 0; i < Math.min(storageClassNames.length, getMaxRepoNum()); i++) {
Class<?> notebookStorageClass;
try {
notebookStorageClass = getClass().forName(storageClassNames[i].trim());
Constructor<?> constructor = notebookStorageClass.getConstructor(
ZeppelinConfiguration.class);
repos.add((NotebookRepo) constructor.newInstance(conf));
} catch (ClassNotFoundException | NoSuchMethodException | SecurityException |
InstantiationException | IllegalAccessException | IllegalArgumentException |
InvocationTargetException e) {
LOG.warn("Failed to initialize {} notebook storage class", storageClassNames[i], e);
}
}
// couldn't initialize any storage, use default
if (getRepoCount() == 0) {
LOG.info("No storage could be initialized, using default {} storage", defaultStorage);
initializeDefaultStorage(conf);
}
// sync for anonymous mode on start
if (getRepoCount() > 1 && conf.getBoolean(ConfVars.ZEPPELIN_ANONYMOUS_ALLOWED)) {
try {
sync(AuthenticationInfo.ANONYMOUS);
} catch (IOException e) {
LOG.error("Couldn't sync on start ", e);
}
}
}
@SuppressWarnings("static-access")
private void initializeDefaultStorage(ZeppelinConfiguration conf) {
Class<?> notebookStorageClass;
try {
notebookStorageClass = getClass().forName(defaultStorage);
Constructor<?> constructor = notebookStorageClass.getConstructor(
ZeppelinConfiguration.class);
repos.add((NotebookRepo) constructor.newInstance(conf));
} catch (ClassNotFoundException | NoSuchMethodException | SecurityException |
InstantiationException | IllegalAccessException | IllegalArgumentException |
InvocationTargetException e) {
LOG.warn("Failed to initialize {} notebook storage class {}", defaultStorage, e);
}
}
public List<NotebookRepoWithSettings> getNotebookRepos(AuthenticationInfo subject) {
List<NotebookRepoWithSettings> reposSetting = Lists.newArrayList();
NotebookRepoWithSettings repoWithSettings;
for (NotebookRepo repo : repos) {
repoWithSettings = NotebookRepoWithSettings
.builder(repo.getClass().getSimpleName())
.className(repo.getClass().getName())
.settings(repo.getSettings(subject))
.build();
reposSetting.add(repoWithSettings);
}
return reposSetting;
}
public NotebookRepoWithSettings updateNotebookRepo(String name, Map<String, String> settings,
AuthenticationInfo subject) {
NotebookRepoWithSettings updatedSettings = NotebookRepoWithSettings.EMPTY;
for (NotebookRepo repo : repos) {
if (repo.getClass().getName().equals(name)) {
repo.updateSettings(settings, subject);
updatedSettings = NotebookRepoWithSettings
.builder(repo.getClass().getSimpleName())
.className(repo.getClass().getName())
.settings(repo.getSettings(subject))
.build();
break;
}
}
return updatedSettings;
}
/**
* Lists Notebooks from the first repository
*/
@Override
public List<NoteInfo> list(AuthenticationInfo subject) throws IOException {
return getRepo(0).list(subject);
}
/* list from specific repo (for tests) */
List<NoteInfo> list(int repoIndex, AuthenticationInfo subject) throws IOException {
return getRepo(repoIndex).list(subject);
}
/**
* Returns from Notebook from the first repository
*/
@Override
public Note get(String noteId, AuthenticationInfo subject) throws IOException {
return getRepo(0).get(noteId, subject);
}
/* get note from specific repo (for tests) */
Note get(int repoIndex, String noteId, AuthenticationInfo subject) throws IOException {
return getRepo(repoIndex).get(noteId, subject);
}
/**
* Saves to all repositories
*/
@Override
public void save(Note note, AuthenticationInfo subject) throws IOException {
getRepo(0).save(note, subject);
if (getRepoCount() > 1) {
try {
getRepo(1).save(note, subject);
}
catch (IOException e) {
LOG.info(e.getMessage() + ": Failed to write to secondary storage");
}
}
}
/* save note to specific repo (for tests) */
void save(int repoIndex, Note note, AuthenticationInfo subject) throws IOException {
getRepo(repoIndex).save(note, subject);
}
@Override
public void remove(String noteId, AuthenticationInfo subject) throws IOException {
for (NotebookRepo repo : repos) {
repo.remove(noteId, subject);
}
/* TODO(khalid): handle case when removing from secondary storage fails */
}
void remove(int repoIndex, String noteId, AuthenticationInfo subject) throws IOException {
getRepo(repoIndex).remove(noteId, subject);
}
/**
* Copies new/updated notes from source to destination storage
*
* @throws IOException
*/
void sync(int sourceRepoIndex, int destRepoIndex, AuthenticationInfo subject) throws IOException {
LOG.info("Sync started");
NotebookAuthorization auth = NotebookAuthorization.getInstance();
NotebookRepo srcRepo = getRepo(sourceRepoIndex);
NotebookRepo dstRepo = getRepo(destRepoIndex);
List <NoteInfo> allSrcNotes = srcRepo.list(subject);
List <NoteInfo> srcNotes = auth.filterByUser(allSrcNotes, subject);
List <NoteInfo> dstNotes = dstRepo.list(subject);
Map<String, List<String>> noteIds = notesCheckDiff(srcNotes, srcRepo, dstNotes, dstRepo,
subject);
List<String> pushNoteIds = noteIds.get(pushKey);
List<String> pullNoteIds = noteIds.get(pullKey);
List<String> delDstNoteIds = noteIds.get(delDstKey);
if (!pushNoteIds.isEmpty()) {
LOG.info("Notes with the following IDs will be pushed");
for (String id : pushNoteIds) {
LOG.info("ID : " + id);
}
pushNotes(subject, pushNoteIds, srcRepo, dstRepo, false);
} else {
LOG.info("Nothing to push");
}
if (!pullNoteIds.isEmpty()) {
LOG.info("Notes with the following IDs will be pulled");
for (String id : pullNoteIds) {
LOG.info("ID : " + id);
}
pushNotes(subject, pullNoteIds, dstRepo, srcRepo, true);
} else {
LOG.info("Nothing to pull");
}
if (!delDstNoteIds.isEmpty()) {
LOG.info("Notes with the following IDs will be deleted from dest");
for (String id : delDstNoteIds) {
LOG.info("ID : " + id);
}
deleteNotes(subject, delDstNoteIds, dstRepo);
} else {
LOG.info("Nothing to delete from dest");
}
LOG.info("Sync ended");
}
public void sync(AuthenticationInfo subject) throws IOException {
sync(0, 1, subject);
}
private void pushNotes(AuthenticationInfo subject, List<String> ids, NotebookRepo localRepo,
NotebookRepo remoteRepo, boolean setPermissions) {
for (String id : ids) {
try {
remoteRepo.save(localRepo.get(id, subject), subject);
if (setPermissions && emptyNoteAcl(id)) {
makePrivate(id, subject);
}
} catch (IOException e) {
LOG.error("Failed to push note to storage, moving onto next one", e);
}
}
}
private boolean emptyNoteAcl(String noteId) {
NotebookAuthorization notebookAuthorization = NotebookAuthorization.getInstance();
return notebookAuthorization.getOwners(noteId).isEmpty()
&& notebookAuthorization.getReaders(noteId).isEmpty()
&& notebookAuthorization.getWriters(noteId).isEmpty();
}
private void makePrivate(String noteId, AuthenticationInfo subject) {
if (AuthenticationInfo.isAnonymous(subject)) {
LOG.info("User is anonymous, permissions are not set for pulled notes");
return;
}
NotebookAuthorization notebookAuthorization = NotebookAuthorization.getInstance();
Set<String> users = notebookAuthorization.getOwners(noteId);
users.add(subject.getUser());
notebookAuthorization.setOwners(noteId, users);
users = notebookAuthorization.getReaders(noteId);
users.add(subject.getUser());
notebookAuthorization.setReaders(noteId, users);
users = notebookAuthorization.getWriters(noteId);
users.add(subject.getUser());
notebookAuthorization.setWriters(noteId, users);
}
private void deleteNotes(AuthenticationInfo subject, List<String> ids, NotebookRepo repo)
throws IOException {
for (String id : ids) {
repo.remove(id, subject);
}
}
public int getRepoCount() {
return repos.size();
}
int getMaxRepoNum() {
return maxRepoNum;
}
NotebookRepo getRepo(int repoIndex) throws IOException {
if (repoIndex < 0 || repoIndex >= getRepoCount()) {
throw new IOException("Requested storage index " + repoIndex
+ " isn't initialized," + " repository count is " + getRepoCount());
}
return repos.get(repoIndex);
}
private Map<String, List<String>> notesCheckDiff(List<NoteInfo> sourceNotes,
NotebookRepo sourceRepo, List<NoteInfo> destNotes, NotebookRepo destRepo,
AuthenticationInfo subject) {
List <String> pushIDs = new ArrayList<>();
List <String> pullIDs = new ArrayList<>();
List <String> delDstIDs = new ArrayList<>();
NoteInfo dnote;
Date sdate, ddate;
for (NoteInfo snote : sourceNotes) {
dnote = containsID(destNotes, snote.getId());
if (dnote != null) {
try {
/* note exists in source and destination storage systems */
sdate = lastModificationDate(sourceRepo.get(snote.getId(), subject));
ddate = lastModificationDate(destRepo.get(dnote.getId(), subject));
} catch (IOException e) {
LOG.error("Cannot access previously listed note {} from storage ", dnote.getId(), e);
continue;
}
if (sdate.compareTo(ddate) != 0) {
if (sdate.after(ddate) || oneWaySync) {
/* if source contains more up to date note - push
* if oneWaySync is enabled, always push no matter who's newer */
pushIDs.add(snote.getId());
LOG.info("Modified note is added to push list : " + sdate);
} else {
/* destination contains more up to date note - pull */
LOG.info("Modified note is added to pull list : " + ddate);
pullIDs.add(snote.getId());
}
}
} else {
/* note exists in source storage, and absent in destination
* view source as up to date - push
* (another scenario : note was deleted from destination - not considered)*/
pushIDs.add(snote.getId());
}
}
for (NoteInfo note : destNotes) {
dnote = containsID(sourceNotes, note.getId());
if (dnote == null) {
/* note exists in destination storage, and absent in source */
if (oneWaySync) {
/* if oneWaySync is enabled, delete the note from destination */
LOG.info("Extraneous note is added to delete dest list : " + note.getId());
delDstIDs.add(note.getId());
} else {
/* if oneWaySync is disabled, pull the note from destination */
LOG.info("Missing note is added to pull list : " + note.getId());
pullIDs.add(note.getId());
}
}
}
Map<String, List<String>> map = new HashMap<>();
map.put(pushKey, pushIDs);
map.put(pullKey, pullIDs);
map.put(delDstKey, delDstIDs);
return map;
}
private NoteInfo containsID(List <NoteInfo> notes, String id) {
for (NoteInfo note : notes) {
if (note.getId().equals(id)) {
return note;
}
}
return null;
}
/**
* checks latest modification date based on Paragraph fields
* @return -Date
*/
private Date lastModificationDate(Note note) {
Date latest = new Date(0L);
Date tempCreated, tempStarted, tempFinished;
for (Paragraph paragraph : note.getParagraphs()) {
tempCreated = paragraph.getDateCreated();
tempStarted = paragraph.getDateStarted();
tempFinished = paragraph.getDateFinished();
if (tempCreated != null && tempCreated.after(latest)) {
latest = tempCreated;
}
if (tempStarted != null && tempStarted.after(latest)) {
latest = tempStarted;
}
if (tempFinished != null && tempFinished.after(latest)) {
latest = tempFinished;
}
}
return latest;
}
@Override
public void close() {
LOG.info("Closing all notebook storages");
for (NotebookRepo repo: repos) {
repo.close();
}
}
//checkpoint to all available storages
@Override
public Revision checkpoint(String noteId, String checkpointMsg, AuthenticationInfo subject)
throws IOException {
int repoCount = getRepoCount();
int repoBound = Math.min(repoCount, getMaxRepoNum());
int errorCount = 0;
String errorMessage = "";
List<Revision> allRepoCheckpoints = new ArrayList<>();
Revision rev = null;
for (int i = 0; i < repoBound; i++) {
try {
allRepoCheckpoints.add(getRepo(i).checkpoint(noteId, checkpointMsg, subject));
} catch (IOException e) {
LOG.warn("Couldn't checkpoint in {} storage with index {} for note {}",
getRepo(i).getClass().toString(), i, noteId);
errorMessage += "Error on storage class " + getRepo(i).getClass().toString() +
" with index " + i + " : " + e.getMessage() + "\n";
errorCount++;
}
}
// throw exception if failed to commit for all initialized repos
if (errorCount == repoBound) {
throw new IOException(errorMessage);
}
if (allRepoCheckpoints.size() > 0) {
rev = allRepoCheckpoints.get(0);
// if failed to checkpoint on first storage, then return result on second
if (allRepoCheckpoints.size() > 1 && rev == null) {
rev = allRepoCheckpoints.get(1);
}
}
return rev;
}
@Override
public Note get(String noteId, String revId, AuthenticationInfo subject) {
Note revisionNote = null;
try {
revisionNote = getRepo(0).get(noteId, revId, subject);
} catch (IOException e) {
LOG.error("Failed to get revision {} of note {}", revId, noteId, e);
}
return revisionNote;
}
@Override
public List<Revision> revisionHistory(String noteId, AuthenticationInfo subject) {
List<Revision> revisions = Collections.emptyList();
try {
revisions = getRepo(0).revisionHistory(noteId, subject);
} catch (IOException e) {
LOG.error("Failed to list revision history", e);
}
return revisions;
}
@Override
public List<NotebookRepoSettingsInfo> getSettings(AuthenticationInfo subject) {
List<NotebookRepoSettingsInfo> repoSettings = Collections.emptyList();
try {
repoSettings = getRepo(0).getSettings(subject);
} catch (IOException e) {
LOG.error("Cannot get notebook repo settings", e);
}
return repoSettings;
}
@Override
public void updateSettings(Map<String, String> settings, AuthenticationInfo subject) {
try {
getRepo(0).updateSettings(settings, subject);
} catch (IOException e) {
LOG.error("Cannot update notebook repo settings", e);
}
}
@Override
public Note setNoteRevision(String noteId, String revId, AuthenticationInfo subject)
throws IOException {
int repoCount = getRepoCount();
int repoBound = Math.min(repoCount, getMaxRepoNum());
Note currentNote = null, revisionNote = null;
for (int i = 0; i < repoBound; i++) {
try {
currentNote = getRepo(i).setNoteRevision(noteId, revId, subject);
} catch (IOException e) {
// already logged
currentNote = null;
}
// second condition assures that fist successful is returned
if (currentNote != null && revisionNote == null) {
revisionNote = currentNote;
}
}
return revisionNote;
}
}
| 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/repo/NotebookRepoWithSettings.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/repo/NotebookRepoWithSettings.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.repo;
import java.util.Collections;
import java.util.List;
import org.apache.commons.lang.StringUtils;
/**
* Representation of a notebook repo with settings. This is mostly a Wrapper around notebook repo
* information plus settings.
*/
public class NotebookRepoWithSettings {
public static final NotebookRepoWithSettings EMPTY =
NotebookRepoWithSettings.builder(StringUtils.EMPTY).build();
public String name;
public String className;
public List<NotebookRepoSettingsInfo> settings;
private NotebookRepoWithSettings() {}
public static Builder builder(String name) {
return new Builder(name);
}
private NotebookRepoWithSettings(Builder builder) {
name = builder.name;
className = builder.className;
settings = builder.settings;
}
public boolean isEmpty() {
return this.equals(EMPTY);
}
/**
* Simple builder :).
*/
public static class Builder {
private final String name;
private String className = StringUtils.EMPTY;
private List<NotebookRepoSettingsInfo> settings = Collections.emptyList();
public Builder(String name) {
this.name = name;
}
public NotebookRepoWithSettings build() {
return new NotebookRepoWithSettings(this);
}
public Builder className(String className) {
this.className = className;
return this;
}
public Builder settings(List<NotebookRepoSettingsInfo> settings) {
this.settings = settings;
return this;
}
}
}
| 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/repo/zeppelinhub/ZeppelinHubRepo.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/repo/zeppelinhub/ZeppelinHubRepo.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.repo.zeppelinhub;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.zeppelin.conf.ZeppelinConfiguration;
import org.apache.zeppelin.notebook.Note;
import org.apache.zeppelin.notebook.NoteInfo;
import org.apache.zeppelin.notebook.repo.NotebookRepo;
import org.apache.zeppelin.notebook.repo.NotebookRepoSettingsInfo;
import org.apache.zeppelin.notebook.repo.zeppelinhub.model.Instance;
import org.apache.zeppelin.notebook.repo.zeppelinhub.model.UserTokenContainer;
import org.apache.zeppelin.notebook.repo.zeppelinhub.model.UserSessionContainer;
import org.apache.zeppelin.notebook.repo.zeppelinhub.rest.ZeppelinhubRestApiHandler;
import org.apache.zeppelin.notebook.repo.zeppelinhub.websocket.Client;
import org.apache.zeppelin.notebook.repo.zeppelinhub.websocket.utils.ZeppelinhubUtils;
import org.apache.zeppelin.user.AuthenticationInfo;
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;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
/**
* ZeppelinHub repo class.
*/
public class ZeppelinHubRepo implements NotebookRepo {
private static final Logger LOG = LoggerFactory.getLogger(ZeppelinHubRepo.class);
private static final String DEFAULT_SERVER = "https://www.zeppelinhub.com";
static final String ZEPPELIN_CONF_PROP_NAME_SERVER = "zeppelinhub.api.address";
static final String ZEPPELIN_CONF_PROP_NAME_TOKEN = "zeppelinhub.api.token";
public static final String TOKEN_HEADER = "X-Zeppelin-Token";
private static final Gson GSON = new Gson();
private static final Note EMPTY_NOTE = new Note();
private final Client websocketClient;
private final UserTokenContainer tokenManager;
private String token;
private ZeppelinhubRestApiHandler restApiClient;
private final ZeppelinConfiguration conf;
public ZeppelinHubRepo(ZeppelinConfiguration conf) {
this.conf = conf;
String zeppelinHubUrl = getZeppelinHubUrl(conf);
LOG.info("Initializing ZeppelinHub integration module");
token = conf.getString("ZEPPELINHUB_API_TOKEN", ZEPPELIN_CONF_PROP_NAME_TOKEN, "");
restApiClient = ZeppelinhubRestApiHandler.newInstance(zeppelinHubUrl);
//TODO(khalid): check which realm for authentication, pass to token manager
tokenManager = UserTokenContainer.init(restApiClient, token);
websocketClient = Client.initialize(getZeppelinWebsocketUri(conf),
getZeppelinhubWebsocketUri(conf), token, conf);
websocketClient.start();
}
private String getZeppelinHubWsUri(URI api) throws URISyntaxException {
URI apiRoot = api;
String scheme = apiRoot.getScheme();
int port = apiRoot.getPort();
if (port <= 0) {
port = (scheme != null && scheme.equals("https")) ? 443 : 80;
}
if (scheme == null) {
LOG.info("{} is not a valid zeppelinhub server address. proceed with default address {}",
apiRoot, DEFAULT_SERVER);
apiRoot = new URI(DEFAULT_SERVER);
scheme = apiRoot.getScheme();
port = apiRoot.getPort();
if (port <= 0) {
port = (scheme != null && scheme.equals("https")) ? 443 : 80;
}
}
String ws = scheme.equals("https") ? "wss://" : "ws://";
return ws + apiRoot.getHost() + ":" + port + "/async";
}
String getZeppelinhubWebsocketUri(ZeppelinConfiguration conf) {
String zeppelinHubUri = StringUtils.EMPTY;
try {
zeppelinHubUri = getZeppelinHubWsUri(new URI(conf.getString("ZEPPELINHUB_API_ADDRESS",
ZEPPELIN_CONF_PROP_NAME_SERVER, DEFAULT_SERVER)));
} catch (URISyntaxException e) {
LOG.error("Cannot get ZeppelinHub URI", e);
}
return zeppelinHubUri;
}
private String getZeppelinWebsocketUri(ZeppelinConfiguration conf) {
int port = conf.getServerPort();
if (port <= 0) {
port = 80;
}
String ws = conf.useSsl() ? "wss" : "ws";
return ws + "://localhost:" + port + "/ws";
}
// Used in tests
void setZeppelinhubRestApiHandler(ZeppelinhubRestApiHandler zeppelinhub) {
restApiClient = zeppelinhub;
}
String getZeppelinHubUrl(ZeppelinConfiguration conf) {
if (conf == null) {
LOG.error("Invalid configuration, cannot be null. Using default address {}", DEFAULT_SERVER);
return DEFAULT_SERVER;
}
URI apiRoot;
String zeppelinhubUrl;
try {
String url = conf.getString("ZEPPELINHUB_API_ADDRESS",
ZEPPELIN_CONF_PROP_NAME_SERVER,
DEFAULT_SERVER);
apiRoot = new URI(url);
} catch (URISyntaxException e) {
LOG.error("Invalid zeppelinhub url, using default address {}", DEFAULT_SERVER, e);
return DEFAULT_SERVER;
}
String scheme = apiRoot.getScheme();
if (scheme == null) {
LOG.info("{} is not a valid zeppelinhub server address. proceed with default address {}",
apiRoot, DEFAULT_SERVER);
zeppelinhubUrl = DEFAULT_SERVER;
} else {
zeppelinhubUrl = scheme + "://" + apiRoot.getHost();
if (apiRoot.getPort() > 0) {
zeppelinhubUrl += ":" + apiRoot.getPort();
}
}
return zeppelinhubUrl;
}
private boolean isSubjectValid(AuthenticationInfo subject) {
if (subject == null) {
return false;
}
return (subject.isAnonymous() && !conf.isAnonymousAllowed()) ? false : true;
}
@Override
public List<NoteInfo> list(AuthenticationInfo subject) throws IOException {
if (!isSubjectValid(subject)) {
return Collections.emptyList();
}
String token = getUserToken(subject.getUser());
String response = restApiClient.get(token, StringUtils.EMPTY);
List<NoteInfo> notes = GSON.fromJson(response, new TypeToken<List<NoteInfo>>() {}.getType());
if (notes == null) {
return Collections.emptyList();
}
LOG.info("ZeppelinHub REST API listing notes ");
return notes;
}
@Override
public Note get(String noteId, AuthenticationInfo subject) throws IOException {
if (StringUtils.isBlank(noteId) || !isSubjectValid(subject)) {
return EMPTY_NOTE;
}
String token = getUserToken(subject.getUser());
String response = restApiClient.get(token, noteId);
Note note = GSON.fromJson(response, Note.class);
if (note == null) {
return EMPTY_NOTE;
}
LOG.info("ZeppelinHub REST API get note {} ", noteId);
return note;
}
@Override
public void save(Note note, AuthenticationInfo subject) throws IOException {
if (note == null || !isSubjectValid(subject)) {
throw new IOException("Zeppelinhub failed to save note");
}
String jsonNote = GSON.toJson(note);
String token = getUserToken(subject.getUser());
LOG.info("ZeppelinHub REST API saving note {} ", note.getId());
restApiClient.put(token, jsonNote);
}
@Override
public void remove(String noteId, AuthenticationInfo subject) throws IOException {
if (StringUtils.isBlank(noteId) || !isSubjectValid(subject)) {
throw new IOException("Zeppelinhub failed to remove note");
}
String token = getUserToken(subject.getUser());
LOG.info("ZeppelinHub REST API removing note {} ", noteId);
restApiClient.del(token, noteId);
}
@Override
public void close() {
websocketClient.stop();
restApiClient.close();
}
@Override
public Revision checkpoint(String noteId, String checkpointMsg, AuthenticationInfo subject)
throws IOException {
if (StringUtils.isBlank(noteId) || !isSubjectValid(subject)) {
return Revision.EMPTY;
}
String endpoint = Joiner.on("/").join(noteId, "checkpoint");
String content = GSON.toJson(ImmutableMap.of("message", checkpointMsg));
String token = getUserToken(subject.getUser());
String response = restApiClient.putWithResponseBody(token, endpoint, content);
return GSON.fromJson(response, Revision.class);
}
@Override
public Note get(String noteId, String revId, AuthenticationInfo subject) throws IOException {
if (StringUtils.isBlank(noteId) || StringUtils.isBlank(revId) || !isSubjectValid(subject)) {
return EMPTY_NOTE;
}
String endpoint = Joiner.on("/").join(noteId, "checkpoint", revId);
String token = getUserToken(subject.getUser());
String response = restApiClient.get(token, endpoint);
Note note = GSON.fromJson(response, Note.class);
if (note == null) {
return EMPTY_NOTE;
}
LOG.info("ZeppelinHub REST API get note {} revision {}", noteId, revId);
return note;
}
@Override
public List<Revision> revisionHistory(String noteId, AuthenticationInfo subject) {
if (StringUtils.isBlank(noteId) || !isSubjectValid(subject)) {
return Collections.emptyList();
}
String endpoint = Joiner.on("/").join(noteId, "checkpoint");
List<Revision> history = Collections.emptyList();
try {
String token = getUserToken(subject.getUser());
String response = restApiClient.get(token, endpoint);
history = GSON.fromJson(response, new TypeToken<List<Revision>>(){}.getType());
} catch (IOException e) {
LOG.error("Cannot get note history", e);
}
return history;
}
private String getUserToken(String user) {
return tokenManager.getUserToken(user);
}
@Override
public List<NotebookRepoSettingsInfo> getSettings(AuthenticationInfo subject) {
if (!isSubjectValid(subject)) {
return Collections.emptyList();
}
List<NotebookRepoSettingsInfo> settings = Lists.newArrayList();
String user = subject.getUser();
String zeppelinHubUserSession = UserSessionContainer.instance.getSession(user);
String userToken = getUserToken(user);
List<Instance> instances;
List<Map<String, String>> values = Lists.newLinkedList();
try {
instances = tokenManager.getUserInstances(zeppelinHubUserSession);
} catch (IOException e) {
LOG.warn("Couldnt find instances for the session {}, returning empty collection",
zeppelinHubUserSession);
// user not logged
//TODO(xxx): handle this case.
instances = Collections.emptyList();
}
NotebookRepoSettingsInfo repoSetting = NotebookRepoSettingsInfo.newInstance();
repoSetting.type = NotebookRepoSettingsInfo.Type.DROPDOWN;
for (Instance instance : instances) {
if (instance.token.equals(userToken)) {
repoSetting.selected = Integer.toString(instance.id);
}
values.add(ImmutableMap.of("name", instance.name, "value", Integer.toString(instance.id)));
}
repoSetting.value = values;
repoSetting.name = "Instance";
settings.add(repoSetting);
return settings;
}
private void changeToken(int instanceId, String user) {
if (instanceId <= 0) {
LOG.error("User {} tried to switch to a non valid instance {}", user, instanceId);
return;
}
LOG.info("User {} will switch instance", user);
String ticket = UserSessionContainer.instance.getSession(user);
List<Instance> instances;
String currentToken = StringUtils.EMPTY, targetToken = StringUtils.EMPTY;
try {
instances = tokenManager.getUserInstances(ticket);
if (instances.isEmpty()) {
return;
}
currentToken = tokenManager.getExistingUserToken(user);
for (Instance instance : instances) {
if (instance.id == instanceId) {
LOG.info("User {} switched to instance {}", user, instance.name);
tokenManager.setUserToken(user, instance.token);
targetToken = instance.token;
break;
}
}
if (!StringUtils.isBlank(currentToken) && !StringUtils.isBlank(targetToken)) {
ZeppelinhubUtils.userSwitchTokenRoutine(user, currentToken, targetToken);
}
} catch (IOException e) {
LOG.error("Cannot switch instance for user {}", user, e);
}
}
@Override
public void updateSettings(Map<String, String> settings, AuthenticationInfo subject) {
if (!isSubjectValid(subject)) {
LOG.error("Invalid subject, cannot update Zeppelinhub settings");
return;
}
if (settings == null || settings.isEmpty()) {
LOG.error("Cannot update ZeppelinHub repo settings because of invalid settings");
return;
}
int instanceId = 0;
if (settings.containsKey("Instance")) {
try {
instanceId = Integer.parseInt(settings.get("Instance"));
} catch (NumberFormatException e) {
LOG.error("ZeppelinHub Instance Id in not a valid integer", e);
}
}
changeToken(instanceId, subject.getUser());
}
@Override
public Note setNoteRevision(String noteId, String revId, AuthenticationInfo subject)
throws IOException {
// Auto-generated method stub
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/notebook/repo/zeppelinhub/model/UserTokenContainer.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/repo/zeppelinhub/model/UserTokenContainer.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.repo.zeppelinhub.model;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.apache.commons.lang.StringUtils;
import org.apache.zeppelin.notebook.repo.zeppelinhub.rest.ZeppelinhubRestApiHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* User token manager class.
*
*/
public class UserTokenContainer {
private static final Logger LOG = LoggerFactory.getLogger(UserTokenContainer.class);
private static UserTokenContainer instance = null;
private ConcurrentMap<String, String> userTokens = new ConcurrentHashMap<String, String>();
private final ZeppelinhubRestApiHandler restApiClient;
private String defaultToken;
public static UserTokenContainer init(ZeppelinhubRestApiHandler restClient,
String defaultToken) {
if (instance == null) {
instance = new UserTokenContainer(restClient, defaultToken);
}
return instance;
}
private UserTokenContainer(ZeppelinhubRestApiHandler restClient, String defaultToken) {
restApiClient = restClient;
this.defaultToken = defaultToken;
}
public static UserTokenContainer getInstance() {
return instance;
}
public void setUserToken(String username, String token) {
if (StringUtils.isBlank(username) || StringUtils.isBlank(token)) {
LOG.warn("Can't set empty user token");
return;
}
userTokens.put(username, token);
}
public String getUserToken(String principal) {
if (StringUtils.isBlank(principal) || "anonymous".equals(principal)) {
if (StringUtils.isBlank(defaultToken)) {
return StringUtils.EMPTY;
} else {
userTokens.putIfAbsent(principal, defaultToken);
return defaultToken;
}
}
String token = userTokens.get(principal);
if (StringUtils.isBlank(token)) {
String ticket = UserSessionContainer.instance.getSession(principal);
try {
token = getDefaultZeppelinInstanceToken(ticket);
if (StringUtils.isBlank(token)) {
if (!StringUtils.isBlank(defaultToken)) {
token = defaultToken;
}
} else {
userTokens.putIfAbsent(principal, token);
}
} catch (IOException e) {
LOG.error("Cannot get user token", e);
token = StringUtils.EMPTY;
}
}
return token;
}
public String getExistingUserToken(String principal) {
if (StringUtils.isBlank(principal) || "anonymous".equals(principal)) {
return StringUtils.EMPTY;
}
String token = userTokens.get(principal);
if (token == null) {
return StringUtils.EMPTY;
}
return token;
}
public String removeUserToken(String username) {
return userTokens.remove(username);
}
/**
* Get user default instance.
* From now, it will be from the first instance from the list,
* But later we can think about marking a default one and return it instead :)
*/
public String getDefaultZeppelinInstanceToken(String ticket) throws IOException {
List<Instance> instances = getUserInstances(ticket);
if (instances.isEmpty()) {
return StringUtils.EMPTY;
}
String token = instances.get(0).token;
LOG.debug("The following instance has been assigned {} with token {}", instances.get(0).name,
token);
return token;
}
/**
* Get list of user instances from Zeppelinhub.
* This will avoid and remove the needs of setting up token in zeppelin-env.sh.
*/
public List<Instance> getUserInstances(String ticket) throws IOException {
if (StringUtils.isBlank(ticket)) {
return Collections.emptyList();
}
return restApiClient.getInstances(ticket);
}
public List<String> getAllTokens() {
return new ArrayList<String>(userTokens.values());
}
public Map<String, String> getAllUserTokens() {
return new HashMap<String, String>(userTokens);
}
}
| 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/repo/zeppelinhub/model/UserSessionContainer.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/repo/zeppelinhub/model/UserSessionContainer.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.repo.zeppelinhub.model;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.lang.StringUtils;
/**
* Simple and yet dummy container for zeppelinhub session.
*
*/
public class UserSessionContainer {
private static class Entity {
public final String userSession;
Entity(String userSession) {
this.userSession = userSession;
}
}
private Map<String, Entity> sessions = new ConcurrentHashMap<>();
public static final UserSessionContainer instance = new UserSessionContainer();
public synchronized String getSession(String principal) {
Entity entry = sessions.get(principal);
if (entry == null) {
return StringUtils.EMPTY;
}
return entry.userSession;
}
public synchronized String setSession(String principal, String userSession) {
Entity entry = new Entity(userSession);
sessions.put(principal, entry);
return entry.userSession;
}
}
| 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/repo/zeppelinhub/model/Instance.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/repo/zeppelinhub/model/Instance.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.repo.zeppelinhub.model;
/**
* ZeppelinHub Instance structure.
*
*/
public class Instance {
public int id;
public String name;
public String token;
}
| 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/repo/zeppelinhub/security/Authentication.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/repo/zeppelinhub/security/Authentication.java | package org.apache.zeppelin.notebook.repo.zeppelinhub.security;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang3.StringUtils;
import org.apache.zeppelin.conf.ZeppelinConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.util.Collections;
import java.util.Map;
/**
* Authentication module.
*
*/
public class Authentication implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(Authentication.class);
private String principal = "anonymous";
private String ticket = "anonymous";
private String roles = StringUtils.EMPTY;
private final HttpClient client;
private String loginEndpoint;
// Cipher is an AES in CBC mode
private static final String CIPHER_ALGORITHM = "AES";
private static final String CIPHER_MODE = "AES/CBC/PKCS5PADDING";
private static final String KEY = "AbtEr99DxsWWbJkP";
private static final int ivSize = 16;
private static final String ZEPPELIN_CONF_ANONYMOUS_ALLOWED = "zeppelin.anonymous.allowed";
private static final String ZEPPELINHUB_USER_KEY = "zeppelinhub.user.key";
private String token;
private boolean authEnabled;
private boolean authenticated;
String userKey;
private Gson gson = new Gson();
private static Authentication instance = null;
public static Authentication initialize(String token, ZeppelinConfiguration conf) {
if (instance == null && conf != null) {
instance = new Authentication(token, conf);
}
return instance;
}
public static Authentication getInstance() {
return instance;
}
private Authentication(String token, ZeppelinConfiguration conf) {
MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
client = new HttpClient(connectionManager);
this.token = token;
authEnabled = !conf.getBoolean("ZEPPELIN_ALLOW_ANONYMOUS",
ZEPPELIN_CONF_ANONYMOUS_ALLOWED, true);
userKey = conf.getString("ZEPPELINHUB_USER_KEY",
ZEPPELINHUB_USER_KEY, "");
loginEndpoint = getLoginEndpoint(conf);
}
public String getPrincipal() {
return this.principal;
}
public String getTicket() {
return this.ticket;
}
public String getRoles() {
return this.roles;
}
public boolean isAuthenticated() {
return authenticated;
}
private String getLoginEndpoint(ZeppelinConfiguration conf) {
int port = conf.getInt("ZEPPELIN_PORT", "zeppelin.server.port" , 7045);
if (port <= 0) {
port = 8080;
}
String scheme = "http";
if (conf.useSsl()) {
scheme = "https";
}
String endpoint = scheme + "://localhost:" + port + "/api/login";
return endpoint;
}
public boolean authenticate() {
if (authEnabled) {
if (!StringUtils.isEmpty(userKey)) {
String authKey = getAuthKey(userKey);
Map<String, String> authCredentials = login(authKey, loginEndpoint);
if (isEmptyMap(authCredentials)) {
return false;
}
principal = authCredentials.containsKey("principal") ? authCredentials.get("principal")
: principal;
ticket = authCredentials.containsKey("ticket") ? authCredentials.get("ticket") : ticket;
roles = authCredentials.containsKey("roles") ? authCredentials.get("roles") : roles;
LOG.info("Authenticated into Zeppelin as {} and roles {}", principal, roles);
return true;
} else {
LOG.warn("ZEPPELINHUB_USER_KEY isn't provided. Please provide your credentials"
+ "for your instance in ZeppelinHub website and generate your key.");
}
}
return false;
}
// returns login:password
private String getAuthKey(String userKey) {
LOG.debug("Encrypted user key is {}", userKey);
if (StringUtils.isBlank(userKey)) {
LOG.warn("ZEPPELINHUB_USER_KEY is blank");
return StringUtils.EMPTY;
}
//use hashed token as a salt
String hashedToken = Integer.toString(token.hashCode());
return decrypt(userKey, hashedToken);
}
private String decrypt(String value, String initVector) {
LOG.debug("IV is {}, IV length is {}", initVector, initVector.length());
if (StringUtils.isBlank(value) || StringUtils.isBlank(initVector)) {
LOG.error("String to decode or salt is not provided");
return StringUtils.EMPTY;
}
try {
IvParameterSpec iv = generateIV(initVector);
Key key = generateKey();
Cipher cipher = Cipher.getInstance(CIPHER_MODE);
cipher.init(Cipher.DECRYPT_MODE, key, iv);
byte[] decryptedString = Base64.decodeBase64(toBytes(value));
decryptedString = cipher.doFinal(decryptedString);
return new String(decryptedString);
} catch (GeneralSecurityException e) {
LOG.error("Error when decrypting", e);
return StringUtils.EMPTY;
}
}
@SuppressWarnings("unchecked")
private Map<String, String> login(String authKey, String endpoint) {
String[] credentials = authKey.split(":");
if (credentials.length != 2) {
return Collections.emptyMap();
}
PostMethod post = new PostMethod(endpoint);
post.addRequestHeader("Origin", "http://localhost");
post.addParameter(new NameValuePair("userName", credentials[0]));
post.addParameter(new NameValuePair("password", credentials[1]));
try {
int code = client.executeMethod(post);
if (code == HttpStatus.SC_OK) {
String content = post.getResponseBodyAsString();
Map<String, Object> resp = gson.fromJson(content,
new TypeToken<Map<String, Object>>() {}.getType());
LOG.info("Received from Zeppelin LoginRestApi : " + content);
return (Map<String, String>) resp.get("body");
} else {
LOG.error("Failed Zeppelin login {}, status code {}", endpoint, code);
return Collections.emptyMap();
}
} catch (IOException e) {
LOG.error("Cannot login into Zeppelin", e);
return Collections.emptyMap();
}
}
private Key generateKey() {
return new SecretKeySpec(toBytes(KEY), CIPHER_ALGORITHM);
}
private byte[] toBytes(String value) {
byte[] bytes;
try {
bytes = value.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
LOG.warn("UTF-8 isn't supported ", e);
bytes = value.getBytes();
}
return bytes;
}
private IvParameterSpec generateIV(String ivString) {
byte[] ivFromBytes = toBytes(ivString);
byte[] iv16ToBytes = new byte[ivSize];
System.arraycopy(ivFromBytes, 0, iv16ToBytes, 0, Math.min(ivFromBytes.length, ivSize));
return new IvParameterSpec(iv16ToBytes);
}
private boolean isEmptyMap(Map<String, String> map) {
return map == null || map.isEmpty();
}
@Override
public void run() {
authenticated = authenticate();
LOG.info("Scheduled authentication status is {}", authenticated);
}
}
| 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/repo/zeppelinhub/rest/ZeppelinhubRestApiHandler.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/repo/zeppelinhub/rest/ZeppelinhubRestApiHandler.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.repo.zeppelinhub.rest;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.zeppelin.notebook.repo.zeppelinhub.model.Instance;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.client.api.Response;
import org.eclipse.jetty.client.api.Result;
import org.eclipse.jetty.client.util.InputStreamResponseListener;
import org.eclipse.jetty.client.util.StringContentProvider;
import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
/**
* REST API handler.
*
*/
public class ZeppelinhubRestApiHandler {
private static final Logger LOG = LoggerFactory.getLogger(ZeppelinhubRestApiHandler.class);
public static final String ZEPPELIN_TOKEN_HEADER = "X-Zeppelin-Token";
private static final String USER_SESSION_HEADER = "X-User-Session";
private static final String DEFAULT_API_PATH = "/api/v1/zeppelin";
private static boolean PROXY_ON = false;
//TODO(xxx): possibly switch to jetty-client > 9.3.12 when adopt jvm 1.8
private static HttpProxyClient proxyClient;
private final HttpClient client;
private String zepelinhubUrl;
public static ZeppelinhubRestApiHandler newInstance(String zeppelinhubUrl) {
return new ZeppelinhubRestApiHandler(zeppelinhubUrl);
}
private ZeppelinhubRestApiHandler(String zeppelinhubUrl) {
this.zepelinhubUrl = zeppelinhubUrl + DEFAULT_API_PATH + "/";
readProxyConf();
client = getAsyncClient();
try {
client.start();
} catch (Exception e) {
LOG.error("Cannot initialize ZeppelinHub REST async client", e);
}
}
private void readProxyConf() {
//try reading https_proxy
String proxyHostString = StringUtils.isBlank(System.getenv("https_proxy")) ?
System.getenv("HTTPS_PROXY") : System.getenv("https_proxy");
if (StringUtils.isBlank(proxyHostString)) {
//try http_proxy if no https_proxy
proxyHostString = StringUtils.isBlank(System.getenv("http_proxy")) ?
System.getenv("HTTP_PROXY") : System.getenv("http_proxy");
}
if (!StringUtils.isBlank(proxyHostString)) {
URI uri = null;
try {
uri = new URI(proxyHostString);
} catch (URISyntaxException e) {
LOG.warn("Proxy uri doesn't follow correct syntax", e);
}
if (uri != null) {
PROXY_ON = true;
proxyClient = HttpProxyClient.newInstance(uri);
}
}
}
private HttpClient getAsyncClient() {
SslContextFactory sslContextFactory = new SslContextFactory();
HttpClient httpClient = new HttpClient(sslContextFactory);
// Configure HttpClient
httpClient.setFollowRedirects(false);
httpClient.setMaxConnectionsPerDestination(100);
// Config considerations
//TODO(khalid): consider multi-threaded connection manager case
return httpClient;
}
/**
* Fetch zeppelin instances for a given user.
* @param ticket
* @return
* @throws IOException
*/
public List<Instance> getInstances(String ticket) throws IOException {
InputStreamResponseListener listener = new InputStreamResponseListener();
Response response;
String url = zepelinhubUrl + "instances";
String data;
Request request = client.newRequest(url).header(USER_SESSION_HEADER, ticket);
request.send(listener);
try {
response = listener.get(30, TimeUnit.SECONDS);
} catch (InterruptedException | TimeoutException | ExecutionException e) {
LOG.error("Cannot perform request to ZeppelinHub", e);
throw new IOException("Cannot perform GET request to ZeppelinHub", e);
}
int code = response.getStatus();
if (code == 200) {
try (InputStream responseContent = listener.getInputStream()) {
data = IOUtils.toString(responseContent, "UTF-8");
}
} else {
LOG.error("ZeppelinHub GET {} returned with status {} ", url, code);
throw new IOException("Cannot perform GET request to ZeppelinHub");
}
Type listType = new TypeToken<ArrayList<Instance>>() {}.getType();
return new Gson().fromJson(data, listType);
}
public String get(String token, String argument) throws IOException {
if (StringUtils.isBlank(token)) {
return StringUtils.EMPTY;
}
String url = zepelinhubUrl + argument;
if (PROXY_ON) {
return sendToZeppelinHubViaProxy(new HttpGet(url), StringUtils.EMPTY, token, true);
} else {
return sendToZeppelinHub(HttpMethod.GET, url, StringUtils.EMPTY, token, true);
}
}
public String putWithResponseBody(String token, String url, String json) throws IOException {
if (StringUtils.isBlank(url) || StringUtils.isBlank(json)) {
LOG.error("Empty note, cannot send it to zeppelinHub");
throw new IOException("Cannot send emtpy note to zeppelinHub");
}
if (PROXY_ON) {
return sendToZeppelinHubViaProxy(new HttpPut(zepelinhubUrl + url), json, token, true);
} else {
return sendToZeppelinHub(HttpMethod.PUT, zepelinhubUrl + url, json, token, true);
}
}
public void put(String token, String jsonNote) throws IOException {
if (StringUtils.isBlank(jsonNote)) {
LOG.error("Cannot save empty note/string to ZeppelinHub");
return;
}
if (PROXY_ON) {
sendToZeppelinHubViaProxy(new HttpPut(zepelinhubUrl), jsonNote, token, false);
} else {
sendToZeppelinHub(HttpMethod.PUT, zepelinhubUrl, jsonNote, token, false);
}
}
public void del(String token, String argument) throws IOException {
if (StringUtils.isBlank(argument)) {
LOG.error("Cannot delete empty note from ZeppelinHub");
return;
}
if (PROXY_ON) {
sendToZeppelinHubViaProxy(new HttpDelete(zepelinhubUrl + argument), StringUtils.EMPTY, token,
false);
} else {
sendToZeppelinHub(HttpMethod.DELETE, zepelinhubUrl + argument, StringUtils.EMPTY, token,
false);
}
}
private String sendToZeppelinHubViaProxy(HttpRequestBase request,
String json,
String token,
boolean withResponse) throws IOException {
request.setHeader(ZEPPELIN_TOKEN_HEADER, token);
if (request.getMethod().equals(HttpPost.METHOD_NAME)) {
HttpPost post = (HttpPost) request;
StringEntity content = new StringEntity(json, "application/json;charset=UTF-8");
post.setEntity(content);
}
if (request.getMethod().equals(HttpPut.METHOD_NAME)) {
HttpPut put = (HttpPut) request;
StringEntity content = new StringEntity(json, "application/json;charset=UTF-8");
put.setEntity(content);
}
String body = StringUtils.EMPTY;
if (proxyClient != null) {
body = proxyClient.sendToZeppelinHub(request, withResponse);
} else {
LOG.warn("Proxy client request was submitted while not correctly initialized");
}
return body;
}
private String sendToZeppelinHub(HttpMethod method,
String url,
String json,
String token,
boolean withResponse)
throws IOException {
Request request = client.newRequest(url).method(method).header(ZEPPELIN_TOKEN_HEADER, token);
if ((method.equals(HttpMethod.PUT) || method.equals(HttpMethod.POST))
&& !StringUtils.isBlank(json)) {
request.content(new StringContentProvider(json, "UTF-8"), "application/json;charset=UTF-8");
}
return withResponse ?
sendToZeppelinHub(request) : sendToZeppelinHubWithoutResponseBody(request);
}
private String sendToZeppelinHubWithoutResponseBody(Request request) throws IOException {
request.send(new Response.CompleteListener() {
@Override
public void onComplete(Result result) {
Request req = result.getRequest();
LOG.info("ZeppelinHub {} {} returned with status {}: {}", req.getMethod(),
req.getURI(), result.getResponse().getStatus(), result.getResponse().getReason());
}
});
return StringUtils.EMPTY;
}
private String sendToZeppelinHub(final Request request) throws IOException {
InputStreamResponseListener listener = new InputStreamResponseListener();
Response response;
String data;
request.send(listener);
try {
response = listener.get(30, TimeUnit.SECONDS);
} catch (InterruptedException | TimeoutException | ExecutionException e) {
String method = request.getMethod();
LOG.error("Cannot perform {} request to ZeppelinHub", method, e);
throw new IOException("Cannot perform " + method + " request to ZeppelinHub", e);
}
int code = response.getStatus();
if (code == 200) {
try (InputStream responseContent = listener.getInputStream()) {
data = IOUtils.toString(responseContent, "UTF-8");
}
} else {
String method = response.getRequest().getMethod();
String url = response.getRequest().getURI().toString();
LOG.error("ZeppelinHub {} {} returned with status {} ", method, url, code);
throw new IOException("Cannot perform " + method + " request to ZeppelinHub");
}
return data;
}
public void close() {
try {
client.stop();
if (proxyClient != null) {
proxyClient.stop();
}
} catch (Exception e) {
LOG.info("Couldn't stop ZeppelinHub client properly", 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/main/java/org/apache/zeppelin/notebook/repo/zeppelinhub/rest/HttpProxyClient.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/repo/zeppelinhub/rest/HttpProxyClient.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.repo.zeppelinhub.rest;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.net.ssl.SSLContext;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ssl.BrowserCompatHostnameVerifier;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.impl.client.DefaultRedirectStrategy;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager;
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
import org.apache.http.nio.conn.NoopIOSessionStrategy;
import org.apache.http.nio.conn.SchemeIOSessionStrategy;
import org.apache.http.nio.conn.ssl.SSLIOSessionStrategy;
import org.apache.http.nio.reactor.ConnectingIOReactor;
import org.apache.http.nio.reactor.IOReactorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This is http client class for the case of proxy usage
* jetty-client has issue with https over proxy for 9.2.x
* https://github.com/eclipse/jetty.project/issues/408
* https://github.com/eclipse/jetty.project/issues/827
*
*/
public class HttpProxyClient {
private static final Logger LOG = LoggerFactory.getLogger(HttpProxyClient.class);
public static final String ZEPPELIN_TOKEN_HEADER = "X-Zeppelin-Token";
private CloseableHttpAsyncClient client;
private URI proxyUri;
public static HttpProxyClient newInstance(URI proxyUri) {
return new HttpProxyClient(proxyUri);
}
private HttpProxyClient(URI uri) {
this.proxyUri = uri;
client = getAsyncProxyHttpClient(proxyUri);
client.start();
}
public URI getProxyUri() {
return proxyUri;
}
private CloseableHttpAsyncClient getAsyncProxyHttpClient(URI proxyUri) {
LOG.info("Creating async proxy http client");
PoolingNHttpClientConnectionManager cm = getAsyncConnectionManager();
HttpHost proxy = new HttpHost(proxyUri.getHost(), proxyUri.getPort());
HttpAsyncClientBuilder clientBuilder = HttpAsyncClients.custom();
if (cm != null) {
clientBuilder = clientBuilder.setConnectionManager(cm);
}
if (proxy != null) {
clientBuilder = clientBuilder.setProxy(proxy);
}
clientBuilder = setRedirects(clientBuilder);
return clientBuilder.build();
}
private PoolingNHttpClientConnectionManager getAsyncConnectionManager() {
ConnectingIOReactor ioReactor = null;
PoolingNHttpClientConnectionManager cm = null;
try {
ioReactor = new DefaultConnectingIOReactor();
// ssl setup
SSLContext sslcontext = SSLContexts.createSystemDefault();
X509HostnameVerifier hostnameVerifier = new BrowserCompatHostnameVerifier();
@SuppressWarnings("deprecation")
Registry<SchemeIOSessionStrategy> sessionStrategyRegistry = RegistryBuilder
.<SchemeIOSessionStrategy>create()
.register("http", NoopIOSessionStrategy.INSTANCE)
.register("https", new SSLIOSessionStrategy(sslcontext, hostnameVerifier))
.build();
cm = new PoolingNHttpClientConnectionManager(ioReactor, sessionStrategyRegistry);
} catch (IOReactorException e) {
LOG.error("Couldn't initialize multi-threaded async client ", e);
return null;
}
return cm;
}
private HttpAsyncClientBuilder setRedirects(HttpAsyncClientBuilder clientBuilder) {
clientBuilder.setRedirectStrategy(new DefaultRedirectStrategy() {
/** Redirectable methods. */
private String[] REDIRECT_METHODS = new String[] {
HttpGet.METHOD_NAME, HttpPost.METHOD_NAME,
HttpPut.METHOD_NAME, HttpDelete.METHOD_NAME, HttpHead.METHOD_NAME
};
@Override
protected boolean isRedirectable(String method) {
for (String m : REDIRECT_METHODS) {
if (m.equalsIgnoreCase(method)) {
return true;
}
}
return false;
}
});
return clientBuilder;
}
public String sendToZeppelinHub(HttpRequestBase request,
boolean withResponse) throws IOException {
return withResponse ?
sendAndGetResponse(request) : sendWithoutResponseBody(request);
}
private String sendWithoutResponseBody(HttpRequestBase request) throws IOException {
FutureCallback<HttpResponse> callback = getCallback(request);
client.execute(request, callback);
return StringUtils.EMPTY;
}
private String sendAndGetResponse(HttpRequestBase request) throws IOException {
String data = StringUtils.EMPTY;
try {
HttpResponse response = client.execute(request, null).get(30, TimeUnit.SECONDS);
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
try (InputStream responseContent = response.getEntity().getContent()) {
data = IOUtils.toString(responseContent, "UTF-8");
}
} else {
LOG.error("ZeppelinHub {} {} returned with status {} ", request.getMethod(),
request.getURI(), code);
throw new IOException("Cannot perform " + request.getMethod() + " request to ZeppelinHub");
}
} catch (InterruptedException | ExecutionException | TimeoutException
| NullPointerException e) {
throw new IOException(e);
}
return data;
}
private FutureCallback<HttpResponse> getCallback(final HttpRequestBase request) {
return new FutureCallback<HttpResponse>() {
public void completed(final HttpResponse response) {
request.releaseConnection();
LOG.info("Note {} completed with {} status", request.getMethod(),
response.getStatusLine());
}
public void failed(final Exception ex) {
request.releaseConnection();
LOG.error("Note {} failed with {} message", request.getMethod(),
ex.getMessage());
}
public void cancelled() {
request.releaseConnection();
LOG.info("Note {} was canceled", request.getMethod());
}
};
}
public void stop() {
try {
client.close();
} catch (Exception e) {
LOG.error("Failed to close proxy client ", 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/main/java/org/apache/zeppelin/notebook/repo/zeppelinhub/websocket/Client.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/repo/zeppelinhub/websocket/Client.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.repo.zeppelinhub.websocket;
import org.apache.zeppelin.conf.ZeppelinConfiguration;
import org.apache.zeppelin.notebook.socket.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Client to connect Zeppelin and ZeppelinHub via websocket API.
* Implemented using singleton pattern.
*
*/
public class Client {
private static final Logger LOG = LoggerFactory.getLogger(Client.class);
private final ZeppelinhubClient zeppelinhubClient;
private final ZeppelinClient zeppelinClient;
private static Client instance = null;
private static final int MB = 1048576;
private static final int MAXIMUM_NOTE_SIZE = 64 * MB;
public static Client initialize(String zeppelinUri, String zeppelinhubUri, String token,
ZeppelinConfiguration conf) {
if (instance == null) {
instance = new Client(zeppelinUri, zeppelinhubUri, token, conf);
}
return instance;
}
public static Client getInstance() {
return instance;
}
private Client(String zeppelinUri, String zeppelinhubUri, String token,
ZeppelinConfiguration conf) {
LOG.debug("Init Client");
zeppelinhubClient = ZeppelinhubClient.initialize(zeppelinhubUri, token);
zeppelinClient = ZeppelinClient.initialize(zeppelinUri, token, conf);
}
public void start() {
if (zeppelinhubClient != null) {
zeppelinhubClient.start();
}
if (zeppelinClient != null) {
zeppelinClient.start();
}
}
public void stop() {
if (zeppelinhubClient != null) {
zeppelinhubClient.stop();
}
if (zeppelinClient != null) {
zeppelinClient.stop();
}
}
public void relayToZeppelinHub(String message, String token) {
zeppelinhubClient.send(message, token);
}
public void relayToZeppelin(Message message, String noteId) {
zeppelinClient.send(message, noteId);
}
public static int getMaxNoteSize() {
return MAXIMUM_NOTE_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/main/java/org/apache/zeppelin/notebook/repo/zeppelinhub/websocket/ZeppelinhubClient.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/repo/zeppelinhub/websocket/ZeppelinhubClient.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.repo.zeppelinhub.websocket;
import java.io.IOException;
import java.net.HttpCookie;
import java.net.URI;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang.StringUtils;
import org.apache.zeppelin.notebook.repo.zeppelinhub.ZeppelinHubRepo;
import org.apache.zeppelin.notebook.repo.zeppelinhub.websocket.listener.ZeppelinhubWebsocket;
import org.apache.zeppelin.notebook.repo.zeppelinhub.websocket.protocol.ZeppelinHubOp;
import org.apache.zeppelin.notebook.repo.zeppelinhub.websocket.protocol.ZeppelinhubMessage;
import org.apache.zeppelin.notebook.repo.zeppelinhub.websocket.scheduler.SchedulerService;
import org.apache.zeppelin.notebook.repo.zeppelinhub.websocket.scheduler.ZeppelinHubHeartbeat;
import org.apache.zeppelin.notebook.repo.zeppelinhub.websocket.session.ZeppelinhubSession;
import org.apache.zeppelin.notebook.repo.zeppelinhub.websocket.utils.ZeppelinhubUtils;
import org.apache.zeppelin.notebook.socket.Message;
import org.apache.zeppelin.notebook.socket.Message.OP;
import org.apache.zeppelin.ticket.TicketContainer;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
import org.eclipse.jetty.websocket.client.WebSocketClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
/**
* Manage a zeppelinhub websocket connection.
*/
public class ZeppelinhubClient {
private static final Logger LOG = LoggerFactory.getLogger(ZeppelinhubClient.class);
private final WebSocketClient client;
private final URI zeppelinhubWebsocketUrl;
private final String zeppelinhubToken;
private static final long CONNECTION_IDLE_TIME = TimeUnit.SECONDS.toMillis(30);
private static ZeppelinhubClient instance = null;
private static Gson gson;
private SchedulerService schedulerService;
private Map<String, ZeppelinhubSession> sessionMap =
new ConcurrentHashMap<String, ZeppelinhubSession>();
public static ZeppelinhubClient initialize(String zeppelinhubUrl, String token) {
if (instance == null) {
instance = new ZeppelinhubClient(zeppelinhubUrl, token);
}
return instance;
}
public static ZeppelinhubClient getInstance() {
return instance;
}
private ZeppelinhubClient(String url, String token) {
zeppelinhubWebsocketUrl = URI.create(url);
client = createNewWebsocketClient();
zeppelinhubToken = token;
schedulerService = SchedulerService.create(10);
gson = new Gson();
LOG.info("Initialized ZeppelinHub websocket client on {}", zeppelinhubWebsocketUrl);
}
public void start() {
try {
client.start();
addRoutines();
} catch (Exception e) {
LOG.error("Cannot connect to zeppelinhub via websocket", e);
}
}
public void initUser(String token) {
}
public void stop() {
LOG.info("Stopping Zeppelinhub websocket client");
try {
schedulerService.close();
client.stop();
} catch (Exception e) {
LOG.error("Cannot stop zeppelinhub websocket client", e);
}
}
public void stopUser(String token) {
removeSession(token);
}
public String getToken() {
return this.zeppelinhubToken;
}
public void send(String msg, String token) {
ZeppelinhubSession zeppelinhubSession = getSession(token);
if (!isConnectedToZeppelinhub(zeppelinhubSession)) {
LOG.info("Zeppelinhub connection is not open, opening it");
zeppelinhubSession = connect(token);
if (zeppelinhubSession == ZeppelinhubSession.EMPTY) {
LOG.warn("While connecting to ZeppelinHub received empty session, cannot send the message");
return;
}
}
zeppelinhubSession.sendByFuture(msg);
}
private boolean isConnectedToZeppelinhub(ZeppelinhubSession zeppelinhubSession) {
return (zeppelinhubSession != null && zeppelinhubSession.isSessionOpen());
}
private ZeppelinhubSession connect(String token) {
if (StringUtils.isBlank(token)) {
LOG.debug("Can't connect with empty token");
return ZeppelinhubSession.EMPTY;
}
ZeppelinhubSession zeppelinhubSession;
try {
ZeppelinhubWebsocket ws = ZeppelinhubWebsocket.newInstance(token);
ClientUpgradeRequest request = getConnectionRequest(token);
Future<Session> future = client.connect(ws, zeppelinhubWebsocketUrl, request);
Session session = future.get();
zeppelinhubSession = ZeppelinhubSession.createInstance(session, token);
setSession(token, zeppelinhubSession);
} catch (IOException | InterruptedException | ExecutionException e) {
LOG.info("Couldnt connect to zeppelinhub", e);
zeppelinhubSession = ZeppelinhubSession.EMPTY;
}
return zeppelinhubSession;
}
private void setSession(String token, ZeppelinhubSession session) {
sessionMap.put(token, session);
}
private ZeppelinhubSession getSession(String token) {
return sessionMap.get(token);
}
public void removeSession(String token) {
ZeppelinhubSession zeppelinhubSession = getSession(token);
if (zeppelinhubSession == null) {
return;
}
zeppelinhubSession.close();
sessionMap.remove(token);
}
private ClientUpgradeRequest getConnectionRequest(String token) {
ClientUpgradeRequest request = new ClientUpgradeRequest();
request.setCookies(Lists.newArrayList(new HttpCookie(ZeppelinHubRepo.TOKEN_HEADER, token)));
return request;
}
private WebSocketClient createNewWebsocketClient() {
SslContextFactory sslContextFactory = new SslContextFactory();
WebSocketClient client = new WebSocketClient(sslContextFactory);
client.setMaxTextMessageBufferSize(Client.getMaxNoteSize());
client.getPolicy().setMaxTextMessageSize(Client.getMaxNoteSize());
client.setMaxIdleTimeout(CONNECTION_IDLE_TIME);
return client;
}
private void addRoutines() {
schedulerService.add(ZeppelinHubHeartbeat.newInstance(this), 10, 23);
}
public void handleMsgFromZeppelinHub(String message) {
ZeppelinhubMessage hubMsg = ZeppelinhubMessage.deserialize(message);
if (hubMsg.equals(ZeppelinhubMessage.EMPTY)) {
LOG.error("Cannot handle ZeppelinHub message is empty");
return;
}
String op = StringUtils.EMPTY;
if (hubMsg.op instanceof String) {
op = (String) hubMsg.op;
} else {
LOG.error("Message OP from ZeppelinHub isn't string {}", hubMsg.op);
return;
}
if (ZeppelinhubUtils.isZeppelinHubOp(op)) {
handleZeppelinHubOpMsg(ZeppelinhubUtils.toZeppelinHubOp(op), hubMsg, message);
} else if (ZeppelinhubUtils.isZeppelinOp(op)) {
forwardToZeppelin(ZeppelinhubUtils.toZeppelinOp(op), hubMsg);
}
}
private void handleZeppelinHubOpMsg(ZeppelinHubOp op, ZeppelinhubMessage hubMsg, String msg) {
if (op == null || msg.equals(ZeppelinhubMessage.EMPTY)) {
LOG.error("Cannot handle empty op or msg");
return;
}
switch (op) {
case RUN_NOTEBOOK:
runAllParagraph(hubMsg.meta.get("noteId"), msg);
break;
default:
LOG.debug("Received {} from ZeppelinHub, not handled", op);
break;
}
}
@SuppressWarnings("unchecked")
private void forwardToZeppelin(Message.OP op, ZeppelinhubMessage hubMsg) {
Message zeppelinMsg = new Message(op);
if (!(hubMsg.data instanceof Map)) {
LOG.error("Data field of message from ZeppelinHub isn't in correct Map format");
return;
}
zeppelinMsg.data = (Map<String, Object>) hubMsg.data;
zeppelinMsg.principal = hubMsg.meta.get("owner");
zeppelinMsg.ticket = TicketContainer.instance.getTicket(zeppelinMsg.principal);
Client client = Client.getInstance();
if (client == null) {
LOG.warn("Base client isn't initialized, returning");
return;
}
client.relayToZeppelin(zeppelinMsg, hubMsg.meta.get("noteId"));
}
boolean runAllParagraph(String noteId, String hubMsg) {
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-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/repo/zeppelinhub/websocket/ZeppelinClient.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/repo/zeppelinhub/websocket/ZeppelinClient.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.repo.zeppelinhub.websocket;
import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import org.apache.commons.lang3.StringUtils;
import org.apache.zeppelin.conf.ZeppelinConfiguration;
import org.apache.zeppelin.notebook.NotebookAuthorization;
import org.apache.zeppelin.notebook.repo.zeppelinhub.model.UserTokenContainer;
import org.apache.zeppelin.notebook.repo.zeppelinhub.security.Authentication;
import org.apache.zeppelin.notebook.repo.zeppelinhub.websocket.listener.WatcherWebsocket;
import org.apache.zeppelin.notebook.repo.zeppelinhub.websocket.listener.ZeppelinWebsocket;
import org.apache.zeppelin.notebook.repo.zeppelinhub.websocket.protocol.ZeppelinhubMessage;
import org.apache.zeppelin.notebook.repo.zeppelinhub.websocket.scheduler.SchedulerService;
import org.apache.zeppelin.notebook.repo.zeppelinhub.websocket.scheduler.ZeppelinHeartbeat;
import org.apache.zeppelin.notebook.socket.Message;
import org.apache.zeppelin.notebook.socket.Message.OP;
import org.apache.zeppelin.util.WatcherSecurityKey;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
import org.eclipse.jetty.websocket.client.WebSocketClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
/**
* Zeppelin websocket client.
*
*/
public class ZeppelinClient {
private static final Logger LOG = LoggerFactory.getLogger(ZeppelinClient.class);
private final URI zeppelinWebsocketUrl;
private final WebSocketClient wsClient;
private static Gson gson;
// Keep track of current open connection per notebook.
private ConcurrentHashMap<String, Session> notesConnection;
// Listen to every note actions.
private static Session watcherSession;
private static ZeppelinClient instance = null;
private SchedulerService schedulerService;
private Authentication authModule;
private static final int MIN = 60;
private static final String ORIGIN = "Origin";
private static final Set<String> actionable = new HashSet<String>(Arrays.asList(
// running events
"ANGULAR_OBJECT_UPDATE",
"PROGRESS",
"NOTE",
"PARAGRAPH",
"PARAGRAPH_UPDATE_OUTPUT",
"PARAGRAPH_APPEND_OUTPUT",
"PARAGRAPH_CLEAR_OUTPUT",
"PARAGRAPH_REMOVE",
// run or stop events
"RUN_PARAGRAPH",
"CANCEL_PARAGRAPH"));
public static ZeppelinClient initialize(String zeppelinUrl, String token,
ZeppelinConfiguration conf) {
if (instance == null) {
instance = new ZeppelinClient(zeppelinUrl, token, conf);
}
return instance;
}
public static ZeppelinClient getInstance() {
return instance;
}
private ZeppelinClient(String zeppelinUrl, String token, ZeppelinConfiguration conf) {
zeppelinWebsocketUrl = URI.create(zeppelinUrl);
wsClient = createNewWebsocketClient();
gson = new Gson();
notesConnection = new ConcurrentHashMap<>();
schedulerService = SchedulerService.getInstance();
authModule = Authentication.initialize(token, conf);
if (authModule != null) {
SchedulerService.getInstance().addOnce(authModule, 10);
}
LOG.info("Initialized Zeppelin websocket client on {}", zeppelinWebsocketUrl);
}
private WebSocketClient createNewWebsocketClient() {
SslContextFactory sslContextFactory = new SslContextFactory();
WebSocketClient client = new WebSocketClient(sslContextFactory);
client.setMaxIdleTimeout(5 * MIN * 1000);
client.setMaxTextMessageBufferSize(Client.getMaxNoteSize());
client.getPolicy().setMaxTextMessageSize(Client.getMaxNoteSize());
//TODO(khalid): other client settings
return client;
}
public void start() {
try {
if (wsClient != null) {
wsClient.start();
addRoutines();
} else {
LOG.warn("Cannot start zeppelin websocket client - isn't initialized");
}
} catch (Exception e) {
LOG.error("Cannot start Zeppelin websocket client", e);
}
}
private void addRoutines() {
schedulerService.add(ZeppelinHeartbeat.newInstance(this), 10, 1 * MIN);
new Timer().schedule(new java.util.TimerTask() {
@Override
public void run() {
int time = 0;
while (time < 5 * MIN) {
watcherSession = openWatcherSession();
if (watcherSession == null) {
try {
Thread.sleep(5000);
time += 5;
} catch (InterruptedException e) {
//continue
}
} else {
break;
}
}
}
}, 5000);
}
public void stop() {
try {
if (wsClient != null) {
removeAllConnections();
wsClient.stop();
} else {
LOG.warn("Cannot stop zeppelin websocket client - isn't initialized");
}
if (watcherSession != null) {
watcherSession.close();
}
} catch (Exception e) {
LOG.error("Cannot stop Zeppelin websocket client", e);
}
}
public String serialize(Message zeppelinMsg) {
if (credentialsAvailable()) {
zeppelinMsg.principal = authModule.getPrincipal();
zeppelinMsg.ticket = authModule.getTicket();
zeppelinMsg.roles = authModule.getRoles();
}
String msg = gson.toJson(zeppelinMsg);
return msg;
}
private boolean credentialsAvailable() {
return Authentication.getInstance() != null && Authentication.getInstance().isAuthenticated();
}
public Message deserialize(String zeppelinMessage) {
if (StringUtils.isBlank(zeppelinMessage)) {
return null;
}
Message msg;
try {
msg = gson.fromJson(zeppelinMessage, Message.class);
} catch (JsonSyntaxException ex) {
LOG.error("Cannot deserialize zeppelin message", ex);
msg = null;
}
return msg;
}
private Session openWatcherSession() {
ClientUpgradeRequest request = new ClientUpgradeRequest();
request.setHeader(WatcherSecurityKey.HTTP_HEADER, WatcherSecurityKey.getKey());
request.setHeader(ORIGIN, "*");
WatcherWebsocket socket = WatcherWebsocket.createInstace();
Future<Session> future = null;
Session session = null;
try {
future = wsClient.connect(socket, zeppelinWebsocketUrl, request);
session = future.get();
} catch (IOException | InterruptedException | ExecutionException e) {
LOG.error("Couldn't establish websocket connection to Zeppelin ", e);
return session;
}
return session;
}
public void send(Message msg, String noteId) {
Session noteSession = getZeppelinConnection(noteId, msg.principal, msg.ticket);
if (!isSessionOpen(noteSession)) {
LOG.error("Cannot open websocket connection to Zeppelin note {}", noteId);
return;
}
noteSession.getRemote().sendStringByFuture(serialize(msg));
}
public Session getZeppelinConnection(String noteId, String principal, String ticket) {
if (StringUtils.isBlank(noteId)) {
LOG.warn("Cannot get Websocket session with blanck noteId");
return null;
}
return getNoteSession(noteId, principal, ticket);
}
/*
private Message zeppelinGetNoteMsg(String noteId) {
Message getNoteMsg = new Message(Message.OP.GET_NOTE);
HashMap<String, Object> data = new HashMap<>();
data.put("id", noteId);
getNoteMsg.data = data;
return getNoteMsg;
}
*/
private Session getNoteSession(String noteId, String principal, String ticket) {
LOG.info("Getting Note websocket connection for note {}", noteId);
Session session = notesConnection.get(noteId);
if (!isSessionOpen(session)) {
LOG.info("No open connection for note {}, opening one", noteId);
notesConnection.remove(noteId);
session = openNoteSession(noteId, principal, ticket);
}
return session;
}
private Session openNoteSession(String noteId, String principal, String ticket) {
ClientUpgradeRequest request = new ClientUpgradeRequest();
request.setHeader(ORIGIN, "*");
ZeppelinWebsocket socket = new ZeppelinWebsocket(noteId);
Future<Session> future = null;
Session session = null;
try {
future = wsClient.connect(socket, zeppelinWebsocketUrl, request);
session = future.get();
} catch (IOException | InterruptedException | ExecutionException e) {
LOG.error("Couldn't establish websocket connection to Zeppelin ", e);
return session;
}
if (notesConnection.containsKey(noteId)) {
session.close();
session = notesConnection.get(noteId);
} else {
String getNote = serialize(zeppelinGetNoteMsg(noteId, principal, ticket));
session.getRemote().sendStringByFuture(getNote);
notesConnection.put(noteId, session);
}
return session;
}
private boolean isSessionOpen(Session session) {
return (session != null) && (session.isOpen());
}
private Message zeppelinGetNoteMsg(String noteId, String principal, String ticket) {
Message getNoteMsg = new Message(Message.OP.GET_NOTE);
HashMap<String, Object> data = new HashMap<String, Object>();
data.put("id", noteId);
getNoteMsg.data = data;
getNoteMsg.principal = principal;
getNoteMsg.ticket = ticket;
return getNoteMsg;
}
public void handleMsgFromZeppelin(String message, String noteId) {
Map<String, String> meta = new HashMap<>();
//TODO(khalid): don't use zeppelinhubToken in this class, decouple
meta.put("noteId", noteId);
Message zeppelinMsg = deserialize(message);
if (zeppelinMsg == null) {
return;
}
String token;
if (!isActionable(zeppelinMsg.op)) {
return;
}
token = UserTokenContainer.getInstance().getUserToken(zeppelinMsg.principal);
Client client = Client.getInstance();
if (client == null) {
LOG.warn("Client isn't initialized yet");
return;
}
ZeppelinhubMessage hubMsg = ZeppelinhubMessage.newMessage(zeppelinMsg, meta);
if (StringUtils.isEmpty(token)) {
relayToAllZeppelinHub(hubMsg, noteId);
} else {
client.relayToZeppelinHub(hubMsg.serialize(), token);
}
}
private void relayToAllZeppelinHub(ZeppelinhubMessage hubMsg, String noteId) {
if (StringUtils.isBlank(noteId)) {
return;
}
NotebookAuthorization noteAuth = NotebookAuthorization.getInstance();
Map<String, String> userTokens = UserTokenContainer.getInstance().getAllUserTokens();
Client client = Client.getInstance();
Set<String> userAndRoles;
String token;
for (String user: userTokens.keySet()) {
userAndRoles = noteAuth.getRoles(user);
userAndRoles.add(user);
if (noteAuth.isReader(noteId, userAndRoles)) {
token = userTokens.get(user);
hubMsg.meta.put("token", token);
client.relayToZeppelinHub(hubMsg.serialize(), token);
}
}
}
private boolean isActionable(OP action) {
if (action == null) {
return false;
}
return actionable.contains(action.name());
}
public void removeNoteConnection(String noteId) {
if (StringUtils.isBlank(noteId)) {
LOG.error("Cannot remove session for empty noteId");
return;
}
if (notesConnection.containsKey(noteId)) {
Session connection = notesConnection.get(noteId);
if (connection.isOpen()) {
connection.close();
}
notesConnection.remove(noteId);
}
LOG.info("Removed note websocket connection for note {}", noteId);
}
private void removeAllConnections() {
if (watcherSession != null && watcherSession.isOpen()) {
watcherSession.close();
}
Session noteSession = null;
for (Map.Entry<String, Session> note: notesConnection.entrySet()) {
noteSession = note.getValue();
if (isSessionOpen(noteSession)) {
noteSession.close();
}
}
notesConnection.clear();
}
public void ping() {
if (watcherSession == null) {
LOG.debug("Cannot send PING event, no watcher found");
return;
}
watcherSession.getRemote().sendStringByFuture(serialize(new Message(OP.PING)));
}
/**
* Only used in test.
*/
public int countConnectedNotes() {
return notesConnection.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/main/java/org/apache/zeppelin/notebook/repo/zeppelinhub/websocket/utils/ZeppelinhubUtils.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/repo/zeppelinhub/websocket/utils/ZeppelinhubUtils.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.repo.zeppelinhub.websocket.utils;
import java.util.HashMap;
import org.apache.commons.lang.StringUtils;
import org.apache.zeppelin.notebook.repo.zeppelinhub.model.UserTokenContainer;
import org.apache.zeppelin.notebook.repo.zeppelinhub.websocket.ZeppelinhubClient;
import org.apache.zeppelin.notebook.repo.zeppelinhub.websocket.protocol.ZeppelinHubOp;
import org.apache.zeppelin.notebook.repo.zeppelinhub.websocket.protocol.ZeppelinhubMessage;
import org.apache.zeppelin.notebook.socket.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Helper class.
*
*/
public class ZeppelinhubUtils {
private static final Logger LOG = LoggerFactory.getLogger(ZeppelinhubUtils.class);
public static String liveMessage(String token) {
if (StringUtils.isBlank(token)) {
LOG.error("Cannot create Live message: token is null or empty");
return ZeppelinhubMessage.EMPTY.serialize();
}
HashMap<String, Object> data = new HashMap<>();
data.put("token", token);
return ZeppelinhubMessage
.newMessage(ZeppelinHubOp.LIVE, data, new HashMap<String, String>())
.serialize();
}
public static String deadMessage(String token) {
if (StringUtils.isBlank(token)) {
LOG.error("Cannot create Dead message: token is null or empty");
return ZeppelinhubMessage.EMPTY.serialize();
}
HashMap<String, Object> data = new HashMap<>();
data.put("token", token);
return ZeppelinhubMessage
.newMessage(ZeppelinHubOp.DEAD, data, new HashMap<String, String>())
.serialize();
}
public static String pingMessage(String token) {
if (StringUtils.isBlank(token)) {
LOG.error("Cannot create Ping message: token is null or empty");
return ZeppelinhubMessage.EMPTY.serialize();
}
HashMap<String, Object> data = new HashMap<>();
data.put("token", token);
return ZeppelinhubMessage
.newMessage(ZeppelinHubOp.PING, data, new HashMap<String, String>())
.serialize();
}
public static ZeppelinHubOp toZeppelinHubOp(String text) {
ZeppelinHubOp hubOp = null;
try {
hubOp = ZeppelinHubOp.valueOf(text);
} catch (IllegalArgumentException e) {
// in case of non Hub op
}
return hubOp;
}
public static boolean isZeppelinHubOp(String text) {
return (toZeppelinHubOp(text) != null);
}
public static Message.OP toZeppelinOp(String text) {
Message.OP zeppelinOp = null;
try {
zeppelinOp = Message.OP.valueOf(text);
} catch (IllegalArgumentException e) {
// in case of non Hub op
}
return zeppelinOp;
}
public static boolean isZeppelinOp(String text) {
return (toZeppelinOp(text) != null);
}
public static void userLoginRoutine(String username) {
LOG.debug("Executing user login routine");
String token = UserTokenContainer.getInstance().getUserToken(username);
UserTokenContainer.getInstance().setUserToken(username, token);
String msg = ZeppelinhubUtils.liveMessage(token);
ZeppelinhubClient.getInstance()
.send(msg, token);
}
public static void userLogoutRoutine(String username) {
LOG.debug("Executing user logout routine");
String token = UserTokenContainer.getInstance().removeUserToken(username);
String msg = ZeppelinhubUtils.deadMessage(token);
ZeppelinhubClient.getInstance()
.send(msg, token);
ZeppelinhubClient.getInstance().removeSession(token);
}
public static void userSwitchTokenRoutine(String username, String originToken,
String targetToken) {
String offMsg = ZeppelinhubUtils.deadMessage(originToken);
ZeppelinhubClient.getInstance().send(offMsg, originToken);
ZeppelinhubClient.getInstance().removeSession(originToken);
String onMsg = ZeppelinhubUtils.liveMessage(targetToken);
ZeppelinhubClient.getInstance().send(onMsg, targetToken);
}
}
| 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/repo/zeppelinhub/websocket/scheduler/ZeppelinHubHeartbeat.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/repo/zeppelinhub/websocket/scheduler/ZeppelinHubHeartbeat.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.repo.zeppelinhub.websocket.scheduler;
import org.apache.zeppelin.notebook.repo.zeppelinhub.model.UserTokenContainer;
import org.apache.zeppelin.notebook.repo.zeppelinhub.websocket.ZeppelinhubClient;
import org.apache.zeppelin.notebook.repo.zeppelinhub.websocket.utils.ZeppelinhubUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Routine that send PING event to zeppelinhub.
*
*/
public class ZeppelinHubHeartbeat implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(ZeppelinHubHeartbeat.class);
private ZeppelinhubClient client;
public static ZeppelinHubHeartbeat newInstance(ZeppelinhubClient client) {
return new ZeppelinHubHeartbeat(client);
}
private ZeppelinHubHeartbeat(ZeppelinhubClient client) {
this.client = client;
}
@Override
public void run() {
LOG.debug("Sending PING to zeppelinhub token");
for (String token: UserTokenContainer.getInstance().getAllTokens()) {
client.send(ZeppelinhubUtils.pingMessage(token), token);
}
}
}
| 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/repo/zeppelinhub/websocket/scheduler/SchedulerService.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/repo/zeppelinhub/websocket/scheduler/SchedulerService.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.repo.zeppelinhub.websocket.scheduler;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* Creates a thread pool that can schedule zeppelinhub commands.
*
*/
public class SchedulerService {
private final ScheduledExecutorService pool;
private static SchedulerService instance = null;
private SchedulerService(int numberOfThread) {
pool = Executors.newScheduledThreadPool(numberOfThread);
}
public static SchedulerService create(int numberOfThread) {
if (instance == null) {
instance = new SchedulerService(numberOfThread);
}
return instance;
}
public static SchedulerService getInstance() {
if (instance == null) {
instance = new SchedulerService(2);
}
return instance;
}
public void add(Runnable service, int firstExecution, int period) {
pool.scheduleAtFixedRate(service, firstExecution, period, TimeUnit.SECONDS);
}
public void addOnce(Runnable service, int firstExecution) {
pool.schedule(service, firstExecution, TimeUnit.SECONDS);
}
public void close() {
pool.shutdown();
}
}
| 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/repo/zeppelinhub/websocket/scheduler/ZeppelinHeartbeat.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/repo/zeppelinhub/websocket/scheduler/ZeppelinHeartbeat.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.repo.zeppelinhub.websocket.scheduler;
import org.apache.zeppelin.notebook.repo.zeppelinhub.websocket.ZeppelinClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Routine that sends PING to all connected Zeppelin ws connections.
*
*/
public class ZeppelinHeartbeat implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(ZeppelinHubHeartbeat.class);
private ZeppelinClient client;
public static ZeppelinHeartbeat newInstance(ZeppelinClient client) {
return new ZeppelinHeartbeat(client);
}
private ZeppelinHeartbeat(ZeppelinClient client) {
this.client = client;
}
@Override
public void run() {
LOG.debug("Sending PING to Zeppelin Websocket Server");
client.ping();
}
}
| 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/repo/zeppelinhub/websocket/session/ZeppelinhubSession.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/repo/zeppelinhub/websocket/session/ZeppelinhubSession.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.repo.zeppelinhub.websocket.session;
import org.apache.commons.lang.StringUtils;
import org.eclipse.jetty.websocket.api.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Zeppelinhub session.
*/
public class ZeppelinhubSession {
private static final Logger LOG = LoggerFactory.getLogger(ZeppelinhubSession.class);
private Session session;
private final String token;
public static final ZeppelinhubSession EMPTY = new ZeppelinhubSession(null, StringUtils.EMPTY);
public static ZeppelinhubSession createInstance(Session session, String token) {
return new ZeppelinhubSession(session, token);
}
private ZeppelinhubSession(Session session, String token) {
this.session = session;
this.token = token;
}
public boolean isSessionOpen() {
return ((session != null) && (session.isOpen()));
}
public void close() {
if (isSessionOpen()) {
session.close();
}
}
public void sendByFuture(String msg) {
if (StringUtils.isBlank(msg)) {
LOG.error("Cannot send event to Zeppelinhub, msg is empty");
}
if (isSessionOpen()) {
session.getRemote().sendStringByFuture(msg);
} else {
LOG.error("Cannot send event to Zeppelinhub, session is 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/notebook/repo/zeppelinhub/websocket/listener/ZeppelinhubWebsocket.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/repo/zeppelinhub/websocket/listener/ZeppelinhubWebsocket.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.repo.zeppelinhub.websocket.listener;
import org.apache.zeppelin.notebook.repo.zeppelinhub.websocket.ZeppelinhubClient;
import org.apache.zeppelin.notebook.repo.zeppelinhub.websocket.utils.ZeppelinhubUtils;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.WebSocketListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Zeppelinhub websocket handler.
*/
public class ZeppelinhubWebsocket implements WebSocketListener {
private Logger LOG = LoggerFactory.getLogger(ZeppelinhubWebsocket.class);
private Session zeppelinHubSession;
private final String token;
private ZeppelinhubWebsocket(String token) {
this.token = token;
}
public static ZeppelinhubWebsocket newInstance(String token) {
return new ZeppelinhubWebsocket(token);
}
@Override
public void onWebSocketBinary(byte[] payload, int offset, int len) {}
@Override
public void onWebSocketClose(int statusCode, String reason) {
LOG.info("Closing websocket connection [{}] : {}", statusCode, reason);
send(ZeppelinhubUtils.deadMessage(token));
this.zeppelinHubSession = null;
}
@Override
public void onWebSocketConnect(Session session) {
LOG.info("Opening a new session to Zeppelinhub {}", session.hashCode());
this.zeppelinHubSession = session;
send(ZeppelinhubUtils.liveMessage(token));
}
@Override
public void onWebSocketError(Throwable cause) {
LOG.error("Remote websocket error");
}
@Override
public void onWebSocketText(String message) {
// handle message from ZeppelinHub.
ZeppelinhubClient client = ZeppelinhubClient.getInstance();
if (client != null) {
client.handleMsgFromZeppelinHub(message);
}
}
private boolean isSessionOpen() {
return ((zeppelinHubSession != null) && (zeppelinHubSession.isOpen())) ? true : false;
}
private void send(String msg) {
if (isSessionOpen()) {
zeppelinHubSession.getRemote().sendStringByFuture(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-zengine/src/main/java/org/apache/zeppelin/notebook/repo/zeppelinhub/websocket/listener/WatcherWebsocket.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/repo/zeppelinhub/websocket/listener/WatcherWebsocket.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.repo.zeppelinhub.websocket.listener;
import org.apache.commons.lang.StringUtils;
import org.apache.zeppelin.notebook.repo.zeppelinhub.websocket.ZeppelinClient;
import org.apache.zeppelin.notebook.socket.Message;
import org.apache.zeppelin.notebook.socket.Message.OP;
import org.apache.zeppelin.notebook.socket.WatcherMessage;
import org.apache.zeppelin.ticket.TicketContainer;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.WebSocketListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
/**
* Zeppelin Watcher that will forward user note to ZeppelinHub.
*
*/
public class WatcherWebsocket implements WebSocketListener {
private static final Logger LOG = LoggerFactory.getLogger(ZeppelinWebsocket.class);
private static final Gson GSON = new Gson();
private static final String watcherPrincipal = "watcher";
public Session connection;
public static WatcherWebsocket createInstace() {
return new WatcherWebsocket();
}
@Override
public void onWebSocketBinary(byte[] payload, int offset, int len) {
}
@Override
public void onWebSocketClose(int code, String reason) {
LOG.info("WatcherWebsocket connection closed with code: {}, message: {}", code, reason);
}
@Override
public void onWebSocketConnect(Session session) {
LOG.info("WatcherWebsocket connection opened");
this.connection = session;
Message watcherMsg = new Message(OP.WATCHER);
watcherMsg.principal = watcherPrincipal;
watcherMsg.ticket = TicketContainer.instance.getTicket(watcherPrincipal);
session.getRemote().sendStringByFuture(GSON.toJson(watcherMsg));
}
@Override
public void onWebSocketError(Throwable cause) {
LOG.warn("WatcherWebsocket socket connection error ", cause);
}
@Override
public void onWebSocketText(String message) {
WatcherMessage watcherMsg = GSON.fromJson(message, WatcherMessage.class);
if (StringUtils.isBlank(watcherMsg.noteId)) {
return;
}
try {
ZeppelinClient zeppelinClient = ZeppelinClient.getInstance();
if (zeppelinClient != null) {
zeppelinClient.handleMsgFromZeppelin(watcherMsg.message, watcherMsg.noteId);
}
} catch (Exception e) {
LOG.error("Failed to send message to ZeppelinHub: ", 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/main/java/org/apache/zeppelin/notebook/repo/zeppelinhub/websocket/listener/ZeppelinWebsocket.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/repo/zeppelinhub/websocket/listener/ZeppelinWebsocket.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.repo.zeppelinhub.websocket.listener;
import org.apache.zeppelin.notebook.repo.zeppelinhub.websocket.ZeppelinClient;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.WebSocketListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Zeppelin websocket listener class.
*
*/
public class ZeppelinWebsocket implements WebSocketListener {
private static final Logger LOG = LoggerFactory.getLogger(ZeppelinWebsocket.class);
public Session connection;
public String noteId;
public ZeppelinWebsocket(String noteId) {
this.noteId = noteId;
}
@Override
public void onWebSocketBinary(byte[] arg0, int arg1, int arg2) {
}
@Override
public void onWebSocketClose(int code, String message) {
LOG.info("Zeppelin connection closed with code: {}, message: {}", code, message);
ZeppelinClient.getInstance().removeNoteConnection(noteId);
}
@Override
public void onWebSocketConnect(Session session) {
LOG.info("Zeppelin connection opened");
this.connection = session;
}
@Override
public void onWebSocketError(Throwable e) {
LOG.warn("Zeppelin socket connection error ", e);
ZeppelinClient.getInstance().removeNoteConnection(noteId);
}
@Override
public void onWebSocketText(String data) {
LOG.debug("Zeppelin client received Message: " + data);
// propagate to ZeppelinHub
try {
ZeppelinClient zeppelinClient = ZeppelinClient.getInstance();
if (zeppelinClient != null) {
zeppelinClient.handleMsgFromZeppelin(data, noteId);
}
} catch (Exception e) {
LOG.error("Failed to send message to ZeppelinHub: {}", e.toString());
}
}
}
| 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/repo/zeppelinhub/websocket/protocol/ZeppelinHubOp.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/repo/zeppelinhub/websocket/protocol/ZeppelinHubOp.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.repo.zeppelinhub.websocket.protocol;
/**
* Zeppelinhub Op.
*/
public enum ZeppelinHubOp {
LIVE,
DEAD,
PING,
PONG,
RUN_NOTEBOOK,
WELCOME,
ZEPPELIN_STATUS
}
| 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/repo/zeppelinhub/websocket/protocol/ZeppelinhubMessage.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/repo/zeppelinhub/websocket/protocol/ZeppelinhubMessage.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.repo.zeppelinhub.websocket.protocol;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.zeppelin.notebook.repo.zeppelinhub.websocket.Client;
import org.apache.zeppelin.notebook.socket.Message;
import org.apache.zeppelin.notebook.socket.Message.OP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
/**
* Zeppelinhub message class.
*
*/
public class ZeppelinhubMessage {
private static final Gson gson = new Gson();
private static final Logger LOG = LoggerFactory.getLogger(Client.class);
public static final ZeppelinhubMessage EMPTY = new ZeppelinhubMessage();
public Object op;
public Object data;
public Map<String, String> meta = Maps.newHashMap();
private ZeppelinhubMessage() {
this.op = OP.LIST_NOTES;
this.data = null;
}
private ZeppelinhubMessage(Object op, Object data, Map<String, String> meta) {
this.op = op;
this.data = data;
this.meta = meta;
}
public static ZeppelinhubMessage newMessage(Object op, Object data, Map<String, String> meta) {
return new ZeppelinhubMessage(op, data, meta);
}
public static ZeppelinhubMessage newMessage(Message zeppelinMsg, Map<String, String> meta) {
if (zeppelinMsg == null) {
return EMPTY;
}
return new ZeppelinhubMessage(zeppelinMsg.op, zeppelinMsg.data, meta);
}
public String serialize() {
return gson.toJson(this, ZeppelinhubMessage.class);
}
public static ZeppelinhubMessage deserialize(String zeppelinhubMessage) {
if (StringUtils.isBlank(zeppelinhubMessage)) {
return EMPTY;
}
ZeppelinhubMessage msg;
try {
msg = gson.fromJson(zeppelinhubMessage, ZeppelinhubMessage.class);
} catch (JsonSyntaxException ex) {
LOG.error("Cannot deserialize zeppelinhub message", ex);
msg = EMPTY;
}
return 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-zengine/src/main/java/org/apache/zeppelin/notebook/socket/WatcherMessage.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/socket/WatcherMessage.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.socket;
import com.google.gson.Gson;
/**
* Zeppelin websocket massage template class for watcher socket.
*/
public class WatcherMessage {
public String message;
public String noteId;
public String subject;
private static final Gson gson = new Gson();
public static Builder builder(String noteId) {
return new Builder(noteId);
}
private WatcherMessage(Builder builder) {
this.noteId = builder.noteId;
this.message = builder.message;
this.subject = builder.subject;
}
public String serialize() {
return gson.toJson(this);
}
/**
* Simple builder.
*/
public static class Builder {
private final String noteId;
private String subject;
private String message;
public Builder(String noteId) {
this.noteId = noteId;
}
public Builder subject(String subject) {
this.subject = subject;
return this;
}
public Builder message(String message) {
this.message = message;
return this;
}
public WatcherMessage build() {
return new WatcherMessage(this);
}
}
}
| 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/socket/Message.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/socket/Message.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.socket;
import java.util.HashMap;
import java.util.Map;
/**
* Zeppelin websocket massage template class.
*/
public class Message {
/**
* Representation of event type.
*/
public static enum OP {
GET_HOME_NOTE, // [c-s] load note for home screen
GET_NOTE, // [c-s] client load note
// @param id note id
NOTE, // [s-c] note info
// @param note serialized Note object
PARAGRAPH, // [s-c] paragraph info
// @param paragraph serialized paragraph object
PROGRESS, // [s-c] progress update
// @param id paragraph id
// @param progress percentage progress
NEW_NOTE, // [c-s] create new notebook
DEL_NOTE, // [c-s] delete notebook
// @param id note id
REMOVE_FOLDER,
MOVE_NOTE_TO_TRASH,
MOVE_FOLDER_TO_TRASH,
RESTORE_FOLDER,
RESTORE_NOTE,
RESTORE_ALL,
EMPTY_TRASH,
ADD_RULE,
RUN_ACTION,
CLONE_NOTE, // [c-s] clone new notebook
// @param id id of note to clone
// @param name name for the cloned note
IMPORT_NOTE, // [c-s] import notebook
// @param object notebook
NOTE_UPDATE,
NOTE_RENAME,
UPDATE_PERSONALIZED_MODE, // [c-s] update personalized mode (boolean)
// @param note id and boolean personalized mode value
FOLDER_RENAME,
RUN_PARAGRAPH, // [c-s] run paragraph
// @param id paragraph id
// @param paragraph paragraph content.ie. script
// @param config paragraph config
// @param params paragraph params
COMMIT_PARAGRAPH, // [c-s] commit paragraph
// @param id paragraph id
// @param title paragraph title
// @param paragraph paragraph content.ie. script
// @param config paragraph config
// @param params paragraph params
CANCEL_PARAGRAPH, // [c-s] cancel paragraph run
// @param id paragraph id
MOVE_PARAGRAPH, // [c-s] move paragraph order
// @param id paragraph id
// @param index index the paragraph want to go
INSERT_PARAGRAPH, // [c-s] create new paragraph below current paragraph
// @param target index
COPY_PARAGRAPH, // [c-s] create new para below current para as a copy of current para
// @param target index
// @param title paragraph title
// @param paragraph paragraph content.ie. script
// @param config paragraph config
// @param params paragraph params
EDITOR_SETTING, // [c-s] ask paragraph editor setting
// @param magic magic keyword written in paragraph
// ex) spark.spark or spark
COMPLETION, // [c-s] ask completion candidates
// @param id
// @param buf current code
// @param cursor cursor position in code
COMPLETION_LIST, // [s-c] send back completion candidates list
// @param id
// @param completions list of string
LIST_NOTES, // [c-s] ask list of note
RELOAD_NOTES_FROM_REPO, // [c-s] reload notes from repo
NOTES_INFO, // [s-c] list of note infos
// @param notes serialized List<NoteInfo> object
PARAGRAPH_REMOVE,
PARAGRAPH_CLEAR_OUTPUT, // [c-s] clear output of paragraph
PARAGRAPH_CLEAR_ALL_OUTPUT, // [c-s] clear output of all paragraphs
PARAGRAPH_APPEND_OUTPUT, // [s-c] append output
PARAGRAPH_UPDATE_OUTPUT, // [s-c] update (replace) output
PING,
AUTH_INFO,
ANGULAR_OBJECT_UPDATE, // [s-c] add/update angular object
ANGULAR_OBJECT_REMOVE, // [s-c] add angular object del
ANGULAR_OBJECT_UPDATED, // [c-s] angular object value updated,
ANGULAR_OBJECT_CLIENT_BIND, // [c-s] angular object updated from AngularJS z object
ANGULAR_OBJECT_CLIENT_UNBIND, // [c-s] angular object unbind from AngularJS z object
LIST_CONFIGURATIONS, // [c-s] ask all key/value pairs of configurations
CONFIGURATIONS_INFO, // [s-c] all key/value pairs of configurations
// @param settings serialized Map<String, String> object
CHECKPOINT_NOTE, // [c-s] checkpoint note to storage repository
// @param noteId
// @param checkpointName
LIST_REVISION_HISTORY, // [c-s] list revision history of the notebook
// @param noteId
NOTE_REVISION, // [c-s] get certain revision of note
// @param noteId
// @param revisionId
SET_NOTE_REVISION, // [c-s] set current notebook head to this revision
// @param noteId
// @param revisionId
APP_APPEND_OUTPUT, // [s-c] append output
APP_UPDATE_OUTPUT, // [s-c] update (replace) output
APP_LOAD, // [s-c] on app load
APP_STATUS_CHANGE, // [s-c] on app status change
LIST_NOTE_JOBS, // [c-s] get note job management information
LIST_UPDATE_NOTE_JOBS, // [c-s] get job management information for until unixtime
UNSUBSCRIBE_UPDATE_NOTE_JOBS, // [c-s] unsubscribe job information for job management
// @param unixTime
GET_INTERPRETER_BINDINGS, // [c-s] get interpreter bindings
// @param noteId
SAVE_INTERPRETER_BINDINGS, // [c-s] save interpreter bindings
// @param noteId
// @param selectedSettingIds
INTERPRETER_BINDINGS, // [s-c] interpreter bindings
GET_INTERPRETER_SETTINGS, // [c-s] get interpreter settings
INTERPRETER_SETTINGS, // [s-c] interpreter settings
ERROR_INFO, // [s-c] error information to be sent
SESSION_LOGOUT, // [s-c] error information to be sent
WATCHER, // [s-c] Change websocket to watcher mode.
PARAGRAPH_ADDED, // [s-c] paragraph is added
PARAGRAPH_REMOVED, // [s-c] paragraph deleted
PARAGRAPH_MOVED, // [s-c] paragraph moved
NOTE_UPDATED, // [s-c] paragraph updated(name, config)
RUN_ALL_PARAGRAPHS // [c-s] run all paragraphs
}
public static final Message EMPTY = new Message(null);
public OP op;
public Map<String, Object> data = new HashMap<>();
public String ticket = "anonymous";
public String principal = "anonymous";
public String roles = "";
public Message(OP op) {
this.op = op;
}
public Message put(String k, Object v) {
data.put(k, v);
return this;
}
public Object get(String k) {
return data.get(k);
}
public <T> T getType(String key) {
return (T) data.get(key);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Message{");
sb.append("data=").append(data);
sb.append(", op=").append(op);
sb.append('}');
return sb.toString();
}
}
| 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/utility/IdHashes.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/notebook/utility/IdHashes.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.utility;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* Generate Tiny ID.
*/
public class IdHashes {
private static final char[] DICTIONARY = new char[] {'1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
'W', 'X', 'Y', 'Z'};
/**
* encodes the given string into the base of the dictionary provided in the constructor.
*
* @param value the number to encode.
* @return the encoded string.
*/
private static String encode(Long value) {
List<Character> result = new ArrayList<>();
BigInteger base = new BigInteger("" + DICTIONARY.length);
int exponent = 1;
BigInteger remaining = new BigInteger(value.toString());
while (true) {
BigInteger a = base.pow(exponent); // 16^1 = 16
BigInteger b = remaining.mod(a); // 119 % 16 = 7 | 112 % 256 = 112
BigInteger c = base.pow(exponent - 1);
BigInteger d = b.divide(c);
// if d > dictionary.length, we have a problem. but BigInteger doesnt have
// a greater than method :-( hope for the best. theoretically, d is always
// an index of the dictionary!
result.add(DICTIONARY[d.intValue()]);
remaining = remaining.subtract(b); // 119 - 7 = 112 | 112 - 112 = 0
// finished?
if (remaining.equals(BigInteger.ZERO)) {
break;
}
exponent++;
}
// need to reverse it, since the start of the list contains the least significant values
StringBuffer sb = new StringBuffer();
for (int i = result.size() - 1; i >= 0; i--) {
sb.append(result.get(i));
}
return sb.toString();
}
public static String generateId() {
return encode(System.currentTimeMillis() + new Random().nextInt());
}
}
| 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/interpreter/InterpreterFactory.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/interpreter/InterpreterFactory.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;
import com.google.common.base.Joiner;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Type;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.nio.file.attribute.PosixFilePermission;
import java.util.Enumeration;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.internal.StringMap;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.NullArgumentException;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonatype.aether.RepositoryException;
import org.sonatype.aether.repository.Authentication;
import org.sonatype.aether.repository.Proxy;
import org.sonatype.aether.repository.RemoteRepository;
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.display.AngularObjectRegistry;
import org.apache.zeppelin.display.AngularObjectRegistryListener;
import org.apache.zeppelin.helium.ApplicationEventListener;
import org.apache.zeppelin.interpreter.Interpreter.RegisteredInterpreter;
import org.apache.zeppelin.interpreter.remote.RemoteAngularObjectRegistry;
import org.apache.zeppelin.interpreter.remote.RemoteInterpreter;
import org.apache.zeppelin.interpreter.remote.RemoteInterpreterProcessListener;
import org.apache.zeppelin.scheduler.Job;
import org.apache.zeppelin.scheduler.Job.Status;
/**
* Manage interpreters.
*/
public class InterpreterFactory implements InterpreterGroupFactory {
private static final Logger logger = LoggerFactory.getLogger(InterpreterFactory.class);
private Map<String, URLClassLoader> cleanCl =
Collections.synchronizedMap(new HashMap<String, URLClassLoader>());
private ZeppelinConfiguration conf;
private final InterpreterSettingManager interpreterSettingManager;
private Gson gson;
private AngularObjectRegistryListener angularObjectRegistryListener;
private final RemoteInterpreterProcessListener remoteInterpreterProcessListener;
private final ApplicationEventListener appEventListener;
private boolean shiroEnabled;
private Map<String, String> env = new HashMap<>();
private Interpreter devInterpreter;
public InterpreterFactory(ZeppelinConfiguration conf,
AngularObjectRegistryListener angularObjectRegistryListener,
RemoteInterpreterProcessListener remoteInterpreterProcessListener,
ApplicationEventListener appEventListener, DependencyResolver depResolver,
boolean shiroEnabled, InterpreterSettingManager interpreterSettingManager)
throws InterpreterException, IOException, RepositoryException {
this.conf = conf;
this.angularObjectRegistryListener = angularObjectRegistryListener;
this.remoteInterpreterProcessListener = remoteInterpreterProcessListener;
this.appEventListener = appEventListener;
this.shiroEnabled = shiroEnabled;
GsonBuilder builder = new GsonBuilder();
builder.setPrettyPrinting();
gson = builder.create();
this.interpreterSettingManager = interpreterSettingManager;
//TODO(jl): Fix it not to use InterpreterGroupFactory
interpreterSettingManager.setInterpreterGroupFactory(this);
logger.info("shiroEnabled: {}", shiroEnabled);
}
/**
* @param id interpreterGroup id. Combination of interpreterSettingId + noteId/userId/shared
* depends on interpreter mode
*/
@Override
public InterpreterGroup createInterpreterGroup(String id, InterpreterOption option)
throws InterpreterException, NullArgumentException {
//When called from REST API without option we receive NPE
if (option == null) {
throw new NullArgumentException("option");
}
AngularObjectRegistry angularObjectRegistry;
InterpreterGroup interpreterGroup = new InterpreterGroup(id);
if (option.isRemote()) {
angularObjectRegistry =
new RemoteAngularObjectRegistry(id, angularObjectRegistryListener, interpreterGroup);
} else {
angularObjectRegistry = new AngularObjectRegistry(id, angularObjectRegistryListener);
// TODO(moon) : create distributed resource pool for local interpreters and set
}
interpreterGroup.setAngularObjectRegistry(angularObjectRegistry);
return interpreterGroup;
}
public void createInterpretersForNote(InterpreterSetting interpreterSetting, String user,
String noteId, String interpreterSessionKey) {
InterpreterGroup interpreterGroup = interpreterSetting.getInterpreterGroup(user, noteId);
InterpreterOption option = interpreterSetting.getOption();
Properties properties = (Properties) interpreterSetting.getProperties();
// if interpreters are already there, wait until they're being removed
synchronized (interpreterGroup) {
long interpreterRemovalWaitStart = System.nanoTime();
// interpreter process supposed to be terminated by RemoteInterpreterProcess.dereference()
// in ZEPPELIN_INTERPRETER_CONNECT_TIMEOUT msec. However, if termination of the process and
// removal from interpreter group take too long, throw an error.
long minTimeout = 10L * 1000 * 1000000; // 10 sec
long interpreterRemovalWaitTimeout = Math.max(minTimeout,
conf.getInt(ConfVars.ZEPPELIN_INTERPRETER_CONNECT_TIMEOUT) * 1000000L * 2);
while (interpreterGroup.containsKey(interpreterSessionKey)) {
if (System.nanoTime() - interpreterRemovalWaitStart > interpreterRemovalWaitTimeout) {
throw new InterpreterException("Can not create interpreter");
}
try {
interpreterGroup.wait(1000);
} catch (InterruptedException e) {
logger.debug(e.getMessage(), e);
}
}
}
logger.info("Create interpreter instance {} for note {}", interpreterSetting.getName(), noteId);
List<InterpreterInfo> interpreterInfos = interpreterSetting.getInterpreterInfos();
String path = interpreterSetting.getPath();
InterpreterRunner runner = interpreterSetting.getInterpreterRunner();
Interpreter interpreter;
for (InterpreterInfo info : interpreterInfos) {
if (option.isRemote()) {
if (option.isExistingProcess()) {
interpreter =
connectToRemoteRepl(interpreterSessionKey, info.getClassName(), option.getHost(),
option.getPort(), properties, interpreterSetting.getId(), user,
option.isUserImpersonate);
} else {
interpreter = createRemoteRepl(path, interpreterSessionKey, info.getClassName(),
properties, interpreterSetting.getId(), user, option.isUserImpersonate(), runner);
}
} else {
interpreter = createRepl(interpreterSetting.getPath(), info.getClassName(), properties);
}
synchronized (interpreterGroup) {
List<Interpreter> interpreters = interpreterGroup.get(interpreterSessionKey);
if (null == interpreters) {
interpreters = new ArrayList<>();
interpreterGroup.put(interpreterSessionKey, interpreters);
}
if (info.isDefaultInterpreter()) {
interpreters.add(0, interpreter);
} else {
interpreters.add(interpreter);
}
}
logger.info("Interpreter {} {} created", interpreter.getClassName(), interpreter.hashCode());
interpreter.setInterpreterGroup(interpreterGroup);
}
}
private Interpreter createRepl(String dirName, String className, Properties property)
throws InterpreterException {
logger.info("Create repl {} from {}", className, dirName);
ClassLoader oldcl = Thread.currentThread().getContextClassLoader();
try {
URLClassLoader ccl = cleanCl.get(dirName);
if (ccl == null) {
// classloader fallback
ccl = URLClassLoader.newInstance(new URL[]{}, oldcl);
}
boolean separateCL = true;
try { // check if server's classloader has driver already.
Class cls = this.getClass().forName(className);
if (cls != null) {
separateCL = false;
}
} catch (Exception e) {
logger.error("exception checking server classloader driver", e);
}
URLClassLoader cl;
if (separateCL == true) {
cl = URLClassLoader.newInstance(new URL[]{}, ccl);
} else {
cl = ccl;
}
Thread.currentThread().setContextClassLoader(cl);
Class<Interpreter> replClass = (Class<Interpreter>) cl.loadClass(className);
Constructor<Interpreter> constructor =
replClass.getConstructor(new Class[]{Properties.class});
Interpreter repl = constructor.newInstance(property);
repl.setClassloaderUrls(ccl.getURLs());
LazyOpenInterpreter intp = new LazyOpenInterpreter(new ClassloaderInterpreter(repl, cl));
return intp;
} catch (SecurityException e) {
throw new InterpreterException(e);
} catch (NoSuchMethodException e) {
throw new InterpreterException(e);
} catch (IllegalArgumentException e) {
throw new InterpreterException(e);
} catch (InstantiationException e) {
throw new InterpreterException(e);
} catch (IllegalAccessException e) {
throw new InterpreterException(e);
} catch (InvocationTargetException e) {
throw new InterpreterException(e);
} catch (ClassNotFoundException e) {
throw new InterpreterException(e);
} finally {
Thread.currentThread().setContextClassLoader(oldcl);
}
}
private Interpreter connectToRemoteRepl(String interpreterSessionKey, String className,
String host, int port, Properties property, String interpreterSettingId, String userName,
Boolean isUserImpersonate) {
int connectTimeout = conf.getInt(ConfVars.ZEPPELIN_INTERPRETER_CONNECT_TIMEOUT);
int maxPoolSize = conf.getInt(ConfVars.ZEPPELIN_INTERPRETER_MAX_POOL_SIZE);
String localRepoPath = conf.getInterpreterLocalRepoPath() + "/" + interpreterSettingId;
LazyOpenInterpreter intp = new LazyOpenInterpreter(
new RemoteInterpreter(property, interpreterSessionKey, className, host, port, localRepoPath,
connectTimeout, maxPoolSize, remoteInterpreterProcessListener, appEventListener,
userName, isUserImpersonate, conf.getInt(ConfVars.ZEPPELIN_INTERPRETER_OUTPUT_LIMIT)));
return intp;
}
Interpreter createRemoteRepl(String interpreterPath, String interpreterSessionKey,
String className, Properties property, String interpreterSettingId,
String userName, Boolean isUserImpersonate, InterpreterRunner interpreterRunner) {
int connectTimeout = conf.getInt(ConfVars.ZEPPELIN_INTERPRETER_CONNECT_TIMEOUT);
String localRepoPath = conf.getInterpreterLocalRepoPath() + "/" + interpreterSettingId;
int maxPoolSize = conf.getInt(ConfVars.ZEPPELIN_INTERPRETER_MAX_POOL_SIZE);
String interpreterRunnerPath;
if (null != interpreterRunner) {
interpreterRunnerPath = interpreterRunner.getPath();
Path p = Paths.get(interpreterRunnerPath);
if (!p.isAbsolute()) {
interpreterRunnerPath = Joiner.on(File.separator)
.join(interpreterPath, interpreterRunnerPath);
}
} else {
interpreterRunnerPath = conf.getInterpreterRemoteRunnerPath();
}
RemoteInterpreter remoteInterpreter =
new RemoteInterpreter(property, interpreterSessionKey, className,
interpreterRunnerPath, interpreterPath, localRepoPath, connectTimeout, maxPoolSize,
remoteInterpreterProcessListener, appEventListener, userName, isUserImpersonate,
conf.getInt(ConfVars.ZEPPELIN_INTERPRETER_OUTPUT_LIMIT));
remoteInterpreter.addEnv(env);
return new LazyOpenInterpreter(remoteInterpreter);
}
private List<Interpreter> createOrGetInterpreterList(String user, String noteId,
InterpreterSetting setting) {
InterpreterGroup interpreterGroup = setting.getInterpreterGroup(user, noteId);
synchronized (interpreterGroup) {
String interpreterSessionKey =
interpreterSettingManager.getInterpreterSessionKey(user, noteId, setting);
if (!interpreterGroup.containsKey(interpreterSessionKey)) {
createInterpretersForNote(setting, user, noteId, interpreterSessionKey);
}
return interpreterGroup.get(interpreterSessionKey);
}
}
private InterpreterSetting getInterpreterSettingByGroup(List<InterpreterSetting> settings,
String group) {
Preconditions.checkNotNull(group, "group should be not null");
for (InterpreterSetting setting : settings) {
if (group.equals(setting.getName())) {
return setting;
}
}
return null;
}
private String getInterpreterClassFromInterpreterSetting(InterpreterSetting setting,
String name) {
Preconditions.checkNotNull(name, "name should be not null");
for (InterpreterInfo info : setting.getInterpreterInfos()) {
String infoName = info.getName();
if (null != info.getName() && name.equals(infoName)) {
return info.getClassName();
}
}
return null;
}
private Interpreter getInterpreter(String user, String noteId, InterpreterSetting setting,
String name) {
Preconditions.checkNotNull(noteId, "noteId should be not null");
Preconditions.checkNotNull(setting, "setting should be not null");
Preconditions.checkNotNull(name, "name should be not null");
String className;
if (null != (className = getInterpreterClassFromInterpreterSetting(setting, name))) {
List<Interpreter> interpreterGroup = createOrGetInterpreterList(user, noteId, setting);
for (Interpreter interpreter : interpreterGroup) {
if (className.equals(interpreter.getClassName())) {
return interpreter;
}
}
}
return null;
}
public Interpreter getInterpreter(String user, String noteId, String replName) {
List<InterpreterSetting> settings = interpreterSettingManager.getInterpreterSettings(noteId);
InterpreterSetting setting;
Interpreter interpreter;
if (settings == null || settings.size() == 0) {
return null;
}
if (replName == null || replName.trim().length() == 0) {
// get default settings (first available)
// TODO(jl): Fix it in case of returning null
InterpreterSetting defaultSettings = interpreterSettingManager
.getDefaultInterpreterSetting(settings);
return createOrGetInterpreterList(user, noteId, defaultSettings).get(0);
}
String[] replNameSplit = replName.split("\\.");
if (replNameSplit.length == 2) {
String group = null;
String name = null;
group = replNameSplit[0];
name = replNameSplit[1];
setting = getInterpreterSettingByGroup(settings, group);
if (null != setting) {
interpreter = getInterpreter(user, noteId, setting, name);
if (null != interpreter) {
return interpreter;
}
}
throw new InterpreterException(replName + " interpreter not found");
} else {
// first assume replName is 'name' of interpreter. ('groupName' is ommitted)
// search 'name' from first (default) interpreter group
// TODO(jl): Handle with noteId to support defaultInterpreter per note.
setting = interpreterSettingManager.getDefaultInterpreterSetting(settings);
interpreter = getInterpreter(user, noteId, setting, replName);
if (null != interpreter) {
return interpreter;
}
// next, assume replName is 'group' of interpreter ('name' is ommitted)
// search interpreter group and return first interpreter.
setting = getInterpreterSettingByGroup(settings, replName);
if (null != setting) {
List<Interpreter> interpreters = createOrGetInterpreterList(user, noteId, setting);
if (null != interpreters) {
return interpreters.get(0);
}
}
// Support the legacy way to use it
for (InterpreterSetting s : settings) {
if (s.getGroup().equals(replName)) {
List<Interpreter> interpreters = createOrGetInterpreterList(user, noteId, s);
if (null != interpreters) {
return interpreters.get(0);
}
}
}
}
return null;
}
public Map<String, String> getEnv() {
return env;
}
public void setEnv(Map<String, String> env) {
this.env = env;
}
}
| 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/interpreter/InterpreterSettingManager.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/interpreter/InterpreterSettingManager.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;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.internal.StringMap;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
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.RegisteredInterpreter;
import org.apache.zeppelin.scheduler.Job;
import org.apache.zeppelin.scheduler.Job.Status;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonatype.aether.RepositoryException;
import org.sonatype.aether.repository.Authentication;
import org.sonatype.aether.repository.Proxy;
import org.sonatype.aether.repository.RemoteRepository;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.lang.reflect.Type;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.StandardCharsets;
import java.nio.file.DirectoryStream.Filter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermission;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import static java.nio.file.attribute.PosixFilePermission.OWNER_READ;
import static java.nio.file.attribute.PosixFilePermission.OWNER_WRITE;
/**
* TBD
*/
public class InterpreterSettingManager {
private static final Logger logger = LoggerFactory.getLogger(InterpreterSettingManager.class);
private static final String SHARED_SESSION = "shared_session";
private static final Map<String, Object> DEFAULT_EDITOR = ImmutableMap.of(
"language", (Object) "text",
"editOnDblClick", false);
private final ZeppelinConfiguration zeppelinConfiguration;
private final Path interpreterDirPath;
private final Path interpreterBindingPath;
/**
* This is only references with default settings, name and properties
* key: InterpreterSetting.name
*/
private final Map<String, InterpreterSetting> interpreterSettingsRef;
/**
* This is used by creating and running Interpreters
* key: InterpreterSetting.id <- This is becuase backward compatibility
*/
private final Map<String, InterpreterSetting> interpreterSettings;
private final Map<String, List<String>> interpreterBindings;
private final DependencyResolver dependencyResolver;
private final List<RemoteRepository> interpreterRepositories;
private final InterpreterOption defaultOption;
private final Map<String, URLClassLoader> cleanCl;
@Deprecated
private String[] interpreterClassList;
private String[] interpreterGroupOrderList;
private InterpreterGroupFactory interpreterGroupFactory;
private final Gson gson;
public InterpreterSettingManager(ZeppelinConfiguration zeppelinConfiguration,
DependencyResolver dependencyResolver, InterpreterOption interpreterOption)
throws IOException, RepositoryException {
this.zeppelinConfiguration = zeppelinConfiguration;
this.interpreterDirPath = Paths.get(zeppelinConfiguration.getInterpreterDir());
logger.debug("InterpreterRootPath: {}", interpreterDirPath);
this.interpreterBindingPath = Paths.get(zeppelinConfiguration.getInterpreterSettingPath());
logger.debug("InterpreterBindingPath: {}", interpreterBindingPath);
this.interpreterSettingsRef = Maps.newConcurrentMap();
this.interpreterSettings = Maps.newConcurrentMap();
this.interpreterBindings = Maps.newConcurrentMap();
this.dependencyResolver = dependencyResolver;
this.interpreterRepositories = dependencyResolver.getRepos();
this.defaultOption = interpreterOption;
this.cleanCl = Collections.synchronizedMap(new HashMap<String, URLClassLoader>());
String replsConf = zeppelinConfiguration.getString(ConfVars.ZEPPELIN_INTERPRETERS);
this.interpreterClassList = replsConf.split(",");
String groupOrder = zeppelinConfiguration.getString(ConfVars.ZEPPELIN_INTERPRETER_GROUP_ORDER);
this.interpreterGroupOrderList = groupOrder.split(",");
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setPrettyPrinting();
this.gson = gsonBuilder.create();
init();
}
/**
* Remember this method doesn't keep current connections after being called
*/
private void loadFromFile() {
if (!Files.exists(interpreterBindingPath)) {
// nothing to read
return;
}
InterpreterInfoSaving infoSaving;
try (BufferedReader json =
Files.newBufferedReader(interpreterBindingPath, StandardCharsets.UTF_8)) {
infoSaving = gson.fromJson(json, InterpreterInfoSaving.class);
for (String k : infoSaving.interpreterSettings.keySet()) {
InterpreterSetting setting = infoSaving.interpreterSettings.get(k);
List<InterpreterInfo> infos = setting.getInterpreterInfos();
// Convert json StringMap to Properties
StringMap<String> p = (StringMap<String>) setting.getProperties();
Properties properties = new Properties();
for (String key : p.keySet()) {
properties.put(key, p.get(key));
}
setting.setProperties(properties);
// Always use separate interpreter process
// While we decided to turn this feature on always (without providing
// enable/disable option on GUI).
// previously created setting should turn this feature on here.
setting.getOption().setRemote(true);
// Update transient information from InterpreterSettingRef
InterpreterSetting interpreterSettingObject =
interpreterSettingsRef.get(setting.getGroup());
if (interpreterSettingObject == null) {
logger.warn("can't get InterpreterSetting " +
"Information From loaded Interpreter Setting Ref - {} ", setting.getGroup());
continue;
}
String depClassPath = interpreterSettingObject.getPath();
setting.setPath(depClassPath);
for (InterpreterInfo info : infos) {
if (info.getEditor() == null) {
Map<String, Object> editor = getEditorFromSettingByClassName(interpreterSettingObject,
info.getClassName());
info.setEditor(editor);
}
}
setting.setInterpreterGroupFactory(interpreterGroupFactory);
loadInterpreterDependencies(setting);
interpreterSettings.put(k, setting);
}
interpreterBindings.putAll(infoSaving.interpreterBindings);
if (infoSaving.interpreterRepositories != null) {
for (RemoteRepository repo : infoSaving.interpreterRepositories) {
if (!dependencyResolver.getRepos().contains(repo)) {
this.interpreterRepositories.add(repo);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void saveToFile() throws IOException {
String jsonString;
synchronized (interpreterSettings) {
InterpreterInfoSaving info = new InterpreterInfoSaving();
info.interpreterBindings = interpreterBindings;
info.interpreterSettings = interpreterSettings;
info.interpreterRepositories = interpreterRepositories;
jsonString = gson.toJson(info);
}
if (!Files.exists(interpreterBindingPath)) {
Files.createFile(interpreterBindingPath);
try {
Set<PosixFilePermission> permissions = EnumSet.of(OWNER_READ, OWNER_WRITE);
Files.setPosixFilePermissions(interpreterBindingPath, permissions);
} catch (UnsupportedOperationException e) {
// File system does not support Posix file permissions (likely windows) - continue anyway.
logger.warn("unable to setPosixFilePermissions on '{}'.", interpreterBindingPath);
};
}
FileOutputStream fos = new FileOutputStream(interpreterBindingPath.toFile(), false);
OutputStreamWriter out = new OutputStreamWriter(fos);
out.append(jsonString);
out.close();
fos.close();
}
//TODO(jl): Fix it to remove InterpreterGroupFactory
public void setInterpreterGroupFactory(InterpreterGroupFactory interpreterGroupFactory) {
for (InterpreterSetting setting : interpreterSettings.values()) {
setting.setInterpreterGroupFactory(interpreterGroupFactory);
}
this.interpreterGroupFactory = interpreterGroupFactory;
}
private void init() throws InterpreterException, IOException, RepositoryException {
String interpreterJson = zeppelinConfiguration.getInterpreterJson();
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (Files.exists(interpreterDirPath)) {
for (Path interpreterDir : Files
.newDirectoryStream(interpreterDirPath, new Filter<Path>() {
@Override
public boolean accept(Path entry) throws IOException {
return Files.exists(entry) && Files.isDirectory(entry);
}
})) {
String interpreterDirString = interpreterDir.toString();
/**
* Register interpreter by the following ordering
* 1. Register it from path {ZEPPELIN_HOME}/interpreter/{interpreter_name}/
* interpreter-setting.json
* 2. Register it from interpreter-setting.json in classpath
* {ZEPPELIN_HOME}/interpreter/{interpreter_name}
* 3. Register it by Interpreter.register
*/
if (!registerInterpreterFromPath(interpreterDirString, interpreterJson)) {
if (!registerInterpreterFromResource(cl, interpreterDirString, interpreterJson)) {
/*
* TODO(jongyoul)
* - Remove these codes below because of legacy code
* - Support ThreadInterpreter
*/
URLClassLoader ccl = new URLClassLoader(
recursiveBuildLibList(interpreterDir.toFile()), cl);
for (String className : interpreterClassList) {
try {
// Load classes
Class.forName(className, true, ccl);
Set<String> interpreterKeys = Interpreter.registeredInterpreters.keySet();
for (String interpreterKey : interpreterKeys) {
if (className
.equals(Interpreter.registeredInterpreters.get(interpreterKey)
.getClassName())) {
Interpreter.registeredInterpreters.get(interpreterKey)
.setPath(interpreterDirString);
logger.info("Interpreter " + interpreterKey + " found. class=" + className);
cleanCl.put(interpreterDirString, ccl);
}
}
} catch (Throwable t) {
// nothing to do
}
}
}
}
}
}
for (RegisteredInterpreter registeredInterpreter : Interpreter.registeredInterpreters
.values()) {
logger
.debug("Registered: {} -> {}. Properties: {}", registeredInterpreter.getInterpreterKey(),
registeredInterpreter.getClassName(), registeredInterpreter.getProperties());
}
// RegisteredInterpreters -> interpreterSettingRef
InterpreterInfo interpreterInfo;
for (RegisteredInterpreter r : Interpreter.registeredInterpreters.values()) {
interpreterInfo =
new InterpreterInfo(r.getClassName(), r.getName(), r.isDefaultInterpreter(),
r.getEditor());
add(r.getGroup(), interpreterInfo, r.getProperties(), defaultOption, r.getPath(),
r.getRunner());
}
for (String settingId : interpreterSettingsRef.keySet()) {
InterpreterSetting setting = interpreterSettingsRef.get(settingId);
logger.info("InterpreterSettingRef name {}", setting.getName());
}
loadFromFile();
// if no interpreter settings are loaded, create default set
if (0 == interpreterSettings.size()) {
Map<String, InterpreterSetting> temp = new HashMap<>();
InterpreterSetting interpreterSetting;
for (InterpreterSetting setting : interpreterSettingsRef.values()) {
interpreterSetting = createFromInterpreterSettingRef(setting);
temp.put(setting.getName(), interpreterSetting);
}
for (String group : interpreterGroupOrderList) {
if (null != (interpreterSetting = temp.remove(group))) {
interpreterSettings.put(interpreterSetting.getId(), interpreterSetting);
}
}
for (InterpreterSetting setting : temp.values()) {
interpreterSettings.put(setting.getId(), setting);
}
saveToFile();
}
for (String settingId : interpreterSettings.keySet()) {
InterpreterSetting setting = interpreterSettings.get(settingId);
logger.info("InterpreterSetting group {} : id={}, name={}", setting.getGroup(), settingId,
setting.getName());
}
}
private boolean registerInterpreterFromResource(ClassLoader cl, String interpreterDir,
String interpreterJson) throws IOException, RepositoryException {
URL[] urls = recursiveBuildLibList(new File(interpreterDir));
ClassLoader tempClassLoader = new URLClassLoader(urls, cl);
Enumeration<URL> interpreterSettings = tempClassLoader.getResources(interpreterJson);
if (!interpreterSettings.hasMoreElements()) {
return false;
}
for (URL url : Collections.list(interpreterSettings)) {
try (InputStream inputStream = url.openStream()) {
logger.debug("Reading {} from {}", interpreterJson, url);
List<RegisteredInterpreter> registeredInterpreterList =
getInterpreterListFromJson(inputStream);
registerInterpreters(registeredInterpreterList, interpreterDir);
}
}
return true;
}
private boolean registerInterpreterFromPath(String interpreterDir, String interpreterJson)
throws IOException, RepositoryException {
Path interpreterJsonPath = Paths.get(interpreterDir, interpreterJson);
if (Files.exists(interpreterJsonPath)) {
logger.debug("Reading {}", interpreterJsonPath);
List<RegisteredInterpreter> registeredInterpreterList =
getInterpreterListFromJson(interpreterJsonPath);
registerInterpreters(registeredInterpreterList, interpreterDir);
return true;
}
return false;
}
private List<RegisteredInterpreter> getInterpreterListFromJson(Path filename)
throws FileNotFoundException {
return getInterpreterListFromJson(new FileInputStream(filename.toFile()));
}
private List<RegisteredInterpreter> getInterpreterListFromJson(InputStream stream) {
Type registeredInterpreterListType = new TypeToken<List<RegisteredInterpreter>>() {
}.getType();
return gson.fromJson(new InputStreamReader(stream), registeredInterpreterListType);
}
private void registerInterpreters(List<RegisteredInterpreter> registeredInterpreters,
String absolutePath) throws IOException, RepositoryException {
for (RegisteredInterpreter registeredInterpreter : registeredInterpreters) {
InterpreterInfo interpreterInfo =
new InterpreterInfo(registeredInterpreter.getClassName(), registeredInterpreter.getName(),
registeredInterpreter.isDefaultInterpreter(), registeredInterpreter.getEditor());
// use defaultOption if it is not specified in interpreter-setting.json
InterpreterOption option = registeredInterpreter.getOption() == null ? defaultOption :
registeredInterpreter.getOption();
add(registeredInterpreter.getGroup(), interpreterInfo, registeredInterpreter.getProperties(),
option, absolutePath, registeredInterpreter.getRunner());
}
}
public InterpreterSetting getDefaultInterpreterSetting(List<InterpreterSetting> settings) {
if (settings == null || settings.isEmpty()) {
return null;
}
return settings.get(0);
}
public InterpreterSetting getDefaultInterpreterSetting(String noteId) {
return getDefaultInterpreterSetting(getInterpreterSettings(noteId));
}
public List<InterpreterSetting> getInterpreterSettings(String noteId) {
List<String> interpreterSettingIds = getNoteInterpreterSettingBinding(noteId);
LinkedList<InterpreterSetting> settings = new LinkedList<>();
Iterator<String> iter = interpreterSettingIds.iterator();
while (iter.hasNext()) {
String id = iter.next();
InterpreterSetting setting = get(id);
if (setting == null) {
// interpreter setting is removed from factory. remove id from here, too
iter.remove();
} else {
settings.add(setting);
}
}
return settings;
}
private List<String> getNoteInterpreterSettingBinding(String noteId) {
LinkedList<String> bindings = new LinkedList<>();
List<String> settingIds = interpreterBindings.get(noteId);
if (settingIds != null) {
bindings.addAll(settingIds);
}
return bindings;
}
private InterpreterSetting createFromInterpreterSettingRef(String name) {
Preconditions.checkNotNull(name, "reference name should be not null");
InterpreterSetting settingRef = interpreterSettingsRef.get(name);
return createFromInterpreterSettingRef(settingRef);
}
private InterpreterSetting createFromInterpreterSettingRef(InterpreterSetting o) {
// should return immutable objects
List<InterpreterInfo> infos = (null == o.getInterpreterInfos()) ?
new ArrayList<InterpreterInfo>() : new ArrayList<>(o.getInterpreterInfos());
List<Dependency> deps = (null == o.getDependencies()) ?
new ArrayList<Dependency>() : new ArrayList<>(o.getDependencies());
Properties props =
convertInterpreterProperties((Map<String, InterpreterProperty>) o.getProperties());
InterpreterOption option = InterpreterOption.fromInterpreterOption(o.getOption());
InterpreterSetting setting = new InterpreterSetting(o.getName(), o.getName(),
infos, props, deps, option, o.getPath(), o.getInterpreterRunner());
setting.setInterpreterGroupFactory(interpreterGroupFactory);
return setting;
}
private Properties convertInterpreterProperties(Map<String, InterpreterProperty> p) {
Properties properties = new Properties();
for (String key : p.keySet()) {
properties.put(key, p.get(key).getValue());
}
return properties;
}
public Map<String, Object> getEditorSetting(Interpreter interpreter, String user, String noteId,
String replName) {
Map<String, Object> editor = DEFAULT_EDITOR;
String group = StringUtils.EMPTY;
try {
String defaultSettingName = getDefaultInterpreterSetting(noteId).getName();
List<InterpreterSetting> intpSettings = getInterpreterSettings(noteId);
for (InterpreterSetting intpSetting : intpSettings) {
String[] replNameSplit = replName.split("\\.");
if (replNameSplit.length == 2) {
group = replNameSplit[0];
}
// when replName is 'name' of interpreter
if (defaultSettingName.equals(intpSetting.getName())) {
editor = getEditorFromSettingByClassName(intpSetting, interpreter.getClassName());
}
// when replName is 'alias name' of interpreter or 'group' of interpreter
if (replName.equals(intpSetting.getName()) || group.equals(intpSetting.getName())) {
editor = getEditorFromSettingByClassName(intpSetting, interpreter.getClassName());
break;
}
}
} catch (NullPointerException e) {
logger.debug("Couldn't get interpreter editor setting");
}
return editor;
}
public Map<String, Object> getEditorFromSettingByClassName(InterpreterSetting intpSetting,
String className) {
List<InterpreterInfo> intpInfos = intpSetting.getInterpreterInfos();
for (InterpreterInfo intpInfo : intpInfos) {
if (className.equals(intpInfo.getClassName())) {
if (intpInfo.getEditor() == null) {
break;
}
return intpInfo.getEditor();
}
}
return DEFAULT_EDITOR;
}
private void loadInterpreterDependencies(final InterpreterSetting setting) {
setting.setStatus(InterpreterSetting.Status.DOWNLOADING_DEPENDENCIES);
setting.setErrorReason(null);
interpreterSettings.put(setting.getId(), setting);
synchronized (interpreterSettings) {
final Thread t = new Thread() {
public void run() {
try {
// dependencies to prevent library conflict
File localRepoDir = new File(zeppelinConfiguration.getInterpreterLocalRepoPath() + "/" +
setting.getId());
if (localRepoDir.exists()) {
try {
FileUtils.forceDelete(localRepoDir);
} catch (FileNotFoundException e) {
logger.info("A file that does not exist cannot be deleted, nothing to worry", e);
}
}
// load dependencies
List<Dependency> deps = setting.getDependencies();
if (deps != null) {
for (Dependency d : deps) {
File destDir = new File(
zeppelinConfiguration.getRelativeDir(ConfVars.ZEPPELIN_DEP_LOCALREPO));
if (d.getExclusions() != null) {
dependencyResolver.load(d.getGroupArtifactVersion(), d.getExclusions(),
new File(destDir, setting.getId()));
} else {
dependencyResolver
.load(d.getGroupArtifactVersion(), new File(destDir, setting.getId()));
}
}
}
setting.setStatus(InterpreterSetting.Status.READY);
setting.setErrorReason(null);
} catch (Exception e) {
logger.error(String.format("Error while downloading repos for interpreter group : %s," +
" go to interpreter setting page click on edit and save it again to make " +
"this interpreter work properly. : %s",
setting.getGroup(), e.getLocalizedMessage()), e);
setting.setErrorReason(e.getLocalizedMessage());
setting.setStatus(InterpreterSetting.Status.ERROR);
} finally {
interpreterSettings.put(setting.getId(), setting);
}
}
};
t.start();
}
}
/**
* Overwrite dependency jar under local-repo/{interpreterId}
* if jar file in original path is changed
*/
private void copyDependenciesFromLocalPath(final InterpreterSetting setting) {
setting.setStatus(InterpreterSetting.Status.DOWNLOADING_DEPENDENCIES);
interpreterSettings.put(setting.getId(), setting);
synchronized (interpreterSettings) {
final Thread t = new Thread() {
public void run() {
try {
List<Dependency> deps = setting.getDependencies();
if (deps != null) {
for (Dependency d : deps) {
File destDir = new File(
zeppelinConfiguration.getRelativeDir(ConfVars.ZEPPELIN_DEP_LOCALREPO));
int numSplits = d.getGroupArtifactVersion().split(":").length;
if (!(numSplits >= 3 && numSplits <= 6)) {
dependencyResolver.copyLocalDependency(d.getGroupArtifactVersion(),
new File(destDir, setting.getId()));
}
}
}
setting.setStatus(InterpreterSetting.Status.READY);
} catch (Exception e) {
logger.error(String.format("Error while copying deps for interpreter group : %s," +
" go to interpreter setting page click on edit and save it again to make " +
"this interpreter work properly.",
setting.getGroup()), e);
setting.setErrorReason(e.getLocalizedMessage());
setting.setStatus(InterpreterSetting.Status.ERROR);
} finally {
interpreterSettings.put(setting.getId(), setting);
}
}
};
t.start();
}
}
/**
* Return ordered interpreter setting list.
* The list does not contain more than one setting from the same interpreter class.
* Order by InterpreterClass (order defined by ZEPPELIN_INTERPRETERS), Interpreter setting name
*/
public List<String> getDefaultInterpreterSettingList() {
// this list will contain default interpreter setting list
List<String> defaultSettings = new LinkedList<>();
// to ignore the same interpreter group
Map<String, Boolean> interpreterGroupCheck = new HashMap<>();
List<InterpreterSetting> sortedSettings = get();
for (InterpreterSetting setting : sortedSettings) {
if (defaultSettings.contains(setting.getId())) {
continue;
}
if (!interpreterGroupCheck.containsKey(setting.getName())) {
defaultSettings.add(setting.getId());
interpreterGroupCheck.put(setting.getName(), true);
}
}
return defaultSettings;
}
List<RegisteredInterpreter> getRegisteredInterpreterList() {
return new ArrayList<>(Interpreter.registeredInterpreters.values());
}
private boolean findDefaultInterpreter(List<InterpreterInfo> infos) {
for (InterpreterInfo interpreterInfo : infos) {
if (interpreterInfo.isDefaultInterpreter()) {
return true;
}
}
return false;
}
public InterpreterSetting createNewSetting(String name, String group,
List<Dependency> dependencies, InterpreterOption option, Properties p) throws IOException {
if (name.indexOf(".") >= 0) {
throw new IOException("'.' is invalid for InterpreterSetting name.");
}
InterpreterSetting setting = createFromInterpreterSettingRef(group);
setting.setName(name);
setting.setGroup(group);
setting.appendDependencies(dependencies);
setting.setInterpreterOption(option);
setting.setProperties(p);
setting.setInterpreterGroupFactory(interpreterGroupFactory);
interpreterSettings.put(setting.getId(), setting);
loadInterpreterDependencies(setting);
saveToFile();
return setting;
}
private InterpreterSetting add(String group, InterpreterInfo interpreterInfo,
Map<String, InterpreterProperty> interpreterProperties, InterpreterOption option, String path,
InterpreterRunner runner)
throws InterpreterException, IOException, RepositoryException {
ArrayList<InterpreterInfo> infos = new ArrayList<>();
infos.add(interpreterInfo);
return add(group, infos, new ArrayList<Dependency>(), option, interpreterProperties, path,
runner);
}
/**
* @param group InterpreterSetting reference name
*/
public InterpreterSetting add(String group, ArrayList<InterpreterInfo> interpreterInfos,
List<Dependency> dependencies, InterpreterOption option,
Map<String, InterpreterProperty> interpreterProperties, String path,
InterpreterRunner runner) {
Preconditions.checkNotNull(group, "name should not be null");
Preconditions.checkNotNull(interpreterInfos, "interpreterInfos should not be null");
Preconditions.checkNotNull(dependencies, "dependencies should not be null");
Preconditions.checkNotNull(option, "option should not be null");
Preconditions.checkNotNull(interpreterProperties, "properties should not be null");
InterpreterSetting interpreterSetting;
synchronized (interpreterSettingsRef) {
if (interpreterSettingsRef.containsKey(group)) {
interpreterSetting = interpreterSettingsRef.get(group);
// Append InterpreterInfo
List<InterpreterInfo> infos = interpreterSetting.getInterpreterInfos();
boolean hasDefaultInterpreter = findDefaultInterpreter(infos);
for (InterpreterInfo interpreterInfo : interpreterInfos) {
if (!infos.contains(interpreterInfo)) {
if (!hasDefaultInterpreter && interpreterInfo.isDefaultInterpreter()) {
hasDefaultInterpreter = true;
infos.add(0, interpreterInfo);
} else {
infos.add(interpreterInfo);
}
}
}
// Append dependencies
List<Dependency> dependencyList = interpreterSetting.getDependencies();
for (Dependency dependency : dependencies) {
if (!dependencyList.contains(dependency)) {
dependencyList.add(dependency);
}
}
// Append properties
Map<String, InterpreterProperty> properties =
(Map<String, InterpreterProperty>) interpreterSetting.getProperties();
for (String key : interpreterProperties.keySet()) {
if (!properties.containsKey(key)) {
properties.put(key, interpreterProperties.get(key));
}
}
} else {
interpreterSetting =
new InterpreterSetting(group, null, interpreterInfos, interpreterProperties,
dependencies, option, path, runner);
interpreterSettingsRef.put(group, interpreterSetting);
}
}
if (dependencies.size() > 0) {
loadInterpreterDependencies(interpreterSetting);
}
interpreterSetting.setInterpreterGroupFactory(interpreterGroupFactory);
return interpreterSetting;
}
/**
* map interpreter ids into noteId
*
* @param noteId note id
* @param ids InterpreterSetting id list
*/
public void setInterpreters(String user, String noteId, List<String> ids) throws IOException {
putNoteInterpreterSettingBinding(user, noteId, ids);
}
private void putNoteInterpreterSettingBinding(String user, String noteId,
List<String> settingList) throws IOException {
List<String> unBindedSettings = new LinkedList<>();
synchronized (interpreterSettings) {
List<String> oldSettings = interpreterBindings.get(noteId);
if (oldSettings != null) {
for (String oldSettingId : oldSettings) {
if (!settingList.contains(oldSettingId)) {
unBindedSettings.add(oldSettingId);
}
}
}
interpreterBindings.put(noteId, settingList);
saveToFile();
for (String settingId : unBindedSettings) {
InterpreterSetting setting = get(settingId);
removeInterpretersForNote(setting, user, noteId);
}
}
}
public void removeInterpretersForNote(InterpreterSetting interpreterSetting, String user,
String noteId) {
//TODO(jl): This is only for hotfix. You should fix it as a beautiful way
InterpreterOption interpreterOption = interpreterSetting.getOption();
if (!(InterpreterOption.SHARED.equals(interpreterOption.perNote)
&& InterpreterOption.SHARED.equals(interpreterOption.perUser))) {
interpreterSetting.closeAndRemoveInterpreterGroup(noteId, "");
}
}
public String getInterpreterSessionKey(String user, String noteId, InterpreterSetting setting) {
InterpreterOption option = setting.getOption();
String key;
if (option.isExistingProcess()) {
key = Constants.EXISTING_PROCESS;
} else if (option.perNoteScoped() && option.perUserScoped()) {
key = user + ":" + noteId;
} else if (option.perUserScoped()) {
key = user;
} else if (option.perNoteScoped()) {
key = noteId;
} 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-zengine/src/main/java/org/apache/zeppelin/interpreter/InterpreterInfoSaving.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/interpreter/InterpreterInfoSaving.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;
import org.sonatype.aether.repository.RemoteRepository;
import java.util.List;
import java.util.Map;
/**
*
*/
public class InterpreterInfoSaving {
public Map<String, InterpreterSetting> interpreterSettings;
public Map<String, List<String>> interpreterBindings;
public List<RemoteRepository> interpreterRepositories;
}
| 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/interpreter/InterpreterSetting.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/interpreter/InterpreterSetting.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;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import com.google.gson.annotations.SerializedName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.zeppelin.dep.Dependency;
import static org.apache.zeppelin.notebook.utility.IdHashes.generateId;
/**
* Interpreter settings
*/
public class InterpreterSetting {
private static final Logger logger = LoggerFactory.getLogger(InterpreterSetting.class);
private static final String SHARED_PROCESS = "shared_process";
private String id;
private String name;
// always be null in case of InterpreterSettingRef
private String group;
private transient Map<String, String> infos;
/**
* properties can be either Properties or Map<String, InterpreterProperty>
* properties should be:
* - Properties when Interpreter instances are saved to `conf/interpreter.json` file
* - Map<String, InterpreterProperty> when Interpreters are registered
* : this is needed after https://github.com/apache/zeppelin/pull/1145
* which changed the way of getting default interpreter setting AKA interpreterSettingsRef
* Note(mina): In order to simplify the implementation, I chose to change properties
* from Properties to Object instead of creating new classes.
*/
private Object properties;
private Status status;
private String errorReason;
@SerializedName("interpreterGroup")
private List<InterpreterInfo> interpreterInfos;
private final transient Map<String, InterpreterGroup> interpreterGroupRef = new HashMap<>();
private List<Dependency> dependencies = new LinkedList<>();
private InterpreterOption option;
private transient String path;
@SerializedName("runner")
private InterpreterRunner interpreterRunner;
@Deprecated
private transient InterpreterGroupFactory interpreterGroupFactory;
private final transient ReentrantReadWriteLock.ReadLock interpreterGroupReadLock;
private final transient ReentrantReadWriteLock.WriteLock interpreterGroupWriteLock;
public InterpreterSetting() {
ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
interpreterGroupReadLock = lock.readLock();
interpreterGroupWriteLock = lock.writeLock();
}
public InterpreterSetting(String id, String name, String group,
List<InterpreterInfo> interpreterInfos, Object properties, List<Dependency> dependencies,
InterpreterOption option, String path, InterpreterRunner runner) {
this();
this.id = id;
this.name = name;
this.group = group;
this.interpreterInfos = interpreterInfos;
this.properties = properties;
this.dependencies = dependencies;
this.option = option;
this.path = path;
this.status = Status.READY;
this.interpreterRunner = runner;
}
public InterpreterSetting(String name, String group, List<InterpreterInfo> interpreterInfos,
Object properties, List<Dependency> dependencies, InterpreterOption option, String path,
InterpreterRunner runner) {
this(generateId(), name, group, interpreterInfos, properties, dependencies, option, path,
runner);
}
/**
* Create interpreter from interpreterSettingRef
*
* @param o interpreterSetting from interpreterSettingRef
*/
public InterpreterSetting(InterpreterSetting o) {
this(generateId(), o.getName(), o.getGroup(), o.getInterpreterInfos(), o.getProperties(),
o.getDependencies(), o.getOption(), o.getPath(), o.getInterpreterRunner());
}
public String getId() {
return id;
}
public String getName() {
return name;
}
String getGroup() {
return group;
}
private String getInterpreterProcessKey(String user, String noteId) {
InterpreterOption option = getOption();
String key;
if (getOption().isExistingProcess) {
key = Constants.EXISTING_PROCESS;
} else if (getOption().isProcess()) {
key = (option.perUserIsolated() ? user : "") + ":" + (option.perNoteIsolated() ? noteId : "");
} else {
key = SHARED_PROCESS;
}
//logger.debug("getInterpreterProcessKey: {} for InterpreterSetting Id: {}, Name: {}",
// key, getId(), getName());
return key;
}
private boolean isEqualInterpreterKeyProcessKey(String refKey, String processKey) {
InterpreterOption option = getOption();
int validCount = 0;
if (getOption().isProcess()
&& !(option.perUserIsolated() == true && option.perNoteIsolated() == true)) {
List<String> processList = Arrays.asList(processKey.split(":"));
List<String> refList = Arrays.asList(refKey.split(":"));
if (refList.size() <= 1 || processList.size() <= 1) {
return refKey.equals(processKey);
}
if (processList.get(0).equals("") || processList.get(0).equals(refList.get(0))) {
validCount = validCount + 1;
}
if (processList.get(1).equals("") || processList.get(1).equals(refList.get(1))) {
validCount = validCount + 1;
}
return (validCount >= 2);
} else {
return refKey.equals(processKey);
}
}
String getInterpreterSessionKey(String user, String noteId) {
InterpreterOption option = getOption();
String key;
if (option.isExistingProcess()) {
key = Constants.EXISTING_PROCESS;
} else if (option.perNoteScoped() && option.perUserScoped()) {
key = user + ":" + noteId;
} else if (option.perUserScoped()) {
key = user;
} else if (option.perNoteScoped()) {
key = noteId;
} else {
key = "shared_session";
}
logger.debug("Interpreter session key: {}, for note: {}, user: {}, InterpreterSetting Name: " +
"{}", key, noteId, user, getName());
return key;
}
public InterpreterGroup getInterpreterGroup(String user, String noteId) {
String key = getInterpreterProcessKey(user, noteId);
if (!interpreterGroupRef.containsKey(key)) {
String interpreterGroupId = getId() + ":" + key;
InterpreterGroup intpGroup =
interpreterGroupFactory.createInterpreterGroup(interpreterGroupId, getOption());
interpreterGroupWriteLock.lock();
logger.debug("create interpreter group with groupId:" + interpreterGroupId);
interpreterGroupRef.put(key, intpGroup);
interpreterGroupWriteLock.unlock();
}
try {
interpreterGroupReadLock.lock();
return interpreterGroupRef.get(key);
} finally {
interpreterGroupReadLock.unlock();
}
}
public Collection<InterpreterGroup> getAllInterpreterGroups() {
try {
interpreterGroupReadLock.lock();
return new LinkedList<>(interpreterGroupRef.values());
} finally {
interpreterGroupReadLock.unlock();
}
}
void closeAndRemoveInterpreterGroup(String noteId, String user) {
if (user.equals("anonymous")) {
user = "";
}
String processKey = getInterpreterProcessKey(user, noteId);
String sessionKey = getInterpreterSessionKey(user, noteId);
List<InterpreterGroup> groupToRemove = new LinkedList<>();
InterpreterGroup groupItem;
for (String intpKey : new HashSet<>(interpreterGroupRef.keySet())) {
if (isEqualInterpreterKeyProcessKey(intpKey, processKey)) {
interpreterGroupWriteLock.lock();
// TODO(jl): interpreterGroup has two or more sessionKeys inside it. thus we should not
// remove interpreterGroup if it has two or more values.
groupItem = interpreterGroupRef.get(intpKey);
interpreterGroupWriteLock.unlock();
groupToRemove.add(groupItem);
}
for (InterpreterGroup groupToClose : groupToRemove) {
// TODO(jl): Fix the logic removing session. Now, it's handled into groupToClose.clsose()
groupToClose.close(interpreterGroupRef, intpKey, sessionKey);
}
groupToRemove.clear();
}
//Remove session because all interpreters in this session are closed
//TODO(jl): Change all code to handle interpreter one by one or all at once
}
void closeAndRemoveAllInterpreterGroups() {
for (String processKey : new HashSet<>(interpreterGroupRef.keySet())) {
InterpreterGroup interpreterGroup = interpreterGroupRef.get(processKey);
for (String sessionKey : new HashSet<>(interpreterGroup.keySet())) {
interpreterGroup.close(interpreterGroupRef, processKey, sessionKey);
}
}
}
void shutdownAndRemoveAllInterpreterGroups() {
for (InterpreterGroup interpreterGroup : interpreterGroupRef.values()) {
interpreterGroup.shutdown();
}
}
public Object getProperties() {
return properties;
}
public List<Dependency> getDependencies() {
if (dependencies == null) {
return new LinkedList<>();
}
return dependencies;
}
public void setDependencies(List<Dependency> dependencies) {
this.dependencies = dependencies;
}
public InterpreterOption getOption() {
if (option == null) {
option = new InterpreterOption();
}
return option;
}
public void setOption(InterpreterOption option) {
this.option = option;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public List<InterpreterInfo> getInterpreterInfos() {
return interpreterInfos;
}
void setInterpreterGroupFactory(InterpreterGroupFactory interpreterGroupFactory) {
this.interpreterGroupFactory = interpreterGroupFactory;
}
void appendDependencies(List<Dependency> dependencies) {
for (Dependency dependency : dependencies) {
if (!this.dependencies.contains(dependency)) {
this.dependencies.add(dependency);
}
}
}
void setInterpreterOption(InterpreterOption interpreterOption) {
this.option = interpreterOption;
}
public void setProperties(Properties p) {
this.properties = p;
}
void setGroup(String group) {
this.group = group;
}
void setName(String name) {
this.name = name;
}
/***
* Interpreter status
*/
public enum Status {
DOWNLOADING_DEPENDENCIES,
ERROR,
READY
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public String getErrorReason() {
return errorReason;
}
public void setErrorReason(String errorReason) {
this.errorReason = errorReason;
}
public void setInfos(Map<String, String> infos) {
this.infos = infos;
}
public Map<String, String> getInfos() {
return infos;
}
public InterpreterRunner getInterpreterRunner() {
return interpreterRunner;
}
public void setInterpreterRunner(InterpreterRunner interpreterRunner) {
this.interpreterRunner = interpreterRunner;
}
}
| 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/interpreter/InterpreterGroupFactory.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/interpreter/InterpreterGroupFactory.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;
import org.apache.commons.lang.NullArgumentException;
/**
* Created InterpreterGroup
*/
public interface InterpreterGroupFactory {
InterpreterGroup createInterpreterGroup(String interpreterGroupId, InterpreterOption 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-zengine/src/main/java/org/apache/zeppelin/interpreter/InterpreterInfo.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/interpreter/InterpreterInfo.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;
import com.google.gson.annotations.SerializedName;
import java.util.Map;
/**
* Information of interpreters in this interpreter setting.
* this will be serialized for conf/interpreter.json and REST api response.
*/
public class InterpreterInfo {
private String name;
@SerializedName("class") private String className;
private boolean defaultInterpreter = false;
private Map<String, Object> editor;
public InterpreterInfo(String className, String name, boolean defaultInterpreter,
Map<String, Object> editor) {
this.className = className;
this.name = name;
this.defaultInterpreter = defaultInterpreter;
this.editor = editor;
}
public String getName() {
return name;
}
public String getClassName() {
return className;
}
public void setName(String name) {
this.name = name;
}
boolean isDefaultInterpreter() {
return defaultInterpreter;
}
public Map<String, Object> getEditor() {
return editor;
}
public void setEditor(Map<String, Object> editor) {
this.editor = editor;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof InterpreterInfo)) {
return false;
}
InterpreterInfo other = (InterpreterInfo) obj;
boolean sameName =
null == getName() ? null == other.getName() : getName().equals(other.getName());
boolean sameClassName = null == getClassName() ?
null == other.getClassName() :
getClassName().equals(other.getClassName());
boolean sameIsDefaultInterpreter = defaultInterpreter == other.isDefaultInterpreter();
return sameName && sameClassName && sameIsDefaultInterpreter;
}
}
| 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/interpreter/install/InstallInterpreter.java | smart-zeppelin/zeppelin-zengine/src/main/java/org/apache/zeppelin/interpreter/install/InstallInterpreter.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.install;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Logger;
import org.apache.zeppelin.conf.ZeppelinConfiguration;
import org.apache.zeppelin.dep.DependencyResolver;
import org.apache.zeppelin.util.Util;
import org.sonatype.aether.RepositoryException;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Commandline utility to install interpreter from maven repository
*/
public class InstallInterpreter {
private final File interpreterListFile;
private final File interpreterBaseDir;
private final List<AvailableInterpreterInfo> availableInterpreters;
private final String localRepoDir;
private URL proxyUrl;
private String proxyUser;
private String proxyPassword;
/**
*
* @param interpreterListFile
* @param interpreterBaseDir interpreter directory for installing binaries
* @throws IOException
*/
public InstallInterpreter(File interpreterListFile, File interpreterBaseDir, String localRepoDir)
throws IOException {
this.interpreterListFile = interpreterListFile;
this.interpreterBaseDir = interpreterBaseDir;
this.localRepoDir = localRepoDir;
availableInterpreters = new LinkedList<>();
readAvailableInterpreters();
}
/**
* Information for available informations
*/
private static class AvailableInterpreterInfo {
public final String name;
public final String artifact;
public final String description;
public AvailableInterpreterInfo(String name, String artifact, String description) {
this.name = name;
this.artifact = artifact;
this.description = description;
}
}
private void readAvailableInterpreters() throws IOException {
if (!interpreterListFile.isFile()) {
System.err.println("Can't find interpreter list " + interpreterListFile.getAbsolutePath());
return;
}
String text = FileUtils.readFileToString(interpreterListFile);
String[] lines = text.split("\n");
Pattern pattern = Pattern.compile("(\\S+)\\s+(\\S+)\\s+(.*)");
int lineNo = 0;
for (String line : lines) {
lineNo++;
if (line == null || line.length() == 0 || line.startsWith("#")) {
continue;
}
Matcher match = pattern.matcher(line);
if (match.groupCount() != 3) {
System.err.println("Error on line " + lineNo + ", " + line);
continue;
}
match.find();
String name = match.group(1);
String artifact = match.group(2);
String description = match.group(3);
availableInterpreters.add(new AvailableInterpreterInfo(name, artifact, description));
}
}
public List<AvailableInterpreterInfo> list() {
for (AvailableInterpreterInfo info : availableInterpreters) {
System.out.println(info.name + "\t\t\t" + info.description);
}
return availableInterpreters;
}
public void installAll() {
for (AvailableInterpreterInfo info : availableInterpreters) {
install(info.name, info.artifact);
}
}
public void install(String [] names) {
for (String name : names) {
install(name);
}
}
public void install(String name) {
// find artifact name
for (AvailableInterpreterInfo info : availableInterpreters) {
if (name.equals(info.name)) {
install(name, info.artifact);
return;
}
}
throw new RuntimeException("Can't find interpreter '" + name + "'");
}
public void install(String [] names, String [] artifacts) {
if (names.length != artifacts.length) {
throw new RuntimeException("Length of given names and artifacts are different");
}
for (int i = 0; i < names.length; i++) {
install(names[i], artifacts[i]);
}
}
public void install(String name, String artifact) {
DependencyResolver depResolver = new DependencyResolver(localRepoDir);
if (proxyUrl != null) {
depResolver.setProxy(proxyUrl, proxyUser, proxyPassword);
}
File installDir = new File(interpreterBaseDir, name);
if (installDir.exists()) {
System.err.println("Directory " + installDir.getAbsolutePath()
+ " already exists"
+ "\n\nSkipped");
return;
}
System.out.println("Install " + name + "(" + artifact + ") to "
+ installDir.getAbsolutePath() + " ... ");
try {
depResolver.load(artifact, installDir);
System.out.println("Interpreter " + name + " installed under " +
installDir.getAbsolutePath() + ".");
startTip();
} catch (RepositoryException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void setProxy(URL proxyUrl, String proxyUser, String proxyPassword) {
this.proxyUrl = proxyUrl;
this.proxyUser = proxyUser;
this.proxyPassword = proxyPassword;
}
public static void usage() {
System.out.println("Options");
System.out.println(" -l, --list List available interpreters");
System.out.println(" -a, --all Install all available interpreters");
System.out.println(" -n, --name [NAMES] Install interpreters (comma separated " +
"list)" +
"e.g. md,shell,jdbc,python,angular");
System.out.println(" -t, --artifact [ARTIFACTS] (Optional with -n) custom artifact names" +
". " +
"(comma separated list correspond to --name) " +
"e.g. customGroup:customArtifact:customVersion");
System.out.println(" --proxy-url [url] (Optional) proxy url. http(s)://host:port");
System.out.println(" --proxy-user [user] (Optional) proxy user");
System.out.println(" --proxy-password [password] (Optional) proxy password");
}
public static void main(String [] args) throws IOException {
if (args.length == 0) {
usage();
return;
}
ZeppelinConfiguration conf = ZeppelinConfiguration.create();
InstallInterpreter installer = new InstallInterpreter(
new File(conf.getInterpreterListPath()),
new File(conf.getInterpreterDir()),
conf.getInterpreterLocalRepoPath());
String names = null;
String artifacts = null;
URL proxyUrl = null;
String proxyUser = null;
String proxyPassword = null;
boolean all = false;
for (int i = 0; i < args.length; i++) {
String arg = args[i].toLowerCase(Locale.US);
switch (arg) {
case "--list":
case "-l":
installer.list();
System.exit(0);
break;
case "--all":
case "-a":
all = true;
break;
case "--name":
case "-n":
names = args[++i];
break;
case "--artifact":
case "-t":
artifacts = args[++i];
break;
case "--version":
case "-v":
Util.getVersion();
break;
case "--proxy-url":
proxyUrl = new URL(args[++i]);
break;
case "--proxy-user":
proxyUser = args[++i];
break;
case "--proxy-password":
proxyPassword = args[++i];
break;
case "--help":
case "-h":
usage();
System.exit(0);
break;
default:
System.out.println("Unknown option " + arg);
}
}
if (proxyUrl != null) {
installer.setProxy(proxyUrl, proxyUser, proxyPassword);
}
if (all) {
installer.installAll();
System.exit(0);
}
if (names != null) {
if (artifacts != null) {
installer.install(names.split(","), artifacts.split(","));
} else {
installer.install(names.split(","));
}
}
}
private static void startTip() {
System.out.println("\n1. Restart Zeppelin"
+ "\n2. Create interpreter setting in 'Interpreter' menu on Zeppelin GUI"
+ "\n3. Then you can bind the interpreter on your 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-interpreter/src/test/java/org/apache/zeppelin/resource/DistributedResourcePoolTest.java | smart-zeppelin/zeppelin-interpreter/src/test/java/org/apache/zeppelin/resource/DistributedResourcePoolTest.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.resource;
import com.google.gson.Gson;
import org.apache.zeppelin.user.AuthenticationInfo;
import org.apache.zeppelin.display.GUI;
import org.apache.zeppelin.interpreter.*;
import org.apache.zeppelin.interpreter.remote.RemoteInterpreter;
import org.apache.zeppelin.interpreter.remote.RemoteInterpreterEventPoller;
import org.apache.zeppelin.interpreter.remote.mock.MockInterpreterResourcePool;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Properties;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Unittest for DistributedResourcePool
*/
public class DistributedResourcePoolTest {
private static final String INTERPRETER_SCRIPT =
System.getProperty("os.name").startsWith("Windows") ?
"../bin/interpreter.cmd" :
"../bin/interpreter.sh";
private InterpreterGroup intpGroup1;
private InterpreterGroup intpGroup2;
private HashMap<String, String> env;
private RemoteInterpreter intp1;
private RemoteInterpreter intp2;
private InterpreterContext context;
private RemoteInterpreterEventPoller eventPoller1;
private RemoteInterpreterEventPoller eventPoller2;
@Before
public void setUp() throws Exception {
env = new HashMap<>();
env.put("ZEPPELIN_CLASSPATH", new File("./target/test-classes").getAbsolutePath());
Properties p = new Properties();
intp1 = new RemoteInterpreter(
p,
"note",
MockInterpreterResourcePool.class.getName(),
new File(INTERPRETER_SCRIPT).getAbsolutePath(),
"fake",
"fakeRepo",
env,
10 * 1000,
null,
null,
"anonymous",
false
);
intpGroup1 = new InterpreterGroup("intpGroup1");
intpGroup1.put("note", new LinkedList<Interpreter>());
intpGroup1.get("note").add(intp1);
intp1.setInterpreterGroup(intpGroup1);
intp2 = new RemoteInterpreter(
p,
"note",
MockInterpreterResourcePool.class.getName(),
new File(INTERPRETER_SCRIPT).getAbsolutePath(),
"fake",
"fakeRepo",
env,
10 * 1000,
null,
null,
"anonymous",
false
);
intpGroup2 = new InterpreterGroup("intpGroup2");
intpGroup2.put("note", new LinkedList<Interpreter>());
intpGroup2.get("note").add(intp2);
intp2.setInterpreterGroup(intpGroup2);
context = new InterpreterContext(
"note",
"id",
null,
"title",
"text",
new AuthenticationInfo(),
new HashMap<String, Object>(),
new GUI(),
null,
null,
new LinkedList<InterpreterContextRunner>(),
null);
intp1.open();
intp2.open();
eventPoller1 = new RemoteInterpreterEventPoller(null, null);
eventPoller1.setInterpreterGroup(intpGroup1);
eventPoller1.setInterpreterProcess(intpGroup1.getRemoteInterpreterProcess());
eventPoller2 = new RemoteInterpreterEventPoller(null, null);
eventPoller2.setInterpreterGroup(intpGroup2);
eventPoller2.setInterpreterProcess(intpGroup2.getRemoteInterpreterProcess());
eventPoller1.start();
eventPoller2.start();
}
@After
public void tearDown() throws Exception {
eventPoller1.shutdown();
intp1.close();
intpGroup1.close();
eventPoller2.shutdown();
intp2.close();
intpGroup2.close();
}
@Test
public void testRemoteDistributedResourcePool() {
Gson gson = new Gson();
InterpreterResult ret;
intp1.interpret("put key1 value1", context);
intp2.interpret("put key2 value2", context);
ret = intp1.interpret("getAll", context);
assertEquals(2, gson.fromJson(ret.message().get(0).getData(), ResourceSet.class).size());
ret = intp2.interpret("getAll", context);
assertEquals(2, gson.fromJson(ret.message().get(0).getData(), ResourceSet.class).size());
ret = intp1.interpret("get key1", context);
assertEquals("value1", gson.fromJson(ret.message().get(0).getData(), String.class));
ret = intp1.interpret("get key2", context);
assertEquals("value2", gson.fromJson(ret.message().get(0).getData(), String.class));
}
@Test
public void testDistributedResourcePool() {
final LocalResourcePool pool2 = new LocalResourcePool("pool2");
final LocalResourcePool pool3 = new LocalResourcePool("pool3");
DistributedResourcePool pool1 = new DistributedResourcePool("pool1", new ResourcePoolConnector() {
@Override
public ResourceSet getAllResources() {
ResourceSet set = pool2.getAll();
set.addAll(pool3.getAll());
ResourceSet remoteSet = new ResourceSet();
Gson gson = new Gson();
for (Resource s : set) {
RemoteResource remoteResource = gson.fromJson(gson.toJson(s), RemoteResource.class);
remoteResource.setResourcePoolConnector(this);
remoteSet.add(remoteResource);
}
return remoteSet;
}
@Override
public Object readResource(ResourceId id) {
if (id.getResourcePoolId().equals(pool2.id())) {
return pool2.get(id.getName()).get();
}
if (id.getResourcePoolId().equals(pool3.id())) {
return pool3.get(id.getName()).get();
}
return null;
}
});
assertEquals(0, pool1.getAll().size());
// test get() can get from pool
pool2.put("object1", "value2");
assertEquals(1, pool1.getAll().size());
assertTrue(pool1.get("object1").isRemote());
assertEquals("value2", pool1.get("object1").get());
// test get() is locality aware
pool1.put("object1", "value1");
assertEquals(1, pool2.getAll().size());
assertEquals("value1", pool1.get("object1").get());
// test getAll() is locality aware
assertEquals("value1", pool1.getAll().get(0).get());
assertEquals("value2", pool1.getAll().get(1).get());
}
@Test
public void testResourcePoolUtils() {
Gson gson = new Gson();
InterpreterResult ret;
// when create some resources
intp1.interpret("put note1:paragraph1:key1 value1", context);
intp1.interpret("put note1:paragraph2:key1 value2", context);
intp2.interpret("put note2:paragraph1:key1 value1", context);
intp2.interpret("put note2:paragraph2:key2 value2", context);
// then get all resources.
assertEquals(4, ResourcePoolUtils.getAllResources().size());
// when remove all resources from note1
ResourcePoolUtils.removeResourcesBelongsToNote("note1");
// then resources should be removed.
assertEquals(2, ResourcePoolUtils.getAllResources().size());
assertEquals("", gson.fromJson(
intp1.interpret("get note1:paragraph1:key1", context).message().get(0).getData(),
String.class));
assertEquals("", gson.fromJson(
intp1.interpret("get note1:paragraph2:key1", context).message().get(0).getData(),
String.class));
// when remove all resources from note2:paragraph1
ResourcePoolUtils.removeResourcesBelongsToParagraph("note2", "paragraph1");
// then 1
assertEquals(1, ResourcePoolUtils.getAllResources().size());
assertEquals("value2", gson.fromJson(
intp1.interpret("get note2:paragraph2:key2", context).message().get(0).getData(),
String.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-interpreter/src/test/java/org/apache/zeppelin/resource/ResourceTest.java | smart-zeppelin/zeppelin-interpreter/src/test/java/org/apache/zeppelin/resource/ResourceTest.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.resource;
import org.junit.Test;
import java.io.IOException;
import java.nio.ByteBuffer;
import static org.junit.Assert.assertEquals;
/**
* Test for Resource
*/
public class ResourceTest {
@Test
public void testSerializeDeserialize() throws IOException, ClassNotFoundException {
ByteBuffer buffer = Resource.serializeObject("hello");
assertEquals("hello", Resource.deserializeObject(buffer));
}
}
| 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-interpreter/src/test/java/org/apache/zeppelin/resource/LocalResourcePoolTest.java | smart-zeppelin/zeppelin-interpreter/src/test/java/org/apache/zeppelin/resource/LocalResourcePoolTest.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.resource;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Unittest for LocalResourcePool
*/
public class LocalResourcePoolTest {
@Test
public void testGetPutResourcePool() {
LocalResourcePool pool = new LocalResourcePool("pool1");
assertEquals("pool1", pool.id());
assertNull(pool.get("notExists"));
pool.put("item1", "value1");
Resource resource = pool.get("item1");
assertNotNull(resource);
assertEquals(pool.id(), resource.getResourceId().getResourcePoolId());
assertEquals("value1", resource.get());
assertTrue(resource.isLocal());
assertTrue(resource.isSerializable());
assertEquals(1, pool.getAll().size());
assertNotNull(pool.remove("item1"));
assertNull(pool.remove("item1"));
}
}
| 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-interpreter/src/test/java/org/apache/zeppelin/resource/ResourceSetTest.java | smart-zeppelin/zeppelin-interpreter/src/test/java/org/apache/zeppelin/resource/ResourceSetTest.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.resource;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Unit test for ResourceSet
*/
public class ResourceSetTest {
@Test
public void testFilterByName() {
ResourceSet set = new ResourceSet();
set.add(new Resource(new ResourceId("poo1", "resource1"), "value1"));
set.add(new Resource(new ResourceId("poo1", "resource2"), new Integer(2)));
assertEquals(2, set.filterByNameRegex(".*").size());
assertEquals(1, set.filterByNameRegex("resource1").size());
assertEquals(1, set.filterByNameRegex("resource2").size());
assertEquals(0, set.filterByNameRegex("res").size());
assertEquals(2, set.filterByNameRegex("res.*").size());
}
@Test
public void testFilterByClassName() {
ResourceSet set = new ResourceSet();
set.add(new Resource(new ResourceId("poo1", "resource1"), "value1"));
set.add(new Resource(new ResourceId("poo1", "resource2"), new Integer(2)));
assertEquals(1, set.filterByClassnameRegex(".*String").size());
assertEquals(1, set.filterByClassnameRegex(String.class.getName()).size());
assertEquals(1, set.filterByClassnameRegex(".*Integer").size());
assertEquals(1, set.filterByClassnameRegex(Integer.class.getName()).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-interpreter/src/test/java/org/apache/zeppelin/helium/MockApplication1.java | smart-zeppelin/zeppelin-interpreter/src/test/java/org/apache/zeppelin/helium/MockApplication1.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.interpreter.InterpreterContext;
import org.apache.zeppelin.resource.ResourceSet;
/**
* Mock application
*/
public class MockApplication1 extends Application {
boolean unloaded;
int run;
public MockApplication1(ApplicationContext context) {
super(context);
unloaded = false;
run = 0;
}
@Override
public void run(ResourceSet args) {
run++;
}
@Override
public void unload() {
unloaded = true;
}
public boolean isUnloaded() {
return unloaded;
}
public int getNumRun() {
return run;
}
}
| 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-interpreter/src/test/java/org/apache/zeppelin/helium/ApplicationLoaderTest.java | smart-zeppelin/zeppelin-interpreter/src/test/java/org/apache/zeppelin/helium/ApplicationLoaderTest.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.commons.io.FileUtils;
import org.apache.zeppelin.dep.DependencyResolver;
import org.apache.zeppelin.interpreter.InterpreterOutput;
import org.apache.zeppelin.interpreter.InterpreterOutputListener;
import org.apache.zeppelin.interpreter.InterpreterResultMessageOutput;
import org.apache.zeppelin.resource.LocalResourcePool;
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.*;
public class ApplicationLoaderTest {
private File tmpDir;
@Before
public void setUp() {
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 loadUnloadApplication() throws Exception {
// given
LocalResourcePool resourcePool = new LocalResourcePool("pool1");
DependencyResolver dep = new DependencyResolver(tmpDir.getAbsolutePath());
ApplicationLoader appLoader = new ApplicationLoader(resourcePool, dep);
HeliumPackage pkg1 = createPackageInfo(MockApplication1.class.getName(), "artifact1");
ApplicationContext context1 = createContext("note1", "paragraph1", "app1");
// when load application
MockApplication1 app = (MockApplication1) ((ClassLoaderApplication)
appLoader.load(pkg1, context1)).getInnerApplication();
// then
assertFalse(app.isUnloaded());
assertEquals(0, app.getNumRun());
// when unload
app.unload();
// then
assertTrue(app.isUnloaded());
assertEquals(0, app.getNumRun());
}
public HeliumPackage createPackageInfo(String className, String artifact) {
HeliumPackage app1 = new HeliumPackage(
HeliumPackage.Type.APPLICATION,
"name1",
"desc1",
artifact,
className,
new String[][]{{}},
"license",
"icon");
return app1;
}
public ApplicationContext createContext(String noteId, String paragraphId, String appInstanceId) {
ApplicationContext context1 = new ApplicationContext(
noteId,
paragraphId,
appInstanceId,
null,
new InterpreterOutput(null));
return context1;
}
}
| 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-interpreter/src/test/java/org/apache/zeppelin/user/CredentialsTest.java | smart-zeppelin/zeppelin-interpreter/src/test/java/org/apache/zeppelin/user/CredentialsTest.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.user;
import static org.junit.Assert.*;
import org.junit.Test;
import java.io.IOException;
public class CredentialsTest {
@Test
public void testDefaultProperty() throws IOException {
Credentials credentials = new Credentials(false, null);
UserCredentials userCredentials = new UserCredentials();
UsernamePassword up1 = new UsernamePassword("user2", "password");
userCredentials.putUsernamePassword("hive(vertica)", up1);
credentials.putUserCredentials("user1", userCredentials);
UserCredentials uc2 = credentials.getUserCredentials("user1");
UsernamePassword up2 = uc2.getUsernamePassword("hive(vertica)");
assertEquals(up1.getUsername(), up2.getUsername());
assertEquals(up1.getPassword(), up2.getPassword());
}
}
| 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-interpreter/src/test/java/org/apache/zeppelin/display/AngularObjectTest.java | smart-zeppelin/zeppelin-interpreter/src/test/java/org/apache/zeppelin/display/AngularObjectTest.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;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.zeppelin.interpreter.InterpreterContext;
import org.junit.Test;
public class AngularObjectTest {
@Test
public void testEquals() {
assertEquals(
new AngularObject("name", "value", "note1", null, null),
new AngularObject("name", "value", "note1", null, null)
);
assertEquals(
new AngularObject("name", "value", "note1", "paragraph1", null),
new AngularObject("name", "value", "note1", "paragraph1", null)
);
assertEquals(
new AngularObject("name", "value", null, null, null),
new AngularObject("name", "value", null, null, null)
);
assertEquals(
new AngularObject("name", "value1", null, null, null),
new AngularObject("name", "value2", null, null, null)
);
assertNotSame(
new AngularObject("name1", "value", null, null, null),
new AngularObject("name2", "value", null, null, null)
);
assertNotSame(
new AngularObject("name1", "value", "note1", null, null),
new AngularObject("name2", "value", "note2", null, null)
);
assertNotSame(
new AngularObject("name1", "value", "note", null, null),
new AngularObject("name2", "value", null, null, null)
);
assertNotSame(
new AngularObject("name", "value", "note", "paragraph1", null),
new AngularObject("name", "value", "note", "paragraph2", null)
);
assertNotSame(
new AngularObject("name", "value", "note1", null, null),
new AngularObject("name", "value", "note1", "paragraph1", null)
);
}
@Test
public void testListener() {
final AtomicInteger updated = new AtomicInteger(0);
AngularObject ao = new AngularObject("name", "value", "note1", null, new AngularObjectListener() {
@Override
public void updated(AngularObject updatedObject) {
updated.incrementAndGet();
}
});
assertEquals(0, updated.get());
ao.set("newValue");
assertEquals(1, updated.get());
assertEquals("newValue", ao.get());
ao.set("newValue");
assertEquals(2, updated.get());
ao.set("newnewValue", false);
assertEquals(2, updated.get());
assertEquals("newnewValue", ao.get());
}
@Test
public void testWatcher() throws InterruptedException {
final AtomicInteger updated = new AtomicInteger(0);
final AtomicInteger onWatch = new AtomicInteger(0);
AngularObject ao = new AngularObject("name", "value", "note1", null, new AngularObjectListener() {
@Override
public void updated(AngularObject updatedObject) {
updated.incrementAndGet();
}
});
ao.addWatcher(new AngularObjectWatcher(null) {
@Override
public void watch(Object oldObject, Object newObject, InterpreterContext context) {
onWatch.incrementAndGet();
}
});
assertEquals(0, onWatch.get());
ao.set("newValue");
Thread.sleep(500);
assertEquals(1, onWatch.get());
}
}
| 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-interpreter/src/test/java/org/apache/zeppelin/display/InputTest.java | smart-zeppelin/zeppelin-interpreter/src/test/java/org/apache/zeppelin/display/InputTest.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;
import java.util.HashMap;
import java.util.Map;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import org.apache.zeppelin.display.Input.ParamOption;
public class InputTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void testFormExtraction() {
// input form
String script = "${input_form=}";
Map<String, Input> forms = Input.extractSimpleQueryForm(script);
assertEquals(1, forms.size());
Input form = forms.get("input_form");
assertEquals("input_form", form.name);
assertNull(form.displayName);
assertEquals("", form.defaultValue);
assertNull(form.options);
// input form with display name & default value
script = "${input_form(Input Form)=xxx}";
forms = Input.extractSimpleQueryForm(script);
form = forms.get("input_form");
assertEquals("xxx", form.defaultValue);
// selection form
script = "${select_form(Selection Form)=op1,op1|op2(Option 2)|op3}";
form = Input.extractSimpleQueryForm(script).get("select_form");
assertEquals("select_form", form.name);
assertEquals("op1", form.defaultValue);
assertArrayEquals(new ParamOption[]{new ParamOption("op1", null),
new ParamOption("op2", "Option 2"), new ParamOption("op3", null)}, form.options);
// checkbox form
script = "${checkbox:checkbox_form=op1,op1|op2|op3}";
form = Input.extractSimpleQueryForm(script).get("checkbox_form");
assertEquals("checkbox_form", form.name);
assertEquals("checkbox", form.type);
assertArrayEquals(new Object[]{"op1"}, (Object[]) form.defaultValue);
assertArrayEquals(new ParamOption[]{new ParamOption("op1", null),
new ParamOption("op2", null), new ParamOption("op3", null)}, form.options);
// checkbox form with multiple default checks
script = "${checkbox:checkbox_form(Checkbox Form)=op1|op3,op1(Option 1)|op2|op3}";
form = Input.extractSimpleQueryForm(script).get("checkbox_form");
assertEquals("checkbox_form", form.name);
assertEquals("Checkbox Form", form.displayName);
assertEquals("checkbox", form.type);
assertArrayEquals(new Object[]{"op1", "op3"}, (Object[]) form.defaultValue);
assertArrayEquals(new ParamOption[]{new ParamOption("op1", "Option 1"),
new ParamOption("op2", null), new ParamOption("op3", null)}, form.options);
// checkbox form with no default check
script = "${checkbox:checkbox_form(Checkbox Form)=,op1(Option 1)|op2(Option 2)|op3(Option 3)}";
form = Input.extractSimpleQueryForm(script).get("checkbox_form");
assertEquals("checkbox_form", form.name);
assertEquals("Checkbox Form", form.displayName);
assertEquals("checkbox", form.type);
assertArrayEquals(new Object[]{}, (Object[]) form.defaultValue);
assertArrayEquals(new ParamOption[]{new ParamOption("op1", "Option 1"),
new ParamOption("op2", "Option 2"), new ParamOption("op3", "Option 3")}, form.options);
}
@Test
public void testFormSubstitution() {
// test form substitution without new forms
String script = "INPUT=${input_form=}SELECTED=${select_form(Selection Form)=,s_op1|s_op2|s_op3}\n" +
"CHECKED=${checkbox:checkbox_form=c_op1|c_op2,c_op1|c_op2|c_op3}";
Map<String, Object> params = new HashMap<>();
params.put("input_form", "some_input");
params.put("select_form", "s_op2");
params.put("checkbox_form", new String[]{"c_op1", "c_op3"});
String replaced = Input.getSimpleQuery(params, script);
assertEquals("INPUT=some_inputSELECTED=s_op2\nCHECKED=c_op1,c_op3", replaced);
// test form substitution with new forms
script = "INPUT=${input_form=}SELECTED=${select_form(Selection Form)=,s_op1|s_op2|s_op3}\n" +
"CHECKED=${checkbox:checkbox_form=c_op1|c_op2,c_op1|c_op2|c_op3}\n" +
"NEW_CHECKED=${checkbox( and ):new_check=nc_a|nc_c,nc_a|nc_b|nc_c}";
replaced = Input.getSimpleQuery(params, script);
assertEquals("INPUT=some_inputSELECTED=s_op2\nCHECKED=c_op1,c_op3\n" +
"NEW_CHECKED=nc_a and nc_c", replaced);
// test form substitution with obsoleted values
script = "INPUT=${input_form=}SELECTED=${select_form(Selection Form)=,s_op1|s_op2|s_op3}\n" +
"CHECKED=${checkbox:checkbox_form=c_op1|c_op2,c_op1|c_op2|c_op3_new}\n" +
"NEW_CHECKED=${checkbox( and ):new_check=nc_a|nc_c,nc_a|nc_b|nc_c}";
replaced = Input.getSimpleQuery(params, script);
assertEquals("INPUT=some_inputSELECTED=s_op2\nCHECKED=c_op1\n" +
"NEW_CHECKED=nc_a and nc_c", replaced);
}
}
| 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-interpreter/src/test/java/org/apache/zeppelin/display/AngularObjectRegistryTest.java | smart-zeppelin/zeppelin-interpreter/src/test/java/org/apache/zeppelin/display/AngularObjectRegistryTest.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;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
public class AngularObjectRegistryTest {
@Test
public void testBasic() {
final AtomicInteger onAdd = new AtomicInteger(0);
final AtomicInteger onUpdate = new AtomicInteger(0);
final AtomicInteger onRemove = new AtomicInteger(0);
AngularObjectRegistry registry = new AngularObjectRegistry("intpId",
new AngularObjectRegistryListener() {
@Override
public void onAdd(String interpreterGroupId, AngularObject object) {
onAdd.incrementAndGet();
}
@Override
public void onUpdate(String interpreterGroupId, AngularObject object) {
onUpdate.incrementAndGet();
}
@Override
public void onRemove(String interpreterGroupId, String name, String noteId, String paragraphId) {
onRemove.incrementAndGet();
}
});
registry.add("name1", "value1", "note1", null);
assertEquals(1, registry.getAll("note1", null).size());
assertEquals(1, onAdd.get());
assertEquals(0, onUpdate.get());
registry.get("name1", "note1", null).set("newValue");
assertEquals(1, onUpdate.get());
registry.remove("name1", "note1", null);
assertEquals(0, registry.getAll("note1", null).size());
assertEquals(1, onRemove.get());
assertEquals(null, registry.get("name1", "note1", null));
// namespace
registry.add("name1", "value11", "note2", null);
assertEquals("value11", registry.get("name1", "note2", null).get());
assertEquals(null, registry.get("name1", "note1", null));
// null namespace
registry.add("name1", "global1", null, null);
assertEquals("global1", registry.get("name1", null, null).get());
}
@Test
public void testGetDependOnScope() {
AngularObjectRegistry registry = new AngularObjectRegistry("intpId", null);
AngularObject ao1 = registry.add("name1", "o1", "noteId1", "paragraphId1");
AngularObject ao2 = registry.add("name2", "o2", "noteId1", "paragraphId1");
AngularObject ao3 = registry.add("name2", "o3", "noteId1", "paragraphId2");
AngularObject ao4 = registry.add("name3", "o4", "noteId1", null);
AngularObject ao5 = registry.add("name4", "o5", null, null);
assertNull(registry.get("name3", "noteId1", "paragraphId1"));
assertNull(registry.get("name1", "noteId2", null));
assertEquals("o1", registry.get("name1", "noteId1", "paragraphId1").get());
assertEquals("o2", registry.get("name2", "noteId1", "paragraphId1").get());
assertEquals("o3", registry.get("name2", "noteId1", "paragraphId2").get());
assertEquals("o4", registry.get("name3", "noteId1", null).get());
assertEquals("o5", registry.get("name4", null, null).get());
}
@Test
public void testGetAllDependOnScope() {
AngularObjectRegistry registry = new AngularObjectRegistry("intpId", null);
AngularObject ao1 = registry.add("name1", "o", "noteId1", "paragraphId1");
AngularObject ao2 = registry.add("name2", "o", "noteId1", "paragraphId1");
AngularObject ao3 = registry.add("name2", "o", "noteId1", "paragraphId2");
AngularObject ao4 = registry.add("name3", "o", "noteId1", null);
AngularObject ao5 = registry.add("name4", "o", null, null);
assertEquals(2, registry.getAll("noteId1", "paragraphId1").size());
assertEquals(1, registry.getAll("noteId1", "paragraphId2").size());
assertEquals(1, registry.getAll("noteId1", null).size());
assertEquals(1, registry.getAll(null, null).size());
assertEquals(5, registry.getAllWithGlobal("noteId1").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-interpreter/src/test/java/org/apache/zeppelin/scheduler/FIFOSchedulerTest.java | smart-zeppelin/zeppelin-interpreter/src/test/java/org/apache/zeppelin/scheduler/FIFOSchedulerTest.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.scheduler;
import org.apache.zeppelin.scheduler.Job;
import org.apache.zeppelin.scheduler.Scheduler;
import org.apache.zeppelin.scheduler.SchedulerFactory;
import org.apache.zeppelin.scheduler.Job.Status;
import junit.framework.TestCase;
public class FIFOSchedulerTest extends TestCase {
private SchedulerFactory schedulerSvc;
@Override
public void setUp() throws Exception{
schedulerSvc = new SchedulerFactory();
}
@Override
public void tearDown(){
}
public void testRun() throws InterruptedException{
Scheduler s = schedulerSvc.createOrGetFIFOScheduler("test");
assertEquals(0, s.getJobsRunning().size());
assertEquals(0, s.getJobsWaiting().size());
Job job1 = new SleepingJob("job1", null, 500);
Job job2 = new SleepingJob("job2", null, 500);
s.submit(job1);
s.submit(job2);
Thread.sleep(200);
assertEquals(Status.RUNNING, job1.getStatus());
assertEquals(Status.PENDING, job2.getStatus());
assertEquals(1, s.getJobsRunning().size());
assertEquals(1, s.getJobsWaiting().size());
Thread.sleep(500);
assertEquals(Status.FINISHED, job1.getStatus());
assertEquals(Status.RUNNING, job2.getStatus());
assertTrue((500 < (Long)job1.getReturn()));
assertEquals(1, s.getJobsRunning().size());
assertEquals(0, s.getJobsWaiting().size());
}
public void testAbort() throws InterruptedException{
Scheduler s = schedulerSvc.createOrGetFIFOScheduler("test");
assertEquals(0, s.getJobsRunning().size());
assertEquals(0, s.getJobsWaiting().size());
Job job1 = new SleepingJob("job1", null, 500);
Job job2 = new SleepingJob("job2", null, 500);
s.submit(job1);
s.submit(job2);
Thread.sleep(200);
job1.abort();
job2.abort();
Thread.sleep(200);
assertEquals(Status.ABORT, job1.getStatus());
assertEquals(Status.ABORT, job2.getStatus());
assertTrue((500 > (Long)job1.getReturn()));
assertEquals(null, job2.getReturn());
}
public void testRemoveFromWaitingQueue() throws InterruptedException{
Scheduler s = schedulerSvc.createOrGetFIFOScheduler("test");
assertEquals(0, s.getJobsRunning().size());
assertEquals(0, s.getJobsWaiting().size());
Job job1 = new SleepingJob("job1", null, 500);
Job job2 = new SleepingJob("job2", null, 500);
s.submit(job1);
s.submit(job2);
Thread.sleep(200);
job1.abort();
job2.abort();
Thread.sleep(200);
assertEquals(Status.ABORT, job1.getStatus());
assertEquals(Status.ABORT, job2.getStatus());
assertTrue((500 > (Long)job1.getReturn()));
assertEquals(null, job2.getReturn());
}
} | 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-interpreter/src/test/java/org/apache/zeppelin/scheduler/RemoteSchedulerTest.java | smart-zeppelin/zeppelin-interpreter/src/test/java/org/apache/zeppelin/scheduler/RemoteSchedulerTest.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.scheduler;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Properties;
import org.apache.zeppelin.display.AngularObjectRegistry;
import org.apache.zeppelin.interpreter.*;
import org.apache.zeppelin.user.AuthenticationInfo;
import org.apache.zeppelin.display.GUI;
import org.apache.zeppelin.interpreter.remote.RemoteInterpreter;
import org.apache.zeppelin.interpreter.remote.RemoteInterpreterProcessListener;
import org.apache.zeppelin.interpreter.remote.mock.MockInterpreterA;
import org.apache.zeppelin.resource.LocalResourcePool;
import org.apache.zeppelin.scheduler.Job.Status;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class RemoteSchedulerTest implements RemoteInterpreterProcessListener {
private static final String INTERPRETER_SCRIPT =
System.getProperty("os.name").startsWith("Windows") ?
"../bin/interpreter.cmd" :
"../bin/interpreter.sh";
private SchedulerFactory schedulerSvc;
private static final int TICK_WAIT = 100;
private static final int MAX_WAIT_CYCLES = 100;
@Before
public void setUp() throws Exception{
schedulerSvc = new SchedulerFactory();
}
@After
public void tearDown(){
}
@Test
public void test() throws Exception {
Properties p = new Properties();
final InterpreterGroup intpGroup = new InterpreterGroup();
Map<String, String> env = new HashMap<>();
env.put("ZEPPELIN_CLASSPATH", new File("./target/test-classes").getAbsolutePath());
final RemoteInterpreter intpA = new RemoteInterpreter(
p,
"note",
MockInterpreterA.class.getName(),
new File(INTERPRETER_SCRIPT).getAbsolutePath(),
"fake",
"fakeRepo",
env,
10 * 1000,
this,
null,
"anonymous",
false);
intpGroup.put("note", new LinkedList<Interpreter>());
intpGroup.get("note").add(intpA);
intpA.setInterpreterGroup(intpGroup);
intpA.open();
Scheduler scheduler = schedulerSvc.createOrGetRemoteScheduler("test", "note",
intpA.getInterpreterProcess(),
10);
Job job = new Job("jobId", "jobName", null, 200) {
Object results;
@Override
public Object getReturn() {
return results;
}
@Override
public int progress() {
return 0;
}
@Override
public Map<String, Object> info() {
return null;
}
@Override
protected Object jobRun() throws Throwable {
intpA.interpret("1000", new InterpreterContext(
"note",
"jobId",
null,
"title",
"text",
new AuthenticationInfo(),
new HashMap<String, Object>(),
new GUI(),
new AngularObjectRegistry(intpGroup.getId(), null),
new LocalResourcePool("pool1"),
new LinkedList<InterpreterContextRunner>(), null));
return "1000";
}
@Override
protected boolean jobAbort() {
return false;
}
@Override
public void setResult(Object results) {
this.results = results;
}
};
scheduler.submit(job);
int cycles = 0;
while (!job.isRunning() && cycles < MAX_WAIT_CYCLES) {
Thread.sleep(TICK_WAIT);
cycles++;
}
assertTrue(job.isRunning());
Thread.sleep(5*TICK_WAIT);
assertEquals(0, scheduler.getJobsWaiting().size());
assertEquals(1, scheduler.getJobsRunning().size());
cycles = 0;
while (!job.isTerminated() && cycles < MAX_WAIT_CYCLES) {
Thread.sleep(TICK_WAIT);
cycles++;
}
assertTrue(job.isTerminated());
assertEquals(0, scheduler.getJobsWaiting().size());
assertEquals(0, scheduler.getJobsRunning().size());
intpA.close();
schedulerSvc.removeScheduler("test");
}
@Test
public void testAbortOnPending() throws Exception {
Properties p = new Properties();
final InterpreterGroup intpGroup = new InterpreterGroup();
Map<String, String> env = new HashMap<>();
env.put("ZEPPELIN_CLASSPATH", new File("./target/test-classes").getAbsolutePath());
final RemoteInterpreter intpA = new RemoteInterpreter(
p,
"note",
MockInterpreterA.class.getName(),
new File(INTERPRETER_SCRIPT).getAbsolutePath(),
"fake",
"fakeRepo",
env,
10 * 1000,
this,
null,
"anonymous",
false);
intpGroup.put("note", new LinkedList<Interpreter>());
intpGroup.get("note").add(intpA);
intpA.setInterpreterGroup(intpGroup);
intpA.open();
Scheduler scheduler = schedulerSvc.createOrGetRemoteScheduler("test", "note",
intpA.getInterpreterProcess(),
10);
Job job1 = new Job("jobId1", "jobName1", null, 200) {
Object results;
InterpreterContext context = new InterpreterContext(
"note",
"jobId1",
null,
"title",
"text",
new AuthenticationInfo(),
new HashMap<String, Object>(),
new GUI(),
new AngularObjectRegistry(intpGroup.getId(), null),
new LocalResourcePool("pool1"),
new LinkedList<InterpreterContextRunner>(), null);
@Override
public Object getReturn() {
return results;
}
@Override
public int progress() {
return 0;
}
@Override
public Map<String, Object> info() {
return null;
}
@Override
protected Object jobRun() throws Throwable {
intpA.interpret("1000", context);
return "1000";
}
@Override
protected boolean jobAbort() {
if (isRunning()) {
intpA.cancel(context);
}
return true;
}
@Override
public void setResult(Object results) {
this.results = results;
}
};
Job job2 = new Job("jobId2", "jobName2", null, 200) {
public Object results;
InterpreterContext context = new InterpreterContext(
"note",
"jobId2",
null,
"title",
"text",
new AuthenticationInfo(),
new HashMap<String, Object>(),
new GUI(),
new AngularObjectRegistry(intpGroup.getId(), null),
new LocalResourcePool("pool1"),
new LinkedList<InterpreterContextRunner>(), null);
@Override
public Object getReturn() {
return results;
}
@Override
public int progress() {
return 0;
}
@Override
public Map<String, Object> info() {
return null;
}
@Override
protected Object jobRun() throws Throwable {
intpA.interpret("1000", context);
return "1000";
}
@Override
protected boolean jobAbort() {
if (isRunning()) {
intpA.cancel(context);
}
return true;
}
@Override
public void setResult(Object results) {
this.results = results;
}
};
job2.setResult("result2");
scheduler.submit(job1);
scheduler.submit(job2);
int cycles = 0;
while (!job1.isRunning() && cycles < MAX_WAIT_CYCLES) {
Thread.sleep(TICK_WAIT);
cycles++;
}
assertTrue(job1.isRunning());
assertTrue(job2.getStatus() == Status.PENDING);
job2.abort();
cycles = 0;
while (!job1.isTerminated() && cycles < MAX_WAIT_CYCLES) {
Thread.sleep(TICK_WAIT);
cycles++;
}
assertNotNull(job1.getDateFinished());
assertTrue(job1.isTerminated());
assertNull(job2.getDateFinished());
assertTrue(job2.isTerminated());
assertEquals("result2", job2.getReturn());
intpA.close();
schedulerSvc.removeScheduler("test");
}
@Override
public void onOutputAppend(String noteId, String paragraphId, int index, String output) {
}
@Override
public void onOutputUpdated(String noteId, String paragraphId, int index, InterpreterResult.Type type, String output) {
}
@Override
public void onOutputClear(String noteId, String paragraphId) {
}
@Override
public void onMetaInfosReceived(String settingId, Map<String, String> metaInfos) {
}
@Override
public void onGetParagraphRunners(String noteId, String paragraphId, RemoteWorksEventListener callback) {
if (callback != null) {
callback.onFinished(new LinkedList<>());
}
}
@Override
public void onRemoteRunParagraph(String noteId, String PsaragraphID) 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-interpreter/src/test/java/org/apache/zeppelin/scheduler/ParallelSchedulerTest.java | smart-zeppelin/zeppelin-interpreter/src/test/java/org/apache/zeppelin/scheduler/ParallelSchedulerTest.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.scheduler;
import org.apache.zeppelin.scheduler.Job;
import org.apache.zeppelin.scheduler.Scheduler;
import org.apache.zeppelin.scheduler.SchedulerFactory;
import org.apache.zeppelin.scheduler.Job.Status;
import junit.framework.TestCase;
public class ParallelSchedulerTest extends TestCase {
private SchedulerFactory schedulerSvc;
@Override
public void setUp() throws Exception{
schedulerSvc = new SchedulerFactory();
}
@Override
public void tearDown(){
}
public void testRun() throws InterruptedException{
Scheduler s = schedulerSvc.createOrGetParallelScheduler("test", 2);
assertEquals(0, s.getJobsRunning().size());
assertEquals(0, s.getJobsWaiting().size());
Job job1 = new SleepingJob("job1", null, 500);
Job job2 = new SleepingJob("job2", null, 500);
Job job3 = new SleepingJob("job3", null, 500);
s.submit(job1);
s.submit(job2);
s.submit(job3);
Thread.sleep(200);
assertEquals(Status.RUNNING, job1.getStatus());
assertEquals(Status.RUNNING, job2.getStatus());
assertEquals(Status.PENDING, job3.getStatus());
assertEquals(2, s.getJobsRunning().size());
assertEquals(1, s.getJobsWaiting().size());
Thread.sleep(500);
assertEquals(Status.FINISHED, job1.getStatus());
assertEquals(Status.FINISHED, job2.getStatus());
assertEquals(Status.RUNNING, job3.getStatus());
assertEquals(1, s.getJobsRunning().size());
assertEquals(0, s.getJobsWaiting().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-interpreter/src/test/java/org/apache/zeppelin/scheduler/SleepingJob.java | smart-zeppelin/zeppelin-interpreter/src/test/java/org/apache/zeppelin/scheduler/SleepingJob.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.scheduler;
import java.util.HashMap;
import java.util.Map;
import org.apache.zeppelin.scheduler.Job;
import org.apache.zeppelin.scheduler.JobListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SleepingJob extends Job{
private int time;
boolean abort = false;
private long start;
private int count;
static Logger LOGGER = LoggerFactory.getLogger(SleepingJob.class);
private Object results;
public SleepingJob(String jobName, JobListener listener, int time){
super(jobName, listener);
this.time = time;
count = 0;
}
@Override
public Object jobRun() {
start = System.currentTimeMillis();
while(abort==false){
count++;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
LOGGER.error("Exception in MockInterpreterAngular while interpret Thread.sleep", e);
}
if(System.currentTimeMillis() - start>time) break;
}
return System.currentTimeMillis()-start;
}
@Override
public boolean jobAbort() {
abort = true;
return true;
}
@Override
public void setResult(Object results) {
this.results = results;
}
@Override
public Object getReturn() {
return results;
}
@Override
public int progress() {
long p = (System.currentTimeMillis() - start)*100 / time;
if(p<0) p = 0;
if(p>100) p = 100;
return (int) p;
}
@Override
public Map<String, Object> info() {
Map<String, Object> i = new HashMap<>();
i.put("LoopCount", Integer.toString(count));
return i;
}
}
| 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-interpreter/src/test/java/org/apache/zeppelin/dep/BooterTest.java | smart-zeppelin/zeppelin-interpreter/src/test/java/org/apache/zeppelin/dep/BooterTest.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.dep;
import org.junit.Test;
import java.nio.file.Paths;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
public class BooterTest {
@Test
public void should_return_absolute_path() {
String resolvedPath = Booter.resolveLocalRepoPath("path");
assertTrue(Paths.get(resolvedPath).isAbsolute());
}
@Test
public void should_not_change_absolute_path() {
String absolutePath
= Paths.get("first", "second").toAbsolutePath().toString();
String resolvedPath = Booter.resolveLocalRepoPath(absolutePath);
assertThat(resolvedPath, equalTo(absolutePath));
}
@Test(expected = NullPointerException.class)
public void should_throw_exception_for_null() {
Booter.resolveLocalRepoPath(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-interpreter/src/test/java/org/apache/zeppelin/dep/DependencyResolverTest.java | smart-zeppelin/zeppelin-interpreter/src/test/java/org/apache/zeppelin/dep/DependencyResolverTest.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.dep;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Collections;
import org.apache.commons.io.FileUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.sonatype.aether.RepositoryException;
public class DependencyResolverTest {
private static DependencyResolver resolver;
private static String testPath;
private static File testCopyPath;
private static File tmpDir;
@Rule
public ExpectedException expectedException = ExpectedException.none();
@BeforeClass
public static void setUp() throws Exception {
tmpDir = new File(System.getProperty("java.io.tmpdir")+"/ZeppelinLTest_"+System.currentTimeMillis());
testPath = tmpDir.getAbsolutePath() + "/test-repo";
testCopyPath = new File(tmpDir, "test-copy-repo");
resolver = new DependencyResolver(testPath);
}
@AfterClass
public static void tearDown() throws Exception {
FileUtils.deleteDirectory(tmpDir);
}
@Rule
public final ExpectedException exception = ExpectedException.none();
@Test
public void testAddRepo() {
int reposCnt = resolver.getRepos().size();
resolver.addRepo("securecentral", "https://repo1.maven.org/maven2", false);
assertEquals(reposCnt + 1, resolver.getRepos().size());
}
@Test
public void testDelRepo() {
int reposCnt = resolver.getRepos().size();
resolver.delRepo("securecentral");
resolver.delRepo("badId");
assertEquals(reposCnt - 1, resolver.getRepos().size());
}
@Test
public void testLoad() throws Exception {
// basic load
resolver.load("com.databricks:spark-csv_2.10:1.3.0", testCopyPath);
assertEquals(testCopyPath.list().length, 4);
FileUtils.cleanDirectory(testCopyPath);
// load with exclusions parameter
resolver.load("com.databricks:spark-csv_2.10:1.3.0",
Collections.singletonList("org.scala-lang:scala-library"), testCopyPath);
assertEquals(testCopyPath.list().length, 3);
FileUtils.cleanDirectory(testCopyPath);
// load from added repository
resolver.addRepo("sonatype", "https://oss.sonatype.org/content/repositories/agimatec-releases/", false);
resolver.load("com.agimatec:agimatec-validation:0.9.3", testCopyPath);
assertEquals(testCopyPath.list().length, 8);
// load invalid artifact
resolver.delRepo("sonatype");
exception.expect(RepositoryException.class);
resolver.load("com.agimatec:agimatec-validation:0.9.3", testCopyPath);
}
@Test
public void should_throw_exception_if_dependency_not_found() throws Exception {
expectedException.expectMessage("Source 'one.two:1.0' does not exist");
expectedException.expect(FileNotFoundException.class);
resolver.load("one.two:1.0", testCopyPath);
}
} | 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-interpreter/src/test/java/org/apache/zeppelin/interpreter/InterpreterTest.java | smart-zeppelin/zeppelin-interpreter/src/test/java/org/apache/zeppelin/interpreter/InterpreterTest.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;
import static org.junit.Assert.assertEquals;
import java.util.Properties;
import org.apache.zeppelin.interpreter.remote.mock.MockInterpreterA;
import org.junit.Test;
public class InterpreterTest {
@Test
public void testDefaultProperty() {
Properties p = new Properties();
p.put("p1", "v1");
MockInterpreterA intp = new MockInterpreterA(p);
assertEquals(1, intp.getProperty().size());
assertEquals("v1", intp.getProperty().get("p1"));
assertEquals("v1", intp.getProperty("p1"));
}
@Test
public void testOverriddenProperty() {
Properties p = new Properties();
p.put("p1", "v1");
MockInterpreterA intp = new MockInterpreterA(p);
Properties overriddenProperty = new Properties();
overriddenProperty.put("p1", "v2");
intp.setProperty(overriddenProperty);
assertEquals(1, intp.getProperty().size());
assertEquals("v2", intp.getProperty().get("p1"));
assertEquals("v2", intp.getProperty("p1"));
}
}
| 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-interpreter/src/test/java/org/apache/zeppelin/interpreter/InterpreterResultTest.java | smart-zeppelin/zeppelin-interpreter/src/test/java/org/apache/zeppelin/interpreter/InterpreterResultTest.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;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Test;
public class InterpreterResultTest {
@Test
public void testTextType() {
InterpreterResult result = new InterpreterResult(InterpreterResult.Code.SUCCESS, "this is a TEXT type");
assertEquals("No magic", InterpreterResult.Type.TEXT, result.message().get(0).getType());
result = new InterpreterResult(InterpreterResult.Code.SUCCESS, "%this is a TEXT type");
assertEquals("No magic", InterpreterResult.Type.TEXT, result.message().get(0).getType());
result = new InterpreterResult(InterpreterResult.Code.SUCCESS, "%\n");
assertEquals("No magic", InterpreterResult.Type.TEXT, result.message().get(0).getType());
}
@Test
public void testSimpleMagicType() {
InterpreterResult result = null;
result = new InterpreterResult(InterpreterResult.Code.SUCCESS, "%table col1\tcol2\naaa\t123\n");
assertEquals(InterpreterResult.Type.TABLE, result.message().get(0).getType());
result = new InterpreterResult(InterpreterResult.Code.SUCCESS, "%table\ncol1\tcol2\naaa\t123\n");
assertEquals(InterpreterResult.Type.TABLE, result.message().get(0).getType());
result = new InterpreterResult(InterpreterResult.Code.SUCCESS, "some text before magic word\n%table col1\tcol2\naaa\t123\n");
assertEquals(InterpreterResult.Type.TABLE, result.message().get(1).getType());
}
public void testComplexMagicType() {
InterpreterResult result = null;
result = new InterpreterResult(InterpreterResult.Code.SUCCESS, "some text before %table col1\tcol2\naaa\t123\n");
assertEquals("some text before magic return magic", InterpreterResult.Type.TABLE, result.message().get(0).getType());
result = new InterpreterResult(InterpreterResult.Code.SUCCESS, "%html <h3> This is a hack </h3> %table\n col1\tcol2\naaa\t123\n");
assertEquals("magic A before magic B return magic A", InterpreterResult.Type.HTML, result.message().get(0).getType());
result = new InterpreterResult(InterpreterResult.Code.SUCCESS, "some text before magic word %table col1\tcol2\naaa\t123\n %html <h3> This is a hack </h3>");
assertEquals("text & magic A before magic B return magic A", InterpreterResult.Type.TABLE, result.message().get(0).getType());
result = new InterpreterResult(InterpreterResult.Code.SUCCESS, "%table col1\tcol2\naaa\t123\n %html <h3> This is a hack </h3> %table col1\naaa\n123\n");
assertEquals("magic A, magic B, magic a' return magic A", InterpreterResult.Type.TABLE, result.message().get(0).getType());
}
@Test
public void testSimpleMagicData() {
InterpreterResult result = null;
result = new InterpreterResult(InterpreterResult.Code.SUCCESS, "%table col1\tcol2\naaa\t123\n");
assertEquals("%table col1\tcol2\naaa\t123\n", "col1\tcol2\naaa\t123\n", result.message().get(0).getData());
result = new InterpreterResult(InterpreterResult.Code.SUCCESS, "%table\ncol1\tcol2\naaa\t123\n");
assertEquals("%table\ncol1\tcol2\naaa\t123\n", "col1\tcol2\naaa\t123\n", result.message().get(0).getData());
result = new InterpreterResult(InterpreterResult.Code.SUCCESS, "some text before magic word\n%table col1\tcol2\naaa\t123\n");
assertEquals("some text before magic word\n%table col1\tcol2\naaa\t123\n", "col1\tcol2\naaa\t123\n", result.message().get(1).getData());
}
@Test
public void testComplexMagicData() {
InterpreterResult result = null;
result = new InterpreterResult(InterpreterResult.Code.SUCCESS, "some text before\n%table col1\tcol2\naaa\t123\n");
assertEquals("text before %table", "some text before\n", result.message().get(0).getData());
assertEquals("text after %table", "col1\tcol2\naaa\t123\n", result.message().get(1).getData());
result = new InterpreterResult(InterpreterResult.Code.SUCCESS, "%html <h3> This is a hack </h3>\n%table\ncol1\tcol2\naaa\t123\n");
assertEquals(" <h3> This is a hack </h3>\n", result.message().get(0).getData());
assertEquals("col1\tcol2\naaa\t123\n", result.message().get(1).getData());
result = new InterpreterResult(InterpreterResult.Code.SUCCESS, "some text before magic word\n%table col1\tcol2\naaa\t123\n\n%html <h3> This is a hack </h3>");
assertEquals("<h3> This is a hack </h3>", result.message().get(2).getData());
result = new InterpreterResult(InterpreterResult.Code.SUCCESS, "%table col1\tcol2\naaa\t123\n\n%html <h3> This is a hack </h3>\n%table col1\naaa\n123\n");
assertEquals("col1\naaa\n123\n", result.message().get(2).getData());
result = new InterpreterResult(InterpreterResult.Code.SUCCESS, "%table " + "col1\tcol2\naaa\t123\n\n%table col1\naaa\n123\n");
assertEquals("col1\tcol2\naaa\t123\n", result.message().get(0).getData());
assertEquals("col1\naaa\n123\n", result.message().get(1).getData());
}
@Test
public void testToString() {
assertEquals("%html hello", new InterpreterResult(InterpreterResult.Code.SUCCESS, "%html hello").toString());
}
}
| 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-interpreter/src/test/java/org/apache/zeppelin/interpreter/InterpreterOutputTest.java | smart-zeppelin/zeppelin-interpreter/src/test/java/org/apache/zeppelin/interpreter/InterpreterOutputTest.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;
import static org.junit.Assert.*;
import java.io.IOException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class InterpreterOutputTest implements InterpreterOutputListener {
private InterpreterOutput out;
int numAppendEvent;
int numUpdateEvent;
@Before
public void setUp() {
out = new InterpreterOutput(this);
numAppendEvent = 0;
numUpdateEvent = 0;
}
@After
public void tearDown() throws IOException {
out.close();
}
@Test
public void testDetectNewline() throws IOException {
out.write("hello\nworld");
assertEquals(1, out.size());
assertEquals(InterpreterResult.Type.TEXT, out.getOutputAt(0).getType());
assertEquals("hello\n", new String(out.getOutputAt(0).toByteArray()));
assertEquals(1, numAppendEvent);
assertEquals(1, numUpdateEvent);
out.write("\n");
assertEquals("hello\nworld\n", new String(out.getOutputAt(0).toByteArray()));
assertEquals(2, numAppendEvent);
assertEquals(1, numUpdateEvent);
}
@Test
public void testFlush() throws IOException {
out.write("hello\nworld");
assertEquals("hello\n", new String(out.getOutputAt(0).toByteArray()));
assertEquals(1, numAppendEvent);
assertEquals(1, numUpdateEvent);
out.flush();
assertEquals("hello\nworld", new String(out.getOutputAt(0).toByteArray()));
assertEquals(2, numAppendEvent);
assertEquals(1, numUpdateEvent);
out.clear();
out.write("%html div");
assertEquals("", new String(out.getOutputAt(0).toByteArray()));
assertEquals(InterpreterResult.Type.HTML, out.getOutputAt(0).getType());
out.flush();
assertEquals("div", new String(out.getOutputAt(0).toByteArray()));
}
@Test
public void testType() throws IOException {
// default output stream type is TEXT
out.write("Text\n");
assertEquals(InterpreterResult.Type.TEXT, out.getOutputAt(0).getType());
assertEquals("Text\n", new String(out.getOutputAt(0).toByteArray()));
assertEquals(1, numAppendEvent);
assertEquals(1, numUpdateEvent);
// change type
out.write("%html\n");
assertEquals(InterpreterResult.Type.HTML, out.getOutputAt(1).getType());
assertEquals("", new String(out.getOutputAt(1).toByteArray()));
assertEquals(1, numAppendEvent);
assertEquals(1, numUpdateEvent);
// none TEXT type output stream does not generate append event
out.write("<div>html</div>\n");
assertEquals(InterpreterResult.Type.HTML, out.getOutputAt(1).getType());
assertEquals(1, numAppendEvent);
assertEquals(2, numUpdateEvent);
out.flush();
assertEquals("<div>html</div>\n", new String(out.getOutputAt(1).toByteArray()));
// change type to text again
out.write("%text hello\n");
assertEquals(InterpreterResult.Type.TEXT, out.getOutputAt(2).getType());
assertEquals(2, numAppendEvent);
assertEquals(4, numUpdateEvent);
assertEquals("hello\n", new String(out.getOutputAt(2).toByteArray()));
}
@Test
public void testChangeTypeInTheBeginning() throws IOException {
out.write("%html\nHello");
assertEquals(InterpreterResult.Type.HTML, out.getOutputAt(0).getType());
}
@Test
public void testChangeTypeWithMultipleNewline() throws IOException {
out.write("%html\n");
assertEquals(InterpreterResult.Type.HTML, out.getOutputAt(0).getType());
out.write("%text\n");
assertEquals(InterpreterResult.Type.TEXT, out.getOutputAt(1).getType());
out.write("\n%html\n");
assertEquals(InterpreterResult.Type.HTML, out.getOutputAt(2).getType());
out.write("\n\n%text\n");
assertEquals(InterpreterResult.Type.TEXT, out.getOutputAt(3).getType());
out.write("\n\n\n%html\n");
assertEquals(InterpreterResult.Type.HTML, out.getOutputAt(4).getType());
}
@Test
public void testChangeTypeWithoutData() throws IOException {
out.write("%html\n%table\n");
assertEquals(InterpreterResult.Type.HTML, out.getOutputAt(0).getType());
assertEquals(InterpreterResult.Type.TABLE, out.getOutputAt(1).getType());
}
@Test
public void testMagicData() throws IOException {
out.write("%table col1\tcol2\n\n%html <h3> This is a hack </h3>\t234\n".getBytes());
assertEquals(InterpreterResult.Type.TABLE, out.getOutputAt(0).getType());
assertEquals(InterpreterResult.Type.HTML, out.getOutputAt(1).getType());
assertEquals("col1\tcol2\n", new String(out.getOutputAt(0).toByteArray()));
out.flush();
assertEquals("<h3> This is a hack </h3>\t234\n", new String(out.getOutputAt(1).toByteArray()));
}
@Test
public void testTableCellFormatting() throws IOException {
out.write("%table col1\tcol2\n\n%html val1\tval2\n".getBytes());
assertEquals(InterpreterResult.Type.TABLE, out.getOutputAt(0).getType());
assertEquals("col1\tcol2\n", new String(out.getOutputAt(0).toByteArray()));
out.flush();
assertEquals("val1\tval2\n", new String(out.getOutputAt(1).toByteArray()));
}
@Test
public void testTruncate() throws IOException {
// output is truncated after the new line
InterpreterOutput.limit = 3;
out = new InterpreterOutput(this);
// truncate text
out.write("%text hello\nworld\n");
assertEquals("hello", new String(out.getOutputAt(0).toByteArray()));
assertTrue(new String(out.getOutputAt(1).toByteArray()).contains("Truncated"));
// truncate table
out = new InterpreterOutput(this);
out.write("%table key\tvalue\nhello\t100\nworld\t200\n");
assertEquals("key\tvalue", new String(out.getOutputAt(0).toByteArray()));
assertTrue(new String(out.getOutputAt(1).toByteArray()).contains("Truncated"));
// does not truncate html
out = new InterpreterOutput(this);
out.write("%html hello\nworld\n");
out.flush();
assertEquals("hello\nworld\n", new String(out.getOutputAt(0).toByteArray()));
// restore default
InterpreterOutput.limit = Constants.ZEPPELIN_INTERPRETER_OUTPUT_LIMIT;
}
@Override
public void onUpdateAll(InterpreterOutput out) {
}
@Override
public void onAppend(int index, InterpreterResultMessageOutput out, byte[] line) {
numAppendEvent++;
}
@Override
public void onUpdate(int index, InterpreterResultMessageOutput out) {
numUpdateEvent++;
}
} | 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-interpreter/src/test/java/org/apache/zeppelin/interpreter/InterpreterHookRegistryTest.java | smart-zeppelin/zeppelin-interpreter/src/test/java/org/apache/zeppelin/interpreter/InterpreterHookRegistryTest.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;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
public class InterpreterHookRegistryTest {
@Test
public void testBasic() {
final String PRE_EXEC = InterpreterHookRegistry.HookType.PRE_EXEC;
final String POST_EXEC = InterpreterHookRegistry.HookType.POST_EXEC;
final String PRE_EXEC_DEV = InterpreterHookRegistry.HookType.PRE_EXEC_DEV;
final String POST_EXEC_DEV = InterpreterHookRegistry.HookType.POST_EXEC_DEV;
final String GLOBAL_KEY = InterpreterHookRegistry.GLOBAL_KEY;
final String noteId = "note";
final String className = "class";
final String preExecHook = "pre";
final String postExecHook = "post";
InterpreterHookRegistry registry = new InterpreterHookRegistry("intpId");
// Test register()
registry.register(noteId, className, PRE_EXEC, preExecHook);
registry.register(noteId, className, POST_EXEC, postExecHook);
registry.register(noteId, className, PRE_EXEC_DEV, preExecHook);
registry.register(noteId, className, POST_EXEC_DEV, postExecHook);
// Test get()
assertEquals(registry.get(noteId, className, PRE_EXEC), preExecHook);
assertEquals(registry.get(noteId, className, POST_EXEC), postExecHook);
assertEquals(registry.get(noteId, className, PRE_EXEC_DEV), preExecHook);
assertEquals(registry.get(noteId, className, POST_EXEC_DEV), postExecHook);
// Test Unregister
registry.unregister(noteId, className, PRE_EXEC);
registry.unregister(noteId, className, POST_EXEC);
registry.unregister(noteId, className, PRE_EXEC_DEV);
registry.unregister(noteId, className, POST_EXEC_DEV);
assertNull(registry.get(noteId, className, PRE_EXEC));
assertNull(registry.get(noteId, className, POST_EXEC));
assertNull(registry.get(noteId, className, PRE_EXEC_DEV));
assertNull(registry.get(noteId, className, POST_EXEC_DEV));
// Test Global Scope
registry.register(null, className, PRE_EXEC, preExecHook);
assertEquals(registry.get(GLOBAL_KEY, className, PRE_EXEC), preExecHook);
}
@Test(expected = IllegalArgumentException.class)
public void testValidEventCode() {
InterpreterHookRegistry registry = new InterpreterHookRegistry("intpId");
// Test that only valid event codes ("pre_exec", "post_exec") are accepted
registry.register("foo", "bar", "baz", "whatever");
}
}
| 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-interpreter/src/test/java/org/apache/zeppelin/interpreter/InterpreterOutputChangeWatcherTest.java | smart-zeppelin/zeppelin-interpreter/src/test/java/org/apache/zeppelin/interpreter/InterpreterOutputChangeWatcherTest.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;
import static org.junit.Assert.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class InterpreterOutputChangeWatcherTest implements InterpreterOutputChangeListener {
private File tmpDir;
private File fileChanged;
private int numChanged;
private InterpreterOutputChangeWatcher watcher;
@Before
public void setUp() throws Exception {
watcher = new InterpreterOutputChangeWatcher(this);
watcher.start();
tmpDir = new File(System.getProperty("java.io.tmpdir")+"/ZeppelinLTest_"+System.currentTimeMillis());
tmpDir.mkdirs();
fileChanged = null;
numChanged = 0;
}
@After
public void tearDown() throws Exception {
watcher.shutdown();
delete(tmpDir);
}
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();
}
}
@Test
public void test() throws IOException, InterruptedException {
assertNull(fileChanged);
assertEquals(0, numChanged);
Thread.sleep(1000);
// create new file
File file1 = new File(tmpDir, "test1");
file1.createNewFile();
File file2 = new File(tmpDir, "test2");
file2.createNewFile();
watcher.watch(file1);
Thread.sleep(1000);
FileOutputStream out1 = new FileOutputStream(file1);
out1.write(1);
out1.close();
FileOutputStream out2 = new FileOutputStream(file2);
out2.write(1);
out2.close();
synchronized (this) {
wait(30*1000);
}
assertNotNull(fileChanged);
assertEquals(1, numChanged);
}
@Override
public void fileChanged(File file) {
fileChanged = file;
numChanged++;
synchronized(this) {
notify();
}
}
} | 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-interpreter/src/test/java/org/apache/zeppelin/interpreter/InterpreterContextTest.java | smart-zeppelin/zeppelin-interpreter/src/test/java/org/apache/zeppelin/interpreter/InterpreterContextTest.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;
import static org.junit.Assert.*;
import org.junit.Test;
public class InterpreterContextTest {
@Test
public void testThreadLocal() {
assertNull(InterpreterContext.get());
InterpreterContext.set(new InterpreterContext(null, null, null, null, null, null, null, null, null, null, null, null));
assertNotNull(InterpreterContext.get());
InterpreterContext.remove();
assertNull(InterpreterContext.get());
}
}
| 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-interpreter/src/test/java/org/apache/zeppelin/interpreter/LazyOpenInterpreterTest.java | smart-zeppelin/zeppelin-interpreter/src/test/java/org/apache/zeppelin/interpreter/LazyOpenInterpreterTest.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;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class LazyOpenInterpreterTest {
Interpreter interpreter = mock(Interpreter.class);
@Test
public void isOpenTest() {
InterpreterResult interpreterResult = new InterpreterResult(InterpreterResult.Code.SUCCESS, "");
when(interpreter.interpret(any(String.class), any(InterpreterContext.class))).thenReturn(interpreterResult);
LazyOpenInterpreter lazyOpenInterpreter = new LazyOpenInterpreter(interpreter);
assertFalse("Interpreter is not open", lazyOpenInterpreter.isOpen());
InterpreterContext interpreterContext =
new InterpreterContext("note", "id", null, "title", "text", null, null, null, null, null, null, null);
lazyOpenInterpreter.interpret("intp 1", interpreterContext);
assertTrue("Interpeter is open", lazyOpenInterpreter.isOpen());
}
} | 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-interpreter/src/test/java/org/apache/zeppelin/interpreter/remote/RemoteAngularObjectTest.java | smart-zeppelin/zeppelin-interpreter/src/test/java/org/apache/zeppelin/interpreter/remote/RemoteAngularObjectTest.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.remote;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.zeppelin.display.*;
import org.apache.zeppelin.interpreter.*;
import org.apache.zeppelin.interpreter.remote.mock.MockInterpreterAngular;
import org.apache.zeppelin.resource.LocalResourcePool;
import org.apache.zeppelin.user.AuthenticationInfo;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class RemoteAngularObjectTest implements AngularObjectRegistryListener {
private static final String INTERPRETER_SCRIPT =
System.getProperty("os.name").startsWith("Windows") ?
"../bin/interpreter.cmd" :
"../bin/interpreter.sh";
private InterpreterGroup intpGroup;
private HashMap<String, String> env;
private RemoteInterpreter intp;
private InterpreterContext context;
private RemoteAngularObjectRegistry localRegistry;
private AtomicInteger onAdd;
private AtomicInteger onUpdate;
private AtomicInteger onRemove;
@Before
public void setUp() throws Exception {
onAdd = new AtomicInteger(0);
onUpdate = new AtomicInteger(0);
onRemove = new AtomicInteger(0);
intpGroup = new InterpreterGroup("intpId");
localRegistry = new RemoteAngularObjectRegistry("intpId", this, intpGroup);
intpGroup.setAngularObjectRegistry(localRegistry);
env = new HashMap<>();
env.put("ZEPPELIN_CLASSPATH", new File("./target/test-classes").getAbsolutePath());
Properties p = new Properties();
intp = new RemoteInterpreter(
p,
"note",
MockInterpreterAngular.class.getName(),
new File(INTERPRETER_SCRIPT).getAbsolutePath(),
"fake",
"fakeRepo",
env,
10 * 1000,
null,
null,
"anonymous",
false
);
intpGroup.put("note", new LinkedList<Interpreter>());
intpGroup.get("note").add(intp);
intp.setInterpreterGroup(intpGroup);
context = new InterpreterContext(
"note",
"id",
null,
"title",
"text",
new AuthenticationInfo(),
new HashMap<String, Object>(),
new GUI(),
new AngularObjectRegistry(intpGroup.getId(), null),
new LocalResourcePool("pool1"),
new LinkedList<InterpreterContextRunner>(), null);
intp.open();
}
@After
public void tearDown() throws Exception {
intp.close();
intpGroup.close();
}
@Test
public void testAngularObjectInterpreterSideCRUD() throws InterruptedException {
InterpreterResult ret = intp.interpret("get", context);
Thread.sleep(500); // waitFor eventpoller pool event
String[] result = ret.message().get(0).getData().split(" ");
assertEquals("0", result[0]); // size of registry
assertEquals("0", result[1]); // num watcher called
// create object
ret = intp.interpret("add n1 v1", context);
Thread.sleep(500);
result = ret.message().get(0).getData().split(" ");
assertEquals("1", result[0]); // size of registry
assertEquals("0", result[1]); // num watcher called
assertEquals("v1", localRegistry.get("n1", "note", null).get());
// update object
ret = intp.interpret("update n1 v11", context);
result = ret.message().get(0).getData().split(" ");
Thread.sleep(500);
assertEquals("1", result[0]); // size of registry
assertEquals("1", result[1]); // num watcher called
assertEquals("v11", localRegistry.get("n1", "note", null).get());
// remove object
ret = intp.interpret("remove n1", context);
result = ret.message().get(0).getData().split(" ");
Thread.sleep(500);
assertEquals("0", result[0]); // size of registry
assertEquals("1", result[1]); // num watcher called
assertEquals(null, localRegistry.get("n1", "note", null));
}
@Test
public void testAngularObjectRemovalOnZeppelinServerSide() throws InterruptedException {
// test if angularobject removal from server side propagate to interpreter process's registry.
// will happen when notebook is removed.
InterpreterResult ret = intp.interpret("get", context);
Thread.sleep(500); // waitFor eventpoller pool event
String[] result = ret.message().get(0).getData().split(" ");
assertEquals("0", result[0]); // size of registry
// create object
ret = intp.interpret("add n1 v1", context);
Thread.sleep(500);
result = ret.message().get(0).getData().split(" ");
assertEquals("1", result[0]); // size of registry
assertEquals("v1", localRegistry.get("n1", "note", null).get());
// remove object in local registry.
localRegistry.removeAndNotifyRemoteProcess("n1", "note", null);
ret = intp.interpret("get", context);
Thread.sleep(500); // waitFor eventpoller pool event
result = ret.message().get(0).getData().split(" ");
assertEquals("0", result[0]); // size of registry
}
@Test
public void testAngularObjectAddOnZeppelinServerSide() throws InterruptedException {
// test if angularobject add from server side propagate to interpreter process's registry.
// will happen when zeppelin server loads notebook and restore the object into registry
InterpreterResult ret = intp.interpret("get", context);
Thread.sleep(500); // waitFor eventpoller pool event
String[] result = ret.message().get(0).getData().split(" ");
assertEquals("0", result[0]); // size of registry
// create object
localRegistry.addAndNotifyRemoteProcess("n1", "v1", "note", null);
// get from remote registry
ret = intp.interpret("get", context);
Thread.sleep(500); // waitFor eventpoller pool event
result = ret.message().get(0).getData().split(" ");
assertEquals("1", result[0]); // size of registry
}
@Override
public void onAdd(String interpreterGroupId, AngularObject object) {
onAdd.incrementAndGet();
}
@Override
public void onUpdate(String interpreterGroupId, AngularObject object) {
onUpdate.incrementAndGet();
}
@Override
public void onRemove(String interpreterGroupId, String name, String noteId, String paragraphId) {
onRemove.incrementAndGet();
}
}
| 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-interpreter/src/test/java/org/apache/zeppelin/interpreter/remote/RemoteInterpreterTest.java | smart-zeppelin/zeppelin-interpreter/src/test/java/org/apache/zeppelin/interpreter/remote/RemoteInterpreterTest.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.remote;
import static org.junit.Assert.*;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.thrift.transport.TTransportException;
import org.apache.zeppelin.display.AngularObject;
import org.apache.zeppelin.display.AngularObjectRegistry;
import org.apache.zeppelin.interpreter.remote.mock.MockInterpreterEnv;
import org.apache.zeppelin.interpreter.thrift.RemoteInterpreterResultMessage;
import org.apache.zeppelin.interpreter.thrift.RemoteInterpreterService;
import org.apache.zeppelin.interpreter.thrift.RemoteInterpreterService.Client;
import org.apache.zeppelin.user.AuthenticationInfo;
import org.apache.zeppelin.display.GUI;
import org.apache.zeppelin.interpreter.*;
import org.apache.zeppelin.interpreter.InterpreterResult.Code;
import org.apache.zeppelin.interpreter.remote.mock.MockInterpreterA;
import org.apache.zeppelin.interpreter.remote.mock.MockInterpreterB;
import org.apache.zeppelin.resource.LocalResourcePool;
import org.apache.zeppelin.scheduler.Job;
import org.apache.zeppelin.scheduler.Job.Status;
import org.apache.zeppelin.scheduler.Scheduler;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class RemoteInterpreterTest {
private static final String INTERPRETER_SCRIPT =
System.getProperty("os.name").startsWith("Windows") ?
"../bin/interpreter.cmd" :
"../bin/interpreter.sh";
private InterpreterGroup intpGroup;
private HashMap<String, String> env;
@Before
public void setUp() throws Exception {
intpGroup = new InterpreterGroup();
env = new HashMap<>();
env.put("ZEPPELIN_CLASSPATH", new File("./target/test-classes").getAbsolutePath());
}
@After
public void tearDown() throws Exception {
intpGroup.close();
}
private RemoteInterpreter createMockInterpreterA(Properties p) {
return createMockInterpreterA(p, "note");
}
private RemoteInterpreter createMockInterpreterA(Properties p, String noteId) {
return new RemoteInterpreter(
p,
noteId,
MockInterpreterA.class.getName(),
new File(INTERPRETER_SCRIPT).getAbsolutePath(),
"fake",
"fakeRepo",
env,
10 * 1000,
null,
null,
"anonymous",
false);
}
private RemoteInterpreter createMockInterpreterB(Properties p) {
return createMockInterpreterB(p, "note");
}
private RemoteInterpreter createMockInterpreterB(Properties p, String noteId) {
return new RemoteInterpreter(
p,
noteId,
MockInterpreterB.class.getName(),
new File(INTERPRETER_SCRIPT).getAbsolutePath(),
"fake",
"fakeRepo",
env,
10 * 1000,
null,
null,
"anonymous",
false);
}
@Test
public void testRemoteInterperterCall() throws TTransportException, IOException {
Properties p = new Properties();
intpGroup.put("note", new LinkedList<Interpreter>());
RemoteInterpreter intpA = createMockInterpreterA(p);
intpGroup.get("note").add(intpA);
intpA.setInterpreterGroup(intpGroup);
RemoteInterpreter intpB = createMockInterpreterB(p);
intpGroup.get("note").add(intpB);
intpB.setInterpreterGroup(intpGroup);
RemoteInterpreterProcess process = intpA.getInterpreterProcess();
process.equals(intpB.getInterpreterProcess());
assertFalse(process.isRunning());
assertEquals(0, process.getNumIdleClient());
assertEquals(0, process.referenceCount());
intpA.open(); // initializa all interpreters in the same group
assertTrue(process.isRunning());
assertEquals(1, process.getNumIdleClient());
assertEquals(1, process.referenceCount());
intpA.interpret("1",
new InterpreterContext(
"note",
"id",
null,
"title",
"text",
new AuthenticationInfo(),
new HashMap<String, Object>(),
new GUI(),
new AngularObjectRegistry(intpGroup.getId(), null),
new LocalResourcePool("pool1"),
new LinkedList<InterpreterContextRunner>(), null));
intpB.open();
assertEquals(1, process.referenceCount());
intpA.close();
assertEquals(0, process.referenceCount());
intpB.close();
assertEquals(0, process.referenceCount());
assertFalse(process.isRunning());
}
@Test
public void testRemoteInterperterErrorStatus() throws TTransportException, IOException {
Properties p = new Properties();
RemoteInterpreter intpA = createMockInterpreterA(p);
intpGroup.put("note", new LinkedList<Interpreter>());
intpGroup.get("note").add(intpA);
intpA.setInterpreterGroup(intpGroup);
intpA.open();
InterpreterResult ret = intpA.interpret("non numeric value",
new InterpreterContext(
"noteId",
"id",
null,
"title",
"text",
new AuthenticationInfo(),
new HashMap<String, Object>(),
new GUI(),
new AngularObjectRegistry(intpGroup.getId(), null),
new LocalResourcePool("pool1"),
new LinkedList<InterpreterContextRunner>(), null));
assertEquals(Code.ERROR, ret.code());
}
@Test
public void testRemoteSchedulerSharing() throws TTransportException, IOException {
Properties p = new Properties();
intpGroup.put("note", new LinkedList<Interpreter>());
RemoteInterpreter intpA = new RemoteInterpreter(
p,
"note",
MockInterpreterA.class.getName(),
new File(INTERPRETER_SCRIPT).getAbsolutePath(),
"fake",
"fakeRepo",
env,
10 * 1000,
null,
null,
"anonymous",
false);
intpGroup.get("note").add(intpA);
intpA.setInterpreterGroup(intpGroup);
RemoteInterpreter intpB = new RemoteInterpreter(
p,
"note",
MockInterpreterB.class.getName(),
new File(INTERPRETER_SCRIPT).getAbsolutePath(),
"fake",
"fakeRepo",
env,
10 * 1000,
null,
null,
"anonymous",
false);
intpGroup.get("note").add(intpB);
intpB.setInterpreterGroup(intpGroup);
intpA.open();
intpB.open();
long start = System.currentTimeMillis();
InterpreterResult ret = intpA.interpret("500",
new InterpreterContext(
"note",
"id",
null,
"title",
"text",
new AuthenticationInfo(),
new HashMap<String, Object>(),
new GUI(),
new AngularObjectRegistry(intpGroup.getId(), null),
new LocalResourcePool("pool1"),
new LinkedList<InterpreterContextRunner>(), null));
assertEquals("500", ret.message().get(0).getData());
ret = intpB.interpret("500",
new InterpreterContext(
"note",
"id",
null,
"title",
"text",
new AuthenticationInfo(),
new HashMap<String, Object>(),
new GUI(),
new AngularObjectRegistry(intpGroup.getId(), null),
new LocalResourcePool("pool1"),
new LinkedList<InterpreterContextRunner>(), null));
assertEquals("1000", ret.message().get(0).getData());
long end = System.currentTimeMillis();
assertTrue(end - start >= 1000);
intpA.close();
intpB.close();
}
@Test
public void testRemoteSchedulerSharingSubmit() throws TTransportException, IOException, InterruptedException {
Properties p = new Properties();
intpGroup.put("note", new LinkedList<Interpreter>());
final RemoteInterpreter intpA = createMockInterpreterA(p);
intpGroup.get("note").add(intpA);
intpA.setInterpreterGroup(intpGroup);
final RemoteInterpreter intpB = createMockInterpreterB(p);
intpGroup.get("note").add(intpB);
intpB.setInterpreterGroup(intpGroup);
intpA.open();
intpB.open();
long start = System.currentTimeMillis();
Job jobA = new Job("jobA", null) {
private Object r;
@Override
public Object getReturn() {
return r;
}
@Override
public void setResult(Object results) {
this.r = results;
}
@Override
public int progress() {
return 0;
}
@Override
public Map<String, Object> info() {
return null;
}
@Override
protected Object jobRun() throws Throwable {
return intpA.interpret("500",
new InterpreterContext(
"note",
"jobA",
null,
"title",
"text",
new AuthenticationInfo(),
new HashMap<String, Object>(),
new GUI(),
new AngularObjectRegistry(intpGroup.getId(), null),
new LocalResourcePool("pool1"),
new LinkedList<InterpreterContextRunner>(), null));
}
@Override
protected boolean jobAbort() {
return false;
}
};
intpA.getScheduler().submit(jobA);
Job jobB = new Job("jobB", null) {
private Object r;
@Override
public Object getReturn() {
return r;
}
@Override
public void setResult(Object results) {
this.r = results;
}
@Override
public int progress() {
return 0;
}
@Override
public Map<String, Object> info() {
return null;
}
@Override
protected Object jobRun() throws Throwable {
return intpB.interpret("500",
new InterpreterContext(
"note",
"jobB",
null,
"title",
"text",
new AuthenticationInfo(),
new HashMap<String, Object>(),
new GUI(),
new AngularObjectRegistry(intpGroup.getId(), null),
new LocalResourcePool("pool1"),
new LinkedList<InterpreterContextRunner>(), null));
}
@Override
protected boolean jobAbort() {
return false;
}
};
intpB.getScheduler().submit(jobB);
// wait until both job finished
while (jobA.getStatus() != Status.FINISHED ||
jobB.getStatus() != Status.FINISHED) {
Thread.sleep(100);
}
long end = System.currentTimeMillis();
assertTrue(end - start >= 1000);
assertEquals("1000", ((InterpreterResult) jobB.getReturn()).message().get(0).getData());
intpA.close();
intpB.close();
}
@Test
public void testRunOrderPreserved() throws InterruptedException {
Properties p = new Properties();
intpGroup.put("note", new LinkedList<Interpreter>());
final RemoteInterpreter intpA = createMockInterpreterA(p);
intpGroup.get("note").add(intpA);
intpA.setInterpreterGroup(intpGroup);
intpA.open();
int concurrency = 3;
final List<InterpreterResultMessage> results = new LinkedList<>();
Scheduler scheduler = intpA.getScheduler();
for (int i = 0; i < concurrency; i++) {
final String jobId = Integer.toString(i);
scheduler.submit(new Job(jobId, Integer.toString(i), null, 200) {
private Object r;
@Override
public Object getReturn() {
return r;
}
@Override
public void setResult(Object results) {
this.r = results;
}
@Override
public int progress() {
return 0;
}
@Override
public Map<String, Object> info() {
return null;
}
@Override
protected Object jobRun() throws Throwable {
InterpreterResult ret = intpA.interpret(getJobName(), new InterpreterContext(
"note",
jobId,
null,
"title",
"text",
new AuthenticationInfo(),
new HashMap<String, Object>(),
new GUI(),
new AngularObjectRegistry(intpGroup.getId(), null),
new LocalResourcePool("pool1"),
new LinkedList<InterpreterContextRunner>(), null));
synchronized (results) {
results.addAll(ret.message());
results.notify();
}
return null;
}
@Override
protected boolean jobAbort() {
return false;
}
});
}
// wait for job finished
synchronized (results) {
while (results.size() != concurrency) {
results.wait(300);
}
}
int i = 0;
for (InterpreterResultMessage result : results) {
assertEquals(Integer.toString(i++), result.getData());
}
assertEquals(concurrency, i);
intpA.close();
}
@Test
public void testRunParallel() throws InterruptedException {
Properties p = new Properties();
p.put("parallel", "true");
intpGroup.put("note", new LinkedList<Interpreter>());
final RemoteInterpreter intpA = createMockInterpreterA(p);
intpGroup.get("note").add(intpA);
intpA.setInterpreterGroup(intpGroup);
intpA.open();
int concurrency = 4;
final int timeToSleep = 1000;
final List<InterpreterResultMessage> results = new LinkedList<>();
long start = System.currentTimeMillis();
Scheduler scheduler = intpA.getScheduler();
for (int i = 0; i < concurrency; i++) {
final String jobId = Integer.toString(i);
scheduler.submit(new Job(jobId, Integer.toString(i), null, 300) {
private Object r;
@Override
public Object getReturn() {
return r;
}
@Override
public void setResult(Object results) {
this.r = results;
}
@Override
public int progress() {
return 0;
}
@Override
public Map<String, Object> info() {
return null;
}
@Override
protected Object jobRun() throws Throwable {
String stmt = Integer.toString(timeToSleep);
InterpreterResult ret = intpA.interpret(stmt, new InterpreterContext(
"note",
jobId,
null,
"title",
"text",
new AuthenticationInfo(),
new HashMap<String, Object>(),
new GUI(),
new AngularObjectRegistry(intpGroup.getId(), null),
new LocalResourcePool("pool1"),
new LinkedList<InterpreterContextRunner>(), null));
synchronized (results) {
results.addAll(ret.message());
results.notify();
}
return stmt;
}
@Override
protected boolean jobAbort() {
return false;
}
});
}
// wait for job finished
synchronized (results) {
while (results.size() != concurrency) {
results.wait(300);
}
}
long end = System.currentTimeMillis();
assertTrue(end - start < timeToSleep * concurrency);
intpA.close();
}
@Test
public void testInterpreterGroupResetBeforeProcessStarts() {
Properties p = new Properties();
RemoteInterpreter intpA = createMockInterpreterA(p);
intpA.setInterpreterGroup(intpGroup);
RemoteInterpreterProcess processA = intpA.getInterpreterProcess();
intpA.setInterpreterGroup(new InterpreterGroup(intpA.getInterpreterGroup().getId()));
RemoteInterpreterProcess processB = intpA.getInterpreterProcess();
assertNotSame(processA.hashCode(), processB.hashCode());
}
@Test
public void testInterpreterGroupResetAfterProcessFinished() {
Properties p = new Properties();
intpGroup.put("note", new LinkedList<Interpreter>());
RemoteInterpreter intpA = createMockInterpreterA(p);
intpA.setInterpreterGroup(intpGroup);
RemoteInterpreterProcess processA = intpA.getInterpreterProcess();
intpA.open();
processA.dereference(); // intpA.close();
intpA.setInterpreterGroup(new InterpreterGroup(intpA.getInterpreterGroup().getId()));
RemoteInterpreterProcess processB = intpA.getInterpreterProcess();
assertNotSame(processA.hashCode(), processB.hashCode());
}
@Test
public void testInterpreterGroupResetDuringProcessRunning() throws InterruptedException {
Properties p = new Properties();
intpGroup.put("note", new LinkedList<Interpreter>());
final RemoteInterpreter intpA = createMockInterpreterA(p);
intpGroup.get("note").add(intpA);
intpA.setInterpreterGroup(intpGroup);
intpA.open();
Job jobA = new Job("jobA", null) {
private Object r;
@Override
public Object getReturn() {
return r;
}
@Override
public void setResult(Object results) {
this.r = results;
}
@Override
public int progress() {
return 0;
}
@Override
public Map<String, Object> info() {
return null;
}
@Override
protected Object jobRun() throws Throwable {
return intpA.interpret("2000",
new InterpreterContext(
"note",
"jobA",
null,
"title",
"text",
new AuthenticationInfo(),
new HashMap<String, Object>(),
new GUI(),
new AngularObjectRegistry(intpGroup.getId(), null),
new LocalResourcePool("pool1"),
new LinkedList<InterpreterContextRunner>(), null));
}
@Override
protected boolean jobAbort() {
return false;
}
};
intpA.getScheduler().submit(jobA);
// wait for job started
while (intpA.getScheduler().getJobsRunning().size() == 0) {
Thread.sleep(100);
}
// restart interpreter
RemoteInterpreterProcess processA = intpA.getInterpreterProcess();
intpA.close();
InterpreterGroup newInterpreterGroup =
new InterpreterGroup(intpA.getInterpreterGroup().getId());
newInterpreterGroup.put("note", new LinkedList<Interpreter>());
intpA.setInterpreterGroup(newInterpreterGroup);
intpA.open();
RemoteInterpreterProcess processB = intpA.getInterpreterProcess();
assertNotSame(processA.hashCode(), processB.hashCode());
}
@Test
public void testRemoteInterpreterSharesTheSameSchedulerInstanceInTheSameGroup() {
Properties p = new Properties();
intpGroup.put("note", new LinkedList<Interpreter>());
RemoteInterpreter intpA = createMockInterpreterA(p);
intpGroup.get("note").add(intpA);
intpA.setInterpreterGroup(intpGroup);
RemoteInterpreter intpB = createMockInterpreterB(p);
intpGroup.get("note").add(intpB);
intpB.setInterpreterGroup(intpGroup);
intpA.open();
intpB.open();
assertEquals(intpA.getScheduler(), intpB.getScheduler());
}
@Test
public void testMultiInterpreterSession() {
Properties p = new Properties();
intpGroup.put("sessionA", new LinkedList<Interpreter>());
intpGroup.put("sessionB", new LinkedList<Interpreter>());
RemoteInterpreter intpAsessionA = createMockInterpreterA(p, "sessionA");
intpGroup.get("sessionA").add(intpAsessionA);
intpAsessionA.setInterpreterGroup(intpGroup);
RemoteInterpreter intpBsessionA = createMockInterpreterB(p, "sessionA");
intpGroup.get("sessionA").add(intpBsessionA);
intpBsessionA.setInterpreterGroup(intpGroup);
intpAsessionA.open();
intpBsessionA.open();
assertEquals(intpAsessionA.getScheduler(), intpBsessionA.getScheduler());
RemoteInterpreter intpAsessionB = createMockInterpreterA(p, "sessionB");
intpGroup.get("sessionB").add(intpAsessionB);
intpAsessionB.setInterpreterGroup(intpGroup);
RemoteInterpreter intpBsessionB = createMockInterpreterB(p, "sessionB");
intpGroup.get("sessionB").add(intpBsessionB);
intpBsessionB.setInterpreterGroup(intpGroup);
intpAsessionB.open();
intpBsessionB.open();
assertEquals(intpAsessionB.getScheduler(), intpBsessionB.getScheduler());
assertNotEquals(intpAsessionA.getScheduler(), intpAsessionB.getScheduler());
}
@Test
public void should_push_local_angular_repo_to_remote() throws Exception {
//Given
final Client client = Mockito.mock(Client.class);
final RemoteInterpreter intr = new RemoteInterpreter(new Properties(), "noteId",
MockInterpreterA.class.getName(), "runner", "path", "localRepo", env, 10 * 1000, null,
null, "anonymous", false);
final AngularObjectRegistry registry = new AngularObjectRegistry("spark", null);
registry.add("name", "DuyHai DOAN", "nodeId", "paragraphId");
final InterpreterGroup interpreterGroup = new InterpreterGroup("groupId");
interpreterGroup.setAngularObjectRegistry(registry);
intr.setInterpreterGroup(interpreterGroup);
final java.lang.reflect.Type registryType = new TypeToken<Map<String,
Map<String, AngularObject>>>() {}.getType();
final Gson gson = new Gson();
final String expected = gson.toJson(registry.getRegistry(), registryType);
//When
intr.pushAngularObjectRegistryToRemote(client);
//Then
Mockito.verify(client).angularRegistryPush(expected);
}
@Test
public void testEnvStringPattern() {
assertFalse(RemoteInterpreter.isEnvString(null));
assertFalse(RemoteInterpreter.isEnvString(""));
assertFalse(RemoteInterpreter.isEnvString("abcDEF"));
assertFalse(RemoteInterpreter.isEnvString("ABC-DEF"));
assertTrue(RemoteInterpreter.isEnvString("ABCDEF"));
assertTrue(RemoteInterpreter.isEnvString("ABC_DEF"));
assertTrue(RemoteInterpreter.isEnvString("ABC_DEF123"));
}
@Test
public void testEnvronmentAndPropertySet() {
Properties p = new Properties();
p.setProperty("MY_ENV1", "env value 1");
p.setProperty("my.property.1", "property value 1");
RemoteInterpreter intp = new RemoteInterpreter(
p,
"note",
MockInterpreterEnv.class.getName(),
new File(INTERPRETER_SCRIPT).getAbsolutePath(),
"fake",
"fakeRepo",
env,
10 * 1000,
null,
null,
"anonymous",
false);
intpGroup.put("note", new LinkedList<Interpreter>());
intpGroup.get("note").add(intp);
intp.setInterpreterGroup(intpGroup);
intp.open();
InterpreterContext context = new InterpreterContext(
"noteId",
"id",
null,
"title",
"text",
new AuthenticationInfo(),
new HashMap<String, Object>(),
new GUI(),
new AngularObjectRegistry(intpGroup.getId(), null),
new LocalResourcePool("pool1"),
new LinkedList<InterpreterContextRunner>(), null);
assertEquals("env value 1", intp.interpret("getEnv MY_ENV1", context).message().get(0).getData());
assertEquals(Code.ERROR, intp.interpret("getProperty MY_ENV1", context).code());
assertEquals(Code.ERROR, intp.interpret("getEnv my.property.1", context).code());
assertEquals("property value 1", intp.interpret("getProperty my.property.1", context).message().get(0).getData());
intp.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-interpreter/src/test/java/org/apache/zeppelin/interpreter/remote/RemoteInterpreterOutputTestStream.java | smart-zeppelin/zeppelin-interpreter/src/test/java/org/apache/zeppelin/interpreter/remote/RemoteInterpreterOutputTestStream.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.remote;
import org.apache.zeppelin.display.AngularObjectRegistry;
import org.apache.zeppelin.user.AuthenticationInfo;
import org.apache.zeppelin.display.GUI;
import org.apache.zeppelin.interpreter.*;
import org.apache.zeppelin.interpreter.remote.mock.MockInterpreterOutputStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Properties;
import static org.junit.Assert.assertEquals;
/**
* Test for remote interpreter output stream
*/
public class RemoteInterpreterOutputTestStream implements RemoteInterpreterProcessListener {
private static final String INTERPRETER_SCRIPT =
System.getProperty("os.name").startsWith("Windows") ?
"../bin/interpreter.cmd" :
"../bin/interpreter.sh";
private InterpreterGroup intpGroup;
private HashMap<String, String> env;
@Before
public void setUp() throws Exception {
intpGroup = new InterpreterGroup();
intpGroup.put("note", new LinkedList<Interpreter>());
env = new HashMap<>();
env.put("ZEPPELIN_CLASSPATH", new File("./target/test-classes").getAbsolutePath());
}
@After
public void tearDown() throws Exception {
intpGroup.close();
}
private RemoteInterpreter createMockInterpreter() {
RemoteInterpreter intp = new RemoteInterpreter(
new Properties(),
"note",
MockInterpreterOutputStream.class.getName(),
new File(INTERPRETER_SCRIPT).getAbsolutePath(),
"fake",
"fakeRepo",
env,
10 * 1000,
this,
null,
"anonymous",
false);
intpGroup.get("note").add(intp);
intp.setInterpreterGroup(intpGroup);
return intp;
}
private InterpreterContext createInterpreterContext() {
return new InterpreterContext(
"noteId",
"id",
null,
"title",
"text",
new AuthenticationInfo(),
new HashMap<String, Object>(),
new GUI(),
new AngularObjectRegistry(intpGroup.getId(), null),
null,
new LinkedList<InterpreterContextRunner>(), null);
}
@Test
public void testInterpreterResultOnly() {
RemoteInterpreter intp = createMockInterpreter();
InterpreterResult ret = intp.interpret("SUCCESS::staticresult", createInterpreterContext());
assertEquals(InterpreterResult.Code.SUCCESS, ret.code());
assertEquals("staticresult", ret.message().get(0).getData());
ret = intp.interpret("SUCCESS::staticresult2", createInterpreterContext());
assertEquals(InterpreterResult.Code.SUCCESS, ret.code());
assertEquals("staticresult2", ret.message().get(0).getData());
ret = intp.interpret("ERROR::staticresult3", createInterpreterContext());
assertEquals(InterpreterResult.Code.ERROR, ret.code());
assertEquals("staticresult3", ret.message().get(0).getData());
}
@Test
public void testInterpreterOutputStreamOnly() {
RemoteInterpreter intp = createMockInterpreter();
InterpreterResult ret = intp.interpret("SUCCESS:streamresult:", createInterpreterContext());
assertEquals(InterpreterResult.Code.SUCCESS, ret.code());
assertEquals("streamresult", ret.message().get(0).getData());
ret = intp.interpret("ERROR:streamresult2:", createInterpreterContext());
assertEquals(InterpreterResult.Code.ERROR, ret.code());
assertEquals("streamresult2", ret.message().get(0).getData());
}
@Test
public void testInterpreterResultOutputStreamMixed() {
RemoteInterpreter intp = createMockInterpreter();
InterpreterResult ret = intp.interpret("SUCCESS:stream:static", createInterpreterContext());
assertEquals(InterpreterResult.Code.SUCCESS, ret.code());
assertEquals("stream", ret.message().get(0).getData());
assertEquals("static", ret.message().get(1).getData());
}
@Test
public void testOutputType() {
RemoteInterpreter intp = createMockInterpreter();
InterpreterResult ret = intp.interpret("SUCCESS:%html hello:", createInterpreterContext());
assertEquals(InterpreterResult.Type.HTML, ret.message().get(0).getType());
assertEquals("hello", ret.message().get(0).getData());
ret = intp.interpret("SUCCESS:%html\nhello:", createInterpreterContext());
assertEquals(InterpreterResult.Type.HTML, ret.message().get(0).getType());
assertEquals("hello", ret.message().get(0).getData());
ret = intp.interpret("SUCCESS:%html hello:%angular world", createInterpreterContext());
assertEquals(InterpreterResult.Type.HTML, ret.message().get(0).getType());
assertEquals("hello", ret.message().get(0).getData());
assertEquals(InterpreterResult.Type.ANGULAR, ret.message().get(1).getType());
assertEquals("world", ret.message().get(1).getData());
}
@Override
public void onOutputAppend(String noteId, String paragraphId, int index, String output) {
}
@Override
public void onOutputUpdated(String noteId, String paragraphId, int index, InterpreterResult.Type type, String output) {
}
@Override
public void onOutputClear(String noteId, String paragraphId) {
}
@Override
public void onMetaInfosReceived(String settingId, Map<String, String> metaInfos) {
}
@Override
public void onGetParagraphRunners(String noteId, String paragraphId, RemoteWorksEventListener callback) {
if (callback != null) {
callback.onFinished(new LinkedList<>());
}
}
@Override
public void onRemoteRunParagraph(String noteId, String ParagraphID) 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-interpreter/src/test/java/org/apache/zeppelin/interpreter/remote/RemoteInterpreterUtilsTest.java | smart-zeppelin/zeppelin-interpreter/src/test/java/org/apache/zeppelin/interpreter/remote/RemoteInterpreterUtilsTest.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.remote;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import org.apache.zeppelin.interpreter.remote.RemoteInterpreterUtils;
import org.junit.Test;
public class RemoteInterpreterUtilsTest {
@Test
public void testFindRandomAvailablePortOnAllLocalInterfaces() throws IOException {
assertTrue(RemoteInterpreterUtils.findRandomAvailablePortOnAllLocalInterfaces() > 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-interpreter/src/test/java/org/apache/zeppelin/interpreter/remote/RemoteInterpreterProcessTest.java | smart-zeppelin/zeppelin-interpreter/src/test/java/org/apache/zeppelin/interpreter/remote/RemoteInterpreterProcessTest.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.remote;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.mockito.Mockito.*;
import java.util.HashMap;
import java.util.Properties;
import org.apache.thrift.TException;
import org.apache.thrift.transport.TTransportException;
import org.apache.zeppelin.interpreter.Constants;
import org.apache.zeppelin.interpreter.InterpreterException;
import org.apache.zeppelin.interpreter.InterpreterGroup;
import org.apache.zeppelin.interpreter.thrift.RemoteInterpreterService.Client;
import org.junit.Test;
public class RemoteInterpreterProcessTest {
private static final String INTERPRETER_SCRIPT =
System.getProperty("os.name").startsWith("Windows") ?
"../bin/interpreter.cmd" :
"../bin/interpreter.sh";
private static final int DUMMY_PORT=3678;
@Test
public void testStartStop() {
InterpreterGroup intpGroup = new InterpreterGroup();
RemoteInterpreterManagedProcess rip = new RemoteInterpreterManagedProcess(
INTERPRETER_SCRIPT, "nonexists", "fakeRepo", new HashMap<String, String>(),
10 * 1000, null, null);
assertFalse(rip.isRunning());
assertEquals(0, rip.referenceCount());
assertEquals(1, rip.reference(intpGroup, "anonymous", false));
assertEquals(2, rip.reference(intpGroup, "anonymous", false));
assertEquals(true, rip.isRunning());
assertEquals(1, rip.dereference());
assertEquals(true, rip.isRunning());
assertEquals(0, rip.dereference());
assertEquals(false, rip.isRunning());
}
@Test
public void testClientFactory() throws Exception {
InterpreterGroup intpGroup = new InterpreterGroup();
RemoteInterpreterManagedProcess rip = new RemoteInterpreterManagedProcess(
INTERPRETER_SCRIPT, "nonexists", "fakeRepo", new HashMap<String, String>(),
mock(RemoteInterpreterEventPoller.class), 10 * 1000);
rip.reference(intpGroup, "anonymous", false);
assertEquals(0, rip.getNumActiveClient());
assertEquals(0, rip.getNumIdleClient());
Client client = rip.getClient();
assertEquals(1, rip.getNumActiveClient());
assertEquals(0, rip.getNumIdleClient());
rip.releaseClient(client);
assertEquals(0, rip.getNumActiveClient());
assertEquals(1, rip.getNumIdleClient());
rip.dereference();
}
@Test
public void testStartStopRemoteInterpreter() throws TException, InterruptedException {
RemoteInterpreterServer server = new RemoteInterpreterServer(3678);
server.start();
boolean running = false;
long startTime = System.currentTimeMillis();
while (System.currentTimeMillis() - startTime < 10 * 1000) {
if (server.isRunning()) {
running = true;
break;
} else {
Thread.sleep(200);
}
}
Properties properties = new Properties();
properties.setProperty(Constants.ZEPPELIN_INTERPRETER_PORT, "3678");
properties.setProperty(Constants.ZEPPELIN_INTERPRETER_HOST, "localhost");
InterpreterGroup intpGroup = mock(InterpreterGroup.class);
when(intpGroup.getProperty()).thenReturn(properties);
when(intpGroup.containsKey(Constants.EXISTING_PROCESS)).thenReturn(true);
RemoteInterpreterProcess rip = new RemoteInterpreterManagedProcess(
INTERPRETER_SCRIPT,
"nonexists",
"fakeRepo",
new HashMap<String, String>(),
mock(RemoteInterpreterEventPoller.class)
, 10 * 1000);
assertFalse(rip.isRunning());
assertEquals(0, rip.referenceCount());
assertEquals(1, rip.reference(intpGroup, "anonymous", false));
assertEquals(true, rip.isRunning());
}
@Test
public void testPropagateError() throws TException, InterruptedException {
InterpreterGroup intpGroup = new InterpreterGroup();
RemoteInterpreterManagedProcess rip = new RemoteInterpreterManagedProcess(
"echo hello_world", "nonexists", "fakeRepo", new HashMap<String, String>(),
10 * 1000, null, null);
assertFalse(rip.isRunning());
assertEquals(0, rip.referenceCount());
try {
assertEquals(1, rip.reference(intpGroup, "anonymous", false));
} catch (InterpreterException e) {
e.getMessage().contains("hello_world");
}
assertEquals(0, rip.referenceCount());
}
}
| 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-interpreter/src/test/java/org/apache/zeppelin/interpreter/remote/AppendOutputRunnerTest.java | smart-zeppelin/zeppelin-interpreter/src/test/java/org/apache/zeppelin/interpreter/remote/AppendOutputRunnerTest.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.remote;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggingEvent;
import org.junit.After;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
public class AppendOutputRunnerTest {
private static final int NUM_EVENTS = 10000;
private static final int NUM_CLUBBED_EVENTS = 100;
private static final ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> future = null;
/* It is being accessed by multiple threads.
* While loop for 'loopForBufferCompletion' could
* run for-ever.
*/
private volatile static int numInvocations = 0;
@After
public void afterEach() {
if (future != null) {
future.cancel(true);
}
}
@Test
public void testSingleEvent() throws InterruptedException {
RemoteInterpreterProcessListener listener = mock(RemoteInterpreterProcessListener.class);
String[][] buffer = {{"note", "para", "data\n"}};
loopForCompletingEvents(listener, 1, buffer);
verify(listener, times(1)).onOutputAppend(any(String.class), any(String.class), anyInt(), any(String.class));
verify(listener, times(1)).onOutputAppend("note", "para", 0, "data\n");
}
@Test
public void testMultipleEventsOfSameParagraph() throws InterruptedException {
RemoteInterpreterProcessListener listener = mock(RemoteInterpreterProcessListener.class);
String note1 = "note1";
String para1 = "para1";
String[][] buffer = {
{note1, para1, "data1\n"},
{note1, para1, "data2\n"},
{note1, para1, "data3\n"}
};
loopForCompletingEvents(listener, 1, buffer);
verify(listener, times(1)).onOutputAppend(any(String.class), any(String.class), anyInt(), any(String.class));
verify(listener, times(1)).onOutputAppend(note1, para1, 0, "data1\ndata2\ndata3\n");
}
@Test
public void testMultipleEventsOfDifferentParagraphs() throws InterruptedException {
RemoteInterpreterProcessListener listener = mock(RemoteInterpreterProcessListener.class);
String note1 = "note1";
String note2 = "note2";
String para1 = "para1";
String para2 = "para2";
String[][] buffer = {
{note1, para1, "data1\n"},
{note1, para2, "data2\n"},
{note2, para1, "data3\n"},
{note2, para2, "data4\n"}
};
loopForCompletingEvents(listener, 4, buffer);
verify(listener, times(4)).onOutputAppend(any(String.class), any(String.class), anyInt(), any(String.class));
verify(listener, times(1)).onOutputAppend(note1, para1, 0, "data1\n");
verify(listener, times(1)).onOutputAppend(note1, para2, 0, "data2\n");
verify(listener, times(1)).onOutputAppend(note2, para1, 0, "data3\n");
verify(listener, times(1)).onOutputAppend(note2, para2, 0, "data4\n");
}
@Test
public void testClubbedData() throws InterruptedException {
RemoteInterpreterProcessListener listener = mock(RemoteInterpreterProcessListener.class);
AppendOutputRunner runner = new AppendOutputRunner(listener);
future = service.scheduleWithFixedDelay(runner, 0,
AppendOutputRunner.BUFFER_TIME_MS, TimeUnit.MILLISECONDS);
Thread thread = new Thread(new BombardEvents(runner));
thread.start();
thread.join();
Thread.sleep(1000);
/* NUM_CLUBBED_EVENTS is a heuristic number.
* It has been observed that for 10,000 continuos event
* calls, 30-40 Web-socket calls are made. Keeping
* the unit-test to a pessimistic 100 web-socket calls.
*/
verify(listener, atMost(NUM_CLUBBED_EVENTS)).onOutputAppend(any(String.class), any(String.class), anyInt(), any(String.class));
}
@Test
public void testWarnLoggerForLargeData() throws InterruptedException {
RemoteInterpreterProcessListener listener = mock(RemoteInterpreterProcessListener.class);
AppendOutputRunner runner = new AppendOutputRunner(listener);
String data = "data\n";
int numEvents = 100000;
for (int i=0; i<numEvents; i++) {
runner.appendBuffer("noteId", "paraId", 0, data);
}
TestAppender appender = new TestAppender();
Logger logger = Logger.getRootLogger();
logger.addAppender(appender);
Logger.getLogger(RemoteInterpreterEventPoller.class);
runner.run();
List<LoggingEvent> log;
int warnLogCounter;
LoggingEvent sizeWarnLogEntry = null;
do {
warnLogCounter = 0;
log = appender.getLog();
for (LoggingEvent logEntry: log) {
if (Level.WARN.equals(logEntry.getLevel())) {
sizeWarnLogEntry = logEntry;
warnLogCounter += 1;
}
}
} while(warnLogCounter != 2);
String loggerString = "Processing size for buffered append-output is high: " +
(data.length() * numEvents) + " characters.";
assertTrue(loggerString.equals(sizeWarnLogEntry.getMessage()));
}
private class BombardEvents implements Runnable {
private final AppendOutputRunner runner;
private BombardEvents(AppendOutputRunner runner) {
this.runner = runner;
}
@Override
public void run() {
String noteId = "noteId";
String paraId = "paraId";
for (int i=0; i<NUM_EVENTS; i++) {
runner.appendBuffer(noteId, paraId, 0, "data\n");
}
}
}
private class TestAppender extends AppenderSkeleton {
private final List<LoggingEvent> log = new ArrayList<>();
@Override
public boolean requiresLayout() {
return false;
}
@Override
protected void append(final LoggingEvent loggingEvent) {
log.add(loggingEvent);
}
@Override
public void close() {
}
public List<LoggingEvent> getLog() {
return new ArrayList<>(log);
}
}
private void prepareInvocationCounts(RemoteInterpreterProcessListener listener) {
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
numInvocations += 1;
return null;
}
}).when(listener).onOutputAppend(any(String.class), any(String.class), anyInt(), any(String.class));
}
private void loopForCompletingEvents(RemoteInterpreterProcessListener listener,
int numTimes, String[][] buffer) {
numInvocations = 0;
prepareInvocationCounts(listener);
AppendOutputRunner runner = new AppendOutputRunner(listener);
for (String[] bufferElement: buffer) {
runner.appendBuffer(bufferElement[0], bufferElement[1], 0, bufferElement[2]);
}
future = service.scheduleWithFixedDelay(runner, 0,
AppendOutputRunner.BUFFER_TIME_MS, TimeUnit.MILLISECONDS);
long startTimeMs = System.currentTimeMillis();
while(numInvocations != numTimes) {
if (System.currentTimeMillis() - startTimeMs > 2000) {
fail("Buffered events were not sent for 2 seconds");
}
}
}
} | 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-interpreter/src/test/java/org/apache/zeppelin/interpreter/remote/RemoteInterpreterServerTest.java | smart-zeppelin/zeppelin-interpreter/src/test/java/org/apache/zeppelin/interpreter/remote/RemoteInterpreterServerTest.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.remote;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.apache.thrift.TException;
import org.apache.zeppelin.interpreter.remote.RemoteInterpreterServer;
import org.apache.zeppelin.interpreter.remote.RemoteInterpreterUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class RemoteInterpreterServerTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void testStartStop() throws InterruptedException, IOException, TException {
RemoteInterpreterServer server = new RemoteInterpreterServer(
RemoteInterpreterUtils.findRandomAvailablePortOnAllLocalInterfaces());
assertEquals(false, server.isRunning());
server.start();
long startTime = System.currentTimeMillis();
boolean running = false;
while (System.currentTimeMillis() - startTime < 10 * 1000) {
if (server.isRunning()) {
running = true;
break;
} else {
Thread.sleep(200);
}
}
assertEquals(true, running);
assertEquals(true, RemoteInterpreterUtils.checkIfRemoteEndpointAccessible("localhost", server.getPort()));
server.shutdown();
while (System.currentTimeMillis() - startTime < 10 * 1000) {
if (server.isRunning()) {
Thread.sleep(200);
} else {
running = false;
break;
}
}
assertEquals(false, running);
}
class ShutdownRun implements Runnable {
private RemoteInterpreterServer serv = null;
public ShutdownRun(RemoteInterpreterServer serv) {
this.serv = serv;
}
@Override
public void run() {
try {
serv.shutdown();
} catch (Exception ex) {};
}
};
@Test
public void testStartStopWithQueuedEvents() throws InterruptedException, IOException, TException {
RemoteInterpreterServer server = new RemoteInterpreterServer(
RemoteInterpreterUtils.findRandomAvailablePortOnAllLocalInterfaces());
assertEquals(false, server.isRunning());
server.start();
long startTime = System.currentTimeMillis();
boolean running = false;
while (System.currentTimeMillis() - startTime < 10 * 1000) {
if (server.isRunning()) {
running = true;
break;
} else {
Thread.sleep(200);
}
}
assertEquals(true, running);
assertEquals(true, RemoteInterpreterUtils.checkIfRemoteEndpointAccessible("localhost", server.getPort()));
//just send an event on the client queue
server.eventClient.onAppStatusUpdate("","","","");
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
Runnable task = new ShutdownRun(server);
executor.schedule(task, 0, TimeUnit.MILLISECONDS);
while (System.currentTimeMillis() - startTime < 10 * 1000) {
if (server.isRunning()) {
Thread.sleep(200);
} else {
running = false;
break;
}
}
executor.shutdown();
//cleanup environment for next tests
server.shutdown();
assertEquals(false, running);
}
}
| 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-interpreter/src/test/java/org/apache/zeppelin/interpreter/remote/mock/MockInterpreterB.java | smart-zeppelin/zeppelin-interpreter/src/test/java/org/apache/zeppelin/interpreter/remote/mock/MockInterpreterB.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.remote.mock;
import java.util.List;
import java.util.Properties;
import org.apache.zeppelin.interpreter.Interpreter;
import org.apache.zeppelin.interpreter.InterpreterContext;
import org.apache.zeppelin.interpreter.InterpreterException;
import org.apache.zeppelin.interpreter.InterpreterGroup;
import org.apache.zeppelin.interpreter.InterpreterPropertyBuilder;
import org.apache.zeppelin.interpreter.InterpreterResult;
import org.apache.zeppelin.interpreter.InterpreterResult.Code;
import org.apache.zeppelin.interpreter.WrappedInterpreter;
import org.apache.zeppelin.interpreter.thrift.InterpreterCompletion;
import org.apache.zeppelin.scheduler.Scheduler;
public class MockInterpreterB extends Interpreter {
public MockInterpreterB(Properties property) {
super(property);
}
@Override
public void open() {
//new RuntimeException().printStackTrace();
}
@Override
public void close() {
}
@Override
public InterpreterResult interpret(String st, InterpreterContext context) {
MockInterpreterA intpA = getInterpreterA();
String intpASt = intpA.getLastStatement();
long timeToSleep = Long.parseLong(st);
if (intpASt != null) {
timeToSleep += Long.parseLong(intpASt);
}
try {
Thread.sleep(timeToSleep);
} catch (NumberFormatException | InterruptedException e) {
throw new InterpreterException(e);
}
return new InterpreterResult(Code.SUCCESS, Long.toString(timeToSleep));
}
@Override
public void cancel(InterpreterContext context) {
}
@Override
public FormType getFormType() {
return FormType.NATIVE;
}
@Override
public int getProgress(InterpreterContext context) {
return 0;
}
@Override
public List<InterpreterCompletion> completion(String buf, int cursor) {
return null;
}
public MockInterpreterA getInterpreterA() {
InterpreterGroup interpreterGroup = getInterpreterGroup();
synchronized (interpreterGroup) {
for (List<Interpreter> interpreters : interpreterGroup.values()) {
boolean belongsToSameNoteGroup = false;
MockInterpreterA a = null;
for (Interpreter intp : interpreters) {
if (intp.getClassName().equals(MockInterpreterA.class.getName())) {
Interpreter p = intp;
while (p instanceof WrappedInterpreter) {
p = ((WrappedInterpreter) p).getInnerInterpreter();
}
a = (MockInterpreterA) p;
}
Interpreter p = intp;
while (p instanceof WrappedInterpreter) {
p = ((WrappedInterpreter) p).getInnerInterpreter();
}
if (this == p) {
belongsToSameNoteGroup = true;
}
}
if (belongsToSameNoteGroup) {
return a;
}
}
}
return null;
}
@Override
public Scheduler getScheduler() {
MockInterpreterA intpA = getInterpreterA();
if (intpA != null) {
return intpA.getScheduler();
}
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-interpreter/src/test/java/org/apache/zeppelin/interpreter/remote/mock/MockInterpreterOutputStream.java | smart-zeppelin/zeppelin-interpreter/src/test/java/org/apache/zeppelin/interpreter/remote/mock/MockInterpreterOutputStream.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.remote.mock;
import org.apache.zeppelin.interpreter.*;
import org.apache.zeppelin.interpreter.thrift.InterpreterCompletion;
import org.apache.zeppelin.scheduler.Scheduler;
import org.apache.zeppelin.scheduler.SchedulerFactory;
import java.io.IOException;
import java.util.List;
import java.util.Properties;
/**
* MockInterpreter to test outputstream
*/
public class MockInterpreterOutputStream extends Interpreter {
private String lastSt;
public MockInterpreterOutputStream(Properties property) {
super(property);
}
@Override
public void open() {
//new RuntimeException().printStackTrace();
}
@Override
public void close() {
}
public String getLastStatement() {
return lastSt;
}
@Override
public InterpreterResult interpret(String st, InterpreterContext context) {
String[] ret = st.split(":");
try {
if (ret[1] != null) {
context.out.write(ret[1]);
}
} catch (IOException e) {
throw new InterpreterException(e);
}
return new InterpreterResult(InterpreterResult.Code.valueOf(ret[0]), (ret.length > 2) ?
ret[2] : "");
}
@Override
public void cancel(InterpreterContext context) {
}
@Override
public FormType getFormType() {
return FormType.NATIVE;
}
@Override
public int getProgress(InterpreterContext context) {
return 0;
}
@Override
public List<InterpreterCompletion> completion(String buf, int cursor) {
return null;
}
@Override
public Scheduler getScheduler() {
return SchedulerFactory.singleton().createOrGetFIFOScheduler("interpreter_" + this.hashCode());
}
}
| 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-interpreter/src/test/java/org/apache/zeppelin/interpreter/remote/mock/MockInterpreterEnv.java | smart-zeppelin/zeppelin-interpreter/src/test/java/org/apache/zeppelin/interpreter/remote/mock/MockInterpreterEnv.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.remote.mock;
import org.apache.zeppelin.interpreter.*;
import org.apache.zeppelin.interpreter.thrift.InterpreterCompletion;
import org.apache.zeppelin.scheduler.Scheduler;
import org.apache.zeppelin.scheduler.SchedulerFactory;
import java.util.List;
import java.util.Properties;
public class MockInterpreterEnv extends Interpreter {
public MockInterpreterEnv(Properties property) {
super(property);
}
@Override
public void open() {
}
@Override
public void close() {
}
@Override
public InterpreterResult interpret(String st, InterpreterContext context) {
String[] cmd = st.split(" ");
if (cmd[0].equals("getEnv")) {
return new InterpreterResult(InterpreterResult.Code.SUCCESS, System.getenv(cmd[1]));
} else if (cmd[0].equals("getProperty")){
return new InterpreterResult(InterpreterResult.Code.SUCCESS, System.getProperty(cmd[1]));
} else {
return new InterpreterResult(InterpreterResult.Code.ERROR, cmd[0]);
}
}
@Override
public void cancel(InterpreterContext context) {
}
@Override
public FormType getFormType() {
return FormType.NATIVE;
}
@Override
public int getProgress(InterpreterContext context) {
return 0;
}
@Override
public List<InterpreterCompletion> completion(String buf, int cursor) {
return null;
}
@Override
public Scheduler getScheduler() {
return SchedulerFactory.singleton().createOrGetFIFOScheduler("interpreter_" + this.hashCode());
}
}
| 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-interpreter/src/test/java/org/apache/zeppelin/interpreter/remote/mock/MockInterpreterA.java | smart-zeppelin/zeppelin-interpreter/src/test/java/org/apache/zeppelin/interpreter/remote/mock/MockInterpreterA.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.remote.mock;
import java.util.List;
import java.util.Properties;
import org.apache.zeppelin.interpreter.Interpreter;
import org.apache.zeppelin.interpreter.InterpreterContext;
import org.apache.zeppelin.interpreter.InterpreterException;
import org.apache.zeppelin.interpreter.InterpreterPropertyBuilder;
import org.apache.zeppelin.interpreter.InterpreterResult;
import org.apache.zeppelin.interpreter.InterpreterResult.Code;
import org.apache.zeppelin.interpreter.thrift.InterpreterCompletion;
import org.apache.zeppelin.scheduler.Scheduler;
import org.apache.zeppelin.scheduler.SchedulerFactory;
public class MockInterpreterA extends Interpreter {
private String lastSt;
public MockInterpreterA(Properties property) {
super(property);
}
@Override
public void open() {
//new RuntimeException().printStackTrace();
}
@Override
public void close() {
}
public String getLastStatement() {
return lastSt;
}
@Override
public InterpreterResult interpret(String st, InterpreterContext context) {
try {
Thread.sleep(Long.parseLong(st));
this.lastSt = st;
} catch (NumberFormatException | InterruptedException e) {
throw new InterpreterException(e);
}
return new InterpreterResult(Code.SUCCESS, st);
}
@Override
public void cancel(InterpreterContext context) {
}
@Override
public FormType getFormType() {
return FormType.NATIVE;
}
@Override
public int getProgress(InterpreterContext context) {
return 0;
}
@Override
public List<InterpreterCompletion> completion(String buf, int cursor) {
return null;
}
@Override
public Scheduler getScheduler() {
if (getProperty("parallel") != null && getProperty("parallel").equals("true")) {
return SchedulerFactory.singleton().createOrGetParallelScheduler("interpreter_" + this.hashCode(), 10);
} else {
return SchedulerFactory.singleton().createOrGetFIFOScheduler("interpreter_" + this.hashCode());
}
}
}
| 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-interpreter/src/test/java/org/apache/zeppelin/interpreter/remote/mock/MockInterpreterResourcePool.java | smart-zeppelin/zeppelin-interpreter/src/test/java/org/apache/zeppelin/interpreter/remote/mock/MockInterpreterResourcePool.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.remote.mock;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
import com.google.gson.Gson;
import org.apache.zeppelin.display.AngularObjectRegistry;
import org.apache.zeppelin.display.AngularObjectWatcher;
import org.apache.zeppelin.interpreter.Interpreter;
import org.apache.zeppelin.interpreter.InterpreterContext;
import org.apache.zeppelin.interpreter.InterpreterPropertyBuilder;
import org.apache.zeppelin.interpreter.InterpreterResult;
import org.apache.zeppelin.interpreter.InterpreterResult.Code;
import org.apache.zeppelin.interpreter.thrift.InterpreterCompletion;
import org.apache.zeppelin.resource.Resource;
import org.apache.zeppelin.resource.ResourcePool;
public class MockInterpreterResourcePool extends Interpreter {
AtomicInteger numWatch = new AtomicInteger(0);
public MockInterpreterResourcePool(Properties property) {
super(property);
}
@Override
public void open() {
}
@Override
public void close() {
}
@Override
public InterpreterResult interpret(String st, InterpreterContext context) {
String[] stmt = st.split(" ");
String cmd = stmt[0];
String noteId = null;
String paragraphId = null;
String name = null;
if (stmt.length >= 2) {
String[] npn = stmt[1].split(":");
if (npn.length == 3) {
noteId = npn[0];
paragraphId = npn[1];
name = npn[2];
} else {
name = stmt[1];
}
}
String value = null;
if (stmt.length == 3) {
value = stmt[2];
}
ResourcePool resourcePool = context.getResourcePool();
Object ret = null;
if (cmd.equals("put")) {
resourcePool.put(noteId, paragraphId, name, value);
} else if (cmd.equalsIgnoreCase("get")) {
Resource resource = resourcePool.get(noteId, paragraphId, name);
if (resource != null) {
ret = resourcePool.get(noteId, paragraphId, name).get();
} else {
ret = "";
}
} else if (cmd.equals("remove")) {
ret = resourcePool.remove(noteId, paragraphId, name);
} else if (cmd.equals("getAll")) {
ret = resourcePool.getAll();
}
try {
Thread.sleep(500); // wait for watcher executed
} catch (InterruptedException e) {
}
Gson gson = new Gson();
return new InterpreterResult(Code.SUCCESS, gson.toJson(ret));
}
@Override
public void cancel(InterpreterContext context) {
}
@Override
public FormType getFormType() {
return FormType.NATIVE;
}
@Override
public int getProgress(InterpreterContext context) {
return 0;
}
@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-interpreter/src/test/java/org/apache/zeppelin/interpreter/remote/mock/MockInterpreterAngular.java | smart-zeppelin/zeppelin-interpreter/src/test/java/org/apache/zeppelin/interpreter/remote/mock/MockInterpreterAngular.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.remote.mock;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.zeppelin.display.AngularObjectRegistry;
import org.apache.zeppelin.display.AngularObjectWatcher;
import org.apache.zeppelin.interpreter.Interpreter;
import org.apache.zeppelin.interpreter.InterpreterContext;
import org.apache.zeppelin.interpreter.InterpreterPropertyBuilder;
import org.apache.zeppelin.interpreter.InterpreterResult;
import org.apache.zeppelin.interpreter.InterpreterResult.Code;
import org.apache.zeppelin.interpreter.thrift.InterpreterCompletion;
public class MockInterpreterAngular extends Interpreter {
AtomicInteger numWatch = new AtomicInteger(0);
public MockInterpreterAngular(Properties property) {
super(property);
}
@Override
public void open() {
}
@Override
public void close() {
}
@Override
public InterpreterResult interpret(String st, InterpreterContext context) {
String[] stmt = st.split(" ");
String cmd = stmt[0];
String name = null;
if (stmt.length >= 2) {
name = stmt[1];
}
String value = null;
if (stmt.length == 3) {
value = stmt[2];
}
AngularObjectRegistry registry = context.getAngularObjectRegistry();
if (cmd.equals("add")) {
registry.add(name, value, context.getNoteId(), null);
registry.get(name, context.getNoteId(), null).addWatcher(new AngularObjectWatcher
(null) {
@Override
public void watch(Object oldObject, Object newObject,
InterpreterContext context) {
numWatch.incrementAndGet();
}
});
} else if (cmd.equalsIgnoreCase("update")) {
registry.get(name, context.getNoteId(), null).set(value);
} else if (cmd.equals("remove")) {
registry.remove(name, context.getNoteId(), null);
}
try {
Thread.sleep(500); // wait for watcher executed
} catch (InterruptedException e) {
logger.error("Exception in MockInterpreterAngular while interpret Thread.sleep", e);
}
String msg = registry.getAll(context.getNoteId(), null).size() + " " + Integer.toString(numWatch
.get());
return new InterpreterResult(Code.SUCCESS, msg);
}
@Override
public void cancel(InterpreterContext context) {
}
@Override
public FormType getFormType() {
return FormType.NATIVE;
}
@Override
public int getProgress(InterpreterContext context) {
return 0;
}
@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-interpreter/src/main/java/org/apache/zeppelin/resource/DistributedResourcePool.java | smart-zeppelin/zeppelin-interpreter/src/main/java/org/apache/zeppelin/resource/DistributedResourcePool.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.resource;
/**
* distributed resource pool
*/
public class DistributedResourcePool extends LocalResourcePool {
private final ResourcePoolConnector connector;
public DistributedResourcePool(String id, ResourcePoolConnector connector) {
super(id);
this.connector = connector;
}
@Override
public Resource get(String name) {
return get(name, true);
}
@Override
public Resource get(String noteId, String paragraphId, String name) {
return get(noteId, paragraphId, name, true);
}
/**
* get resource by name.
* @param name
* @param remote false only return from local resource
* @return null if resource not found.
*/
public Resource get(String name, boolean remote) {
// try local first
Resource resource = super.get(name);
if (resource != null) {
return resource;
}
if (remote) {
ResourceSet resources = connector.getAllResources().filterByName(name);
if (resources.isEmpty()) {
return null;
} else {
return resources.get(0);
}
} else {
return null;
}
}
/**
* get resource by name.
* @param name
* @param remote false only return from local resource
* @return null if resource not found.
*/
public Resource get(String noteId, String paragraphId, String name, boolean remote) {
// try local first
Resource resource = super.get(noteId, paragraphId, name);
if (resource != null) {
return resource;
}
if (remote) {
ResourceSet resources = connector.getAllResources()
.filterByNoteId(noteId)
.filterByParagraphId(paragraphId)
.filterByName(name);
if (resources.isEmpty()) {
return null;
} else {
return resources.get(0);
}
} else {
return null;
}
}
@Override
public ResourceSet getAll() {
return getAll(true);
}
/**
* Get all resource from the pool
* @param remote false only return local resource
* @return
*/
public ResourceSet getAll(boolean remote) {
ResourceSet all = super.getAll();
if (remote) {
all.addAll(connector.getAllResources());
}
return all;
}
}
| 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-interpreter/src/main/java/org/apache/zeppelin/resource/Resource.java | smart-zeppelin/zeppelin-interpreter/src/main/java/org/apache/zeppelin/resource/Resource.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.resource;
import java.io.*;
import java.nio.ByteBuffer;
/**
* Information and reference to the resource
*/
public class Resource {
private final transient Object r;
private final boolean serializable;
private final ResourceId resourceId;
private final String className;
/**
* Create local resource
* @param resourceId
* @param r must not be null
*/
Resource(ResourceId resourceId, Object r) {
this.r = r;
this.resourceId = resourceId;
this.serializable = r instanceof Serializable;
this.className = r.getClass().getName();
}
/**
* Create remote object
* @param resourceId
*/
Resource(ResourceId resourceId, boolean serializable, String className) {
this.r = null;
this.resourceId = resourceId;
this.serializable = serializable;
this.className = className;
}
public ResourceId getResourceId() {
return resourceId;
}
public String getClassName() {
return className;
}
/**
*
* @return null when this is remote resource and not serializable.
*/
public Object get() {
if (isLocal() || isSerializable()){
return r;
} else {
return null;
}
}
public boolean isSerializable() {
return serializable;
}
/**
* if it is remote object
* @return
*/
public boolean isRemote() {
return !isLocal();
}
/**
* Whether it is locally accessible or not
* @return
*/
public boolean isLocal() {
return true;
}
public static ByteBuffer serializeObject(Object o) throws IOException {
if (o == null || !(o instanceof Serializable)) {
return null;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
ObjectOutputStream oos;
oos = new ObjectOutputStream(out);
oos.writeObject(o);
oos.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return ByteBuffer.wrap(out.toByteArray());
}
public static Object deserializeObject(ByteBuffer buf)
throws IOException, ClassNotFoundException {
if (buf == null) {
return null;
}
InputStream ins = ByteBufferInputStream.get(buf);
ObjectInputStream oin;
Object object = null;
oin = new ObjectInputStream(ins);
object = oin.readObject();
oin.close();
ins.close();
return object;
}
}
| 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-interpreter/src/main/java/org/apache/zeppelin/resource/ResourcePoolConnector.java | smart-zeppelin/zeppelin-interpreter/src/main/java/org/apache/zeppelin/resource/ResourcePoolConnector.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.resource;
/**
* Connect resource pools running in remote process
*/
public interface ResourcePoolConnector {
/**
* Get list of resources from all other resource pools in remote processes
* @return
*/
public ResourceSet getAllResources();
/**
* Read remote object
* @return
*/
public Object readResource(ResourceId id);
}
| 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-interpreter/src/main/java/org/apache/zeppelin/resource/ResourcePoolUtils.java | smart-zeppelin/zeppelin-interpreter/src/main/java/org/apache/zeppelin/resource/ResourcePoolUtils.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.resource;
import com.google.gson.Gson;
import org.apache.zeppelin.interpreter.InterpreterGroup;
import org.apache.zeppelin.interpreter.remote.RemoteInterpreterManagedProcess;
import org.apache.zeppelin.interpreter.remote.RemoteInterpreterProcess;
import org.apache.zeppelin.interpreter.thrift.RemoteInterpreterService;
import org.slf4j.Logger;
import java.util.List;
/**
* Utilities for ResourcePool
*/
public class ResourcePoolUtils {
static Logger logger = org.slf4j.LoggerFactory.getLogger(ResourcePoolUtils.class);
public static ResourceSet getAllResources() {
return getAllResourcesExcept(null);
}
public static ResourceSet getAllResourcesExcept(String interpreterGroupExcludsion) {
ResourceSet resourceSet = new ResourceSet();
for (InterpreterGroup intpGroup : InterpreterGroup.getAll()) {
if (interpreterGroupExcludsion != null &&
intpGroup.getId().equals(interpreterGroupExcludsion)) {
continue;
}
RemoteInterpreterProcess remoteInterpreterProcess = intpGroup.getRemoteInterpreterProcess();
if (remoteInterpreterProcess == null) {
ResourcePool localPool = intpGroup.getResourcePool();
if (localPool != null) {
resourceSet.addAll(localPool.getAll());
}
} else if (remoteInterpreterProcess.isRunning()) {
RemoteInterpreterService.Client client = null;
boolean broken = false;
try {
client = remoteInterpreterProcess.getClient();
List<String> resourceList = client.resourcePoolGetAll();
Gson gson = new Gson();
for (String res : resourceList) {
resourceSet.add(gson.fromJson(res, Resource.class));
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
broken = true;
} finally {
if (client != null) {
intpGroup.getRemoteInterpreterProcess().releaseClient(client, broken);
}
}
}
}
return resourceSet;
}
public static void removeResourcesBelongsToNote(String noteId) {
removeResourcesBelongsToParagraph(noteId, null);
}
public static void removeResourcesBelongsToParagraph(String noteId, String paragraphId) {
for (InterpreterGroup intpGroup : InterpreterGroup.getAll()) {
ResourceSet resourceSet = new ResourceSet();
RemoteInterpreterProcess remoteInterpreterProcess = intpGroup.getRemoteInterpreterProcess();
if (remoteInterpreterProcess == null) {
ResourcePool localPool = intpGroup.getResourcePool();
if (localPool != null) {
resourceSet.addAll(localPool.getAll());
}
if (noteId != null) {
resourceSet = resourceSet.filterByNoteId(noteId);
}
if (paragraphId != null) {
resourceSet = resourceSet.filterByParagraphId(paragraphId);
}
for (Resource r : resourceSet) {
localPool.remove(
r.getResourceId().getNoteId(),
r.getResourceId().getParagraphId(),
r.getResourceId().getName());
}
} else if (remoteInterpreterProcess.isRunning()) {
RemoteInterpreterService.Client client = null;
boolean broken = false;
try {
client = remoteInterpreterProcess.getClient();
List<String> resourceList = client.resourcePoolGetAll();
Gson gson = new Gson();
for (String res : resourceList) {
resourceSet.add(gson.fromJson(res, Resource.class));
}
if (noteId != null) {
resourceSet = resourceSet.filterByNoteId(noteId);
}
if (paragraphId != null) {
resourceSet = resourceSet.filterByParagraphId(paragraphId);
}
for (Resource r : resourceSet) {
client.resourceRemove(
r.getResourceId().getNoteId(),
r.getResourceId().getParagraphId(),
r.getResourceId().getName());
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
broken = true;
} finally {
if (client != null) {
intpGroup.getRemoteInterpreterProcess().releaseClient(client, broken);
}
}
}
}
}
}
| 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-interpreter/src/main/java/org/apache/zeppelin/resource/ResourceSet.java | smart-zeppelin/zeppelin-interpreter/src/main/java/org/apache/zeppelin/resource/ResourceSet.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.resource;
import java.util.Collection;
import java.util.LinkedList;
import java.util.regex.Pattern;
/**
* List of resources
*/
public class ResourceSet extends LinkedList<Resource> {
public ResourceSet(Collection<Resource> resources) {
super(resources);
}
public ResourceSet() {
super();
}
public ResourceSet filterByNameRegex(String regex) {
ResourceSet result = new ResourceSet();
for (Resource r : this) {
if (Pattern.matches(regex, r.getResourceId().getName())) {
result.add(r);
}
}
return result;
}
public ResourceSet filterByName(String name) {
ResourceSet result = new ResourceSet();
for (Resource r : this) {
if (r.getResourceId().getName().equals(name)) {
result.add(r);
}
}
return result;
}
public ResourceSet filterByClassnameRegex(String regex) {
ResourceSet result = new ResourceSet();
for (Resource r : this) {
if (Pattern.matches(regex, r.getClassName())) {
result.add(r);
}
}
return result;
}
public ResourceSet filterByClassname(String className) {
ResourceSet result = new ResourceSet();
for (Resource r : this) {
if (r.getClassName().equals(className)) {
result.add(r);
}
}
return result;
}
public ResourceSet filterByNoteId(String noteId) {
ResourceSet result = new ResourceSet();
for (Resource r : this) {
if (equals(r.getResourceId().getNoteId(), noteId)) {
result.add(r);
}
}
return result;
}
public ResourceSet filterByParagraphId(String paragraphId) {
ResourceSet result = new ResourceSet();
for (Resource r : this) {
if (equals(r.getResourceId().getParagraphId(), paragraphId)) {
result.add(r);
}
}
return result;
}
private boolean equals(String a, String b) {
if (a == null && b == null) {
return true;
} else if (a != null && b != null) {
return a.equals(b);
} else {
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-interpreter/src/main/java/org/apache/zeppelin/resource/ResourcePool.java | smart-zeppelin/zeppelin-interpreter/src/main/java/org/apache/zeppelin/resource/ResourcePool.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.resource;
/**
* Interface for ResourcePool
*/
public interface ResourcePool {
/**
* Get unique id of the resource pool
* @return
*/
public String id();
/**
* Get resource from name
* @param name Resource name
* @return null if resource not found
*/
public Resource get(String name);
/**
* Get resource from name
* @param noteId
* @param paragraphId
* @param name Resource name
* @return null if resource not found
*/
public Resource get(String noteId, String paragraphId, String name);
/**
* Get all resources
* @return
*/
public ResourceSet getAll();
/**
* Put an object into resource pool
* @param name
* @param object
*/
public void put(String name, Object object);
/**
* Put an object into resource pool
* Given noteId and paragraphId is identifying resource along with name.
* Object will be automatically removed on related note or paragraph removal.
*
* @param noteId
* @param paragraphId
* @param name
* @param object
*/
public void put(String noteId, String paragraphId, String name, Object object);
/**
* Remove object
* @param name Resource name to remove
* @return removed Resource. null if resource not found
*/
public Resource remove(String name);
/**
* Remove object
* @param noteId
* @param paragraphId
* @param name Resource name to remove
* @return removed Resource. null if resource not found
*/
public Resource remove(String noteId, String paragraphId, String name);
}
| 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-interpreter/src/main/java/org/apache/zeppelin/resource/LocalResourcePool.java | smart-zeppelin/zeppelin-interpreter/src/main/java/org/apache/zeppelin/resource/LocalResourcePool.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.resource;
import java.util.*;
/**
* ResourcePool
*/
public class LocalResourcePool implements ResourcePool {
private final String resourcePoolId;
private final Map<ResourceId, Resource> resources = Collections.synchronizedMap(
new HashMap<ResourceId, Resource>());
/**
* @param id unique id
*/
public LocalResourcePool(String id) {
resourcePoolId = id;
}
/**
* Get unique id of this resource pool
* @return
*/
@Override
public String id() {
return resourcePoolId;
}
/**
* Get resource
* @return null if resource not found
*/
@Override
public Resource get(String name) {
ResourceId resourceId = new ResourceId(resourcePoolId, name);
return resources.get(resourceId);
}
@Override
public Resource get(String noteId, String paragraphId, String name) {
ResourceId resourceId = new ResourceId(resourcePoolId, noteId, paragraphId, name);
return resources.get(resourceId);
}
@Override
public ResourceSet getAll() {
return new ResourceSet(resources.values());
}
/**
* Put resource into the pull
* @param
* @param object object to put into the resource
*/
@Override
public void put(String name, Object object) {
ResourceId resourceId = new ResourceId(resourcePoolId, name);
Resource resource = new Resource(resourceId, object);
resources.put(resourceId, resource);
}
@Override
public void put(String noteId, String paragraphId, String name, Object object) {
ResourceId resourceId = new ResourceId(resourcePoolId, noteId, paragraphId, name);
Resource resource = new Resource(resourceId, object);
resources.put(resourceId, resource);
}
@Override
public Resource remove(String name) {
return resources.remove(new ResourceId(resourcePoolId, name));
}
@Override
public Resource remove(String noteId, String paragraphId, String name) {
return resources.remove(new ResourceId(resourcePoolId, noteId, paragraphId, name));
}
}
| 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-interpreter/src/main/java/org/apache/zeppelin/resource/ByteBufferInputStream.java | smart-zeppelin/zeppelin-interpreter/src/main/java/org/apache/zeppelin/resource/ByteBufferInputStream.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.resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
/**
* InputStream from bytebuffer
*/
public class ByteBufferInputStream extends InputStream {
ByteBuffer buf;
public ByteBufferInputStream(ByteBuffer buf) {
this.buf = buf;
}
public int read() throws IOException {
if (!buf.hasRemaining()) {
return -1;
}
return buf.get() & 0xFF;
}
public int read(byte[] bytes, int off, int len) throws IOException {
if (!buf.hasRemaining()) {
return -1;
}
len = Math.min(len, buf.remaining());
buf.get(bytes, off, len);
return len;
}
public static InputStream get(ByteBuffer buf) {
if (buf.hasArray()) {
return new ByteArrayInputStream(buf.array());
} else {
return new ByteBufferInputStream(buf);
}
}
}
| 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-interpreter/src/main/java/org/apache/zeppelin/resource/ResourceId.java | smart-zeppelin/zeppelin-interpreter/src/main/java/org/apache/zeppelin/resource/ResourceId.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.resource;
/**
* Identifying resource
*/
public class ResourceId {
private final String resourcePoolId;
private final String name;
private final String noteId;
private final String paragraphId;
ResourceId(String resourcePoolId, String name) {
this.resourcePoolId = resourcePoolId;
this.noteId = null;
this.paragraphId = null;
this.name = name;
}
ResourceId(String resourcePoolId, String noteId, String paragraphId, String name) {
this.resourcePoolId = resourcePoolId;
this.noteId = noteId;
this.paragraphId = paragraphId;
this.name = name;
}
public String getResourcePoolId() {
return resourcePoolId;
}
public String getName() {
return name;
}
public String getNoteId() {
return noteId;
}
public String getParagraphId() {
return paragraphId;
}
@Override
public int hashCode() {
return (resourcePoolId + noteId + paragraphId + name).hashCode();
}
@Override
public boolean equals(Object o) {
if (o instanceof ResourceId) {
ResourceId r = (ResourceId) o;
return equals(r.name, name) && equals(r.resourcePoolId, resourcePoolId) &&
equals(r.noteId, noteId) && equals(r.paragraphId, paragraphId);
} else {
return false;
}
}
private boolean equals(String a, String b) {
if (a == null && b == null) {
return true;
} else if (a != null && b != null) {
return a.equals(b);
} else {
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-interpreter/src/main/java/org/apache/zeppelin/resource/RemoteResource.java | smart-zeppelin/zeppelin-interpreter/src/main/java/org/apache/zeppelin/resource/RemoteResource.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.resource;
/**
* Resource that can retrieve data from remote
*/
public class RemoteResource extends Resource {
ResourcePoolConnector resourcePoolConnector;
RemoteResource(ResourceId resourceId, Object r) {
super(resourceId, r);
}
RemoteResource(ResourceId resourceId, boolean serializable, String className) {
super(resourceId, serializable, className);
}
@Override
public Object get() {
if (isSerializable()) {
Object o = resourcePoolConnector.readResource(getResourceId());
return o;
} else {
return null;
}
}
@Override
public boolean isLocal() {
return false;
}
public ResourcePoolConnector getResourcePoolConnector() {
return resourcePoolConnector;
}
public void setResourcePoolConnector(ResourcePoolConnector resourcePoolConnector) {
this.resourcePoolConnector = resourcePoolConnector;
}
}
| 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-interpreter/src/main/java/org/apache/zeppelin/resource/WellKnownResourceName.java | smart-zeppelin/zeppelin-interpreter/src/main/java/org/apache/zeppelin/resource/WellKnownResourceName.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.resource;
/**
* Well known resource names in ResourcePool
*/
public enum WellKnownResourceName {
ZeppelinReplResult("zeppelin.repl.result"), // last object of repl
ZeppelinTableResult("zeppelin.paragraph.result.table"); // paragraph run result
String name;
WellKnownResourceName(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
| 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-interpreter/src/main/java/org/apache/zeppelin/helium/ApplicationEventListener.java | smart-zeppelin/zeppelin-interpreter/src/main/java/org/apache/zeppelin/helium/ApplicationEventListener.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.interpreter.InterpreterResult;
/**
* Event from HeliumApplication running on remote interpreter process
*/
public interface ApplicationEventListener {
public void onOutputAppend(
String noteId, String paragraphId, int index, String appId, String output);
public void onOutputUpdated(
String noteId, String paragraphId, int index, String appId,
InterpreterResult.Type type, String output);
public void onLoad(String noteId, String paragraphId, String appId, HeliumPackage pkg);
public void onStatusChange(String noteId, String paragraphId, String appId, String status);
}
| 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-interpreter/src/main/java/org/apache/zeppelin/helium/ApplicationException.java | smart-zeppelin/zeppelin-interpreter/src/main/java/org/apache/zeppelin/helium/ApplicationException.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;
/**
* Application exception
*/
public class ApplicationException extends Exception {
public ApplicationException(String s) {
super(s);
}
public ApplicationException(Exception e) {
super(e);
}
public 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-interpreter/src/main/java/org/apache/zeppelin/helium/ClassLoaderApplication.java | smart-zeppelin/zeppelin-interpreter/src/main/java/org/apache/zeppelin/helium/ClassLoaderApplication.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;
/**
* Application wrapper
*/
public class ClassLoaderApplication extends Application {
Application app;
ClassLoader cl;
public ClassLoaderApplication(Application app, ClassLoader cl) throws ApplicationException {
super(app.context());
this.app = app;
this.cl = cl;
}
@Override
public void run(ResourceSet args) throws ApplicationException {
// instantiate
ClassLoader oldcl = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(cl);
try {
app.run(args);
} catch (ApplicationException e) {
throw e;
} catch (Exception e) {
throw new ApplicationException(e);
} finally {
Thread.currentThread().setContextClassLoader(oldcl);
}
}
@Override
public void unload() throws ApplicationException {
// instantiate
ClassLoader oldcl = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(cl);
try {
app.unload();
} catch (ApplicationException e) {
throw e;
} catch (Exception e) {
throw new ApplicationException(e);
} finally {
Thread.currentThread().setContextClassLoader(oldcl);
}
}
public ClassLoader getClassLoader() {
return cl;
}
public Application getInnerApplication() {
return app;
}
}
| 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-interpreter/src/main/java/org/apache/zeppelin/helium/HeliumPackage.java | smart-zeppelin/zeppelin-interpreter/src/main/java/org/apache/zeppelin/helium/HeliumPackage.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.annotation.Experimental;
/**
* Helium package definition
*/
@Experimental
public class HeliumPackage {
private Type type;
private String name; // user friendly name of this application
private String description; // description
private String artifact; // artifact name e.g) groupId:artifactId:versionId
private String className; // entry point
private String [][] resources; // resource classnames that requires
// [[ .. and .. and .. ] or [ .. and .. and ..] ..]
private String license;
private String icon;
/**
* Type of package
*/
public static enum Type {
INTERPRETER,
NOTEBOOK_REPO,
APPLICATION,
VISUALIZATION
}
public HeliumPackage(Type type,
String name,
String description,
String artifact,
String className,
String[][] resources,
String license,
String icon) {
this.type = type;
this.name = name;
this.description = description;
this.artifact = artifact;
this.className = className;
this.resources = resources;
this.license = license;
this.icon = icon;
}
@Override
public int hashCode() {
return (type.toString() + artifact + className).hashCode();
}
@Override
public boolean equals(Object o) {
if (!(o instanceof HeliumPackage)) {
return false;
}
HeliumPackage info = (HeliumPackage) o;
return type == info.type && artifact.equals(info.artifact) && className.equals(info.className);
}
public Type getType() {
return type;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public String getArtifact() {
return artifact;
}
public String getClassName() {
return className;
}
public String[][] getResources() {
return resources;
}
public String getLicense() {
return license;
}
public String getIcon() {
return icon;
}
}
| 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-interpreter/src/main/java/org/apache/zeppelin/helium/HeliumAppAngularObjectRegistry.java | smart-zeppelin/zeppelin-interpreter/src/main/java/org/apache/zeppelin/helium/HeliumAppAngularObjectRegistry.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.display.AngularObject;
import org.apache.zeppelin.display.AngularObjectRegistry;
import java.util.List;
/**
* Angular Registry for helium app
*/
public class HeliumAppAngularObjectRegistry {
private final String noteId;
private final String appId;
private final AngularObjectRegistry angularObjectRegistry;
public HeliumAppAngularObjectRegistry(AngularObjectRegistry angularObjectRegistry,
String noteId,
String appId) {
this.angularObjectRegistry = angularObjectRegistry;
this.noteId = noteId;
this.appId = appId;
}
public AngularObject add(String name, Object o) {
return angularObjectRegistry.add(name, o, noteId, appId);
}
public AngularObject remove(String name) {
return angularObjectRegistry.remove(name, noteId, appId);
}
public AngularObject get(String name) {
return angularObjectRegistry.get(name, noteId, appId);
}
public List<AngularObject> getAll() {
return angularObjectRegistry.getAll(noteId, appId);
}
}
| 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-interpreter/src/main/java/org/apache/zeppelin/helium/ApplicationLoader.java | smart-zeppelin/zeppelin-interpreter/src/main/java/org/apache/zeppelin/helium/ApplicationLoader.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.dep.DependencyResolver;
import org.apache.zeppelin.resource.DistributedResourcePool;
import org.apache.zeppelin.resource.Resource;
import org.apache.zeppelin.resource.ResourcePool;
import org.apache.zeppelin.resource.ResourceSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.*;
/**
* Load application
*/
public class ApplicationLoader {
Logger logger = LoggerFactory.getLogger(ApplicationLoader.class);
private final DependencyResolver depResolver;
private final ResourcePool resourcePool;
private final Map<HeliumPackage, Class<Application>> cached;
public ApplicationLoader(ResourcePool resourcePool, DependencyResolver depResolver) {
this.depResolver = depResolver;
this.resourcePool = resourcePool;
cached = Collections.synchronizedMap(
new HashMap<HeliumPackage, Class<Application>>());
}
/**
* Information of loaded application
*/
private static class RunningApplication {
HeliumPackage packageInfo;
String noteId;
String paragraphId;
public RunningApplication(HeliumPackage packageInfo, String noteId, String paragraphId) {
this.packageInfo = packageInfo;
this.noteId = noteId;
this.paragraphId = paragraphId;
}
public HeliumPackage getPackageInfo() {
return packageInfo;
}
public String getNoteId() {
return noteId;
}
public String getParagraphId() {
return paragraphId;
}
@Override
public int hashCode() {
return (paragraphId + noteId + packageInfo.getArtifact() + packageInfo.getClassName())
.hashCode();
}
@Override
public boolean equals(Object o) {
if (!(o instanceof RunningApplication)) {
return false;
}
RunningApplication r = (RunningApplication) o;
return packageInfo.equals(r.getPackageInfo()) && paragraphId.equals(r.getParagraphId()) &&
noteId.equals(r.getNoteId());
}
}
/**
*
* Instantiate application
*
* @param packageInfo
* @param context
* @return
* @throws Exception
*/
public Application load(HeliumPackage packageInfo, ApplicationContext context)
throws Exception {
if (packageInfo.getType() != HeliumPackage.Type.APPLICATION) {
throw new ApplicationException(
"Can't instantiate " + packageInfo.getType() + " package using ApplicationLoader");
}
// check if already loaded
RunningApplication key =
new RunningApplication(packageInfo, context.getNoteId(), context.getParagraphId());
// get resource required by this package
ResourceSet resources = findRequiredResourceSet(packageInfo.getResources(),
context.getNoteId(), context.getParagraphId());
// load class
Class<Application> appClass = loadClass(packageInfo);
// instantiate
ClassLoader oldcl = Thread.currentThread().getContextClassLoader();
ClassLoader cl = appClass.getClassLoader();
Thread.currentThread().setContextClassLoader(cl);
try {
Constructor<Application> constructor = appClass.getConstructor(ApplicationContext.class);
Application app = new ClassLoaderApplication(constructor.newInstance(context), cl);
return app;
} catch (Exception e) {
throw new ApplicationException(e);
} finally {
Thread.currentThread().setContextClassLoader(oldcl);
}
}
public ResourceSet findRequiredResourceSet(
String [][] requiredResources, String noteId, String paragraphId) {
if (requiredResources == null || requiredResources.length == 0) {
return new ResourceSet();
}
ResourceSet allResources;
if (resourcePool instanceof DistributedResourcePool) {
allResources = ((DistributedResourcePool) resourcePool).getAll(false);
} else {
allResources = resourcePool.getAll();
}
return findRequiredResourceSet(requiredResources, noteId, paragraphId, allResources);
}
static ResourceSet findRequiredResourceSet(String [][] requiredResources,
String noteId,
String paragraphId,
ResourceSet resources) {
ResourceSet args = new ResourceSet();
if (requiredResources == null || requiredResources.length == 0) {
return args;
}
resources = resources.filterByNoteId(noteId).filterByParagraphId(paragraphId);
for (String [] requires : requiredResources) {
args.clear();
for (String require : requires) {
boolean found = false;
for (Resource r : resources) {
if (require.startsWith(":") && r.getClassName().equals(require.substring(1))) {
found = true;
} else if (r.getResourceId().getName().equals(require)) {
found = true;
}
if (found) {
args.add(r);
break;
}
}
if (found == false) {
break;
}
}
if (args.size() == requires.length) {
return args;
}
}
return null;
}
private Class<Application> loadClass(HeliumPackage packageInfo) throws Exception {
if (cached.containsKey(packageInfo)) {
return cached.get(packageInfo);
}
// Create Application classloader
List<URL> urlList = new LinkedList<>();
// load artifact
if (packageInfo.getArtifact() != null) {
List<File> paths = depResolver.load(packageInfo.getArtifact());
if (paths != null) {
for (File path : paths) {
urlList.add(path.toURI().toURL());
}
}
}
URLClassLoader applicationClassLoader =
new URLClassLoader(
urlList.toArray(new URL[]{}),
Thread.currentThread().getContextClassLoader());
Class<Application> cls =
(Class<Application>) applicationClassLoader.loadClass(packageInfo.getClassName());
cached.put(packageInfo, cls);
return cls;
}
}
| 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.