file_name stringlengths 6 86 | file_path stringlengths 45 249 | content stringlengths 47 6.26M | file_size int64 47 6.26M | language stringclasses 1 value | extension stringclasses 1 value | repo_name stringclasses 767 values | repo_stars int64 8 14.4k | repo_forks int64 0 1.17k | repo_open_issues int64 0 788 | repo_created_at stringclasses 767 values | repo_pushed_at stringclasses 767 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
BeanThreadScope.java | /FileExtraction/Java_unseen/dataconsulting-pl_APEX-Low-Test-Framework/src/main/java/pl/dataconsulting/APEX_TAF/framework/annotation/BeanThreadScope.java | package pl.dataconsulting.APEX_TAF.framework.annotation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.lang.annotation.*;
@Bean
@Scope("driverscope")
@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface BeanThreadScope {
}
| 441 | Java | .java | dataconsulting-pl/APEX-Low-Test-Framework | 11 | 0 | 13 | 2022-06-28T07:57:50Z | 2023-02-27T10:25:42Z |
APEXComponent.java | /FileExtraction/Java_unseen/dataconsulting-pl_APEX-Low-Test-Framework/src/main/java/pl/dataconsulting/APEX_TAF/framework/annotation/APEXComponent.java | package pl.dataconsulting.APEX_TAF.framework.annotation;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.lang.annotation.*;
@Lazy
@Component
@Scope("prototype")
@Documented
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface APEXComponent {
}
| 394 | Java | .java | dataconsulting-pl/APEX-Low-Test-Framework | 11 | 0 | 13 | 2022-06-28T07:57:50Z | 2023-02-27T10:25:42Z |
WebDriverConfig.java | /FileExtraction/Java_unseen/dataconsulting-pl_APEX-Low-Test-Framework/src/main/java/pl/dataconsulting/APEX_TAF/framework/config/WebDriverConfig.java | package pl.dataconsulting.APEX_TAF.framework.config;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import pl.dataconsulting.APEX_TAF.framework.annotation.BeanThreadScope;
import java.time.Duration;
@Lazy
@Configuration
public class WebDriverConfig {
@Value("${timeout:300}")
private Duration timeout;
@BeanThreadScope
@Scope("driverscope")
@ConditionalOnProperty(name = "browser", havingValue = "chrome")
public WebDriver chromeDriver(){
WebDriverManager.chromedriver().setup();
return new ChromeDriver();
}
@BeanThreadScope
@ConditionalOnProperty(name = "browser", havingValue = "firefox")
public WebDriver firefoxDriver(){
WebDriverManager.firefoxdriver().setup();
return new FirefoxDriver();
}
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public WebDriverWait webDriverWait(WebDriver driver) {
return new WebDriverWait(driver,this.timeout);
}
}
| 1,589 | Java | .java | dataconsulting-pl/APEX-Low-Test-Framework | 11 | 0 | 13 | 2022-06-28T07:57:50Z | 2023-02-27T10:25:42Z |
ScreenShotService.java | /FileExtraction/Java_unseen/dataconsulting-pl_APEX-Low-Test-Framework/src/main/java/pl/dataconsulting/APEX_TAF/framework/service/ScreenShotService.java | package pl.dataconsulting.APEX_TAF.framework.service;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
@Lazy
@Service
public class ScreenShotService {
@Autowired
ApplicationContext ctx;
@Value("${screenshot.path}/")
private Path path;
public void takeScreenShot(final String imageName) throws IOException {
File sourceFile = ((TakesScreenshot) this.ctx.getBean(WebDriver.class)).getScreenshotAs(OutputType.FILE);
String tmp = this.path.resolve(imageName).toString();
FileCopyUtils.copy(sourceFile, this.path.resolve(imageName).toFile());
}
public byte[] getScreenshot(){
return this.ctx.getBean(TakesScreenshot.class).getScreenshotAs(OutputType.BYTES);
}
}
| 1,203 | Java | .java | dataconsulting-pl/APEX-Low-Test-Framework | 11 | 0 | 13 | 2022-06-28T07:57:50Z | 2023-02-27T10:25:42Z |
Asserts.java | /FileExtraction/Java_unseen/dataconsulting-pl_APEX-Low-Test-Framework/src/main/java/pl/dataconsulting/APEX_TAF/framework/util/Asserts.java | package pl.dataconsulting.APEX_TAF.framework.util;
import org.springframework.stereotype.Component;
import org.testng.Assert;
@Component
public class Asserts {
public void assertEqualRegexp(String action, String fieldName, String expected, String was) {
if (!was.matches(expected)) {
setFail(action, fieldName, expected, was);
} else {
System.out.println("OK " + fieldName);
}
}
private void setFail(String action, String fieldName, String expected, String was) {
String messageTemplate = "Value for the column \"%s\" does not match. Expected: '%s' but was: '%s'";
Assert.fail(action + " Expected result: " + String.format(messageTemplate, fieldName, expected, was));
}
}
| 756 | Java | .java | dataconsulting-pl/APEX-Low-Test-Framework | 11 | 0 | 13 | 2022-06-28T07:57:50Z | 2023-02-27T10:25:42Z |
Application.java | /FileExtraction/Java_unseen/DLand-Team_java-browser/Code/src/browser/Application.java | package browser;
import browser.rx.service.InnerMqService;
import browser.ui.MainFrame;
import javax.swing.*;
public class Application {
public static void main(String[] args) {
// 设置主题
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
// UIManager.setLookAndFeel("com.formdev.flatlaf.FlatIntelliJLaf");
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
| UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
// 界面相关配置
JPopupMenu.setDefaultLightWeightPopupEnabled(false);
ToolTipManager.sharedInstance().setLightWeightPopupEnabled(false);
// 注册rxjava
InnerMqService.getInstance();
// 启动界面
SwingUtilities.invokeLater(() -> {
MainFrame.getInstance();
});
}
}
| 927 | Java | .java | DLand-Team/java-browser | 9 | 3 | 0 | 2022-12-29T12:36:36Z | 2023-01-02T08:32:11Z |
Cache.java | /FileExtraction/Java_unseen/DLand-Team_java-browser/Code/src/browser/common/Cache.java | package browser.common;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import browser.assets.entity.History;
import browser.assets.entity.Setting;
import browser.util.BeanUtils;
import browser.util.CommonUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.parser.Feature;
public class Cache {
// 加载历史记录
public static LinkedHashMap<String, History> historyMap = new LinkedHashMap<String, History>() {
{
try {
File dir = new File(Static.HISTORY_JSON_DIR);
if (!dir.exists() || !dir.isDirectory()) {
dir.mkdirs();
}
File file = new File(Static.HISTORY_JSON_PATH);
if (!file.exists() || !file.isFile()) {
CommonUtils.saveStringToFile("{}", Static.HISTORY_JSON_PATH);
}
String str = CommonUtils.readFile(Static.HISTORY_JSON_PATH);
LinkedHashMap<String, History> map = JSONArray.parseObject(str,
new TypeReference<LinkedHashMap<String, History>>() {
}, Feature.OrderedField);
Iterator<Map.Entry<String, History>> iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, History> entry = iter.next();
this.put(entry.getKey(), entry.getValue());
}
} catch (IOException e) {
e.printStackTrace();
}
}
};
// 加载设置
public static Setting setting = new Setting() {
{
Setting st;
try {
File dir = new File(Static.SETTING_JSON_DIR);
if (!dir.exists() || !dir.isDirectory()) {
dir.mkdirs();
}
File file = new File(Static.SETTING_JSON_PATH);
if (!file.exists() || !file.isFile()) {
CommonUtils.saveStringToFile(JSON.toJSONString(new Setting("default")), Static.SETTING_JSON_PATH);
}
String str = CommonUtils.readFile(Static.SETTING_JSON_PATH);
st = JSON.parseObject(str, Setting.class);
} catch (IOException e) {
st = new Setting("default");
e.printStackTrace();
}
try {
BeanUtils.copy(this, st);
} catch (Exception e) {
e.printStackTrace();
}
}
};
} | 2,688 | Java | .java | DLand-Team/java-browser | 9 | 3 | 0 | 2022-12-29T12:36:36Z | 2023-01-02T08:32:11Z |
Static.java | /FileExtraction/Java_unseen/DLand-Team_java-browser/Code/src/browser/common/Static.java | package browser.common;
import browser.util.CommonUtils;
public class Static {
public static final boolean IS_Mac = CommonUtils.isMac();
public static final boolean IS_Windows = CommonUtils.isWindows();
public static final boolean IS_Windows_10 = CommonUtils.isWindows10();
public static final boolean IS_Windows_11 = CommonUtils.isWindows11();
public final static String VERSION = "0.0.1";
public final static String DEFAULT_MAIN_PAGE_ADDRESS = "intelyes.club";
public final static Integer DEFAULT_WIDTH = 1280;
public final static Integer DEFAULT_HEIGHT = 720;
public final static Boolean DEFAULT_IS_MAX_WINDOW = true;
public final static String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.62";
public final static String GIT_ADDRESS = "https://gitee.com/CrimsonHu/chromium_browser_based_on_java";
public final static String HISTORY_JSON_DIR = System.getProperty("user.dir") + "/cache/";
public final static String HISTORY_JSON_PATH = System.getProperty("user.dir") + "/cache/history.json";
public final static String SETTING_JSON_DIR = System.getProperty("user.dir") + "/prefer/";
public final static String SETTING_JSON_PATH = System.getProperty("user.dir") + "/prefer/setting.json";
}
| 1,314 | Java | .java | DLand-Team/java-browser | 9 | 3 | 0 | 2022-12-29T12:36:36Z | 2023-01-02T08:32:11Z |
Script.java | /FileExtraction/Java_unseen/DLand-Team_java-browser/Code/src/browser/common/Script.java | package browser.common;
public class Script {
public static String getIconHref(int browserId) {
return "" +
"{" +
"let sendData = 'get_favicon_href__';" +
"let links = document.getElementsByTagName('link');" +
"if (links != null) {" +
"for (let i = 0; i < links.length; i++) {" +
"let has = false;" +
"let names = links[0].getAttributeNames();" +
"for (let j = 0; j < names.length; j++) {" +
"if (links[0].getAttribute(names[j]) == 'icon' || links[0].getAttribute(names[j]) == 'shortcut icon' ) {" +
"sendData += links[0].getAttribute('href');" +
"has = true;" +
"break;" +
"}" +
"}" +
"if (has) { break; }" +
"}" +
"}" +
"window.cef_java_" + browserId + "({" +
"request: sendData," +
"persistent:false" +
"});" +
"}" +
"";
}
public static String getTitle(int browserId) {
return "" +
"{" +
"let sendData = 'get_title__';" +
"let titles = document.getElementsByTagName('title');" +
"if (titles != null) {" +
"sendData += titles[0].innerText;" +
"}" +
"window.cef_java_" + browserId + "({" +
"request: sendData," +
"persistent:false" +
"});" +
"}" +
"";
}
}
| 1,653 | Java | .java | DLand-Team/java-browser | 9 | 3 | 0 | 2022-12-29T12:36:36Z | 2023-01-02T08:32:11Z |
Setting.java | /FileExtraction/Java_unseen/DLand-Team_java-browser/Code/src/browser/assets/entity/Setting.java | package browser.assets.entity;
import browser.common.Static;
import lombok.Data;
@Data
public class Setting {
private String mainPageAddress;
private Integer defaultWidth;
private Integer defaultHeight;
private Boolean isMaxWindow;
public Setting() {
}
public Setting(String type) {
switch (type) {
case "default":
this.mainPageAddress = Static.DEFAULT_MAIN_PAGE_ADDRESS;
this.defaultWidth = Static.DEFAULT_WIDTH;
this.defaultHeight = Static.DEFAULT_HEIGHT;
this.isMaxWindow = Static.DEFAULT_IS_MAX_WINDOW;
break;
default:
break;
}
}
}
| 577 | Java | .java | DLand-Team/java-browser | 9 | 3 | 0 | 2022-12-29T12:36:36Z | 2023-01-02T08:32:11Z |
History.java | /FileExtraction/Java_unseen/DLand-Team_java-browser/Code/src/browser/assets/entity/History.java | package browser.assets.entity;
import java.io.Serializable;
import lombok.Data;
@Data
public class History implements Serializable {
private String time;
private String fullUrl;
private String host;
private String title;
}
| 232 | Java | .java | DLand-Team/java-browser | 9 | 3 | 0 | 2022-12-29T12:36:36Z | 2023-01-02T08:32:11Z |
MainFrame.java | /FileExtraction/Java_unseen/DLand-Team_java-browser/Code/src/browser/ui/MainFrame.java | package browser.ui;
import browser.assets.entity.History;
import browser.common.Cache;
import browser.common.Static;
import browser.rx.TOPIC;
import browser.rx.client.InnerMqClient;
import browser.rx.service.InnerMqService;
import browser.ui.component.menu.HistoryMenu;
import browser.ui.component.menu.SettingMenu;
import browser.ui.component.menu.ToolMenu;
import browser.ui.component.tab.TabbedPane;
import browser.ui.factory.TabFactory;
import browser.util.CommonUtils;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.ListIterator;
import java.util.Map;
public class MainFrame extends JFrame {
private static volatile MainFrame instance;
private final InnerMqService innerMqService = InnerMqService.getInstance();
private final InnerMqClient client = this.innerMqService.createConnect("MainFrame");
public TabbedPane tabbedPane = new TabbedPane();
public HistoryMenu historyMenu = new HistoryMenu() {
{
if (Cache.historyMap.size() > 0) {
ArrayList<History> lase15History = new ArrayList<>();
ListIterator<Map.Entry<String, History>> iter = new ArrayList<Map.Entry<String, History>>(
Cache.historyMap.entrySet()).listIterator(Cache.historyMap.size());
int count = 1;
while (iter.hasPrevious()) {
Map.Entry<String, History> entry = iter.previous();
lase15History.add(entry.getValue());
count = count + 1;
if (count >= 15) {
break;
}
}
for (int i = lase15History.size() - 1; i >= 0; i--) {
this.addHistoryItem(lase15History.get(i));
}
}
}
};
public ToolMenu toolMenu = new ToolMenu();
public SettingMenu settingMenu = new SettingMenu();
public MainFrame() {
this.setIconImage(
Toolkit.getDefaultToolkit().getImage(MainFrame.class.getResource("/browser/assets/img/icon/chrome_1.png")));
this.getContentPane().setLayout(new BorderLayout(0, 0));
this.getContentPane().add(this.tabbedPane, BorderLayout.CENTER);
/* 默认首页 */
TabFactory.insertTabSync(this.tabbedPane, Cache.setting.getMainPageAddress());
/* -END- 默认首页 */
/* rxjava监听 */
this.subInnerMqMessage();
this.setTitle("Moderate浏览器 - " + Static.VERSION);
if (Cache.setting.getIsMaxWindow()) {
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
this.setSize(new Dimension(Static.DEFAULT_WIDTH, Static.DEFAULT_HEIGHT));
} else {
this.setSize(new Dimension(Cache.setting.getDefaultWidth(), Cache.setting.getDefaultHeight()));
}
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setLocation((Toolkit.getDefaultToolkit().getScreenSize().width - this.getWidth()) / 2,
(Toolkit.getDefaultToolkit().getScreenSize().height - this.getHeight()) / 2);
this.setVisible(true);
this.setResizable(true);
this.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
Cache.setting.setDefaultWidth(e.getComponent().getWidth());
Cache.setting.setDefaultHeight(e.getComponent().getHeight());
CommonUtils.saveSetting();
}
});
this.addWindowStateListener(new WindowStateListener() {
public void windowStateChanged(WindowEvent state) {
if (state.getNewState() == 1 || state.getNewState() == 7) {
Cache.setting.setIsMaxWindow(true);
} else if (state.getNewState() == 0) {
Cache.setting.setIsMaxWindow(false);
} else if (state.getNewState() == 6) {
Cache.setting.setIsMaxWindow(true);
}
CommonUtils.saveSetting();
}
});
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
MainFrame.getInstance().setVisible(false);
innerMqService.destroyClient(client);
tabbedPane.disposeAllTabs();
System.exit(0);
}
});
}
private void subInnerMqMessage() {
this.client.sub(TOPIC.OPEN_NEW_PAGE, (res) -> {
TabFactory.insertTabAsync(this.tabbedPane, (String) res);
});
}
public static MainFrame getInstance() {
if (instance == null) {
synchronized (MainFrame.class) {
if (instance == null) {
instance = new MainFrame();
}
}
}
return instance;
}
}
| 4,956 | Java | .java | DLand-Team/java-browser | 9 | 3 | 0 | 2022-12-29T12:36:36Z | 2023-01-02T08:32:11Z |
TabFactory.java | /FileExtraction/Java_unseen/DLand-Team_java-browser/Code/src/browser/ui/factory/TabFactory.java | package browser.ui.factory;
import browser.ui.component.tab.Tab;
import browser.ui.component.tab.TabCaption;
import browser.ui.component.tab.TabContent;
import browser.ui.component.tab.TabbedPane;
import javax.swing.SwingUtilities;
import java.util.Random;
public final class TabFactory {
/* 异步添加Tab */
public static void insertTabAsync(TabbedPane tabbedPane, String url) {
SwingUtilities.invokeLater(() -> {
insertTab(tabbedPane, url);
});
}
/* 同步添加Tab */
public static void insertTabSync(TabbedPane tabbedPane, String url) {
insertTab(tabbedPane, url);
}
/* insertTab */
private static void insertTab(TabbedPane tabbedPane, String url) {
Tab tab = createTab(tabbedPane, url);
tabbedPane.addTab(tab);
tabbedPane.selectTab(tab);
}
/* createTab */
private static Tab createTab(TabbedPane tabbedPane, String url) {
int browserId = new Random().nextInt(Integer.MAX_VALUE);
// Tab标头
TabCaption tabCaption = new TabCaption(browserId, url);
// Tab容器
TabContent tabContent = new TabContent(browserId, url);
return new Tab(tabCaption, tabContent);
}
}
| 1,232 | Java | .java | DLand-Team/java-browser | 9 | 3 | 0 | 2022-12-29T12:36:36Z | 2023-01-02T08:32:11Z |
HistoryFactory.java | /FileExtraction/Java_unseen/DLand-Team_java-browser/Code/src/browser/ui/factory/HistoryFactory.java | package browser.ui.factory;
public class HistoryFactory {
/** 添加历史记录 */
public static void addHistory(String timeValue) {
}
/** 删除某项历史记录 */
public static void removeSingleHistory(String timeValue) {
}
/** 删除全部历史记录 */
public static void removeAllHistory() {
}
/** 保存历史记录 */
private static void saveHistory(Object history) {
}
}
| 405 | Java | .java | DLand-Team/java-browser | 9 | 3 | 0 | 2022-12-29T12:36:36Z | 2023-01-02T08:32:11Z |
ToolMenu.java | /FileExtraction/Java_unseen/DLand-Team_java-browser/Code/src/browser/ui/component/menu/ToolMenu.java | package browser.ui.component.menu;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
public class ToolMenu extends JPopupMenu {
public ToolMenu() {
JMenuItem htmlItem = new JMenuItem("查看html代码");
htmlItem.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
}
});
this.add(htmlItem);
}
}
| 439 | Java | .java | DLand-Team/java-browser | 9 | 3 | 0 | 2022-12-29T12:36:36Z | 2023-01-02T08:32:11Z |
SettingMenu.java | /FileExtraction/Java_unseen/DLand-Team_java-browser/Code/src/browser/ui/component/menu/SettingMenu.java | package browser.ui.component.menu;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
public class SettingMenu extends JPopupMenu {
public SettingMenu() {
JMenuItem settingItem = new JMenuItem("设置");
this.add(settingItem);
JMenuItem aboutItem = new JMenuItem("关于");
this.add(aboutItem);
}
}
| 332 | Java | .java | DLand-Team/java-browser | 9 | 3 | 0 | 2022-12-29T12:36:36Z | 2023-01-02T08:32:11Z |
HistoryMenu.java | /FileExtraction/Java_unseen/DLand-Team_java-browser/Code/src/browser/ui/component/menu/HistoryMenu.java | package browser.ui.component.menu;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.util.LinkedHashMap;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import browser.assets.entity.History;
import browser.common.Static;
import browser.ui.MainFrame;
import browser.ui.component.menu.item.HistoryMenuItem;
import browser.ui.factory.HistoryFactory;
import browser.ui.factory.TabFactory;
import browser.util.CommonUtils;
public class HistoryMenu extends JPopupMenu {
private JPopupMenu menu = this;
private LinkedHashMap<String, HistoryMenuItem> itemMap = new LinkedHashMap<String, HistoryMenuItem>();
public HistoryMenu() {
JMenuItem historyItem = new JMenuItem("所有历史记录...");
historyItem.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
try {
File historyFile = new File(Static.HISTORY_JSON_PATH);
String js = "let historyJsonText = {}";
if (historyFile.exists() && historyFile.isFile()) {
String json = CommonUtils.readFile(historyFile.getAbsolutePath());
js = "let historyJsonText = '" + json + "'";
}
CommonUtils.saveStringToFile(js,
System.getProperty("user.dir") + "\\resource\\history\\js\\data\\HistoryJsonText.js");
} catch (IOException ex) {
ex.printStackTrace();
}
TabFactory.insertTabAsync(MainFrame.getInstance().tabbedPane,
"file:///" + System.getProperty("user.dir") + "\\resource\\history\\index.html");
}
});
JMenuItem historyCleanItem = new JMenuItem("清空历史记录");
historyCleanItem.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (e.getButton() == 1) {
int n = JOptionPane.showConfirmDialog(MainFrame.getInstance(), "是否删除所有历史记录?");
if (n == JOptionPane.YES_OPTION) {
HistoryFactory.removeAllHistory();
itemMap.keySet().forEach((key) -> menu.remove(itemMap.get(key)));
itemMap.clear();
JOptionPane.showMessageDialog(MainFrame.getInstance(), "已删除历史记录");
}
}
}
});
this.add(historyItem);
this.add(historyCleanItem);
}
public void addHistoryItem(History history) {
HistoryMenuItem item = null;
String pageIconPath = System.getProperty("user.dir") + "\\cache\\" + history.getHost() + "\\favicon.png";
if (itemMap.get(history.getTime().toString()) == null) {
String pageTitle = history.getTitle();
item = new HistoryMenuItem(pageIconPath, pageTitle, history.getTime());
this.add(item, 1);
} else {
item = itemMap.get(history.getTime().toString());
item.setPageIcon(pageIconPath);
item.setPageText(history.getTitle());
}
item.setInnerUrl(history.getFullUrl());
itemMap.put(history.getTime().toString(), item);
if (itemMap.size() > 15) {
String key = itemMap.entrySet().iterator().next().getKey();
this.remove(itemMap.get(key));
itemMap.remove(key);
}
item.itemResize(item, 500);
}
public void removeHistoryItem(String timeValue) {
this.remove(itemMap.get(timeValue));
itemMap.remove(timeValue);
this.setVisible(false);
}
}
| 3,859 | Java | .java | DLand-Team/java-browser | 9 | 3 | 0 | 2022-12-29T12:36:36Z | 2023-01-02T08:32:11Z |
HistoryMenuItem.java | /FileExtraction/Java_unseen/DLand-Team_java-browser/Code/src/browser/ui/component/menu/item/HistoryMenuItem.java | package browser.ui.component.menu.item;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import browser.ui.MainFrame;
import browser.ui.factory.TabFactory;
import browser.util.CommonUtils;
import browser.util.FontUtils;
public class HistoryMenuItem extends JMenuItem {
private int height = 25;
private String time;
private String innerUrl;
public HistoryMenuItem(String iconPath, String title, String time) {
this.time = time;
this.setLayout(new BorderLayout());
this.addPageIcon(iconPath);
this.addPageTitle(title);
this.addCloseButton();
this.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
TabFactory.insertTabAsync(MainFrame.getInstance().tabbedPane, getInnerUrl());
}
});
}
/* set */
public void setPageText(String text) {
JLabel label = (JLabel) this.getComponent(1);
label.setText(text);
}
public void setPageIcon(String iconPath) {
JLabel label = (JLabel) this.getComponent(0);
File img = new File(iconPath);
ImageIcon iconImage;
if (img.exists() && img.isFile()) {
iconImage = new ImageIcon(img.getAbsolutePath());
iconImage.setImage(iconImage.getImage().getScaledInstance(16, 16, Image.SCALE_DEFAULT));
} else {
iconImage = (ImageIcon) CommonUtils.getIcon("/browser/line/file.png");
}
label.setIcon(iconImage);
}
/* -END- set */
/* add */
private void addPageIcon(String iconPath) {
JLabel iconLabel = new JLabel();
iconLabel.setPreferredSize(new Dimension(height + 5, height));
iconLabel.setHorizontalAlignment(JLabel.CENTER);
File img = new File(iconPath);
ImageIcon iconImage;
if (img.exists() && img.isFile()) {
iconImage = new ImageIcon(img.getAbsolutePath());
iconImage.setImage(iconImage.getImage().getScaledInstance(16, 16, Image.SCALE_DEFAULT));
} else {
iconImage = (ImageIcon) CommonUtils.getIcon("/img/browser/line/file.png");
}
iconLabel.setIcon(iconImage);
this.add(iconLabel, BorderLayout.WEST);
}
private void addPageTitle(String title) {
JLabel textLabel = new JLabel(title);
textLabel.setPreferredSize(new Dimension((int) textLabel.getPreferredSize().getWidth(), height));
textLabel.setFont(FontUtils.MicrosoftYahei(12));
textLabel.setMaximumSize(new Dimension(500 - height * 2 - 10, 0));
this.add(textLabel, BorderLayout.CENTER);
}
private void addCloseButton() {
JLabel closeLabel = new JLabel();
closeLabel.setPreferredSize(new Dimension(height + 10, height));
closeLabel.setHorizontalAlignment(JLabel.CENTER);
closeLabel.setIcon(CommonUtils.getIcon("/browser/line/close_1.png"));
closeLabel.setToolTipText("删除该记录");
closeLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
closeLabel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getButton() == 1) {
MainFrame.getInstance().historyMenu.removeHistoryItem(time);
}
}
});
this.add(closeLabel, BorderLayout.EAST);
}
/* -END- add */
public void itemResize(JMenuItem item, int maxWidth) {
Component[] comp = item.getComponents();
double width = 0;
for (int i = 0; i < comp.length; i++) {
width = width + comp[i].getPreferredSize().getWidth();
}
item.setPreferredSize(new Dimension((int) (width > maxWidth ? maxWidth : width), height));
}
public String getTime() {
return time;
}
public String getInnerUrl() {
return innerUrl;
}
public void setInnerUrl(String innerUrl) {
this.innerUrl = innerUrl;
}
}
| 4,267 | Java | .java | DLand-Team/java-browser | 9 | 3 | 0 | 2022-12-29T12:36:36Z | 2023-01-02T08:32:11Z |
ToolBar.java | /FileExtraction/Java_unseen/DLand-Team_java-browser/Code/src/browser/ui/component/bar/ToolBar.java | package browser.ui.component.bar;
import java.awt.*;
import java.awt.event.*;
import java.util.Objects;
import javax.swing.BorderFactory;
import javax.swing.GroupLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.GroupLayout.Alignment;
import javax.swing.border.LineBorder;
import browser.rx.TOPIC;
import browser.rx.client.InnerMqClient;
import browser.rx.service.InnerMqService;
import browser.util.FontUtils;
public class ToolBar extends JPanel {
private static final long serialVersionUID = -8081016013938632494L;
private final String BASE_IMG_PATH = "/browser/assets/img/browser/colorful/";
private final InnerMqService innerMqService = InnerMqService.getInstance();
private final InnerMqClient client;
private String compId;
private JTextField addressTextField;
public ToolBar(int browserId, String url) {
this.compId = "ToolBar-" + browserId;
this.client = innerMqService.createConnect(this.compId);
setBackground(Color.WHITE);
setBorder(new LineBorder(new Color(169, 169, 169)));
JButton backButton = new ToolBarButton(BASE_IMG_PATH + "left.png", "返回");
JButton forwardButton = new ToolBarButton(BASE_IMG_PATH + "right.png", "前进");
JButton refreshButton = new ToolBarButton(BASE_IMG_PATH + "refresh.png", "刷新");
JButton homeButton = new ToolBarButton(BASE_IMG_PATH + "home.png", "主页");
JButton bookmarkButton = new ToolBarButton(BASE_IMG_PATH + "bookmark.png", "书签");
JButton goButton = new ToolBarButton(BASE_IMG_PATH + "href.png", "转到");
JButton reOpenButton = new ToolBarButton(BASE_IMG_PATH + "history.png", "历史记录");
JButton toolButton = new ToolBarButton(BASE_IMG_PATH + "tool.png", "工具");
JButton settingButton = new ToolBarButton(BASE_IMG_PATH + "setting.png", "设置");
this.addressTextField = new JTextField(url);
this.addressTextField.setFocusable(false);
this.addressTextField.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
addressTextField.setFocusable(true);
addressTextField.requestFocus();
innerMqService.pub(TOPIC.ADDRESS_FOCUS, true);
}
});
backButton.setEnabled(false);
forwardButton.setEnabled(false);
// 后退
backButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (backButton.isEnabled() && e.getButton() == 1) {
}
}
});
// 前进
forwardButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (forwardButton.isEnabled() && e.getButton() == 1) {
}
}
});
// 刷新
refreshButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getButton() == 1) {
innerMqService.pub("*" + browserId, TOPIC.RELOAD, true);
}
}
});
// 主页
homeButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getButton() == 1) {
}
}
});
// 书签
// 地址
addressTextField.setFont(FontUtils.MicrosoftYahei(15));
addressTextField.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
addressTextField.setColumns(10);
addressTextField.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == 10 && !"".equals(addressTextField.getText())) {
innerMqService.pub("*" + browserId, TOPIC.LOAD_URL, addressTextField.getText());
}
}
});
// 转到
goButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getButton() == 1 && !"".equals(addressTextField.getText())) {
innerMqService.pub("*" + browserId, TOPIC.LOAD_URL, addressTextField.getText());
}
}
});
// 历史记录
reOpenButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getButton() == 1) {
}
}
});
// 工具
toolButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getButton() == 1) {
}
}
});
// 设置
settingButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getButton() == 1) {
}
}
});
GroupLayout gl_panel_1 = new GroupLayout(this);
gl_panel_1.setHorizontalGroup(gl_panel_1.createParallelGroup(Alignment.LEADING).addGroup(gl_panel_1
.createSequentialGroup()
.addComponent(backButton, GroupLayout.PREFERRED_SIZE, 35, GroupLayout.PREFERRED_SIZE).addGap(0)
.addComponent(forwardButton, GroupLayout.PREFERRED_SIZE, 35, GroupLayout.PREFERRED_SIZE).addGap(0)
.addComponent(refreshButton, GroupLayout.PREFERRED_SIZE, 35, GroupLayout.PREFERRED_SIZE).addGap(0)
.addComponent(homeButton, GroupLayout.PREFERRED_SIZE, 35, GroupLayout.PREFERRED_SIZE).addGap(0)
.addComponent(bookmarkButton, GroupLayout.PREFERRED_SIZE, 35, GroupLayout.PREFERRED_SIZE).addGap(10)
.addComponent(addressTextField, GroupLayout.DEFAULT_SIZE, 726, Short.MAX_VALUE).addGap(10)
.addComponent(goButton, GroupLayout.PREFERRED_SIZE, 35, GroupLayout.PREFERRED_SIZE).addGap(0)
.addComponent(reOpenButton, GroupLayout.PREFERRED_SIZE, 35, GroupLayout.PREFERRED_SIZE).addGap(0)
.addComponent(toolButton, GroupLayout.PREFERRED_SIZE, 35, GroupLayout.PREFERRED_SIZE).addGap(0)
.addComponent(settingButton, GroupLayout.PREFERRED_SIZE, 35, GroupLayout.PREFERRED_SIZE).addGap(0)));
gl_panel_1.setVerticalGroup(gl_panel_1.createParallelGroup(Alignment.LEADING).addGroup(Alignment.TRAILING,
gl_panel_1.createSequentialGroup().addGroup(gl_panel_1.createParallelGroup(Alignment.TRAILING)
.addComponent(addressTextField, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 35,
Short.MAX_VALUE)
.addGroup(Alignment.LEADING,
gl_panel_1.createParallelGroup(Alignment.LEADING, false)
.addComponent(backButton, GroupLayout.DEFAULT_SIZE, 35, Short.MAX_VALUE)
.addComponent(forwardButton, GroupLayout.DEFAULT_SIZE, 35, Short.MAX_VALUE)
.addComponent(refreshButton, GroupLayout.DEFAULT_SIZE, 35, Short.MAX_VALUE)
.addComponent(homeButton, GroupLayout.DEFAULT_SIZE, 35, Short.MAX_VALUE)
.addComponent(bookmarkButton, GroupLayout.DEFAULT_SIZE, 35, Short.MAX_VALUE)
.addComponent(goButton, GroupLayout.DEFAULT_SIZE, 35, Short.MAX_VALUE)
.addComponent(reOpenButton, GroupLayout.DEFAULT_SIZE, 35, Short.MAX_VALUE)
.addComponent(toolButton, GroupLayout.DEFAULT_SIZE, 35, Short.MAX_VALUE)
.addComponent(settingButton, GroupLayout.DEFAULT_SIZE, 35, Short.MAX_VALUE)))
.addGap(0)));
this.setLayout(gl_panel_1);
this.subInnerMqMessage();
}
private void subInnerMqMessage() {
this.client.sub(TOPIC.BROWSER_FOCUS, (res) -> {
this.addressTextField.setFocusable(false);
});
this.client.sub(TOPIC.CHANGE_URL, (res) -> {
this.addressTextField.setText((String) res);
});
}
public void dispose() {
innerMqService.destroyClient(this.client);
}
static class ToolBarButton extends JButton {
public ToolBarButton(String iconPath, String tipText) {
setIcon(new ImageIcon(Objects.requireNonNull(ToolBar.class.getResource(iconPath))));
setToolTipText(tipText);
setFocusable(false);
}
}
} | 9,029 | Java | .java | DLand-Team/java-browser | 9 | 3 | 0 | 2022-12-29T12:36:36Z | 2023-01-02T08:32:11Z |
TabCaptions.java | /FileExtraction/Java_unseen/DLand-Team_java-browser/Code/src/browser/ui/component/tab/TabCaptions.java | package browser.ui.component.tab;
import java.awt.Color;
import java.io.Serial;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.JPanel;
public class TabCaptions extends JPanel {
@Serial
private static final long serialVersionUID = 7549971752593265070L;
private TabCaption selectedTab;
private JPanel tabsPane;
private JPanel buttonsPane;
public TabCaptions() {
createUI();
}
private void createUI() {
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
setBackground(Color.DARK_GRAY);
add(createItemsPane());
add(createButtonsPane());
add(Box.createHorizontalGlue());
}
private JComponent createItemsPane() {
tabsPane = new JPanel();
tabsPane.setOpaque(false);
tabsPane.setLayout(new BoxLayout(tabsPane, BoxLayout.X_AXIS));
return tabsPane;
}
private JComponent createButtonsPane() {
buttonsPane = new JPanel();
buttonsPane.setOpaque(false);
buttonsPane.setLayout(new BoxLayout(buttonsPane, BoxLayout.X_AXIS));
return buttonsPane;
}
public void addTab(TabCaption item) {
tabsPane.add(item);
}
public void removeTab(TabCaption item) {
tabsPane.remove(item);
}
public void addTabButton(TabButton button) {
buttonsPane.add(button);
}
public TabCaption getSelectedTab() {
return selectedTab;
}
public void setSelectedTab(TabCaption selectedTab) {
this.selectedTab = selectedTab;
this.selectedTab.setSelected(true);
}
}
| 1,630 | Java | .java | DLand-Team/java-browser | 9 | 3 | 0 | 2022-12-29T12:36:36Z | 2023-01-02T08:32:11Z |
TabButton.java | /FileExtraction/Java_unseen/DLand-Team_java-browser/Code/src/browser/ui/component/tab/TabButton.java | package browser.ui.component.tab;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.JButton;
public class TabButton extends JButton {
private static final long serialVersionUID = -5634035547632048385L;
public TabButton(Icon icon, String toolTipText) {
setIcon(icon);
setToolTipText(toolTipText);
setOpaque(false);
setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
setContentAreaFilled(false);
setFocusable(false);
}
}
| 511 | Java | .java | DLand-Team/java-browser | 9 | 3 | 0 | 2022-12-29T12:36:36Z | 2023-01-02T08:32:11Z |
TabContent.java | /FileExtraction/Java_unseen/DLand-Team_java-browser/Code/src/browser/ui/component/tab/TabContent.java | package browser.ui.component.tab;
import browser.ui.component.browser.BrowserPanel;
import browser.ui.component.bar.ToolBar;
import java.awt.BorderLayout;
import javax.swing.JPanel;
public class TabContent extends JPanel {
private String compId;
private ToolBar toolBar;
private BrowserPanel browserPanel;
public TabContent(int browserId, String url) {
this.compId = "TabContent-" + browserId;
toolBar = new ToolBar(browserId, url);
browserPanel = new BrowserPanel(browserId, url);
this.setLayout(new BorderLayout());
this.add(toolBar, BorderLayout.NORTH);
this.add(browserPanel, BorderLayout.CENTER);
}
/* 设置加载图标 */
private void setLoadingIcon() {
firePropertyChange("PageIconChanged", null, "loading");
}
/* 设置图标和标题 */
private void setIconAndTitle() {
}
public void dispose() {
this.toolBar.dispose();
this.browserPanel.dispose();
}
}
| 1,001 | Java | .java | DLand-Team/java-browser | 9 | 3 | 0 | 2022-12-29T12:36:36Z | 2023-01-02T08:32:11Z |
TabCaption.java | /FileExtraction/Java_unseen/DLand-Team_java-browser/Code/src/browser/ui/component/tab/TabCaption.java | package browser.ui.component.tab;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import browser.rx.TOPIC;
import browser.rx.client.InnerMqClient;
import browser.rx.service.InnerMqService;
import browser.util.CommonUtils;
import browser.util.FontUtils;
public class TabCaption extends JPanel {
private final InnerMqService innerMqService = InnerMqService.getInstance();
private final InnerMqClient client;
private String compId;
private boolean selected;
private TabCaptionComponent component;
public TabCaption(int browserId, String url) {
this.compId = "TabCaption-" + browserId;
this.client = innerMqService.createConnect(this.compId);
this.setLayout(new BorderLayout());
this.setOpaque(false);
this.add(Box.createHorizontalStrut(1), BorderLayout.EAST);
this.component = new TabCaptionComponent();
this.component.addPropertyChangeListener("CloseButtonPressed", evt -> {
firePropertyChange("CloseButtonPressed", evt.getOldValue(), evt.getNewValue());
});
this.component.addPropertyChangeListener("TabClicked", evt -> {
this.setSelected(true);
});
this.add(component, BorderLayout.CENTER);
this.component.setTitle(url);
this.subInnerMqMessage();
}
private void subInnerMqMessage() {
this.client.sub(TOPIC.CHANGE_ICON, (res) -> {
this.setIcon((String) res);
});
this.client.sub(TOPIC.CHANGE_TITLE, (res) -> {
this.setTitle((String) res);
});
}
public void setIcon(String iconPath) {
this.component.setIcon(iconPath);
}
public void setTitle(String title) {
this.component.setTitle(title);
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
boolean oldValue = this.selected;
this.selected = selected;
this.component.setSelected(selected);
firePropertyChange("TabSelected", oldValue, selected);
}
public void dispose() {
innerMqService.destroyClient(this.client);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(170, 30);
}
@Override
public Dimension getMinimumSize() {
return new Dimension(50, 30);
}
@Override
public Dimension getMaximumSize() {
return getPreferredSize();
}
private static class TabCaptionComponent extends JPanel {
private final Color defaultBackground;
private JLabel iconLabel;
private JLabel textLabel;
private TabCaptionComponent() {
defaultBackground = getBackground();
setLayout(new BorderLayout());
setOpaque(false);
add(createIcon(), BorderLayout.WEST);
add(createLabel(), BorderLayout.CENTER);
add(createCloseButton(), BorderLayout.EAST);
}
/* 图标 */
private JComponent createIcon() {
iconLabel = new JLabel();
iconLabel.setPreferredSize(new Dimension(30, 30));
iconLabel.setHorizontalAlignment(JLabel.CENTER);
iconLabel.setOpaque(false);
iconLabel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
firePropertyChange("TabClicked", false, true);
}
if (e.getButton() == MouseEvent.BUTTON2) {
firePropertyChange("CloseButtonPressed", false, true);
}
}
});
return iconLabel;
}
/* 标签文字 */
private JComponent createLabel() {
textLabel = new JLabel();
textLabel.setOpaque(false);
textLabel.setFont(FontUtils.MicrosoftYahei(13));
textLabel.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0));
textLabel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
firePropertyChange("TabClicked", false, true);
}
if (e.getButton() == MouseEvent.BUTTON2) {
firePropertyChange("CloseButtonPressed", false, true);
}
}
});
return textLabel;
}
/* 关闭按钮 */
private JComponent createCloseButton() {
JButton closeButton = new JButton();
closeButton.setOpaque(false);
closeButton.setToolTipText("Close");
closeButton.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));
closeButton.setPressedIcon(CommonUtils.getIcon("/browser/line/close_pressed.png"));
closeButton.setIcon(CommonUtils.getIcon("/browser/line/close.png"));
closeButton.setContentAreaFilled(false);
closeButton.setFocusable(false);
closeButton.addActionListener(e -> firePropertyChange("CloseButtonPressed", false, true));
return closeButton;
}
/* 设置图标 */
public void setIcon(String iconPath) {
SwingUtilities.invokeLater(() -> {
ImageIcon image = null;
switch (iconPath) {
case "" -> {
image = (ImageIcon) CommonUtils.getIcon("/browser/line/file.png");
}
case "loading" -> {
image = (ImageIcon) CommonUtils.getIcon("/browser/line/loading_1.gif");
}
default -> {
image = new ImageIcon(iconPath);
image.setImage(image.getImage().getScaledInstance(16, 16, Image.SCALE_DEFAULT));
}
}
iconLabel.setIcon(image);
});
}
/* 设置标签文字 */
public void setTitle(String title) {
if (title == null) {
return;
}
SwingUtilities.invokeLater(() -> {
textLabel.setText(title);
textLabel.setToolTipText(title);
});
}
public void setSelected(boolean selected) {
setBackground(selected ? defaultBackground : new Color(150, 150, 150));
repaint();
}
@Override
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setPaint(new GradientPaint(0, 0, Color.LIGHT_GRAY, 0, getHeight(), getBackground()));
g2d.fillRect(0, 0, getWidth(), getHeight());
g2d.dispose();
super.paint(g);
}
}
}
| 7,515 | Java | .java | DLand-Team/java-browser | 9 | 3 | 0 | 2022-12-29T12:36:36Z | 2023-01-02T08:32:11Z |
TabbedPane.java | /FileExtraction/Java_unseen/DLand-Team_java-browser/Code/src/browser/ui/component/tab/TabbedPane.java | package browser.ui.component.tab;
import browser.common.Cache;
import browser.rx.TOPIC;
import browser.rx.service.InnerMqService;
import browser.util.CommonUtils;
import java.awt.BorderLayout;
import java.awt.Window;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TabbedPane extends JPanel {
private final InnerMqService innerMqService = InnerMqService.getInstance();
private final List<Tab> tabs;
private final TabCaptions captions;
private final JComponent contentContainer;
public TabbedPane() {
this.tabs = new ArrayList<Tab>();
this.setLayout(new BorderLayout());
this.captions = new TabCaptions();
this.add(captions, BorderLayout.NORTH);
this.contentContainer = new JPanel(new BorderLayout());
this.add(contentContainer, BorderLayout.CENTER);
TabButton button = new TabButton(CommonUtils.getIcon("/browser/line/new_tab.png"), "新建标签页");
button.addActionListener((e) -> this.innerMqService.pub(TOPIC.OPEN_NEW_PAGE, Cache.setting.getMainPageAddress()));
this.addTabButton(button);
}
public void disposeAllTabs() {
getTabs().forEach(this::disposeTab);
}
private void disposeTab(Tab tab) {
tab.getCaption().setSelected(false);
tab.getCaption().dispose();
tab.getContent().dispose();
removeTab(tab);
if (hasTabs()) {
getLastTab().getCaption().setSelected(true);
} else {
Window window = SwingUtilities.getWindowAncestor(this);
if (window != null) {
window.setVisible(false);
window.dispose();
}
}
}
private Tab findTab(TabCaption item) {
for (Tab tab : getTabs()) {
if (tab.getCaption().equals(item)) {
return tab;
}
}
return null;
}
public void addTab(final Tab tab) {
TabCaption caption = tab.getCaption();
caption.addPropertyChangeListener("CloseButtonPressed", new TabCaptionCloseTabListener());
caption.addPropertyChangeListener("TabSelected", new SelectTabListener());
TabContent content = tab.getContent();
content.addPropertyChangeListener("TabClosed", new TabContentCloseTabListener());
captions.addTab(caption);
tabs.add(tab);
validate();
repaint();
}
private boolean hasTabs() {
return !tabs.isEmpty();
}
private Tab getLastTab() {
return tabs.get(tabs.size() - 1);
}
private List<Tab> getTabs() {
return new ArrayList<Tab>(tabs);
}
public void removeTab(Tab tab) {
TabCaption tabCaption = tab.getCaption();
captions.removeTab(tabCaption);
tabs.remove(tab);
validate();
repaint();
}
public void addTabButton(TabButton button) {
captions.addTabButton(button);
}
public void selectTab(Tab tab) {
TabCaption tabCaption = tab.getCaption();
TabCaption selectedTab = captions.getSelectedTab();
if (selectedTab != null && !selectedTab.equals(tabCaption)) {
selectedTab.setSelected(false);
}
captions.setSelectedTab(tabCaption);
}
private class TabCaptionCloseTabListener implements PropertyChangeListener {
public void propertyChange(PropertyChangeEvent evt) {
TabCaption caption = (TabCaption) evt.getSource();
Tab tab = findTab(caption);
disposeTab(tab);
}
}
private class SelectTabListener implements PropertyChangeListener {
public void propertyChange(PropertyChangeEvent evt) {
TabCaption caption = (TabCaption) evt.getSource();
Tab tab = findTab(caption);
if (caption.isSelected()) {
selectTab(tab);
}
if (!caption.isSelected()) {
TabContent content = tab.getContent();
contentContainer.remove(content);
contentContainer.validate();
contentContainer.repaint();
} else {
final TabContent content = tab.getContent();
contentContainer.add(content, BorderLayout.CENTER);
contentContainer.validate();
contentContainer.repaint();
}
}
}
private class TabContentCloseTabListener implements PropertyChangeListener {
@Override
public void propertyChange(PropertyChangeEvent evt) {
TabContent content = (TabContent) evt.getSource();
Tab tab = findTab(content);
disposeTab(tab);
}
private Tab findTab(TabContent content) {
for (Tab tab : getTabs()) {
if (tab.getContent().equals(content)) {
return tab;
}
}
return null;
}
}
}
| 5,120 | Java | .java | DLand-Team/java-browser | 9 | 3 | 0 | 2022-12-29T12:36:36Z | 2023-01-02T08:32:11Z |
Tab.java | /FileExtraction/Java_unseen/DLand-Team_java-browser/Code/src/browser/ui/component/tab/Tab.java | package browser.ui.component.tab;
public class Tab {
private final TabCaption caption;
private final TabContent content;
public Tab(TabCaption caption, TabContent content) {
this.caption = caption;
this.content = content;
}
public TabCaption getCaption() {
return caption;
}
public TabContent getContent() {
return content;
}
}
| 398 | Java | .java | DLand-Team/java-browser | 9 | 3 | 0 | 2022-12-29T12:36:36Z | 2023-01-02T08:32:11Z |
BrowserPanel.java | /FileExtraction/Java_unseen/DLand-Team_java-browser/Code/src/browser/ui/component/browser/BrowserPanel.java | package browser.ui.component.browser;
import browser.core.ChromiumEmbeddedCoreInst;
import browser.rx.TOPIC;
import browser.rx.client.InnerMqClient;
import browser.rx.service.InnerMqService;
import org.cef.CefClient;
import org.cef.browser.CefBrowser;
import org.cef.handler.CefFocusHandlerAdapter;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class BrowserPanel extends JPanel {
private final InnerMqService innerMqService = InnerMqService.getInstance();
private final InnerMqClient mq;
private String compId;
private CefClient client;
private CefBrowser browser;
private JSplitPane splitPane;
private JPanel framePanel;
private JPanel devToolPanel;
private boolean devToolOpen = false;
public BrowserPanel(int browserId, String url) {
this.compId = "BrowserPanel-" + browserId;
this.mq = this.innerMqService.createConnect(this.compId);
this.client = ChromiumEmbeddedCoreInst.getInstance().createClient(browserId);
this.browser = ChromiumEmbeddedCoreInst.getInstance().createBrowser(this.client, url);
this.browser.setFocus(true);
this.browser.getUIComponent().addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
browser.setFocus(true);
innerMqService.pub(TOPIC.BROWSER_FOCUS, true);
}
});
this.setLayout(new BorderLayout());
this.setFocusable(true);
this.splitPane = new JSplitPane();
this.splitPane.setBorder(null);
this.splitPane.setDividerSize(0);
this.splitPane.setOneTouchExpandable(false);
this.splitPane.setContinuousLayout(false);
this.splitPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
this.add(this.splitPane, BorderLayout.CENTER);
// 浏览器界面
this.framePanel = new JPanel();
this.framePanel.setLayout(new BorderLayout());
this.framePanel.add(this.browser.getUIComponent(), BorderLayout.CENTER);
this.splitPane.setLeftComponent(this.framePanel);
// 开发者工具
this.devToolPanel = new JPanel();
this.devToolPanel.setLayout(new BorderLayout());
this.splitPane.setRightComponent(null);
this.subInnerMqMessage();
}
private void subInnerMqMessage() {
this.mq.sub(TOPIC.ADDRESS_FOCUS, (res) -> {
this.browser.setFocus(false);
});
this.mq.sub(TOPIC.OPEN_DEV_TOOL, (res) -> {
this.toggleDevTools();
});
this.mq.sub(TOPIC.RELOAD, (res) -> {
this.browser.reload();
});
this.mq.sub(TOPIC.LOAD_URL, (res) -> {
this.browser.loadURL((String) res);
});
}
public void dispose() {
this.innerMqService.destroyClient(this.mq);
}
public void toggleDevTools() {
if (this.devToolOpen) {
this.closeDevTools();
this.devToolOpen = false;
} else {
this.openDevTools();
this.devToolOpen = true;
}
}
private void openDevTools() {
this.devToolPanel.add(this.browser.getDevTools().getUIComponent(), BorderLayout.CENTER);
SwingUtilities.invokeLater(() -> {
this.splitPane.setDividerSize(5);
this.splitPane.setRightComponent(devToolPanel);
this.splitPane.setContinuousLayout(true);
this.splitPane.setDividerLocation(this.getSize().width - 500);
});
}
private void closeDevTools() {
this.devToolPanel.removeAll();
SwingUtilities.invokeLater(() -> {
this.splitPane.remove(devToolPanel);
this.splitPane.setDividerSize(0);
this.splitPane.setRightComponent(null);
this.splitPane.setContinuousLayout(false);
this.splitPane.setDividerLocation(this.getSize().width);
});
}
}
| 4,002 | Java | .java | DLand-Team/java-browser | 9 | 3 | 0 | 2022-12-29T12:36:36Z | 2023-01-02T08:32:11Z |
TOPIC.java | /FileExtraction/Java_unseen/DLand-Team_java-browser/Code/src/browser/rx/TOPIC.java | package browser.rx;
public enum TOPIC {
ADDRESS_FOCUS,
BROWSER_FOCUS,
OPEN_NEW_PAGE,
OPEN_DEV_TOOL,
CHANGE_ICON,
CHANGE_TITLE,
CHANGE_URL,
RELOAD,
LOAD_URL,
}
| 201 | Java | .java | DLand-Team/java-browser | 9 | 3 | 0 | 2022-12-29T12:36:36Z | 2023-01-02T08:32:11Z |
SubscribeCallback.java | /FileExtraction/Java_unseen/DLand-Team_java-browser/Code/src/browser/rx/client/SubscribeCallback.java | package browser.rx.client;
public interface SubscribeCallback {
void exec(Object msg);
}
| 96 | Java | .java | DLand-Team/java-browser | 9 | 3 | 0 | 2022-12-29T12:36:36Z | 2023-01-02T08:32:11Z |
InnerMqClient.java | /FileExtraction/Java_unseen/DLand-Team_java-browser/Code/src/browser/rx/client/InnerMqClient.java | package browser.rx.client;
import browser.rx.TOPIC;
import io.reactivex.rxjava3.subjects.PublishSubject;
public interface InnerMqClient {
PublishSubject<Object> sub(TOPIC topic, SubscribeCallback callback);
String getId();
void pub(TOPIC topic, Object msg);
void destroy();
}
| 299 | Java | .java | DLand-Team/java-browser | 9 | 3 | 0 | 2022-12-29T12:36:36Z | 2023-01-02T08:32:11Z |
InnerMqClientImpl.java | /FileExtraction/Java_unseen/DLand-Team_java-browser/Code/src/browser/rx/client/impl/InnerMqClientImpl.java | package browser.rx.client.impl;
import browser.rx.TOPIC;
import browser.rx.client.InnerMqClient;
import browser.rx.client.SubscribeCallback;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.subjects.PublishSubject;
import lombok.Getter;
import java.util.HashMap;
import java.util.Map;
public class InnerMqClientImpl implements InnerMqClient {
public Map<TOPIC, PublishSubject<Object>> subjects = new HashMap<>();
private final CompositeDisposable compositeDisposable = new CompositeDisposable();
private final String id;
private boolean destroyed = false;
public InnerMqClientImpl(String id) {
this.id = id;
}
@Override
public String getId() {
return this.id;
}
@Override
public PublishSubject<Object> sub(TOPIC topic, SubscribeCallback callback) {
PublishSubject<Object> subject = subjects.computeIfAbsent(topic, k -> PublishSubject.create());
this.compositeDisposable.add(subject.subscribe(callback::exec));
return subject;
}
@Override
public void pub(TOPIC topic, Object msg) {
if (this.destroyed) {
return;
}
PublishSubject<Object> subject = subjects.get(topic);
if (subject != null) {
subject.onNext(msg);
}
}
@Override
public void destroy() {
this.destroyed = true;
this.subjects.clear();
if (!this.compositeDisposable.isDisposed()) {
this.compositeDisposable.dispose();
}
}
}
| 1,554 | Java | .java | DLand-Team/java-browser | 9 | 3 | 0 | 2022-12-29T12:36:36Z | 2023-01-02T08:32:11Z |
InnerMqService.java | /FileExtraction/Java_unseen/DLand-Team_java-browser/Code/src/browser/rx/service/InnerMqService.java | package browser.rx.service;
import browser.rx.TOPIC;
import browser.rx.client.InnerMqClient;
import browser.rx.client.impl.InnerMqClientImpl;
import java.util.HashMap;
import java.util.Map;
public class InnerMqService {
private static volatile InnerMqService instance;
public Map<String, InnerMqClient> clients = new HashMap<>(); // 客户端
/* 建立连接 */
public InnerMqClient createConnect(String id) {
return clients.computeIfAbsent(id, k -> new InnerMqClientImpl(id));
}
/* 取消连接 */
public void destroyClient(String id) {
InnerMqClient client = this.clients.get(id);
if (client != null) {
client.destroy();
}
this.clients.remove(id);
}
/* 取消连接 */
public void destroyClient(InnerMqClient client) {
client.destroy();
this.clients.remove(client.getId());
}
public void pub(TOPIC topic, Object msg) {
for (InnerMqClient client : this.clients.values()) {
client.pub(topic, msg);
}
}
public void pub(String id, TOPIC topic, Object msg) {
if (id.indexOf("*") == 0) {
String innerId = id.replace("*", "");
for (Map.Entry<String, InnerMqClient> entry : this.clients.entrySet()) {
if (entry.getKey().contains(innerId)) {
entry.getValue().pub(topic, msg);
}
}
} else {
for (Map.Entry<String, InnerMqClient> entry : this.clients.entrySet()) {
if (entry.getKey().equals(id)) {
entry.getValue().pub(topic, msg);
break;
}
}
}
}
public static InnerMqService getInstance() {
if (instance == null) {
synchronized (InnerMqService.class) {
if (instance == null) {
instance = new InnerMqService();
}
}
}
return instance;
}
}
| 2,012 | Java | .java | DLand-Team/java-browser | 9 | 3 | 0 | 2022-12-29T12:36:36Z | 2023-01-02T08:32:11Z |
ChromiumEmbeddedCoreInst.java | /FileExtraction/Java_unseen/DLand-Team_java-browser/Code/src/browser/core/ChromiumEmbeddedCoreInst.java | package browser.core;
import browser.core.handler.*;
import com.jetbrains.cef.JCefAppConfig;
import org.cef.CefApp;
import org.cef.CefClient;
import org.cef.CefSettings;
import org.cef.browser.CefBrowser;
import org.cef.browser.CefMessageRouter;
import org.cef.browser.CefRendering;
public class ChromiumEmbeddedCoreInst {
private static volatile ChromiumEmbeddedCoreInst instance;
private CefApp cefApp = null;
public ChromiumEmbeddedCoreInst() {
String[] args = JCefAppConfig.getInstance().getAppArgs();
CefSettings settings = JCefAppConfig.getInstance().getCefSettings();
settings.cache_path = System.getProperty("user.dir") + "/context/jcef/data";
// 获取CefApp实例
CefApp.startup(args);
this.cefApp = CefApp.getInstance(args, settings);
}
public CefClient createClient(int browserId) {
CefClient cefClient = this.cefApp.createClient();
// 基础监听事件
cefClient.addLifeSpanHandler(new LifeSpanHandler(browserId));
cefClient.addContextMenuHandler(new MenuHandler(browserId));
cefClient.addLoadHandler(new LoadHandler(browserId));
// 配置一个查询路由,html页面可使用 window.java({}) 和 window.javaCancel({}) 来调用此方法
CefMessageRouter.CefMessageRouterConfig cmrConfig = new CefMessageRouter.CefMessageRouterConfig("cef_java_" + browserId, "cef_java_" + browserId + "_cancel");
// 创建查询路由
CefMessageRouter cmr = CefMessageRouter.create(cmrConfig);
cmr.addHandler(new MessageRouterHandler(browserId), true);
cefClient.addMessageRouter(cmr);
return cefClient;
}
public CefBrowser createBrowser(CefClient client, String url) {
return client.createBrowser(url, CefRendering.DEFAULT, true);
}
public String getVersion() {
return "Chromium Embedded Framework (CEF), " + "ChromeVersion: " + cefApp.getVersion().getChromeVersion();
}
public void dispose() {
cefApp.dispose();
}
public static ChromiumEmbeddedCoreInst getInstance() {
if (instance == null) {
synchronized (ChromiumEmbeddedCoreInst.class) {
if (instance == null) {
instance = new ChromiumEmbeddedCoreInst();
}
}
}
return instance;
}
}
| 2,371 | Java | .java | DLand-Team/java-browser | 9 | 3 | 0 | 2022-12-29T12:36:36Z | 2023-01-02T08:32:11Z |
LifeSpanHandler.java | /FileExtraction/Java_unseen/DLand-Team_java-browser/Code/src/browser/core/handler/LifeSpanHandler.java | package browser.core.handler;
import browser.rx.TOPIC;
import browser.rx.service.InnerMqService;
import org.cef.browser.CefBrowser;
import org.cef.browser.CefFrame;
import org.cef.handler.CefLifeSpanHandlerAdapter;
public class LifeSpanHandler extends CefLifeSpanHandlerAdapter {
private final InnerMqService innerMqService = InnerMqService.getInstance();
public LifeSpanHandler(int browserId) {
}
@Override
public boolean onBeforePopup(CefBrowser browser, CefFrame frame, String targetUrl, String targetFrameName) {
// 打开新窗口
innerMqService.pub(TOPIC.OPEN_NEW_PAGE, targetUrl);
// 返回true表示取消弹出窗口
return true;
}
}
| 706 | Java | .java | DLand-Team/java-browser | 9 | 3 | 0 | 2022-12-29T12:36:36Z | 2023-01-02T08:32:11Z |
MessageRouterHandler.java | /FileExtraction/Java_unseen/DLand-Team_java-browser/Code/src/browser/core/handler/MessageRouterHandler.java | package browser.core.handler;
import browser.rx.TOPIC;
import browser.rx.service.InnerMqService;
import browser.util.IconFinder;
import org.cef.browser.CefBrowser;
import org.cef.browser.CefFrame;
import org.cef.callback.CefQueryCallback;
import org.cef.handler.CefMessageRouterHandlerAdapter;
import javax.swing.*;
public class MessageRouterHandler extends CefMessageRouterHandlerAdapter {
private final InnerMqService innerMqService = InnerMqService.getInstance();
private final int browserId;
public MessageRouterHandler(int browserId) {
this.browserId = browserId;
}
public boolean onQuery(CefBrowser browser, CefFrame frame, long queryId, String request, boolean persistent, CefQueryCallback callback) {
if (request.indexOf("get_title__") == 0) {
String title = request.replaceAll("get_title__", "");
this.innerMqService.pub("*" + this.browserId, TOPIC.CHANGE_TITLE, title);
} else if (request.indexOf("get_favicon_href__") == 0) {
String iconHref = request.replaceAll("get_favicon_href__", "");
SwingUtilities.invokeLater(() -> {
String faviconPath = IconFinder.saveAndGetIcon(browser.getURL(), iconHref);
this.innerMqService.pub("*" + this.browserId, TOPIC.CHANGE_ICON, faviconPath);
});
}
return true;
}
public void onQueryCanceled(CefBrowser browser, CefFrame frame, long queryId) {
}
}
| 1,468 | Java | .java | DLand-Team/java-browser | 9 | 3 | 0 | 2022-12-29T12:36:36Z | 2023-01-02T08:32:11Z |
MenuHandler.java | /FileExtraction/Java_unseen/DLand-Team_java-browser/Code/src/browser/core/handler/MenuHandler.java | package browser.core.handler;
import browser.rx.TOPIC;
import browser.rx.service.InnerMqService;
import org.cef.browser.CefBrowser;
import org.cef.browser.CefFrame;
import org.cef.callback.CefContextMenuParams;
import org.cef.callback.CefMenuModel;
import org.cef.callback.CefMenuModel.MenuId;
import org.cef.handler.CefContextMenuHandlerAdapter;
public class MenuHandler extends CefContextMenuHandlerAdapter {
private final InnerMqService innerMqService = InnerMqService.getInstance();
private final int browserId;
private final static int MENU_ID_DEV_TOOL = 1000001;
public MenuHandler(int browserId) {
this.browserId = browserId;
}
@Override
public void onBeforeContextMenu(CefBrowser browser, CefFrame frame, CefContextMenuParams params, CefMenuModel model) {
//清除菜单项
model.clear();
//剪切、复制、粘贴
model.addItem(MenuId.MENU_ID_COPY, "复制");
model.addItem(MenuId.MENU_ID_CUT, "剪切");
model.addItem(MenuId.MENU_ID_PASTE, "粘贴");
model.addSeparator(); // 分割线
model.addItem(MenuId.MENU_ID_BACK, "返回");
model.setEnabled(MenuId.MENU_ID_BACK, browser.canGoBack());
model.addItem(MenuId.MENU_ID_FORWARD, "前进");
model.setEnabled(MenuId.MENU_ID_FORWARD, browser.canGoForward());
model.addItem(MenuId.MENU_ID_RELOAD, "刷新");
model.addSeparator(); // 分割线
model.addItem(MenuId.MENU_ID_VIEW_SOURCE, "查看源码");
model.addItem(MENU_ID_DEV_TOOL, "开发者工具");
//创建子菜单
// CefMenuModel cmodel = model.addSubMenu(MENU_ID_INJECTION, "脚本注入");
// cmodel.addItem(MENU_ID_ADDTEXT, "添加一段文本");
}
/*
* @see org.cef.handler.CefContextMenuHandler#onContextMenuCommand(org.cef.browser.CefBrowser, org.cef.browser.CefFrame, org.cef.callback.CefContextMenuParams, int, int)
*/
@Override
public boolean onContextMenuCommand(CefBrowser browser, CefFrame frame, CefContextMenuParams params, int commandId, int eventFlags) {
switch (commandId) {
case MenuId.MENU_ID_RELOAD -> {
browser.reload();
return true;
}
case MENU_ID_DEV_TOOL -> {
this.innerMqService.pub("*" + this.browserId, TOPIC.OPEN_DEV_TOOL, true);
return true;
}
}
return false;
}
}
| 2,460 | Java | .java | DLand-Team/java-browser | 9 | 3 | 0 | 2022-12-29T12:36:36Z | 2023-01-02T08:32:11Z |
LoadHandler.java | /FileExtraction/Java_unseen/DLand-Team_java-browser/Code/src/browser/core/handler/LoadHandler.java | package browser.core.handler;
import browser.common.Script;
import browser.rx.TOPIC;
import browser.rx.service.InnerMqService;
import org.cef.browser.CefBrowser;
import org.cef.browser.CefFrame;
import org.cef.handler.CefLoadHandler;
import org.cef.handler.CefLoadHandlerAdapter;
import org.cef.network.CefRequest;
public class LoadHandler extends CefLoadHandlerAdapter {
private final InnerMqService innerMqService = InnerMqService.getInstance();
private final int browserId;
public LoadHandler(int browserId) {
this.browserId = browserId;
}
@Override
public void onLoadStart(CefBrowser browser, CefFrame frame, CefRequest.TransitionType transitionType) {
String url = browser.getURL();
if (url.indexOf("devtools://") == 0) {
return;
}
this.innerMqService.pub("*" + this.browserId, TOPIC.CHANGE_ICON, "loading");
}
@Override
public void onLoadEnd(CefBrowser browser, CefFrame frame, int httpStatusCode) {
this.change(browser);
}
@Override
public void onLoadError(CefBrowser browser, CefFrame frame, CefLoadHandler.ErrorCode errorCode, String errorText, String failedUrl) {
this.change(browser);
}
private void change(CefBrowser browser) {
String url = browser.getURL();
if (url.indexOf("devtools://") == 0) {
return;
}
this.innerMqService.pub("*" + this.browserId, TOPIC.CHANGE_URL, url);
browser.executeJavaScript(Script.getTitle(this.browserId), null, 0);
browser.executeJavaScript(Script.getIconHref(this.browserId), null, 0);
}
}
| 1,632 | Java | .java | DLand-Team/java-browser | 9 | 3 | 0 | 2022-12-29T12:36:36Z | 2023-01-02T08:32:11Z |
FontUtils.java | /FileExtraction/Java_unseen/DLand-Team_java-browser/Code/src/browser/util/FontUtils.java | package browser.util;
import java.awt.*;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
public class FontUtils {
// 微软雅黑
public static Font MicrosoftYahei(float size) {
return getLocalFont("MicrosoftYahei.ttf", Font.PLAIN, size);
}
// 小米兰亭
public static Font MiLT(float size) {
return getLocalFont("MiLT.ttf", Font.PLAIN, size);
}
/**
* 获取本地字体
*/
private static Font getLocalFont(String name, int style, float size) {
Font definedFont = null;
InputStream is = null;
BufferedInputStream bis = null;
try {
is = FontUtils.class.getResourceAsStream("/browser/assets/font/" + name);
bis = new BufferedInputStream(is);
// createFont返回一个使用指定字体类型和输入数据的新 Font。<br>
// 新 Font磅值为 1,样式为 PLAIN,注意 此方法不会关闭 InputStream
definedFont = Font.createFont(Font.TRUETYPE_FONT, bis);
// 复制此 Font对象并应用新样式,创建一个指定磅值的新 Font对象。
definedFont = definedFont.deriveFont(style, size);
} catch (FontFormatException | IOException e) {
e.printStackTrace();
} finally {
try {
if (null != bis) {
bis.close();
}
if (null != is) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return definedFont;
}
}
| 1,660 | Java | .java | DLand-Team/java-browser | 9 | 3 | 0 | 2022-12-29T12:36:36Z | 2023-01-02T08:32:11Z |
DomUtils.java | /FileExtraction/Java_unseen/DLand-Team_java-browser/Code/src/browser/util/DomUtils.java | package browser.util;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class DomUtils {
public static String getTitle(String html) {
Document doc = Jsoup.parse(html);
Elements elements = doc.getElementsByTag("title");
for (Element element : elements) {
return element.text();
}
return null;
}
}
| 440 | Java | .java | DLand-Team/java-browser | 9 | 3 | 0 | 2022-12-29T12:36:36Z | 2023-01-02T08:32:11Z |
CommonUtils.java | /FileExtraction/Java_unseen/DLand-Team_java-browser/Code/src/browser/util/CommonUtils.java | package browser.util;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Objects;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import browser.common.Cache;
import browser.common.Static;
import com.alibaba.fastjson.JSON;
public class CommonUtils {
public static Icon getIcon(String path) {
return new ImageIcon(Objects.requireNonNull(CommonUtils.class.getResource("/browser/assets/img" + path)));
}
/**
* 复制文字到剪贴板
*/
public static void setClipboardText(String writeMe) {
Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable tText = new StringSelection(writeMe);
clip.setContents(tText, null);
}
public static String readFile(String path) throws IOException {
File file = new File(path);
if (!file.exists() || !file.isFile()) {
throw new FileNotFoundException();
}
FileReader reader = new FileReader(file);
BufferedReader br = new BufferedReader(reader);
StringBuilder sb = new StringBuilder();
String s = "";
while ((s = br.readLine()) != null) {
sb.append(s);
}
br.close();
reader.close();
return sb.toString();
}
public static void saveSetting() {
try {
CommonUtils.saveStringToFile(JSON.toJSONString(Cache.setting), Static.SETTING_JSON_PATH);
} catch (IOException e1) {
e1.printStackTrace();
}
}
public static void saveStringToFile(String content, String path) throws IOException {
FileWriter fileWriter = new FileWriter(path);
fileWriter.write(content);
fileWriter.flush();
fileWriter.close();
}
public static void saveObjToFile(Object obj, String path) throws IOException {
File file = new File(path);
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(obj);
oos.flush();
oos.close();
fos.flush();
fos.close();
}
public static boolean isMac() {
return System.getProperties().getProperty("os.name").toUpperCase().contains("MAC OS");
}
public static boolean isWindows() {
return System.getProperties().getProperty("os.name").toUpperCase().contains("WINDOWS");
}
public static boolean isWindows10() {
return System.getProperties().getProperty("os.name").toUpperCase().contains("WINDOWS 10");
}
public static boolean isWindows11() {
return System.getProperties().getProperty("os.name").toUpperCase().contains("WINDOWS 11");
}
}
| 2,883 | Java | .java | DLand-Team/java-browser | 9 | 3 | 0 | 2022-12-29T12:36:36Z | 2023-01-02T08:32:11Z |
IconFinder.java | /FileExtraction/Java_unseen/DLand-Team_java-browser/Code/src/browser/util/IconFinder.java | package browser.util;
import com.ctreber.aclib.image.ico.ICOFile;
import org.apache.commons.io.FileUtils;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
public class IconFinder {
public static String saveAndGetIcon(String browserUrl, String iconHref) {
try {
if (iconHref == null || "".equals(iconHref)) {
return "";
}
String iconUrl = getIconRealUrl(browserUrl, iconHref);
String cacheDirPath = System.getProperty("user.dir") + "/cache/" + new URL(browserUrl).getHost();
File iconCacheDir = new File(cacheDirPath);
if (!iconCacheDir.exists() && !iconCacheDir.isFile()) {
iconCacheDir.mkdirs();
}
String sub = iconUrl.substring(iconUrl.lastIndexOf("."));
if (".ico".equals(sub)) {
File pngFile = new File(cacheDirPath + "/favicon.png");
if (!pngFile.exists() || !pngFile.isFile()) {
File icoFile = new File(cacheDirPath + "/favicon.ico");
FileUtils.copyURLToFile(new URL(iconUrl), icoFile);
ICOFile ico = new ICOFile(new FileInputStream(icoFile));
BufferedImage icoImg = (BufferedImage) ico.getImages().get(0);
ImageIO.write(icoImg, "png", pngFile);
}
return pngFile.getAbsolutePath();
} else if (".jpg".equals(sub) || ".png".equals(sub)) {
File iconFile = new File(cacheDirPath + "/favicon" + sub);
if (!iconFile.exists() || !iconFile.isFile()) {
FileUtils.copyURLToFile(new URL(iconUrl), iconFile);
}
return iconFile.getAbsolutePath();
} else {
return "";
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
// 获取Icon真实地址
private static String getIconRealUrl(String browserUrl, String iconHref) {
if (iconHref.contains("http")) {
return iconHref;
}
try {
if (iconHref.charAt(0) == '/' && iconHref.charAt(1) == '/') {
URL url = new URL(browserUrl);
iconHref = url.getProtocol() + ":" + iconHref;
} else if (iconHref.charAt(0) == '/') {// 判断是否为相对路径或根路径
URL url = new URL(browserUrl);
iconHref = url.getProtocol() + "://" + url.getHost() + iconHref;
} else {
String base = browserUrl.split("#")[0];
iconHref = base + iconHref;
}
return iconHref;
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}
}
}
| 2,909 | Java | .java | DLand-Team/java-browser | 9 | 3 | 0 | 2022-12-29T12:36:36Z | 2023-01-02T08:32:11Z |
BeanUtils.java | /FileExtraction/Java_unseen/DLand-Team_java-browser/Code/src/browser/util/BeanUtils.java | package browser.util;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class BeanUtils {
public static void copy(Object target, Object source) throws Exception {
/*
* 分别获得源对象和目标对象的Class类型对象,Class对象是整个反射机制的源头和灵魂!
*
* Class对象是在类加载的时候产生,保存着类的相关属性,构造器,方法等信息
*/
Class<? extends Object> sourceClz = source.getClass();
Class<? extends Object> targetClz = target.getClass();
// 得到Class对象所表征的类的所有属性(包括私有属性)
Field[] fields = sourceClz.getDeclaredFields();
if (fields.length == 0) {
fields = sourceClz.getSuperclass().getDeclaredFields();
}
for (int i = 0; i < fields.length; i++) {
String fieldName = fields[i].getName();
Field targetField = null;
// 得到targetClz对象所表征的类的名为fieldName的属性,不存在就进入下次循环
try {
targetField = targetClz.getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
targetField = targetClz.getSuperclass().getDeclaredField(fieldName);
}
// 判断sourceClz字段类型和targetClz同名字段类型是否相同
if (fields[i].getType() == targetField.getType()) {
// 由属性名字得到对应get和set方法的名字
String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
String setMethodName = "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
// 由方法的名字得到get和set方法的Method对象
Method getMethod;
Method setMethod;
try {
try {
getMethod = sourceClz.getDeclaredMethod(getMethodName, new Class[] {});
} catch (NoSuchMethodException e) {
getMethod = sourceClz.getSuperclass().getDeclaredMethod(getMethodName, new Class[] {});
}
try {
setMethod = targetClz.getDeclaredMethod(setMethodName, fields[i].getType());
} catch (NoSuchMethodException e) {
setMethod = targetClz.getSuperclass().getDeclaredMethod(setMethodName, fields[i].getType());
}
// 调用source对象的getMethod方法
Object result = getMethod.invoke(source, new Object[] {});
// 调用target对象的setMethod方法
setMethod.invoke(target, result);
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
} else {
throw new Exception("同名属性类型不匹配!");
}
}
}
}
| 2,811 | Java | .java | DLand-Team/java-browser | 9 | 3 | 0 | 2022-12-29T12:36:36Z | 2023-01-02T08:32:11Z |
TopicMapConfigurationPanel.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/TopicMapConfigurationPanel.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* TopicMapCorfigurationPanel.java
*
* Created on 21. marraskuuta 2005, 13:44
*/
package org.wandora.topicmap;
/**
*
* @author olli
*/
public abstract class TopicMapConfigurationPanel extends javax.swing.JPanel {
/**
* Get the parameters user entered. The returned object may be of any type,
* usually determined by the TopicMapType used to create the configuration
* panel. The TopicMapType is used to construct a new topic map with the
* parameter object.
*/
public abstract Object getParameters();
}
| 1,357 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TopicMapReadOnlyException.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/TopicMapReadOnlyException.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* TopicMapReadOnlyException.java
*
* Created on 11. toukokuuta 2006, 11:19
*
*/
package org.wandora.topicmap;
/**
*
* @author olli
*/
public class TopicMapReadOnlyException extends TopicMapException {
/** Creates a new instance of TopicMapReadOnlyException */
public TopicMapReadOnlyException() {
}
}
| 1,140 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
Association.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/Association.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* Association.java
*
* Created on June 10, 2004, 11:12 AM
*/
package org.wandora.topicmap;
import java.util.Collection;
import java.util.Map;
/**
*
* @author olli
*/
public interface Association {
/**
* Gets the type of this association.
*/
public Topic getType() throws TopicMapException ;
/**
* Sets the type of this association replacing the previous type.
*/
public void setType(Topic t) throws TopicMapException ;
/**
* Gets the player with the specified role.
*/
public Topic getPlayer(Topic role) throws TopicMapException ;
/**
* Sets the player with the specified role replacing previous player with
* that role if it exists already.
*/
public void addPlayer(Topic player,Topic role) throws TopicMapException ;
/**
* Adds players to the association. Players are given in a map which
* maps roles to players.
*/
public void addPlayers(Map<Topic,Topic> players) throws TopicMapException ;
/**
* Removes the player with the specified role.
*/
public void removePlayer(Topic role) throws TopicMapException ;
/**
* Gets a Collection of Topics containing the roles of this association.
*/
public Collection<Topic> getRoles() throws TopicMapException ;
/**
* Gets the topic map this association belongs to.
*/
public TopicMap getTopicMap();
/**
* Removes this association.
*/
public void remove() throws TopicMapException ;
/**
* Tests if this association has been removed and thus this object is now
* invalid.
*/
public boolean isRemoved() throws TopicMapException ;
}
| 2,483 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SchemaBox.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/SchemaBox.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* SchemaBox.java
*
* Created on August 10, 2004, 2:47 PM
*/
package org.wandora.topicmap;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* SchemaBox contains many high level methods related to the proprietary topic
* map schema used by Wandora. Some of these methods include:
* <ul>
* <li>Methods to get subclasses and superclasses of a topic. The standard
* superclass-subclass, superclass and subclass topics are used as association type
* and association roles respectively.</li>
* <li>Methods to check if a topic has as one of its types a specific class topic
* or any of its subclasses, subsubclasses etc. That is, subclasses behave as if
* they inherited all properties of their super classes. Thus if a topic is an
* instance of a class topic, it is also instance of all the superclasses of the
* classtopic, and instance of superclasses of those.</li>
* <li>Methods to get content types of a topic taking into account inheritance
* through superclasses. Topic A is content type of topic B if A is of type
* content type and B is an instance of A as specified in previous point in this
* list. That is B doesn't have to be a direct instance of A but can be an instance
* of some other topic that is a subclass (possibly through many associations) of A.</li>
* <li>Methods to get possible association types for a topic. Each content type
* defines what associations that type of topic may have. Possible association types
* for a topic are all the association types specified by all its content types.</li>
* <li>Similar methods for occurrence types.</li>
* <li>A method to get role topics for an association type. The association type
* topic specifies which topics can be used as roles of associations of that type.
* This method gets those role topics.</li>
* </ul>
*
* @author olli
*/
public class SchemaBox {
public static final String ROLECLASS_SI="http://wandora.org/si/core/role-class";
public static final String CONTENTTYPE_SI="http://wandora.org/si/core/content-type";
public static final String ASSOCIATIONTYPE_SI=TMBox.ASSOCIATIONTYPE_SI;
public static final String OCCURRENCETYPE_SI=TMBox.OCCURRENCETYPE_SI;
public static final String ROLE_SI=TMBox.ROLE_SI;
public static final String DEFAULT_OCCURRENCE_SI = "http://wandora.org/si/core/default-occurrence";
public static final String DEFAULT_ASSOCIATION_SI = "http://wandora.org/si/core/default-association";
public static final String DEFAULT_ROLE_1_SI = "http://wandora.org/si/core/default-role-1";
public static final String DEFAULT_ROLE_2_SI = "http://wandora.org/si/core/default-role-2";
public static final String ANY_SI="http://wandora.org/si/core/any";
public static final int COUNT_SINGLE=1;
public static final int COUNT_ATMOSTONE=2;
public static final int COUNT_ATLEASTONE=3;
public static final int COUNT_MULTIPLE=4;
/** Creates a new instance of SchemaBox */
public SchemaBox() {
}
/**
* Checks if a topic is instance of the specified class in the schema. The
* Topic doesn't have to be a direct instance of the class for this method
* to return true. It can be an instance of some other class that is a
* subclass of the specified class or a subclass of a subclass of the specified
* class etc.
*/
public static boolean isInstanceOf(Topic topic,Topic cls) throws TopicMapException {
return isInstanceOf(topic,cls,new LinkedHashSet<>());
}
private static boolean isInstanceOf(Topic topic,Topic cls,Collection<Topic> processed) throws TopicMapException {
if(topic.isOfType(cls)) return true;
else{
processed.add(cls);
Iterator<Topic> iter=getSubClassesOf(cls).iterator();
while(iter.hasNext()){
Topic subcls=(Topic)iter.next();
if(!processed.contains(subcls))
if(isInstanceOf(topic,subcls,processed)) return true;
}
return false;
}
}
/**
* Gets all instances of a class topic. Here instances doesn't mean only
* direct instances but also instances of all subclasses, instances of their
* subclasses etc.
*/
public static Collection<Topic> getInstancesOf(Topic topic) throws TopicMapException {
Set<Topic> topics=new LinkedHashSet<>();
Set<Topic> processed=new LinkedHashSet<>();
getInstancesOf(topic,topics,processed);
return topics;
}
private static void getInstancesOf(Topic topic,Collection<Topic> topics,Collection<Topic> processed) throws TopicMapException {
processed.add(topic);
TopicMap tm=topic.getTopicMap();
topics.addAll(tm.getTopicsOfType(topic));
Iterator<Topic> iter=getSubClassesOf(topic).iterator();
while(iter.hasNext()){
Topic c=(Topic)iter.next();
if(!processed.contains(c))
getInstancesOf(c,topics,processed);
}
}
/**
* Gets the content type topic each topic should be an instance of when
* they are in the specified role in an association. The schema may
* specify a content type for each role with an association. If such an
* association doesn't exist then the role itself is returned and topics
* with this role in an association should be instances of the role topic
* itself.
*/
public static Topic getRoleClass(Topic role) throws TopicMapException {
TopicMap tm=role.getTopicMap();
Topic roleClassType=tm.getTopic(ROLECLASS_SI);
Topic roleType=tm.getTopic(ROLE_SI);
if(roleClassType==null || roleType==null) return role;
Collection<Association> as=role.getAssociations(roleClassType,roleType);
if(as.isEmpty()) return role;
Association a=(Association)as.iterator().next();
Topic p=a.getPlayer(roleClassType);
return p;
}
/**
* Gets sub classes of a topic using the standard topics for association type
* and role topics. Only gets direct sub classes of the topic.
*/
public static Collection<Topic> getSubClassesOf(Topic topic) throws TopicMapException {
return getSubClassesOf(topic,XTMPSI.SUBCLASS,XTMPSI.SUPERCLASS_SUBCLASS,XTMPSI.SUPERCLASS);
}
/**
* Gets sub classes of a topic using custom topics for association type and
* role topics in the association. You need to give a topic for the association type,
* the role topic for the sub class and the role topic for the super class.
* Only gets direct subclasses of the topic.
*/
public static Collection<Topic> getSubClassesOf(Topic topic,String subSI,String assocSI,String superSI) throws TopicMapException {
Set<Topic> topics=new LinkedHashSet<>();
TopicMap tm=topic.getTopicMap();
Topic supersub=tm.getTopic(assocSI);
if(supersub==null) return topics;
Topic superc=tm.getTopic(superSI);
if(superc==null) return topics;
Topic subc=tm.getTopic(subSI);
if(subc==null) return topics;
Iterator<Association> iter=topic.getAssociations(supersub,superc).iterator();
while(iter.hasNext()){
Association a=(Association)iter.next();
Topic t=a.getPlayer(subc);
if(t!=null){
topics.add(t);
}
}
return topics;
}
/**
* Gets super classes of a topic using the standard topics for association type
* and role topics. Only gets direct superclasses of the topic.
*/
public static Collection<Topic> getSuperClassesOf(Topic topic) throws TopicMapException {
return getSuperClassesOf(topic,XTMPSI.SUBCLASS,XTMPSI.SUPERCLASS_SUBCLASS,XTMPSI.SUPERCLASS);
}
/**
* Gets super classes of a topic using custom topics for association type and
* role topics in the association. You need to give a topic for the association type,
* the role topic for the sub class and the role topic for the super class.
* Only gets direct superclasses of the topic.
*/
public static Collection<Topic> getSuperClassesOf(Topic topic,String subSI,String assocSI,String superSI) throws TopicMapException {
Set<Topic> topics=new LinkedHashSet<>();
TopicMap tm=topic.getTopicMap();
Topic supersub=tm.getTopic(assocSI);
if(supersub==null) return topics;
Topic superc=tm.getTopic(superSI);
if(superc==null) return topics;
Topic subc=tm.getTopic(subSI);
if(subc==null) return topics;
Iterator<Association> iter=topic.getAssociations(supersub,subc).iterator();
while(iter.hasNext()){
Association a=(Association)iter.next();
Topic t=a.getPlayer(superc);
if(t!=null){
topics.add(t);
}
}
return topics;
}
/**
* Recursively gets all super classes of a topic using the standard association
* type and association roles. That is gets direct super classes of the topic
* and all their super classes etc.
*/
public static Collection<Topic> getSuperClassesOfRecursive(Topic topic) throws TopicMapException {
Set<Topic> processed=new LinkedHashSet<>();
Set<Topic> classes=new LinkedHashSet<>();
getSuperClassesOfRecursive(topic,processed,classes);
return classes;
}
private static void getSuperClassesOfRecursive(Topic topic, Set<Topic> processed, Set<Topic> classes) throws TopicMapException {
if(processed.contains(topic)) return;
processed.add(topic);
Collection<Topic> cs=getSuperClassesOf(topic);
classes.addAll(cs);
Iterator<Topic> iter=cs.iterator();
while(iter.hasNext()){
Topic c=(Topic)iter.next();
getSuperClassesOfRecursive(c,processed,classes);
}
}
/**
* Gets all content types of this class is an instance of.
* Instance of here means that the topic is
* either a direct instance of the class or it is an instance of a class that
* is a subclass (possibly through many associations) of the content type.
*/
public static Collection<Topic> getContentTypesOf(Topic topic) throws TopicMapException {
Set<Topic> topics=new LinkedHashSet<>();
Set<Topic> processed=new LinkedHashSet<>();
Topic contenttype=topic.getTopicMap().getTopic(CONTENTTYPE_SI);
if(contenttype==null) return topics;
getContentTypesOfNoSupers(topic,processed,topics,contenttype);
Collection<Topic> supers=getSuperClassesOfRecursive(topic);
Iterator<Topic> iter=supers.iterator();
while(iter.hasNext()){
Topic type=(Topic)iter.next();
getContentTypesOfNoSupers(type,processed,topics,contenttype);
}
return topics;
}
private static void getContentTypesOfNoSupers(Topic topic,Collection<Topic> processed, Collection<Topic> types,Topic contenttype) throws TopicMapException {
if(processed.contains(topic)) return;
processed.add(topic);
Iterator<Topic> iter=topic.getTypes().iterator();
while(iter.hasNext()){
Topic type=(Topic)iter.next();
if(type.isOfType(contenttype)) types.add(type);
Collection<Topic> supers=getSuperClassesOfRecursive(type);
Iterator<Topic> iter2=supers.iterator();
while(iter2.hasNext()){
Topic type2=(Topic)iter2.next();
if(type2.isOfType(contenttype)) types.add(type2);
}
}
}
/**
* Gets all association types that can be used with the specified topic.
* Possible association types are specified in the content type topics. This
* method collects all such association types from all content types of the
* specified topic. Content types of the topic are resolved with <code>getContentTypesOf</code>.
*/
public static Collection<Topic> getAssociationTypesFor(Topic topic) throws TopicMapException {
Set<Topic> topics=new LinkedHashSet<>();
Topic atype=topic.getTopicMap().getTopic(ASSOCIATIONTYPE_SI);
if(atype==null) return topics;
Topic ctype=topic.getTopicMap().getTopic(CONTENTTYPE_SI);
if(ctype==null) return topics;
Collection<Topic> ctypes=getContentTypesOf(topic);
Iterator<Topic> iter=ctypes.iterator();
while(iter.hasNext()){
Topic type=(Topic)iter.next();
Iterator<Association> iter2=type.getAssociations(atype,ctype).iterator();
while(iter2.hasNext()){
Association a=(Association)iter2.next();
Topic player=a.getPlayer(atype);
if(player!=null){
topics.add(player);
}
}
}
return topics;
}
/**
* Gets all occurrence types that can be used with the specified topic.
* Possible occurrence types are specified in the content type topics. This
* method collects all such occurrence types from all content types of the
* specified topic. Content types of the topic are resolved with <code>getContentTypesOf</code>.
*/
public static Collection<Topic> getOccurrenceTypesFor(Topic topic) throws TopicMapException {
Set<Topic> topics=new LinkedHashSet<>();
Topic otype=topic.getTopicMap().getTopic(OCCURRENCETYPE_SI);
if(otype==null) return topics;
Topic ctype=topic.getTopicMap().getTopic(CONTENTTYPE_SI);
if(ctype==null) return topics;
Collection<Topic> ctypes=getContentTypesOf(topic);
Iterator<Topic> iter=ctypes.iterator();
while(iter.hasNext()){
Topic type=(Topic)iter.next();
Iterator<Association> iter2=type.getAssociations(otype,ctype).iterator();
while(iter2.hasNext()){
Association a=(Association)iter2.next();
Topic player=a.getPlayer(otype);
if(player!=null){
topics.add(player);
}
}
}
return topics;
}
/**
* Creates a new superclass-subclass association with the specified topics as
* the sub class and the super class.
*/
public static void setSuperClass(Topic subclass,Topic superclass) throws TopicMapException {
TopicMap tm=subclass.getTopicMap();
Topic supersub=TMBox.getOrCreateTopic(tm,XTMPSI.SUPERCLASS_SUBCLASS);
Topic superc=TMBox.getOrCreateTopic(tm,XTMPSI.SUPERCLASS);
Topic subc=TMBox.getOrCreateTopic(tm,XTMPSI.SUBCLASS);
Association a=tm.createAssociation(supersub);
a.addPlayer(subclass, subc);
a.addPlayer(superclass, superc);
}
/**
* Gets all roles that can be used with the specified association type.
* Each association type topic specifies all roles that can (and should)
* be used whit associations of that type. This method gets those roles.
*/
public static Collection<Topic> getAssociationTypeRoles(Topic associationType) throws TopicMapException {
Set<Topic> topics=new LinkedHashSet<>();
TopicMap tm=associationType.getTopicMap();
Topic role=tm.getTopic(ROLE_SI);
if(role==null) return topics;
Topic atype=tm.getTopic(ASSOCIATIONTYPE_SI);
if(atype==null) return topics;
Iterator<Association> iter=associationType.getAssociations(role,atype).iterator();
while(iter.hasNext()){
Association a=(Association)iter.next();
Topic t=a.getPlayer(role);
if(t!=null){
topics.add(t);
}
}
return topics;
}
}
| 16,671 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TopicTools.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/TopicTools.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* TopicTools.java
*
* Created on 1. maaliskuuta 2006, 21:06
*
*/
package org.wandora.topicmap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.wandora.topicmap.layered.ContainerTopicMap;
import org.wandora.topicmap.layered.Layer;
import org.wandora.utils.DataURL;
/**
* This class is a collection of static helpers for accessing
* topics and associations.
*
*
* @author akivela
*/
public class TopicTools {
/** Creates a new instance of TopicTools */
public TopicTools() {
}
/**
* Returns one player of given role in the associations of the topic.
*
* @param topic
* @param roleSI
* @return
*/
public static Topic getFirstPlayerWithRole(Topic topic, String roleSI) {
try {
List<Topic> players = getPlayersWithRole(topic, roleSI);
if(players != null && !players.isEmpty()) {
return players.get(0);
}
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Get all players of given role in the associations of the topic.
*
* @param topic
* @param roleSI
* @return
* @throws org.wandora.topicmap.TopicMapException
*/
public static List<Topic> getPlayersWithRole(Topic topic, String roleSI) throws TopicMapException {
List<Topic> players = new ArrayList<Topic>();
if(topic != null && roleSI != null) {
Topic role = topic.getTopicMap().getTopic(roleSI);
if(role != null) {
Collection associations = topic.getAssociations();
if(associations != null) {
for(Iterator iter = associations.iterator(); iter.hasNext(); ) {
try {
Association a = (Association) iter.next();
if(a.getPlayer(role) != null) players.add(a.getPlayer(role));
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
return players;
}
/**
* Get all players of given role in the associations of a collection of topics.
* Returned topic list may contain same
* topic several times (TODO: is this intended?).
*
* @param topics
* @param roleSI
* @return
*/
public static List<Topic> getPlayersWithRole(Collection topics, String roleSI) {
List<Topic> players = new ArrayList<Topic>();
if(topics != null) {
for(Iterator i = topics.iterator(); i.hasNext(); ) {
try {
Topic topic = (Topic) i.next();
players.addAll(getPlayersWithRole(topic, roleSI));
}
catch (Exception e) {
e.printStackTrace();
}
}
}
return players;
}
/**
* Get all players with one of specified roles in the associations of the topic.
*
* @param topic
* @param roleSIs
* @return
*/
public static List<Topic> getPlayersWithRoles(Topic topic, String[] roleSIs) {
List<Topic> players = new ArrayList<Topic>();
if(topic != null && roleSIs != null) {
String roleSI = null;
for(int i=0; i<roleSIs.length; i++) {
try {
roleSI = roleSIs[i];
players.addAll(getPlayersWithRole( topic, roleSI ));
}
catch (Exception e) {
e.printStackTrace();
}
}
}
return players;
}
/**
* Get all players with one of specified roles in the associations of the topic.
*
* @param topic
* @param roleSIs
* @return
*/
public static List<Topic> getPlayersWithRoles(Topic topic, Collection roleSIs) {
List<Topic> players = new ArrayList<Topic>();
if(topic != null) {
String roleSI = null;
for(Iterator i=roleSIs.iterator(); i.hasNext(); ) {
try {
roleSI = (String) i.next();
players.addAll(getPlayersWithRole( topic, roleSI ));
}
catch (Exception e) {
e.printStackTrace();
}
}
}
return players;
}
/**
* Get all players with one of specified roles in the associations of topics
* in the collection.
*
* @param topics
* @param roleSIs
* @return
*/
public static List<Topic> getPlayersWithRoles(Collection topics, Collection roleSIs) {
List<Topic> players = new ArrayList<Topic>();
if(topics != null) {
for(Iterator i = topics.iterator(); i.hasNext(); ) {
try {
Topic topic = (Topic) i.next();
players.addAll(getPlayersWithRoles(topic, roleSIs));
}
catch (Exception e) {
e.printStackTrace();
}
}
}
return players;
}
/**
* Get all players with one of specified roles in the associations of topics
* in the collection.
*
* @param topics
* @param roleSIs
* @return
*/
public static List<Topic> getPlayersWithRoles(Collection topics, String[] roleSIs) {
List<Topic> players = new ArrayList<Topic>();
if(topics != null) {
for(Iterator i = topics.iterator(); i.hasNext(); ) {
try {
Topic topic = (Topic) i.next();
players.addAll(getPlayersWithRoles(topic, roleSIs));
}
catch (Exception e) {
e.printStackTrace();
}
}
}
return players;
}
/**
* Get all players of all associations of a given type in the topic.
*
* @param topic
* @param associationTypeSI
* @return
* @throws org.wandora.topicmap.TopicMapException
*/
public static List<Topic> getPlayers(Topic topic, String associationTypeSI) throws TopicMapException {
List<Topic> players = new ArrayList<Topic>();
if(topic != null && associationTypeSI != null) {
Topic type = topic.getTopicMap().getTopic(associationTypeSI);
if(type != null) {
Collection associations = topic.getAssociations(type);
for(Iterator iter = associations.iterator(); iter.hasNext(); ) {
try {
Association a = (Association) iter.next();
Collection roles = a.getRoles();
for(Iterator iterRoles = roles.iterator(); iterRoles.hasNext(); ) {
Topic role = (Topic) iterRoles.next();
if(a.getPlayer(role) != topic) players.add(a.getPlayer(role));
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
return players;
}
/**
* Get one player in the associations of given type in the topic that is of given role.
*
* @param topic
* @param associationTypeSI
* @param roleSI
* @return
*/
public static Topic getFirstPlayer(Topic topic, String associationTypeSI, String roleSI) {
try {
List<Topic> players = getPlayers(topic, associationTypeSI, roleSI);
if(!players.isEmpty()) return players.get(0);
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Get all player topics within associations of a given topic. Associations
* are limited to a given association type and player to a given role.
*
* @param topic
* @param associationTypeSI
* @param roleSI
* @return
* @throws TopicMapException
*/
public static List<Topic> getPlayers(Topic topic, String associationTypeSI, String roleSI) throws TopicMapException {
List<Topic> players = new ArrayList<Topic>();
if(topic != null && associationTypeSI != null && roleSI != null) {
Topic type = topic.getTopicMap().getTopic(associationTypeSI);
Topic role = topic.getTopicMap().getTopic(roleSI);
if(type != null && role != null) {
Collection associations = topic.getAssociations(type);
for(Iterator iter = associations.iterator(); iter.hasNext(); ) {
try {
Association a = (Association) iter.next();
if(a.getPlayer(role) != null) players.add(a.getPlayer(role));
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
return players;
}
/**
* Return a list of topics. List contains player topics within associations
* of a given topic. Associations are limited with an association type
* and player with a role topic.
*
* @param topic
* @param associationType
* @param role
* @return
* @throws TopicMapException
*/
public static List<Topic> getPlayers(Topic topic, Topic associationType, Topic role) throws TopicMapException {
List<Topic> players = new ArrayList<Topic>();
if(topic != null && associationType != null && role != null) {
Collection associations = topic.getAssociations(associationType);
for(Iterator iter = associations.iterator(); iter.hasNext(); ) {
try {
Association a = (Association) iter.next();
if(a.getPlayer(role) != null) players.add(a.getPlayer(role));
}
catch (Exception e) {
e.printStackTrace();
}
}
}
return players;
}
/**
* Get all players of associations of a given topics. Associations are
* limited to a given type. Players are limited to a given role.
*
* @param topics
* @param associationTypeSI
* @param roleSI
* @return
*/
public static List<Topic> getPlayers(Collection topics, String associationTypeSI, String roleSI) {
List<Topic> players = new ArrayList<Topic>();
if(topics != null) {
for(Iterator i = topics.iterator(); i.hasNext(); ) {
try {
Topic topic = (Topic) i.next();
players.addAll(getPlayers(topic, associationTypeSI, roleSI));
}
catch (Exception e) {
e.printStackTrace();
}
}
}
return players;
}
/**
* Get all players of a topic if next conditions apply:
* Association type must be same as argument associationTypeSI.
* Player's role must be same as argument roleSI.
* Association must contain role-player pair that specified with arguments
* hasRole and hasPlayer.
*
* @param topic
* @param associationTypeSI
* @param roleSI
* @param hasRole
* @param hasPlayer
* @return
* @throws TopicMapException
*/
public static List<Topic> getPlayers(Topic topic, String associationTypeSI, String roleSI, String hasRole, String hasPlayer) throws TopicMapException {
List<Topic> players = new ArrayList<Topic>();
if(topic != null && associationTypeSI != null && roleSI != null && hasRole != null && hasPlayer != null) {
Topic type = topic.getTopicMap().getTopic(associationTypeSI);
Topic role = topic.getTopicMap().getTopic(roleSI);
Topic hasRoleTopic = topic.getTopicMap().getTopic(hasRole);
Topic hasPlayerTopic = topic.getTopicMap().getTopic(hasPlayer);
if(type != null && role != null && hasRoleTopic != null && hasPlayerTopic != null) {
Collection associations = topic.getAssociations(type);
for(Iterator iter = associations.iterator(); iter.hasNext(); ) {
try {
Association a = (Association) iter.next();
if(a.getPlayer(role) != null) {
if(a.getPlayer(hasRoleTopic).equals(hasPlayerTopic)) {
players.add(a.getPlayer(role));
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
return players;
}
/**
* Get all players of a topic if next conditions apply:
* Association type must be same as argument type.
* Player's role must be same as argument role.
* Association must contain role-player pair that specified with arguments
* hasRole and hasPlayer.
*
* @param topic
* @param type
* @param role
* @param hasRole
* @param hasPlayer
* @return
* @throws TopicMapException
*/
public static List<Topic> getPlayers(Topic topic, Topic type, Topic role, Topic hasRole, Topic hasPlayer) throws TopicMapException {
List<Topic> players = new ArrayList<Topic>();
if(topic != null && type != null && role != null && hasRole != null && hasPlayer != null) {
Collection associations = topic.getAssociations(type);
for(Iterator iter = associations.iterator(); iter.hasNext(); ) {
try {
Association a = (Association) iter.next();
if(a.getPlayer(role) != null) {
if(a.getPlayer(hasRole).equals(hasPlayer)) {
players.add(a.getPlayer(role));
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
return players;
}
/**
* Get all players of topics if next conditions apply:
* Association type must be same as argument associationTypeSI.
* Player's role must be same as argument roleSI.
* Association must contain role-player pair that specified with arguments
* hasRole and hasPlayer.
*
* @param topics
* @param associationTypeSI
* @param roleSI
* @param hasRole
* @param hasPlayer
* @return
* @throws TopicMapException
*/
public static List<Topic> getPlayers(Collection topics, String associationTypeSI, String roleSI, String hasRole, String hasPlayer) throws TopicMapException {
List<Topic> players = new ArrayList<Topic>();
for(Iterator i = topics.iterator(); i.hasNext(); ) {
try {
Topic topic = (Topic) i.next();
players.addAll(getPlayers(topic, associationTypeSI, roleSI, hasRole, hasPlayer));
}
catch (Exception e) {
e.printStackTrace();
}
}
return players;
}
/**
* Gets a sorted list of player topics of a given topic and association type
* and role. Argument sortRole is used to pick up sorting player topic.
* Argument lang is used to get sort name out of sorting player topic.
*
* @param topic
* @param associationTypeSI
* @param roleSI
* @param sortRole
* @param lang
* @return
* @throws TopicMapException
*/
public static List<Topic> getSortedPlayers(Topic topic, String associationTypeSI, String roleSI, String sortRole, String lang) throws TopicMapException {
List players = new ArrayList();
List<Topic> sortedPlayers = new ArrayList<Topic>();
if(topic != null && associationTypeSI != null && roleSI != null && sortRole != null) {
Topic type = topic.getTopicMap().getTopic(associationTypeSI);
Topic role = topic.getTopicMap().getTopic(roleSI);
Topic sortRoleTopic = topic.getTopicMap().getTopic(sortRole);
if(type != null && role != null && sortRole != null) {
Collection associations = topic.getAssociations(type);
for(Iterator iter = associations.iterator(); iter.hasNext(); ) {
try {
Association a = (Association) iter.next();
Topic player = a.getPlayer(role);
if(player != null) {
Topic sortPlayer = a.getPlayer(sortRoleTopic);
if(sortPlayer != null) {
int i=0;
while(i<players.size()) {
Topic[] tc = (Topic[]) players.get(i);
Topic anotherSortPlayer = tc[0];
if(anotherSortPlayer != null) {
String sortName = sortPlayer.getSortName(lang);
String anotherSortName = anotherSortPlayer.getSortName(lang);
if(sortName != null && anotherSortName != null) {
if(sortName.compareTo(anotherSortName) < 0) {
break;
}
}
}
i++;
}
players.add(i, new Topic[] { sortPlayer, player } );
}
else {
players.add(0, new Topic[] { null, player } );
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
//System.out.println("players.size() == " + players.size());
for(int i=0; i<players.size(); i++) {
Topic[] tc = (Topic[]) players.get(i);
if(tc != null && tc.length == 2) {
Topic player = tc[1];
if(player != null) {
sortedPlayers.add(player);
}
}
}
//System.out.println("sortedPlayers.size() == " + sortedPlayers.size());
return sortedPlayers;
}
/**
* Gets a sorted list of player topics of a given topic and association types
* and roles. Argument sortRole is used to pick up sorting player topic.
* Argument lang is used to get sort name out of sorting player topic.
*
* @param topic
* @param associationTypesSI
* @param rolesSI
* @param sortRole
* @param lang
* @return
* @throws TopicMapException
*/
public static List<Topic> getSortedPlayers(Topic topic, Collection associationTypesSI, Collection rolesSI, String sortRole, String lang) throws TopicMapException {
List players = new ArrayList();
List<Topic> sortedPlayers = new ArrayList<Topic>();
Iterator ai = associationTypesSI.iterator();
Iterator ri = rolesSI.iterator();
while(ai.hasNext() && ri.hasNext()) {
String associationTypeSI = (String) ai.next();
String roleSI = (String) ri.next();
if(topic != null && associationTypeSI != null && roleSI != null && sortRole != null) {
Topic type = topic.getTopicMap().getTopic(associationTypeSI);
Topic role = topic.getTopicMap().getTopic(roleSI);
Topic sortRoleTopic = topic.getTopicMap().getTopic(sortRole);
if(type != null && role != null && sortRole != null) {
Collection associations = topic.getAssociations(type);
for(Iterator iter = associations.iterator(); iter.hasNext(); ) {
try {
Association a = (Association) iter.next();
Topic player = a.getPlayer(role);
if(player != null) {
Topic sortPlayer = a.getPlayer(sortRoleTopic);
if(sortPlayer != null) {
int i=0;
while(i<players.size()) {
Topic[] tc = (Topic[]) players.get(i);
Topic anotherSortPlayer = tc[0];
if(anotherSortPlayer != null) {
String sortName = sortPlayer.getSortName(lang);
String anotherSortName = anotherSortPlayer.getSortName(lang);
if(sortName != null && anotherSortName != null) {
if(sortName.compareTo(anotherSortName) < 0) {
break;
}
}
}
i++;
}
players.add(i, new Topic[] { sortPlayer, player } );
}
else {
players.add(0, new Topic[] { null, player } );
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
//System.out.println("players.size() == " + players.size());
for(int i=0; i<players.size(); i++) {
Topic[] tc = (Topic[]) players.get(i);
if(tc != null && tc.length == 2) {
Topic player = tc[1];
if(player != null) {
sortedPlayers.add(player);
}
}
}
//System.out.println("sortedPlayers.size() == " + sortedPlayers.size());
return sortedPlayers;
}
/**
* Returns a list of type topics of a given topic. List of type topics
* is limited to topics that have them selves typed with requiredTypeSi.
*
* @param topic
* @param requiredTypeSI
* @return
*/
public static List<Topic> getTypesOfRequiredType(Topic topic, String requiredTypeSI) {
List<Topic> selectedTypes = new ArrayList<Topic>();
if(topic != null && requiredTypeSI != null) {
try {
Collection types = topic.getTypes();
Topic requiredType = topic.getTopicMap().getTopic(requiredTypeSI);
if(requiredType != null) {
for(Iterator iter = types.iterator(); iter.hasNext(); ) {
Topic type = (Topic) iter.next();
if(type.getTypes().contains(requiredType)) {
selectedTypes.add(type);
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
return selectedTypes;
}
public static List<String> getSLsOfPlayers(Topic topic, String associationTypeSI, String roleSI) throws TopicMapException {
return getSubjectLocatorsOfPlayers(topic, associationTypeSI, roleSI);
}
public static List<String> getSubjectLocatorsOfPlayers(Topic topic, String associationTypeSI, String roleSI) throws TopicMapException {
List<Topic> players = getPlayers(topic, associationTypeSI, roleSI);
List<String> locators = new ArrayList<String>();
for(int i=0; i<players.size(); i++) {
if(players.get(i) != null) {
String sl = players.get(i).getSubjectLocator().toExternalForm();
if(sl != null && sl.length() > 0) {
locators.add(sl);
}
}
}
return locators;
}
/**
* Returns a list subject locators of given topics. Delegates
* operation to method getSubjectLocatorsOfTopics.
*
* @param topics
* @return
*/
public static List<String> getSLsOfTopics(Collection topics) {
return getSubjectLocatorsOfTopics(topics);
}
/**
* Returns a list subject locators of given topics. If a topic
* has no subject locator, the list has no element for the topic.
*
* @param topics
* @return
*/
public static List<String> getSubjectLocatorsOfTopics(Collection topics) {
List<String> locators = new ArrayList<String>();
if(topics != null) {
for(Iterator iter=topics.iterator(); iter.hasNext(); ) {
try {
Topic topic = (Topic) iter.next();
String sl = topic.getSubjectLocator().toExternalForm();
if(sl != null && sl.length() > 0) {
locators.add(sl);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
return locators;
}
/**
* Return a collection of topics. Returned topics are edges of an association
* chain. Association chain is topic path where one travels from a given topic
* through given associations (association type, in-role and out-role). Edge
* topic is found whenever one can not travel any further.
*
* @param source
* @param associationType
* @param baseRole
* @param outRole
* @return
*/
public static Collection<Topic> getEdgeTopics(Collection<Topic> source, Topic associationType, Topic baseRole, Topic outRole) {
List<Topic> rootTopics = new ArrayList<Topic>();
Iterator<Topic> sourceIterator = source.iterator();
while(sourceIterator.hasNext()) {
Topic base = sourceIterator.next();
Topic edge = getEdgeTopic(base, associationType, baseRole, outRole);
if(!rootTopics.contains(edge)) {
rootTopics.add(edge);
}
}
return rootTopics;
}
/**
* Return one edge topic.
*
* @param base
* @param associationType
* @param baseRole
* @param outRole
* @return
*/
public static Topic getEdgeTopic(Topic base, Topic associationType, Topic baseRole, Topic outRole) {
List<Topic> pathTopics = new ArrayList<Topic>();
int MAXDEPTH = 9999;
while(true && --MAXDEPTH > 0) {
try {
Collection<Association> associations = base.getAssociations(associationType, baseRole);
if(associations.size() > 0) {
Iterator<Association> iterator = associations.iterator();
Association association = null;
if(iterator.hasNext()) {
association = iterator.next();
Topic pathTopic = association.getPlayer(outRole);
if(pathTopic != null) {
if(!pathTopics.contains(pathTopic)) {
pathTopics.add(pathTopic);
base = pathTopic;
}
else {
// PATH IS CYCLIC!
break;
}
}
}
}
else break;
}
catch(Exception e) {
e.printStackTrace();
}
}
return base;
}
/**
* Returns one path (a list of topics) that is created traversing associations
* from a given start point to the end point.
*
* @param base
* @param associationType
* @param baseRole
* @param outRole
* @return
*/
public static List<Topic> getSinglePath(Topic base, Topic associationType, Topic baseRole, Topic outRole) {
List<Topic> pathTopics = new ArrayList<Topic>();
int MAXDEPTH = 9999;
while(true && --MAXDEPTH > 0) {
try {
Collection<Association> associations = base.getAssociations(associationType, baseRole);
if(associations.size() > 0) {
Iterator<Association> iterator = associations.iterator();
Association association = null;
if(iterator.hasNext()) {
association = iterator.next();
Topic pathTopic = association.getPlayer(outRole);
if(pathTopic != null) {
if(!pathTopics.contains(pathTopic)) {
pathTopics.add(pathTopic);
base = pathTopic;
}
else {
// PATH IS CYCLIC!
break;
}
}
}
}
else break;
}
catch(Exception e) {
e.printStackTrace();
}
}
return pathTopics;
}
/**
* Returns possible paths where one can traverse given associations
* back to the starting topic.
*
* @param base
* @param associationType
* @param baseRole
* @param outRole
* @return
*/
public static List<List<Topic>> getCyclePaths(Topic base, Topic associationType, Topic baseRole, Topic outRole) {
List<List<Topic>> cycles = new ArrayList<List<Topic>>();
List<Topic> path = new ArrayList<Topic>();
path.add(base);
getCyclePaths(cycles, path, base, associationType, baseRole, outRole);
return cycles;
}
private static void getCyclePaths(List<List<Topic>> cycles, List<Topic> path, Topic base, Topic associationType, Topic baseRole, Topic outRole) {
try {
Collection<Association> associations = base.getAssociations(associationType, baseRole);
if(associations.size() > 0) {
Iterator<Association> iterator = associations.iterator();
Association association = null;
if(iterator.hasNext()) {
association = iterator.next();
Topic pathTopic = association.getPlayer(outRole);
if(pathTopic != null) {
if(path.contains(pathTopic)) {
List<Topic> cycle = new ArrayList<Topic>();
int index = path.indexOf(pathTopic);
for(int i=index; i<path.size(); i++) {
cycle.add(path.get(i));
}
cycle.add(pathTopic);
cycles.add(cycle);
}
else {
path.add(pathTopic);
base = pathTopic;
List<Topic> clonedPath = new ArrayList<Topic>();
clonedPath.addAll(path);
getCyclePaths(cycles, clonedPath, base, associationType, baseRole, outRole);
}
}
}
}
}
catch(Exception e) {
e.printStackTrace();
}
}
//----------------------------------------------------- LOCATOR CLEANING ---
/**
* Checks if given locator contains unwanted characters that make
* the locator "dirty".
*
* @param l
* @return
*/
public static boolean isDirtyLocator(Locator l) {
String s = l.toExternalForm();
if(DataURL.isDataURL(s)) return false;
for(int k=0; k<s.length(); k++) {
if(isDirtyLocatorCharacter(s.charAt(k))) return true;
}
return false;
}
/**
* Method isDirtyLocator uses this method to decide whether or not
* a character is "dirty".
*
* @param c
* @return
*/
public static boolean isDirtyLocatorCharacter(char c) {
if("1234567890poiuytrewqasdfghjklmnbvcxzPOIUYTREWQASDFGHJKLMNBVCXZ$-_.+!*'(),/?:=&#~;%".indexOf(c) != -1) return false;
else return true;
}
public static String schars = "ÄÖÅäöå";
public static String dchars = "AOAAoA";
/**
* Finds a suitable replacement character for some "dirty" characters.
*
* @param c
* @return
*/
public static char repacementLocatorCharacterFor(char c) {
int i = schars.indexOf(c);
if(i == -1) {
if(c < 32) return 0;
return '_';
}
else return dchars.charAt(i);
}
/**
* Removes or replaces all "dirty" characters in the string.
*
* @param s
* @return
*/
public static String cleanDirtyLocator(String s) {
if(DataURL.isDataURL(s)) {
return s;
}
else {
StringBuilder sb = new StringBuilder();
int i = 0;
for(int k=0; k<s.length(); k++) {
char c = s.charAt(k);
if(isDirtyLocatorCharacter(c)) {
c = repacementLocatorCharacterFor(c);
if(c != 0) sb.append(c);
}
else sb.append(c);
}
return sb.toString();
}
}
public static Locator cleanDirtyLocator(Locator l) {
if(l != null) {
l = new Locator(cleanDirtyLocator(l.toExternalForm()));
}
return l;
}
public static int locatorCounter = 0;
/**
* Returns a default locator that can be given to a topic and it
* is very likely (but not sure) that the subject identifier doesn't
* cause accidental merge. Default locator is created with a prefix
* "http://wandora.org/si/temp/", timestamp and locator counter.
*
* @return
*/
public static Locator createDefaultLocator() {
locatorCounter++;
long stamp = System.currentTimeMillis();
String defaultSIprefix = "http://wandora.org/si/temp/";
Locator newLocator = new Locator(defaultSIprefix + stamp + "-" + locatorCounter);
// System.out.println("Creating default SI '"+newLocator.toExternalForm());
return newLocator;
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
public static final String nameOfInstanceType = "instance";
public static final String nameOfTypeType = "type";
/**
* Returns topic's base name if base name exists. Otherwise returns
* topic's first subject identifier.
*
* @param t
* @return
*/
public static String getTopicName(Topic t) {
if(t == null) return null;
String name = null;
try {
name = t.getBaseName();
if(name == null) {
name = t.getOneSubjectIdentifier().toExternalForm();
}
}
catch(Exception e) {
e.printStackTrace();
}
return name;
}
/**
* Returns a flat string array that contains associations (including
* classes and instances) of a given topic. Every n*3:th element of
* the string array is argument topic's name. Every n*3+1:th
* element of the array is association type's name and
* every n*3+2:th element of the array is associated topic's name.
* Role topic's are not included in the array.
*
* @param t
* @return
*/
public static String[] getAssociationsAsTriplets(Topic t) {
if(t == null) return null;
List<String> triplets = new ArrayList<String>();
String tstr = getTopicName(t);
try {
Collection<Topic> types = t.getTypes();
for(Topic type : types) {
triplets.add(tstr);
triplets.add(nameOfTypeType);
triplets.add(getTopicName(type));
}
Collection<Topic> instances = t.getTopicMap().getTopicsOfType(t);
for(Topic instance : instances) {
triplets.add(tstr);
triplets.add(nameOfInstanceType);
triplets.add(getTopicName(instance));
}
Collection<Association> associations = t.getAssociations();
for(Association a : associations) {
Topic type = a.getType();
Collection<Topic> roles = a.getRoles();
boolean skipSame = true;
for(Topic role : roles) {
Topic player = a.getPlayer(role);
if(player.mergesWithTopic(t) && skipSame) {
continue;
}
triplets.add(tstr);
triplets.add(getTopicName(type));
triplets.add(getTopicName(player));
}
}
}
catch(Exception e) {
e.printStackTrace();
}
return triplets.toArray( new String[] {} );
}
/**
* Returns a flat string array that contains associations (including classes
* and instances) of a given topic. Associations are stored as type-player
* pairs. Every odd element of the string array is type topic's name. Every
* even element of the string array is player topic's name. Role topics
* are not stored in the string array.
*
* @param t
* @return
*/
public static String[] getAssociationsAsTypePlayerTuples(Topic t) {
if(t == null) return null;
List<String> tuples = new ArrayList<String>();
try {
Collection<Topic> types = t.getTypes();
for(Topic type : types) {
tuples.add(nameOfTypeType);
tuples.add(getTopicName(type));
}
Collection<Topic> instances = t.getTopicMap().getTopicsOfType(t);
for(Topic instance : instances) {
tuples.add(nameOfInstanceType);
tuples.add(getTopicName(instance));
}
Collection<Association> associations = t.getAssociations();
for(Association a : associations) {
Topic type = a.getType();
Collection<Topic> roles = a.getRoles();
boolean skipSame = true;
for(Topic role : roles) {
Topic player = a.getPlayer(role);
if(player.mergesWithTopic(t) && skipSame) {
continue;
}
tuples.add(getTopicName(type));
tuples.add(getTopicName(player));
}
}
}
catch(Exception e) {
e.printStackTrace();
}
return tuples.toArray( new String[] {} );
}
/**
* Returns given association as a string array where first element
* is association type and next elements association player topics.
* Returned string array doesn't contain role topics.
*
* @param a
* @return
*/
public static String[] getAsTriplet(Association a) {
if(a == null) return null;
List<String> triplet = new ArrayList<String>();
try {
Topic type = a.getType();
triplet.add(getTopicName(type));
Collection<Topic> roles = a.getRoles();
for(Topic role : roles) {
Topic player = a.getPlayer(role);
triplet.add(getTopicName(player));
}
}
catch(Exception e) {
e.printStackTrace();
}
return triplet.toArray( new String[] {} );
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
/**
* Returns a list of topic map layers of given container topic map.
* For example, Wandora's layer stack is a container topic map and
* the method returns all topic maps in the layer stack.
*
* @param tm
* @return
*/
public static List<Layer> getLayers(ContainerTopicMap tm) {
if (tm == null) return null;
List<Layer> layers = new ArrayList<Layer>();
for (Layer l : tm.getLayers()) {
TopicMap ltm = l.getTopicMap();
if(ltm instanceof ContainerTopicMap){
layers.addAll(getLayers((ContainerTopicMap)ltm));
}
layers.add(l);
}
return layers;
}
/**
* Checks if a given topic map is a container topic map. Container
* topic map can contain other topics maps. For example, Wandora's
* layer stack is a container topic map.
*
* @param tm
* @return
*/
public static boolean isTopicMapContainer(TopicMap tm) {
if(tm == null) {
return false;
}
else {
return tm instanceof ContainerTopicMap;
}
}
}
| 43,547 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TopicMapStatOptions.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/TopicMapStatOptions.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* TopicMapStatOptions.java
*
* Created on 25. toukokuuta 2006, 18:26
*
*/
package org.wandora.topicmap;
/**
*
* @author akivela
*/
public class TopicMapStatOptions {
public static final int NUMBER_OF_TOPICS = 1000;
public static final int NUMBER_OF_ASSOCIATIONS = 1100;
public static final int NUMBER_OF_BASE_NAMES = 2000;
public static final int NUMBER_OF_SUBJECT_IDENTIFIERS = 2010;
public static final int NUMBER_OF_SUBJECT_LOCATORS = 2020;
public static final int NUMBER_OF_OCCURRENCES = 2030;
public static final int NUMBER_OF_TOPIC_CLASSES = 2040;
public static final int NUMBER_OF_ASSOCIATION_TYPES = 3000;
public static final int NUMBER_OF_ASSOCIATION_ROLES = 3010;
public static final int NUMBER_OF_ASSOCIATION_PLAYERS = 3020;
// **** REMEMBER TO ADD NEW OPTIONS BELOW TO getAvailableOptions &
// **** describeStatOption ALSO!!
private int option = NUMBER_OF_TOPICS;
/** Creates a new instance of TopicMapStatOptions */
public TopicMapStatOptions() {
}
public TopicMapStatOptions(int option) {
this.option = option;
}
public void setOption(int option) {
this.option = option;
}
public int getOption() {
return this.option;
}
// -------------------------------------------------------------------------
public static int[] getAvailableOptions() {
return new int[] {
NUMBER_OF_TOPICS,
NUMBER_OF_ASSOCIATIONS,
NUMBER_OF_BASE_NAMES,
NUMBER_OF_SUBJECT_IDENTIFIERS,
NUMBER_OF_SUBJECT_LOCATORS,
NUMBER_OF_OCCURRENCES,
NUMBER_OF_TOPIC_CLASSES,
NUMBER_OF_ASSOCIATION_TYPES,
NUMBER_OF_ASSOCIATION_ROLES,
NUMBER_OF_ASSOCIATION_PLAYERS,
};
}
public static String describeStatOption(int opt) {
switch(opt) {
case NUMBER_OF_TOPICS: {
return "Number of topics";
}
case NUMBER_OF_ASSOCIATIONS: {
return "Number of associations";
}
case NUMBER_OF_ASSOCIATION_PLAYERS: {
return "Number of distinct players in associations";
}
case NUMBER_OF_ASSOCIATION_ROLES: {
return "Number of distinct roles in associations";
}
case NUMBER_OF_ASSOCIATION_TYPES: {
return "Number of distinct types of associations";
}
case NUMBER_OF_BASE_NAMES: {
return "Number of topic base names";
}
case NUMBER_OF_OCCURRENCES: {
return "Number of occurrences";
}
case NUMBER_OF_SUBJECT_IDENTIFIERS: {
return "Number of subject identifiers";
}
case NUMBER_OF_SUBJECT_LOCATORS: {
return "Number of subject locators";
}
case NUMBER_OF_TOPIC_CLASSES: {
return "Number of distinct topic classes";
}
}
return "Statistics option description not available";
}
}
| 4,022 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TopicInUseException.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/TopicInUseException.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* TopicInUseException.java
*
* Created on June 17, 2004, 10:41 AM
*/
package org.wandora.topicmap;
/**
* An exception thrown when deleting a topic could not be carried out because
* the topic is used in such a place that it cannot be removed without greatly
* modifying the topic map.
*
* @author olli
*/
public class TopicInUseException extends TopicMapException {
private static final long serialVersionUID = 1L;
public static final int NOREASON=-1;
public static final int USEDIN_ASSOCIATIONTYPE=0;
public static final int USEDIN_ASSOCIATIONROLE=1;
public static final int USEDIN_DATATYPE=2;
public static final int USEDIN_DATAVERSION=3;
public static final int USEDIN_VARIANTSCOPE=4;
public static final int USEDIN_TOPICTYPE=5;
private Topic t;
private int reason;
public TopicInUseException(Topic t){
this(t,NOREASON);
}
public TopicInUseException(Topic t,int reason){
this.t=t;
this.reason=reason;
}
public Topic getTopic(){
return t;
}
public int getReason(){
return reason;
}
}
| 1,928 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TopicMapException.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/TopicMapException.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* TopicMapException.java
*
* Created on 11. toukokuuta 2006, 11:18
*
*/
package org.wandora.topicmap;
/**
*
* @author olli
*/
public class TopicMapException extends org.wandora.exceptions.WandoraException {
/** Creates a new instance of TopicMapException */
public TopicMapException() {
}
public TopicMapException(String s){
super(s);
}
public TopicMapException(Throwable cause){
super(cause);
}
public TopicMapException(String s,Throwable cause){
super(s,cause);
}
}
| 1,355 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TopicMapHashCode.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/TopicMapHashCode.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.wandora.topicmap;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
/**
*
* @author olli
*/
public class TopicMapHashCode {
public static long getTopicIdentifierCode(Topic t) throws TopicMapException {
long h=0;
for(Locator l : t.getSubjectIdentifiers()){
h+=l.hashCode();
}
String bn=t.getBaseName();
if(bn!=null) h+=bn.hashCode();
if(h==0) return 1;
return h;
}
public static long getScopeIdentifierCode(Collection<Topic> scope) throws TopicMapException {
long h=0;
for(Topic t : scope){
h+=getTopicIdentifierCode(t);
}
if(h==0) return 1;
return h;
}
public static long getTopicHashCode(Topic t) throws TopicMapException {
long h=0;
String bn=t.getBaseName();
if(bn!=null) h+=bn.hashCode();
Locator sl=t.getSubjectLocator();
if(sl!=null) h+=sl.hashCode();
for(Locator l : t.getSubjectIdentifiers()){
h+=l.hashCode();
}
for(Set<Topic> scope : t.getVariantScopes()){
String v=t.getVariant(scope);
h+=getScopeIdentifierCode(scope)*v.hashCode();
}
return h;
}
public static long getAssociationHashCode(Association a) throws TopicMapException {
long h=0;
long typeCode=getTopicIdentifierCode(a.getType());
h+=typeCode;
for(Topic role : a.getRoles()){
Topic player=a.getPlayer(role);
h+=typeCode*getTopicIdentifierCode(role)*getTopicIdentifierCode(player);
}
return h;
}
public static long getTopicMapHashCode(TopicMap tm) throws TopicMapException {
long h=0;
Iterator<Topic> iter=tm.getTopics();
while(iter.hasNext()){
h+=getTopicHashCode(iter.next());
}
Iterator<Association> iter2=tm.getAssociations();
while(iter2.hasNext()){
h+=getAssociationHashCode(iter2.next());
}
return h;
}
}
| 2,861 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
Locator.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/Locator.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* Locator.java
*
* Created on June 10, 2004, 11:14 AM
*/
package org.wandora.topicmap;
/**
*
* @author olli
*/
public class Locator implements Comparable<Locator> {
private String reference;
private String notation;
/**
* Creates a new instance of Locator with "URI" notation. Usually you shouldn't call this directly.
* Instead use TopicMap.createLocator.
*/
public Locator(String reference) {
this("URI",reference);
}
/**
* Creates a new instance of Locator. Usually you shouldn't call this directly.
* Instead use TopicMap.createLocator.
*/
public Locator(String notation,String reference) {
this.notation=notation;
this.reference=reference;
if(reference==null) throw new RuntimeException("Trying to create locator with null reference");
}
public String getNotation(){
return notation;
}
public String getReference(){
return reference;
}
@Override
public int hashCode(){
return notation.hashCode()+reference.hashCode();
}
@Override
public boolean equals(Object o){
if(!(o instanceof Locator)) return false;
Locator l=(Locator)o;
return (notation.equals(l.notation) && reference.equals(l.reference));
}
/* this needed to implement tmapi Locator
public Locator resolveRelative(String relative){
}
*/
public String toExternalForm(){
return getReference();
}
@Override
public String toString(){
return toExternalForm();
}
public static Locator parseLocator(String s){
return new Locator(s);
}
@Override
public int compareTo(Locator o) {
int r=notation.compareTo(o.notation);
if(r!=0) return r;
return reference.compareTo(o.reference);
}
}
| 2,689 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TopicMapLogger.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/TopicMapLogger.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* TopicMapLogger.java
*
* Created on 20.6.2006, 14:21
*
*/
package org.wandora.topicmap;
/**
*
* @author akivela
*/
public interface TopicMapLogger {
public void log(String message);
public void log(String message, Exception e);
public void log(Exception e);
public void hlog(String message);
public void setProgress(int n);
public void setProgressMax(int maxn);
public void setLogTitle(String title);
public boolean forceStop();
}
| 1,288 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TopicHashMap.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/TopicHashMap.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* TopicHashMap.java
*
* Created on 30. toukokuuta 2007, 13:55
*
*/
package org.wandora.topicmap;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
/**
*
* @author olli
*/
public class TopicHashMap<K> implements Map<Topic,K> {
public Map<Locator,Topic> siMap;
public Map<String,Topic> bnMap;
public Map<Locator,Topic> slMap;
public Map<Topic,K> valueMap;
/** Creates a new instance of TopicHashMap */
public TopicHashMap() {
clear();
}
public Collection<K> values() {
return valueMap.values();
}
public int size() {
return valueMap.size();
}
public Set<Topic> keySet() {
return valueMap.keySet();
}
public boolean isEmpty() {
return valueMap.isEmpty();
}
public boolean containsValue(Object value) {
return valueMap.containsValue(value);
}
private Topic findInternalKey(Object t){
if(t instanceof Topic) return findInternalKey((Topic)t);
else return null;
}
private Topic findInternalKey(Topic t){
Topic r=null;
try{
if(t.getBaseName()!=null) {
r=bnMap.get(t.getBaseName());
if(r!=null) return r;
}
for(Locator l : t.getSubjectIdentifiers()){
r=siMap.get(l);
if(r!=null) return r;
}
if(t.getSubjectLocator()!=null) {
r=slMap.get(t.getSubjectLocator());
if(r!=null) return r;
}
}catch(TopicMapException tme){tme.printStackTrace();}
return null;
}
public boolean containsKey(Object key) {
if(findInternalKey(key)!=null) return true;
else return false;
}
public void putAll(Map<? extends Topic, ? extends K> m) {
for(Map.Entry<? extends Topic, ? extends K> e : m.entrySet()){
put(e.getKey(),e.getValue());
}
}
public K put(Topic t, K value) {
Topic old=findInternalKey(t);
K oldValue=null;
if(old!=null) {
if(old==t){
return valueMap.put(t,value);
}
else {
oldValue=remove(old);
}
}
try{
if(t.getBaseName()!=null) bnMap.put(t.getBaseName(),t);
for(Locator l : t.getSubjectIdentifiers()){
siMap.put(l,t);
}
if(t.getSubjectLocator()!=null) slMap.put(t.getSubjectLocator(),t);
valueMap.put(t,value);
return oldValue;
}catch(TopicMapException tme){tme.printStackTrace();}
return null;
}
public Set<Map.Entry<Topic, K>> entrySet() {
return valueMap.entrySet();
}
public void clear() {
siMap=new LinkedHashMap<Locator,Topic>();
bnMap=new LinkedHashMap<String,Topic>();
slMap=new LinkedHashMap<Locator,Topic>();
valueMap=new LinkedHashMap<Topic,K>();
}
public K remove(Object key) {
Topic t=findInternalKey(key);
if(t==null) return null;
else {
try{
if(t.getBaseName()!=null) bnMap.remove(t.getBaseName());
for(Locator l : t.getSubjectIdentifiers()){
siMap.remove(l);
}
if(t.getSubjectLocator()!=null) slMap.remove(t.getSubjectLocator());
}catch(TopicMapException tme){tme.printStackTrace();}
return valueMap.remove(t);
}
}
public K get(Object key) {
Topic t=findInternalKey(key);
if(t!=null) return valueMap.get(t);
else return null;
}
}
| 4,563 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TopicMapType.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/TopicMapType.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* TopicMapType.java
*
* Created on 21. marraskuuta 2005, 13:44
*/
package org.wandora.topicmap;
import java.io.IOException;
import javax.swing.Icon;
import javax.swing.JMenuItem;
import org.wandora.application.Wandora;
import org.wandora.topicmap.packageio.PackageInput;
import org.wandora.topicmap.packageio.PackageOutput;
import org.wandora.utils.Options;
/**
* TopicMapType is a class that makes it possible to use a topic map implementation
* in Wandora. The class extending TopicMap implements everything directly
* affecting the contents of the
* topic map. Another class implementing this class, TopicMapType, must implement some
* methods that are needed by Wandora to make it possible to load and save
* topic maps, create new topic maps and configure new and existing topic maps.
* A new topic map implementation may be very useful in some cases without
* implementing TopicMapType but it cannot be used with Wandora.
*
* @author olli
*/
public interface TopicMapType {
/**
* Gets a name for topic map type.
*/
public String getTypeName();
/**
* Create a new topic map with parameters given by TopicMapConfigurationPanel.getParameters.
*/
public TopicMap createTopicMap(Object params) throws TopicMapException ;
/**
* Modifies an existing topic map with parameters given by TopicMapConfigurationPanel.getParameters.
* The method may create a completely new topic map if needed.
*/
public TopicMap modifyTopicMap(TopicMap tm, Object params) throws TopicMapException ;
/**
* Get a configuration panel for the topic map.
*/
public TopicMapConfigurationPanel getConfigurationPanel(Wandora admin, Options options);
/**
* Get a configuration panel that can be used to modify an existing topic map.
*/
public TopicMapConfigurationPanel getModifyConfigurationPanel(Wandora admin, Options options, TopicMap tm);
/**
* Packages a topic map so it can be loaded later by unpackageTopicMap.
* Different implementations may choose to store the topic map in the package
* or only store configuration parameters and have the topicmap in some other
* place such as an external database.
*/
public void packageTopicMap(TopicMap tm,PackageOutput out,String path, TopicMapLogger logger) throws IOException,TopicMapException;
/**
* Unpackages and creates a topic map.
*/
public TopicMap unpackageTopicMap(PackageInput in,String path, TopicMapLogger logger,Wandora wandora) throws IOException,TopicMapException;
public TopicMap unpackageTopicMap(TopicMap tm, PackageInput in, String path, TopicMapLogger logger,Wandora wandora) throws IOException,TopicMapException;
/**
* Get a topic map implementation specific menu structure for this topic map type.
*/
public JMenuItem[] getTopicMapMenu(TopicMap tm,Wandora admin);
/**
* Get an icon that can be used to represent this type of topic map.
*/
public Icon getTypeIcon();
}
| 3,841 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TopicMapTypeManager.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/TopicMapTypeManager.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* TopicMapTypeManager.java
*
* Created on 17. maaliskuuta 2006, 15:45
*/
package org.wandora.topicmap;
import org.wandora.topicmap.database.DatabaseTopicMap;
import org.wandora.topicmap.database.DatabaseTopicMapType;
import org.wandora.topicmap.layered.LayerStack;
import org.wandora.topicmap.layered.LayeredTopicMapType;
import org.wandora.topicmap.linked.LinkedTopicMap;
import org.wandora.topicmap.linked.LinkedTopicMapType;
import org.wandora.topicmap.memory.MemoryTopicMapType;
import org.wandora.topicmap.memory.TopicMapImpl;
import org.wandora.topicmap.query.QueryTopicMap;
import org.wandora.topicmap.query.QueryTopicMapType;
import org.wandora.topicmap.undowrapper.UndoTopicMap;
/**
* <p>
* A class that manages all TopicMapTypes. In particular, has methods to
* get the TopicMapType of a specific class extending TopicMap or an instance
* of such a class.
* </p>
* <p>
* Note that currently the getType methods have hard coded mapping for following
* topic map implementations: TopicMapImpl, RemoteTopicMap, DatabaseTopicMap
* and LayerStack. This means that there is no way to register new topic map
* implementations. In future this class should read or automatically detect
* all implementations.
* </p>
*
* @author olli
*/
public class TopicMapTypeManager {
/** Creates a new instance of TopicMapTypeManager */
public TopicMapTypeManager() {
}
/**
* Get the TopicMapType from a TopicMap.
*/
public static TopicMapType getType(TopicMap tm) {
if(tm == null) return null;
if(tm.getClass().equals(UndoTopicMap.class)) {
tm = ((UndoTopicMap) tm).getWrappedTopicMap();
}
return getType(tm.getClass());
}
/**
* Get the TopicMapType from a topic map implementing class.
*/
public static TopicMapType getType(Class<? extends TopicMap> c){
if(c==LayerStack.class) return new LayeredTopicMapType();
else if(c==DatabaseTopicMap.class) return new DatabaseTopicMapType();
else if(c==org.wandora.topicmap.database2.DatabaseTopicMap.class) return new org.wandora.topicmap.database2.DatabaseTopicMapType();
else if(c==TopicMapImpl.class) return new MemoryTopicMapType();
else if(c==QueryTopicMap.class) return new QueryTopicMapType();
else if(c==LinkedTopicMap.class) return new LinkedTopicMapType();
else if(c==LayerStack.class) return new LayeredTopicMapType();
else return null;
}
}
| 3,285 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
XTMPSI.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/XTMPSI.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* XTMPSI.java
*
* Created on June 7, 2004, 10:38 AM
*/
package org.wandora.topicmap;
/**
* This class provides some standard topic map subject identifiers.
* @author olli
*/
public class XTMPSI {
/**
* The base URL for XTM 1.0 (not actually an XTM PSI).
*/
public static final String XTM1_BASE = "http://www.topicmaps.org/xtm/1.0/";
/**
* The base URL for all XTM 1.0 PSIs.
*/
public static final String PSI_DOC = XTM1_BASE + "core.xtm#";
/**
* Suitability of a topic name for display; for use in the parameters of variant names.
*/
public static final String SORT = PSI_DOC + "sort";
/**
* Suitability of a topic name for use as a sort key; for use in the parameters of variant names.
*/
public static final String DISPLAY = PSI_DOC + "display";
/**
* The core concept of class-instance; the class of association that represents class-instance relationships between topics, and that is semantically equivalent to the use of <instanceOf> subelements.
*/
public static final String CLASS_INSTANCE = PSI_DOC + "class-instance";
/**
* The core concept of class; the role of class as played by one of the members of a class-instance association.
*/
public static final String CLASS = PSI_DOC + "class";
/**
* The core concept of instance; the role of instance as played by one of the members of a class-instance association.
*/
public static final String INSTANCE = PSI_DOC + "instance";
/**
* The core concept of superclass-subclass; the class of association that represents superclass-subclass relationships between topics.
*/
public static final String SUPERCLASS_SUBCLASS = PSI_DOC + "superclass-subclass";
/**
* The core concept of superclass; the role of superclass as played by one of the members of a superclass-subclass association.
*/
public static final String SUPERCLASS = PSI_DOC + "superclass";
/**
* The core concept of subclass; the role of subclass as played by one of the members of a superclass-subclass association.
*/
public static final String SUBCLASS = PSI_DOC + "subclass";
/**
* The core concept of topic; the generic class to which all topics belong unless otherwise specified.
*/
public static final String TOPIC = PSI_DOC + "topic";
/**
* The core concept of association; the generic class to which all associations belong unless otherwise specified.
*/
public static final String ASSOCIATION = PSI_DOC + "association";
/**
* The core concept of occurrence; the generic class to which all occurrences belong unless otherwise specified.
*/
public static final String OCCURRENCE = PSI_DOC + "occurrence";
public static final String LANGUAGE = "http://www.topicmaps.org/xtm/1.0/language.xtm";
/**
* Prefix for language topics.
*/
public static final String LANG_PREFIX = LANGUAGE + "#";
/**
* Language independent.
*/
public static final String LANG_INDEPENDENT = "http://wandora.org/si/core/lang-independent";
/**
* Returns the subject identifier for the specified language or if a null
* http://wandora.orgsi/core/lang-independent
* denoting a language independent version.
*/
public static String getLang(String lang) {
if(lang != null && lang.length()>0) return LANG_PREFIX+lang.toLowerCase();
else return LANG_INDEPENDENT;
}
}
| 4,350 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TopicMap.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/TopicMap.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* TopicMap.java
*
* Created on June 10, 2004, 11:12 AM
*/
package org.wandora.topicmap;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import org.wandora.topicmap.parser.JTMParser;
import org.wandora.topicmap.parser.LTMParser;
import org.wandora.topicmap.parser.XTMAdaptiveParser;
import org.wandora.utils.Tuples.T2;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
/**
* <p>
* The abstract topic map class that all topic map implementations must extend.
* Simple primitive methods are left abstract and more complex methods have
* been implemented using the primitive methods. Some implementations may contain
* data structures that could be used to make complex methods more efficient.
* In this case it is advisable to override and reimplement them.
* </p>
* <p>
* Usually any topic map implementation will also have its own topic and association
* implementations. The createTopic and createAssociation methods are used to
* create topics and associations instead of creating them with new operator.
* </p>
* <p>
* Generally all methods that take topic or association parameters expect them to
* be topics or associations belonging in this topic map. This means that you
* can't get a topic from one topic map and then use it as a parameter of a method
* in some other topic map. There are a few methods where this is allowed. Most
* notably the copy methods that copy topics or associations from one topic map
* in to another and a few methods that test if two topics would merge with
* each other.
* </p>
* @author olli, akivela
*/
public abstract class TopicMap implements TopicMapLogger {
protected TopicMapLogger logger = null;
protected boolean consistencyCheck = true;
protected boolean consistencyCheckWhenXTMImport = false;
protected boolean isReadOnly = false;
public static final String EDITTIME_SI="http://wandora.org/si/core/edittime";
protected TopicMap parentTopicMap;
public Locator createLocator(String reference) throws TopicMapException {
return createLocator("URI",reference);
}
public Locator createLocator(String notation,String reference) throws TopicMapException {
return new Locator(notation,reference);
}
/**
* Gets a topic with subject identifier.
*/
public abstract Topic getTopic(Locator si) throws TopicMapException ;
/**
* Gets a topic with subject identifier. Subject identifier is given as a
* URI reference string instead of Locator.
*/
public Topic getTopic(String si) throws TopicMapException {
return getTopic(createLocator(si));
}
/**
* Gets a topic with subject locator.
*/
public abstract Topic getTopicBySubjectLocator(Locator sl) throws TopicMapException ;
/**
* Gets a topic with subject locator. Subject locator is given as a
* URI reference string instead of Locator.
*/
public Topic getTopicBySubjectLocator(String sl) throws TopicMapException {
return getTopicBySubjectLocator(createLocator(sl));
}
/**
* Creates a new topic without base name, subject identifier, data or any associations.
*/
public abstract Topic createTopic(String id) throws TopicMapException ;
/**
* Creates a new topic without base name, subject identifier, data or any associations.
*/
public abstract Topic createTopic() throws TopicMapException ;
/**
* Creates a new association of the given type without any members.
*/
public abstract Association createAssociation(Topic type) throws TopicMapException ;
/**
* Gets all topics in the topic map that are of the given type.
*/
public abstract Collection<Topic> getTopicsOfType(Topic type) throws TopicMapException ;
/**
* Gets a topic with topic base name.
*/
public abstract Topic getTopicWithBaseName(String name) throws TopicMapException ;
/**
* Gets all topics in the topic map. The topic map may contain a very large number
* of topics and this operation may take a long time to finish even though it
* returns an iterator instead of all topics in a collection.
*
* Ideally this should return a TopicIterator with the special dispose method
* instead of a generic Iterator. The interface remains specifies just Iterator
* for backwards compatibility. See notes in TopicIterator.
*/
public abstract Iterator<Topic> getTopics() throws TopicMapException ;
/**
* Gets the topics whose subject identifiers are given in the array.
* Will always return
* an array of equal size as the parameter array with null elements where
* topics are not found with the given subject identifiers.
*/
public abstract Topic[] getTopics(String[] sis) throws TopicMapException ;
/**
* Returns all associations in the topic map. The topic map may contain a very large
* number of associations and this operation may take a long time to finish even
* though it returns an iterator instead of all associations in a collection.
*/
public abstract Iterator<Association> getAssociations() throws TopicMapException ;
/**
* Returns all associations in the topic map that are of the given type.
* Usually topic maps will either contain none or a very large number of
* associations of any type. Thus this method may potentially be very
* time consuming and require a very large amount of memory.
*/
public abstract Collection<Association> getAssociationsOfType(Topic type) throws TopicMapException ;
/**
* Returns the number of topics in topic map. For some implementations this
* may be a very time consuming operation while for some it is a very simple
* thing to do.
*/
public abstract int getNumTopics() throws TopicMapException ;
/**
* Returns the number of associations in topic map. For some implementations
* this may be a very time consuming operation while for some it is a very
* simple thing to do.
*/
public abstract int getNumAssociations() throws TopicMapException ;
/**
* Copies a topic of different topic map in this topic map. If deep is true then
* topic types, variants and data are also copied. Only stubs of types, data types
* and variant scopes are copied.
*/
public abstract Topic copyTopicIn(Topic t,boolean deep) throws TopicMapException ;
/**
* Copies an association of a different topic map in this topic map. If a topic
* related to the association does not exist in the topic map, then that topic
* is copied with copyTopicIn(t,false). Otherwise the existing topic is used.
* The existence of a topic is checked by trying to get it with one
* (chosen arbitrarily) subject identifier.
*/
public abstract Association copyAssociationIn(Association a) throws TopicMapException ;
/**
* Copies all associations of a topic of a different topic map in this topic
* map using copyAssociationIn.
*/
public abstract void copyTopicAssociationsIn(Topic t) throws TopicMapException ;
/**
* Merges the contents of the given topic map in this topic map. At least one of
* mergeIn(TopicMap) or mergeIn(TopicMap,TopicMapLogger) must be overridden as
* they call each other in default implementation.
*/
public void mergeIn(TopicMap tm) throws TopicMapException {
mergeIn(tm,this);
}
/**
* Merges the contents of the given topic map in this topic map. At least one of
* mergeIn(TopicMap) or mergeIn(TopicMap,TopicMapLogger) must be overridden as
* they call each other in default implementation.
*/
public void mergeIn(TopicMap tm,TopicMapLogger tmLogger) throws TopicMapException {
mergeIn(tm);
}
/**
* NOTE: The two trackDependent methods are mostly deprecated. They are used
* when caching html pages from topics to decide when cached pages need
* to be refreshed. A page needs to be updated when any topic visible
* in the page is changed.
*/
public abstract void setTrackDependent(boolean v) throws TopicMapException ;
public abstract boolean trackingDependent() throws TopicMapException ;
/**
* Sets the topic map listener. Returns the old listener. Usually you will
* either want to chain the listeners calling the old listener after you have
* processed the event or restore the old listener later.
*/
// public abstract TopicMapListener setTopicMapListener(TopicMapListener listener) ;
/**
* Adds a topic map listener.
*/
public abstract void addTopicMapListener(TopicMapListener listener) ;
/**
* Removes a topic map listener.
*/
public abstract void removeTopicMapListener(TopicMapListener listener) ;
/**
* Gets all topic map listeners.
*/
public abstract List<TopicMapListener> getTopicMapListeners();
public void addTopicMapListeners(List<TopicMapListener> listeners){
for(TopicMapListener l : listeners){
addTopicMapListener(l);
}
}
public abstract void disableAllListeners();
public abstract void enableAllListeners();
/**
* Checks if the topic map has been changed since the last call to resetTopicMapChanged.
*/
public abstract boolean isTopicMapChanged() throws TopicMapException ;
/**
* @see #isTopicMapChanged()
*/
public abstract boolean resetTopicMapChanged() throws TopicMapException ;
/**
* Searches the topic map for the given string. Search options are given in a
* separate search options object.
*/
public abstract Collection<Topic> search(String query, TopicMapSearchOptions options) throws TopicMapException ;
public abstract TopicMapStatData getStatistics(TopicMapStatOptions options) throws TopicMapException ;
/**
* Completely clears the topic map. This deletes all associations and topics
* and all information related to them.
*/
public abstract void clearTopicMap() throws TopicMapException;
/**
* If the topic map implementation keeps indexes or caches of topics, calling
* this method will clear such data structures and cause further methods to
* retrieve data directly from the original data source.
*
* (NOTE: should probably be named clearTopicMapCache?)
*/
public abstract void clearTopicMapIndexes() throws TopicMapException;
/**
* Checks if the topic map is in a read only state. This may be because the
* topic map implementation only allows reading, editing requires special
* privileges or a method has been called to set the topic map in read only
* state. When a topic map is read only, all write operations throw
* TopicMapReadOnlyException.
*/
public boolean isReadOnly() {
return isReadOnly;
}
/**
* Sets the topic map in a read-only or read-write state depending on the
* argument. If argument is true, the topic map is set read-only. Notice,
* some topic map implementations may support only one of the states. Topic
* map may not support both states.
*/
public void setReadOnly(boolean readOnly) {
isReadOnly = readOnly;
}
/**
* <p>
* Set consistency check of associations on or off. This should normally be
* turned on but you may turn it off before some big batch operations to
* speed them up. After this operation you need to turn the consistency
* check back on and manually call checkAssociationConsistency unless you
* are sure that the operation did not cause any incensistencies with associations.
* </p><p>
* Note that
* some implementations may not allow turning consistency check off so
* getConsistencyCheck may return a different value that the last parameter
* used for setConsistencyCheck. If turning consistency check off is not
* supported, then it is also not needed to manually call the
* checkAssociationConsistency.
* </p>
* @see #checkAssociationConsistency(TopicMapLogger)
*/
public void setConsistencyCheck(boolean value) throws TopicMapException {
consistencyCheck=value;
}
public boolean getConsistencyCheck() throws TopicMapException {
return consistencyCheck;
}
public void checkAssociationConsistency() throws TopicMapException {
checkAssociationConsistency(getLogger());
}
/**
* Checks association consistency and fixes any inconsistencies. Two
* associations are said to be inconsistent if they have the same type and
* same players with same roles, that is they represent the exact same
* association. If several such associations exist all but one of them need
* to be removed.
*/
public void checkAssociationConsistency(TopicMapLogger logger) throws TopicMapException {
}
/**
* Sets the parent of this topic map.
*/
public void setParentTopicMap(TopicMap parent){
this.parentTopicMap=parent;
}
/**
* Gets the parent of this topic map. Returns null if no parent has been specified.
*/
public TopicMap getParentTopicMap(){
return parentTopicMap;
}
/**
* Gets the root topic map. This is done by iteratively getting the parent of
* this topic map, and the parent of that and so on until getParentTopicMap
* returns null.
*/
public TopicMap getRootTopicMap(){
TopicMap tm=this;
while(true){
TopicMap tm2=tm.getParentTopicMap();
if(tm2==null) return tm;
else tm=tm2;
}
}
/**
* Checks if this topic map is connected to the service providing the topic map.
* Some topic maps that are stored locally will be always connected while
* remotely hosted topic maps may sometime get disconnected.
*/
public boolean isConnected() throws TopicMapException {
return true;
}
/**
* Close the topic map. Free resources used by the topic map,
* the database connection, for example.
*/
public abstract void close();
/**
* Gets topics with the subject identifiers in the collection given as
* parameter. The parameter collection may contain subject identifiers as
* strings or locators or a mix of both. Returned collection will contain
* each topic found with. Note that parameter collection and returned
* collection may be of different size. This can happen when some subject
* identifiers don't match any topics or some topic matches several of the
* subject identifiers. Topics in the returned collection are not ordered
* in any way and it will contain each topic only once.
*/
// TODO: Equals check used in HashSet. May cause some topics to be included
// several times in the returned collection.
public Collection<Topic> getTopics(Collection<?> sis) throws TopicMapException {
Set<Topic> ret=new LinkedHashSet<>();
Iterator<?> iter=sis.iterator();
while(iter.hasNext()){
Object o=iter.next();
Topic t=null;
if(o instanceof Locator){
t=getTopic((Locator)o);
}
else if(o instanceof String){
t=getTopic((String)o);
}
if(t!=null) ret.add(t);
}
return ret;
}
/**
* Gets all topics in the topic map that are of the given type. Parameter
* is the subject identifier of the type topic. If such a topic is not
* found in the topic map, will return an empty collection.
*/
public Collection<Topic> getTopicsOfType(String si) throws TopicMapException {
Topic t=getTopic(si);
if(t!=null) return getTopicsOfType(t);
else return new ArrayList<>();
}
/**
* Like copyTopicIn but does it for a collection of topics.
*/
public Collection<Topic> copyTopicCollectionIn(Collection<Topic> topics,boolean deep) throws TopicMapException {
Set<Topic> copied=new LinkedHashSet<>();
Iterator<Topic> iter=topics.iterator();
while(iter.hasNext()){
Topic t=iter.next();
Topic nt=copyTopicIn(t,deep);
copied.add(nt);
}
return copied;
}
/**
* Gets all topics that would merge with the given topic. Note that usually
* the topic given as a parameter will be a topic in a different topic map
* because for any topic in this topic map you will get a result
* containing only the topic you gave as a parameter.
*/
public Collection<Topic> getMergingTopics(Topic t) throws TopicMapException {
Set<Topic> set=new LinkedHashSet<>();
Collection<Locator> ls=t.getSubjectIdentifiers();
if(ls!=null) {
Iterator<Locator> iter=ls.iterator();
while(iter.hasNext()){
Locator l=iter.next();
Topic to=getTopic(l);
if(to!=null) set.add(to);
}
}
Topic to;
if(t.getSubjectLocator()!=null) {
to=getTopicBySubjectLocator(t.getSubjectLocator());
if(to!=null) set.add(to);
}
if(t.getBaseName()!=null){
to=getTopicWithBaseName(t.getBaseName());
if(to!=null) set.add(to);
}
return set;
}
// ---------------------------------------------------- TOPIC MAP LOGGER ---
public void setLogger(TopicMapLogger logger) {
this.logger = logger;
}
public TopicMapLogger getLogger() {
return this.logger;
}
public void hlog(String message) {
if(logger != null) logger.hlog(message);
else {
System.out.println(message);
}
}
public void log(String message) {
if(logger != null) logger.log(message);
else {
System.out.println(message);
}
}
public void log(String message, Exception e) {
if(logger != null) logger.log(message, e);
else {
System.out.println(message);
e.printStackTrace();
}
}
public void log(Exception e) {
if(logger != null) logger.log(e);
else {
e.printStackTrace();
}
}
public void setProgress(int n) {
if(logger != null) logger.setProgress(n);
}
public void setProgressMax(int maxn) {
if(logger != null) logger.setProgressMax(maxn);
}
public void setLogTitle(String title) {
if(logger != null) logger.setLogTitle(title);
else {
System.out.println(title);
}
}
public boolean forceStop() {
if(logger != null) return logger.forceStop();
else {
return false;
}
}
// ----------------------------------------------------- IMPORT / EXPORT ---
public void importTopicMap(String file) throws IOException,TopicMapException {
importTopicMap(file, this);
}
public void importTopicMap(String file, TopicMapLogger logger) throws IOException,TopicMapException {
importTopicMap(file, this, false);
}
public void importTopicMap(String file, TopicMapLogger logger, boolean checkConsistency) throws IOException,TopicMapException {
if(file != null) {
if(file.toLowerCase().endsWith("ltm")) importLTM(file, logger);
else if(file.toLowerCase().endsWith("jtm")) importJTM(file, logger);
else importXTM(file, logger);
}
}
public void exportTopicMap(String file) throws IOException, TopicMapException {
exportTopicMap(file, this);
}
public void exportTopicMap(String file, TopicMapLogger logger) throws IOException, TopicMapException {
if(file != null) {
String lfile = file.toLowerCase();
if(lfile.endsWith("ltm")) exportLTM(file, logger);
else if(lfile.endsWith("jtm")) exportJTM(file, logger);
else if(lfile.endsWith("xtm10")) exportXTM10(file, logger);
else if(lfile.endsWith("xtm1")) exportXTM10(file, logger);
else if(lfile.endsWith("xt1")) exportXTM10(file, logger);
else exportXTM(file, logger);
}
}
// -------------------------------------------------------------------------
// ----------------------------------------------------------------- LTM ---
// -------------------------------------------------------------------------
public void exportLTM(String file) throws IOException, TopicMapException {
exportLTM(file, this);
}
public void exportLTM(String file, TopicMapLogger logger) throws IOException, TopicMapException {
FileOutputStream fos=new FileOutputStream(file);
exportLTM(fos, logger);
fos.close();
}
public void exportLTM(OutputStream out) throws IOException, TopicMapException {
exportLTM(out, this);
}
public void exportLTM(OutputStream out, TopicMapLogger logger) throws IOException, TopicMapException {
if(logger == null) logger = this;
PrintWriter writer=new PrintWriter(new OutputStreamWriter(out,"UTF-8"));
writer.println("@\"utf-8\"");
int totalCount = this.getNumTopics() + this.getNumAssociations();
logger.setProgressMax(totalCount);
int count = 0;
Iterator<Topic> iter=getTopics();
while(iter.hasNext() && !logger.forceStop()) {
Topic t=iter.next();
if(t == null || t.isRemoved()) continue;
logger.setProgress(count++);
writer.print("[ "+makeLTMTopicId(t));
if(t.getTypes().size()>0){
Iterator<Topic> iter2=t.getTypes().iterator();
if(iter2.hasNext()) writer.print(" :");
while(iter2.hasNext()){
Topic t2=iter2.next();
writer.print(" "+makeLTMTopicId(t2));
}
}
if(t.getBaseName()!=null || t.getVariantScopes().size()>0){
writer.print(" = ");
if(t.getBaseName()==null)
writer.print("");
else
writer.print("\"" + makeLTMString(t.getBaseName()) + "\"");
Iterator<Set<Topic>> iter2=t.getVariantScopes().iterator();
while(iter2.hasNext()) {
Set<Topic> c=iter2.next();
String name=t.getVariant(c);
if(c.size()>0) {
writer.print(" (");
Iterator<Topic> iter3=c.iterator();
writer.print(" \""+makeLTMString(name)+"\"");
if(iter3.hasNext()) {
writer.print(" /");
}
while(iter3.hasNext()) {
Topic st=iter3.next();
writer.print(" "+makeLTMTopicId(st));
}
writer.print(" )");
}
}
}
if(t.getSubjectIdentifiers().size()>0 || t.getSubjectLocator()!=null) {
if(t.getSubjectLocator()!=null) {
writer.print(" %\"" + t.getSubjectLocator().toExternalForm() + "\"");
}
Iterator<Locator> iter2=t.getSubjectIdentifiers().iterator();
while(iter2.hasNext()) {
Locator l=iter2.next();
if(l != null) {
writer.print(" @\"" + l.toExternalForm() + "\"");
}
}
}
writer.println(" ]");
if(t.getDataTypes().size()>0) {
Collection<Topic> types=t.getDataTypes();
Iterator<Topic> iter2=types.iterator();
while(iter2.hasNext()){
Topic type=iter2.next();
Hashtable<Topic,String> ht=t.getData(type);
Iterator<Map.Entry<Topic,String>> iter3=ht.entrySet().iterator();
while(iter3.hasNext()){
Map.Entry<Topic,String> e=iter3.next();
Topic version=e.getKey();
String data=e.getValue();
writer.print("{ "+makeLTMTopicId(t) );
writer.print(", "+makeLTMTopicId(type));
writer.print(", [[" + makeLTMString(data) +"]]");
writer.println(" } / "+makeLTMTopicId(version));
}
}
}
}
if(!logger.forceStop()) {
Iterator<Association> aiter=getAssociations();
while(aiter.hasNext() && !logger.forceStop()) {
logger.setProgress(count++);
Association a=aiter.next();
if(a.getType()!=null) {
writer.print( makeLTMTopicId(a.getType()) + " " );
}
writer.print("( ");
Iterator<Topic> iter2=a.getRoles().iterator();
while(iter2.hasNext()) {
Topic role=iter2.next();
writer.print(makeLTMTopicId( a.getPlayer(role) ) + " : " + makeLTMTopicId( role ));
if(iter2.hasNext()) writer.print(", ");
}
writer.println(" )");
}
}
writer.flush();
}
public String makeLTMString(String str) {
if(str != null && str.length() > 0) {
str = str.replace("\\", "\\u005C" );
str = str.replace("\"", "\\u0022" );
str = str.replace("[", "\\u005B" );
str = str.replace("]", "\\u005D" );
str = str.replace("'", "\\u0027" );
str = str.replace("{", "\\u007B" );
str = str.replace("}", "\\u007D" );
// ***** ESCAPE ALL CONTROL CODES AND NON-ASCII CHARACTERS
StringBuilder strBuffer = new StringBuilder("");
int c = -1;
for(int i=0; i<str.length(); i++) {
c = str.charAt(i);
if(c<31 || c>127) {
String cStr = Integer.toHexString(c);
while(cStr.length()<4) {
cStr = "0"+cStr;
}
strBuffer.append("\\u").append(cStr);
}
else {
strBuffer.append((char) c);
}
}
str = strBuffer.toString();
}
return str;
}
public String makeLTMTopicId(Topic t) {
if(t == null) return "null";
try {
return t.getID();
// int h = t.getID().hashCode();
// int sign = h / Math.abs(h);
// h = Math.abs( 2 * h );
// if(sign == -1) h = h + 1;
// return "t"+h;
}
catch(Exception e) {
return "null";
}
}
public void importLTM(InputStream in) throws IOException, TopicMapException {
if(isReadOnly()) throw new TopicMapReadOnlyException();
importLTM(in, this);
}
public void importLTM(File inFile) throws IOException, TopicMapException {
if(isReadOnly()) throw new TopicMapReadOnlyException();
importLTM(inFile, this);
}
public void importLTM(String file) throws IOException, TopicMapException {
if(isReadOnly()) throw new TopicMapReadOnlyException();
importLTM(file, this);
}
public void importLTM(InputStream in, TopicMapLogger logger) throws IOException, TopicMapException {
if(isReadOnly()) throw new TopicMapReadOnlyException();
LTMParser parser = new LTMParser(this, logger);
parser.parse(in);
parser.init();
}
public void importLTM(File inFile, TopicMapLogger logger) throws IOException, TopicMapException {
if(isReadOnly()) throw new TopicMapReadOnlyException();
if(logger == null) logger = this;
logger.log("Merging LTM file");
LTMParser parser = new LTMParser(this, logger);
parser.parse(inFile);
parser.init();
}
public void importLTM(String fileName, TopicMapLogger logger) throws IOException, TopicMapException {
if(isReadOnly()) throw new TopicMapReadOnlyException();
File file=new File(fileName);
importLTM(file, logger);
}
// -------------------------------------------------------------------------
// ----------------------------------------------------------------- JTM ---
// -------------------------------------------------------------------------
public void exportJTM(String file) throws IOException, TopicMapException {
exportJTM(file, this);
}
public void exportJTM(String file, TopicMapLogger logger) throws IOException, TopicMapException {
FileOutputStream fos=new FileOutputStream(file);
exportJTM(fos, logger);
fos.close();
}
public void exportJTM(OutputStream out) throws IOException, TopicMapException {
exportJTM(out, this);
}
public void exportJTM(OutputStream out, TopicMapLogger logger) throws IOException, TopicMapException {
if(logger == null) logger = this;
PrintWriter writer=new PrintWriter(new OutputStreamWriter(out,"UTF-8"));
List<T2<Topic,Topic>> typeAssociations = new ArrayList<T2<Topic,Topic>>();
int numberOfTopics = this.getNumTopics();
int numberOfAssociations = this.getNumAssociations();
int totalCount = numberOfTopics + numberOfAssociations;
logger.setProgressMax(totalCount);
int count = 0;
writer.println("{\"version\":\"1.0\",");
writer.print(" \"item_type\":\"topicmap\"");
if(totalCount > 0) writer.println(",");
if(numberOfTopics>0) {
writer.println(" \"topics\":[");
}
Iterator<Topic> topics=getTopics();
while(topics.hasNext() && !logger.forceStop()) {
Topic t=topics.next();
if(t == null || t.isRemoved()) continue;
logger.setProgress(count++);
writer.println(" {");
if(t.getSubjectIdentifiers().size()>0) {
writer.println(" \"subject_identifiers\":[");
Iterator<Locator> iter2=t.getSubjectIdentifiers().iterator();
while(iter2.hasNext()) {
Locator l=iter2.next();
if(l != null) {
writer.print(" \"" + l.toExternalForm() + "\"");
if(iter2.hasNext()) {
writer.println(", ");
}
else {
writer.println();
}
}
}
writer.print(" ]");
}
if(t.getSubjectLocator()!=null) {
writer.println(",");
if(t.getSubjectLocator()!=null) {
writer.print(" \"subject_locators\": [ \"" + t.getSubjectLocator().toExternalForm() + "\" ]");
}
}
if(t.getBaseName()!=null || t.getVariantScopes().size()>0) {
writer.println(",");
writer.println(" \"names\":[");
writer.println(" {");
if(t.getBaseName()==null)
writer.print(" \"value\":\"\"");
else
writer.print(" \"value\":\"" + makeJTMString(t.getBaseName()) + "\"");
boolean hasVariants = false;
Iterator<Set<Topic>> variants=t.getVariantScopes().iterator();
if(variants.hasNext()) {
writer.println(",\n \"variants\":[");
hasVariants = true;
}
else writer.println();
while(variants.hasNext()) {
Set<Topic> c=variants.next();
String name=t.getVariant(c);
if(c.size()>0) {
writer.println(" {");
writer.println(" \"value\":\""+makeJTMString(name)+"\",");
Iterator<Topic> variantScopes=c.iterator();
if(variantScopes.hasNext()) {
writer.println(" \"scope\":[");
}
while(variantScopes.hasNext()) {
Topic st=variantScopes.next();
writer.print(" \"si:"+st.getOneSubjectIdentifier().toExternalForm()+"\"");
if(variantScopes.hasNext()) {
writer.println(", ");
}
else {
writer.println("");
writer.println(" ]");
}
}
writer.print(" }");
if(variants.hasNext()) {
writer.println(",");
}
else {
writer.println();
}
}
}
if(hasVariants) {
writer.println(" ]");
}
writer.println(" }");
writer.print(" ]");
}
if(t.getDataTypes().size()>0) {
writer.println(",");
writer.println(" \"occurrences\":[");
Collection<Topic> types=t.getDataTypes();
Iterator<Topic> iter2=types.iterator();
boolean colonRequired = false;
while(iter2.hasNext()){
Topic type=iter2.next();
Hashtable<Topic,String> ht=t.getData(type);
Iterator<Map.Entry<Topic,String>> iter3=ht.entrySet().iterator();
while(iter3.hasNext()) {
if(colonRequired) writer.println(",");
writer.println(" {");
Map.Entry<Topic,String> e=iter3.next();
Topic version=e.getKey();
String data=e.getValue();
writer.println(" \"value\":\""+makeJTMString(data)+"\",");
writer.println(" \"type\":\"si:"+type.getOneSubjectIdentifier().toExternalForm()+"\",");
writer.println(" \"scope\": [ \"si:"+version.getOneSubjectIdentifier().toExternalForm()+"\" ]");
writer.print(" }");
colonRequired = true;
}
}
writer.println();
writer.println(" ]");
}
else {
writer.println();
}
if(t.getTypes().size()>0){
Iterator<Topic> iter2=t.getTypes().iterator();
while(iter2.hasNext()) {
Topic t2=iter2.next();
if(t2 != null && !t2.isRemoved()) {
typeAssociations.add(new T2<>(t2, t));
}
}
}
writer.print(" }");
if(topics.hasNext()) {
writer.println(",");
}
else {
writer.println();
}
}
if(numberOfTopics>0) {
writer.print(" ]");
}
if(!logger.forceStop()) {
if(numberOfAssociations>0 || typeAssociations.size()>0) {
writer.println(",");
writer.println(" \"associations\":[");
}
else {
writer.println();
}
Iterator<Association> associations=getAssociations();
T2<Topic,Topic> typeAssociation = null;
for(Iterator<T2<Topic,Topic>> types = typeAssociations.iterator(); types.hasNext() && !logger.forceStop(); ) {
typeAssociation = types.next();
Topic type = typeAssociation.e1;
Topic instance = typeAssociation.e2;
writer.println(" {");
writer.println(" \"type\":\"si:http://psi.topicmaps.org/iso13250/model/type-instance\",");
writer.println(" \"roles\":[");
writer.println(" {");
writer.println(" \"player\":\"si:"+type.getOneSubjectIdentifier().toExternalForm()+"\",");
writer.println(" \"type\":\"si:http://psi.topicmaps.org/iso13250/model/type\"");
writer.println(" },");
writer.println(" {");
writer.println(" \"player\":\"si:"+instance.getOneSubjectIdentifier().toExternalForm()+"\",");
writer.println(" \"type\":\"si:http://psi.topicmaps.org/iso13250/model/instance\"");
writer.println(" }");
writer.println(" ]");
writer.print(" }");
if(types.hasNext() || associations.hasNext()) {
writer.println(",");
}
else {
writer.println();
}
}
while(associations.hasNext() && !logger.forceStop()) {
logger.setProgress(count++);
writer.println(" {");
Association a=(Association)associations.next();
if(a.getType()!=null) {
writer.println(" \"type\":\"si:"+a.getType().getOneSubjectIdentifier().toExternalForm()+"\",");
}
Iterator<Topic> roles=a.getRoles().iterator();
if(roles.hasNext()) {
writer.println(" \"roles\":[");
}
while(roles.hasNext()) {
writer.println(" {");
Topic role=(Topic)roles.next();
writer.println(" \"player\":\"si:"+a.getPlayer(role).getOneSubjectIdentifier().toExternalForm()+"\",");
writer.println(" \"type\":\"si:"+role.getOneSubjectIdentifier().toExternalForm()+"\"");
writer.print(" }");
if(roles.hasNext()) {
writer.println(",");
}
else {
writer.println();
writer.println(" ]");
}
}
writer.print(" }");
if(associations.hasNext()) {
writer.println(",");
}
else {
writer.println();
}
}
if(numberOfAssociations>0 || typeAssociations.size()>0) {
writer.println(" ]");
}
}
writer.println("}");
writer.flush();
}
public String makeJTMString(String str) {
if(str != null && str.length() > 0) {
//str = str.replace("\n", "\\u000a" );
//str = str.replace("\r", "\\u000c" );
str = str.replace("\\", "\\u005c" );
str = str.replace("\"", "\\u0022" );
str = str.replace("[", "\\u005b" );
str = str.replace("]", "\\u005d" );
str = str.replace("'", "\\u0027" );
str = str.replace("{", "\\u007b" );
str = str.replace("}", "\\u007d" );
// ***** ESCAPE ALL CONTROL CODES AND NON-ASCII CHARACTERS
StringBuilder strBuffer = new StringBuilder("");
int c = -1;
for(int i=0; i<str.length(); i++) {
c = str.charAt(i);
if(c<32 || c>126) {
String cStr = Integer.toHexString(c);
while(cStr.length()<4) {
cStr = "0"+cStr;
}
strBuffer.append("\\u").append(cStr);
}
else {
strBuffer.append((char) c);
}
}
str = strBuffer.toString();
}
return str;
}
public String makeJTMTopicId(Topic t) {
if(t == null) return "null";
try {
return t.getID();
}
catch(Exception e) {
return "null";
}
}
public void importJTM(InputStream in) throws IOException, TopicMapException {
if(isReadOnly()) throw new TopicMapReadOnlyException();
importJTM(in, this);
}
public void importJTM(File inFile) throws IOException, TopicMapException {
if(isReadOnly()) throw new TopicMapReadOnlyException();
importJTM(inFile, this);
}
public void importJTM(String file) throws IOException, TopicMapException {
if(isReadOnly()) throw new TopicMapReadOnlyException();
importJTM(file, this);
}
public void importJTM(InputStream in, TopicMapLogger logger) throws IOException, TopicMapException {
if(isReadOnly()) throw new TopicMapReadOnlyException();
JTMParser parser = new JTMParser(this, logger);
parser.parse(in);
//logger.log("JTM support not available yet!");
}
public void importJTM(File inFile, TopicMapLogger logger) throws IOException, TopicMapException {
if(isReadOnly()) throw new TopicMapReadOnlyException();
if(logger == null) logger = this;
//logger.log("JTM support not available yet!");
JTMParser parser = new JTMParser(this, logger);
parser.parse(inFile);
}
public void importJTM(String fileName, TopicMapLogger logger) throws IOException, TopicMapException {
if(isReadOnly()) throw new TopicMapReadOnlyException();
File file=new File(fileName);
importJTM(file, logger);
}
// -------------------------------------------------------------------------
// ----------------------------------------------------------------- XTM ---
// -------------------------------------------------------------------------
public void exportXTM(OutputStream out) throws IOException, TopicMapException {
exportXTM20(out, this);
}
public void exportXTM(OutputStream out, TopicMapLogger logger) throws IOException, TopicMapException {
exportXTM20(out,logger);
}
public void exportXTM10(OutputStream out) throws IOException, TopicMapException {
exportXTM10(out, this);
}
public void exportXTM10(OutputStream out, TopicMapLogger logger) throws IOException, TopicMapException {
if(logger == null) logger = this;
int totalCount = this.getNumTopics() + this.getNumAssociations();
logger.setProgressMax(totalCount);
int count = 0;
PrintWriter writer=new PrintWriter(new OutputStreamWriter(out,"UTF-8"));
writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
writer.println("<topicMap xmlns=\"http://www.topicmaps.org/xtm/1.0/\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">");
Iterator<Topic> iter=getTopics();
while(iter.hasNext() && !logger.forceStop()) {
Topic t=iter.next();
if(t.isRemoved()) continue;
logger.setProgress(count++);
writer.println("\t<topic id=\""+t.getID()+"\">");
if(t.getTypes().size()>0){
Iterator<Topic> iter2=t.getTypes().iterator();
while(iter2.hasNext()){
Topic t2=iter2.next();
writer.println("\t\t<instanceOf>");
writer.println("\t\t\t<topicRef xlink:href=\"#"+t2.getID()+"\"/>");
writer.println("\t\t</instanceOf>");
}
}
if(t.getSubjectIdentifiers().size()>0 || t.getSubjectLocator()!=null){
writer.println("\t\t<subjectIdentity>");
Iterator<Locator> iter2=t.getSubjectIdentifiers().iterator();
while(iter2.hasNext()){
Locator l=iter2.next();
writer.println("\t\t\t<subjectIndicatorRef xlink:href=\""+escapeXML(l.toExternalForm())+"\"/>");
}
if(t.getSubjectLocator()!=null) writer.println("\t\t\t<resourceRef xlink:href=\""+escapeXML(t.getSubjectLocator().toExternalForm())+"\"/>");
writer.println("\t\t</subjectIdentity>");
}
if(t.getBaseName()!=null || t.getVariantScopes().size()>0){
writer.println("\t\t<baseName>");
if(t.getBaseName()==null)
writer.println("\t\t\t<baseNameString></baseNameString>");
else
writer.println("\t\t\t<baseNameString>"+escapeXML(t.getBaseName())+"</baseNameString>");
Iterator<Set<Topic>> iter2=t.getVariantScopes().iterator();
while(iter2.hasNext()){
Set<Topic> c=iter2.next();
String name=t.getVariant(c);
if(c.size()>0){
writer.println("\t\t\t<variant>");
writer.println("\t\t\t\t<parameters>");
Iterator<Topic> iter3=c.iterator();
while(iter3.hasNext()){
Topic st=iter3.next();
writer.println("\t\t\t\t\t<topicRef xlink:href=\"#"+st.getID()+"\"/>");
}
writer.println("\t\t\t\t</parameters>");
writer.println("\t\t\t\t<variantName>");
writer.println("\t\t\t\t\t<resourceData>"+escapeXML(name)+"</resourceData>");
writer.println("\t\t\t\t</variantName>");
writer.println("\t\t\t</variant>");
}
}
writer.println("\t\t</baseName>");
}
if(t.getDataTypes().size()>0){
Collection<Topic> types=t.getDataTypes();
Iterator<Topic> iter2=types.iterator();
while(iter2.hasNext()){
Topic type=iter2.next();
Hashtable<Topic,String> ht=t.getData(type);
Iterator<Map.Entry<Topic,String>> iter3=ht.entrySet().iterator();
while(iter3.hasNext()){
Map.Entry<Topic,String> e=iter3.next();
Topic version=e.getKey();
String data=e.getValue();
writer.println("\t\t<occurrence>");
writer.println("\t\t\t<instanceOf>");
writer.println("\t\t\t\t<topicRef xlink:href=\"#"+type.getID()+"\"/>");
writer.println("\t\t\t</instanceOf>");
writer.println("\t\t\t<scope>");
writer.println("\t\t\t\t<topicRef xlink:href=\"#"+version.getID()+"\"/>");
writer.println("\t\t\t</scope>");
writer.println("\t\t\t<resourceData>"+escapeXML(data)+"</resourceData>");
writer.println("\t\t</occurrence>");
}
}
}
writer.println("\t</topic>");
}
if(!logger.forceStop()) {
Iterator<Association> aiter=getAssociations();
while(aiter.hasNext() && !logger.forceStop()) {
logger.setProgress(count++);
Association a=aiter.next();
writer.println("\t<association>");
if(a.getType()!=null){
writer.println("\t\t<instanceOf>");
writer.println("\t\t\t<topicRef xlink:href=\"#"+a.getType().getID()+"\"/>");
writer.println("\t\t</instanceOf>");
}
Iterator<Topic> iter2=a.getRoles().iterator();
while(iter2.hasNext()){
Topic role=(Topic)iter2.next();
writer.println("\t\t<member>");
writer.println("\t\t\t<roleSpec>");
writer.println("\t\t\t\t<topicRef xlink:href=\"#"+role.getID()+"\"/>");
writer.println("\t\t\t</roleSpec>");
writer.println("\t\t\t<topicRef xlink:href=\"#"+(a.getPlayer(role).getID())+"\"/>");
writer.println("\t\t</member>");
}
writer.println("\t</association>");
}
}
writer.println("</topicMap>");
writer.flush();
}
public void exportXTM20(OutputStream out, TopicMapLogger logger) throws IOException, TopicMapException {
if(logger == null) logger = this;
int totalCount = this.getNumTopics() + this.getNumAssociations();
logger.setProgressMax(totalCount);
int count = 0;
PrintWriter writer=new PrintWriter(new OutputStreamWriter(out,"UTF-8"));
writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
writer.println("<topicMap xmlns=\"http://www.topicmaps.org/xtm/\" version=\"2.0\">");
Iterator<Topic> iter=getTopics();
while(iter.hasNext() && !logger.forceStop()) {
Topic t=iter.next();
if(t.isRemoved()) continue;
logger.setProgress(count++);
writer.println("\t<topic id=\""+t.getID()+"\">");
if(t.getSubjectLocator()!=null) writer.println("\t\t<subjectLocator href=\""+escapeXML(t.getSubjectLocator().toExternalForm())+"\"/>");
if(t.getSubjectIdentifiers().size()>0 || t.getSubjectLocator()!=null){
Iterator<Locator> iter2=t.getSubjectIdentifiers().iterator();
while(iter2.hasNext()){
Locator l=iter2.next();
writer.println("\t\t<subjectIdentifier href=\""+escapeXML(l.toExternalForm())+"\"/>");
}
}
if(t.getTypes().size()>0){
Iterator<Topic> iter2=t.getTypes().iterator();
writer.println("\t\t<instanceOf>");
while(iter2.hasNext()){
Topic t2=iter2.next();
writer.println("\t\t\t<topicRef href=\"#"+t2.getID()+"\"/>");
}
writer.println("\t\t</instanceOf>");
}
if(t.getBaseName()!=null || t.getVariantScopes().size()>0){
writer.println("\t\t<name>");
if(t.getBaseName()==null)
writer.println("\t\t\t<value></value>");
else
writer.println("\t\t\t<value>"+escapeXML(t.getBaseName())+"</value>");
Iterator<Set<Topic>> iter2=t.getVariantScopes().iterator();
while(iter2.hasNext()){
Set<Topic> c=iter2.next();
String name=t.getVariant(c);
if(c.size()>0){
writer.println("\t\t\t<variant>");
writer.println("\t\t\t\t<scope>");
Iterator<Topic> iter3=c.iterator();
while(iter3.hasNext()){
Topic st=iter3.next();
writer.println("\t\t\t\t\t<topicRef href=\"#"+st.getID()+"\"/>");
}
writer.println("\t\t\t\t</scope>");
writer.println("\t\t\t\t<resourceData>"+escapeXML(name)+"</resourceData>");
writer.println("\t\t\t</variant>");
}
}
writer.println("\t\t</name>");
}
if(t.getDataTypes().size()>0){
Collection<Topic> types=t.getDataTypes();
Iterator<Topic> iter2=types.iterator();
while(iter2.hasNext()){
Topic type=iter2.next();
Hashtable<Topic,String> ht=t.getData(type);
Iterator<Map.Entry<Topic,String>> iter3=ht.entrySet().iterator();
while(iter3.hasNext()){
Map.Entry<Topic,String> e=iter3.next();
Topic version=e.getKey();
String data=e.getValue();
writer.println("\t\t<occurrence>");
writer.println("\t\t\t<type>");
writer.println("\t\t\t\t<topicRef href=\"#"+type.getID()+"\"/>");
writer.println("\t\t\t</type>");
writer.println("\t\t\t<scope>");
writer.println("\t\t\t\t<topicRef href=\"#"+version.getID()+"\"/>");
writer.println("\t\t\t</scope>");
writer.println("\t\t\t<resourceData>"+escapeXML(data)+"</resourceData>");
writer.println("\t\t</occurrence>");
}
}
}
writer.println("\t</topic>");
}
if(!logger.forceStop()) {
Iterator<Association> aiter=getAssociations();
while(aiter.hasNext() && !logger.forceStop()) {
logger.setProgress(count++);
Association a=aiter.next();
writer.println("\t<association>");
if(a.getType()!=null){
writer.println("\t\t<type>");
writer.println("\t\t\t<topicRef href=\"#"+a.getType().getID()+"\"/>");
writer.println("\t\t</type>");
}
Iterator<Topic> iter2=a.getRoles().iterator();
while(iter2.hasNext()){
Topic role=iter2.next();
writer.println("\t\t<role>");
writer.println("\t\t\t<type>");
writer.println("\t\t\t\t<topicRef href=\"#"+role.getID()+"\"/>");
writer.println("\t\t\t</type>");
writer.println("\t\t\t<topicRef href=\"#"+(a.getPlayer(role).getID())+"\"/>");
writer.println("\t\t</role>");
}
writer.println("\t</association>");
}
}
writer.println("</topicMap>");
writer.flush();
}
public void importXTM(InputStream in) throws IOException, TopicMapException {
if(isReadOnly()) throw new TopicMapReadOnlyException();
importXTM(in, this);
}
public void importXTM(InputStream in, TopicMapLogger logger) throws IOException, TopicMapException {
if(isReadOnly()) throw new TopicMapReadOnlyException();
importXTM(in, logger, consistencyCheckWhenXTMImport);
}
public void importXTM(InputStream in, TopicMapLogger logger, boolean checkConsistency) throws IOException, TopicMapException {
if(isReadOnly()) throw new TopicMapReadOnlyException();
if(logger == null) logger = this;
boolean oldCheck = getConsistencyCheck();
if(checkConsistency != oldCheck) {
logger.log("Changing consistency check to '"+checkConsistency +"'.");
setConsistencyCheck(checkConsistency);
}
try {
javax.xml.parsers.SAXParserFactory factory=javax.xml.parsers.SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(false);
javax.xml.parsers.SAXParser parser=factory.newSAXParser();
XMLReader reader=parser.getXMLReader();
XTMParser xtm1parser = new XTMParser(logger);
// adaptive parser either uses xtm 1.0 or 2.0 parser depending on the version attribute
XTMAdaptiveParser parserHandler=new XTMAdaptiveParser(this,logger,xtm1parser);
reader.setContentHandler(parserHandler);
reader.setErrorHandler(parserHandler);
reader.parse(new InputSource(in));
// Debugging
/* Iterator iter=getTopics();
while(iter.hasNext()){
Topic t=(Topic)iter.next();
if(t.getSubjectIdentifiers().size()==0) System.out.println("Parsed topic doesn't have subject identifiers");
// else System.out.println(t.getSubjectIdentifiers().iterator().next());
}*/
}
catch(org.xml.sax.SAXParseException se) {
logger.log("Position "+se.getLineNumber()+":"+se.getColumnNumber(), se);
}
catch(org.xml.sax.SAXException saxe) {
if(! "user_interrupt".equals(saxe.getMessage())) {
logger.log(saxe);
}
}
catch(Exception e){
logger.log(e);
}
finally {
if(checkConsistency != oldCheck) {
logger.log("Restoring consistency check to '"+oldCheck+"'.");
setConsistencyCheck(oldCheck);
}
}
}
public void importXTM(String file, TopicMapLogger logger) throws IOException, TopicMapException {
if(isReadOnly()) throw new TopicMapReadOnlyException();
FileInputStream fis=new FileInputStream(file);
importXTM(fis, logger);
fis.close();
}
public void importXTM(String file) throws IOException, TopicMapException {
if(isReadOnly()) throw new TopicMapReadOnlyException();
importXTM(file, this);
}
public void exportXTM(String file) throws IOException, TopicMapException {
exportXTM(file, this);
}
public void exportXTM20(String file) throws IOException, TopicMapException {
exportXTM(file, this);
}
public void exportXTM(String file, TopicMapLogger logger) throws IOException, TopicMapException {
FileOutputStream fos=new FileOutputStream(file);
exportXTM(fos, logger);
fos.close();
}
public void exportXTM10(String file, TopicMapLogger logger) throws IOException, TopicMapException {
FileOutputStream fos=new FileOutputStream(file);
exportXTM10(fos, logger);
fos.close();
}
/**
* Makes a Locator that can be used as subject identifier or locator. The locator
* is guaranteed to be unique and will not cause merges with other topics
* in this topic map.
*/
public Locator makeSubjectIndicatorAsLocator() throws TopicMapException {
String s=makeSubjectIndicator();
return createLocator(s);
}
private int SICounter = 0;
/**
* Makes a URI that can be used as subject identifier or locator. The URI
* is guaranteed to be unique and will not cause merges with other topics
* in this topic map.
*/
public String makeSubjectIndicator() {
String si="http://wandora.org/si/temp/";
si += System.currentTimeMillis();
si += "-" + SICounter;
if( SICounter++ > 10000000 ) SICounter = 0;
return si;
}
public String escapeXML(String data){
if(data.indexOf('&')>=0) data=data.replaceAll("&","&");
if(data.indexOf('<')>=0) data=data.replaceAll("<","<");
if(data.indexOf('"')>=0) data=data.replaceAll("\"",""");
StringBuilder buf=new StringBuilder(data);
for(int i=0;i<buf.length();i++){
char c=buf.charAt(i);
if(c<32){
if(c!='\t' && c!='\r' && c!='\n') buf.setCharAt(i,' ');
}
}
return buf.toString();
}
private class XTMParser implements org.xml.sax.ContentHandler, org.xml.sax.ErrorHandler {
public static final String XMLNS_XTM = "http://www.topicmaps.org/xtm/1.0/";
public static final String TAG_SCOPE = "scope";
public static final String TAG_INSTANCEOF = "instanceOf";
public static final String TAG_SUBJECTIDENTITY = "subjectIdentity";
public static final String TAG_BASENAMESTRING = "baseNameString";
public static final String TAG_BASENAME = "baseName";
public static final String TAG_TOPICREF = "topicRef";
public static final String TAG_SUBJECTINDICATORREF = "subjectIndicatorRef";
public static final String TAG_VARIANTNAME = "variantName";
public static final String TAG_PARAMETERS = "parameters";
public static final String TAG_ASSOCIATION = "association";
public static final String TAG_MEMBER = "member";
public static final String TAG_VARIANT = "variant";
public static final String TAG_TOPIC_MAP = "topicMap";
public static final String TAG_TOPIC = "topic";
public static final String TAG_ROLESPEC = "roleSpec";
public static final String TAG_OCCURRENCE = "occurrence";
public static final String TAG_RESOURCEREF = "resourceRef";
public static final String TAG_RESOURCEDATA = "resourceData";
public static final String TAG_MERGEMAP = "mergeMap";
public static final String XMLNS_XLINK = "http://www.w3.org/1999/xlink";
private static final int STATE_START = 0;
private static final int STATE_TOPICMAP = 1;
private static final int STATE_TOPIC = 2;
private static final int STATE_INSTANCEOF = 3;
private static final int STATE_SUBJECTIDENTITY = 4;
private static final int STATE_BASENAME = 5;
private static final int STATE_SCOPE = 6;
private static final int STATE_VARIANT = 7;
private static final int STATE_PARAMETERS = 8;
private static final int STATE_VARIANTNAME = 9;
private static final int STATE_ASSOCIATION = 10;
private static final int STATE_MEMBER = 11;
private static final int STATE_ROLESPEC = 12;
private static final int STATE_BASENAMESTRING = 13;
private static final int STATE_VARIANTRESOURCEDATA = 14;
private static final int STATE_OCCURRENCE = 15;
private static final int STATE_OCCURRENCEINSTANCEOF = 16;
private static final int STATE_RESOURCEDATA = 17;
private Collection<Topic> parsedType;
private Topic parsedRole;
private Collection<Topic> parsedTopicCollection;
private Topic parsedTopicRef;
private Locator parsedSubjectLocator;
private Collection<Locator> parsedSubjectIdentifiers;
private String parsedBaseName;
private Collection<Topic> parsedScope;
private Collection<Topic> parsedParameters;
private Collection<VariantName> parsedVariants;
private Collection<VariantName> parsedBaseNameVariants;
private Collection<Occurrence> parsedOccurrences;
private Collection<Topic> parsedPlayers;
private Collection<Member> parsedMembers;
private String parsedVariantName;
private String topicID;
private Topic parsedOccurrenceType;
private String parsedOccurrenceData;
private String parsedOccurrenceRef;
private long parsedEdittime;
private String associationID;
/*
* Occurrences are used to carry wandora specific data. These are marked with specific occurrence
* types. We must parse the whole topic map before we can be sure that the occurrence type topics
* have their subject identifiers set, so we collect all parsed occurrence data in allOccurrences
* and add them when the topicmap element ends (that is at </topicmap>).
*/
private Hashtable<Topic,Collection<Occurrence>> allOccurrences;
private IntegerStack stateStack;
private int state;
private Map<String,Topic> idmapping;
private Hashtable mergemap;
private TopicMapLogger logger;
private int count;
private int topicCount;
private int associationCount;
private int occurrenceCount;
public XTMParser(TopicMapLogger logger) {
if(logger != null) this.logger = logger;
else logger = TopicMap.this;
count = 0;
topicCount = 0;
associationCount = 0;
occurrenceCount = 0;
idmapping=new LinkedHashMap<>();
mergemap=new Hashtable<>();
state=STATE_START;
stateStack=new IntegerStack();
}
@Override
public void characters(char[] buf,int start,int length){
switch(state){
case STATE_BASENAMESTRING:
parsedBaseName+=new String(buf,start,length);
break;
case STATE_VARIANTRESOURCEDATA:
parsedVariantName+=new String(buf,start,length);
break;
case STATE_RESOURCEDATA:
parsedOccurrenceData+=new String(buf,start,length);
break;
}
}
@Override
public void startElement(String uri, String localName, String qName, org.xml.sax.Attributes attributes) throws org.xml.sax.SAXException {
if(logger.forceStop()) {
throw new org.xml.sax.SAXException("user_interrupt");
}
try {
switch(state){
case STATE_START:
if(qName.equals(TAG_TOPIC_MAP)){
stateStack.push(state);
state=STATE_TOPICMAP;
allOccurrences=new Hashtable<>();
}
else logger.log("Parse exception: Expecting "+TAG_TOPIC_MAP); // TODO: throw exception
break;
case STATE_TOPICMAP:
if(qName.equals(TAG_TOPIC)){
topicID=attributes.getValue("id");
stateStack.push(state);
state=STATE_TOPIC;
parsedType=new LinkedHashSet<>();
parsedBaseName=null;
parsedSubjectIdentifiers=new LinkedHashSet<>();
parsedSubjectLocator=null;
parsedOccurrences=new LinkedHashSet<>();
parsedVariants=new LinkedHashSet<>();
parsedEdittime=0;
topicCount++;
}
else if(qName.equals(TAG_ASSOCIATION)){
associationID=attributes.getValue("id");
stateStack.push(state);
state=STATE_ASSOCIATION;
parsedType=new LinkedHashSet<>();
parsedMembers=new LinkedHashSet<>();
associationCount++;
}
else logger.log("Parse exception: Expecting "+TAG_TOPIC+" or "+TAG_ASSOCIATION+" got "+qName);
break;
case STATE_TOPIC:
if(qName.equals(TAG_INSTANCEOF)){
stateStack.push(state);
state=STATE_INSTANCEOF;
}
else if(qName.equals(TAG_SUBJECTIDENTITY)){
stateStack.push(state);
state=STATE_SUBJECTIDENTITY;
}
else if(qName.equals(TAG_BASENAME)){
stateStack.push(state);
state=STATE_BASENAME;
parsedBaseName=null;
parsedScope=new LinkedHashSet<>();
parsedBaseNameVariants=new LinkedHashSet<>();
}
else if(qName.equals(TAG_OCCURRENCE)){
stateStack.push(state);
state=STATE_OCCURRENCE;
parsedScope=new LinkedHashSet<>();
parsedOccurrenceType=null;
parsedOccurrenceData=null;
parsedOccurrenceRef=null;
occurrenceCount++;
}
else logger.log("Parse exception: Expecting "+TAG_INSTANCEOF+", "+TAG_SUBJECTIDENTITY+", "+TAG_BASENAME+" or "+TAG_OCCURRENCE+" got "+qName);
break;
case STATE_INSTANCEOF:
if(qName.equals(TAG_TOPICREF)){
String href=attributes.getValue(XMLNS_XLINK,"href");
parsedType.add(getOrCreateTopic(href));
}
else if(qName.equals(TAG_SUBJECTINDICATORREF)){
Locator l=createLocator(attributes.getValue(XMLNS_XLINK,"href"));
Topic t=getTopic(l);
if(t==null){
t=createTopic();
t.addSubjectIdentifier(createLocator(attributes.getValue(XMLNS_XLINK,"href")));
}
parsedType.add(t);
}
else logger.log("Parse exception: Expecting "+TAG_TOPICREF+" or "+TAG_SUBJECTINDICATORREF);
break;
case STATE_SUBJECTIDENTITY:
if(qName.equals(TAG_SUBJECTINDICATORREF)){
String href=attributes.getValue(XMLNS_XLINK,"href");
parsedSubjectIdentifiers.add(createLocator(href));
}
else if(qName.equals(TAG_RESOURCEREF)){
String href=attributes.getValue(XMLNS_XLINK,"href");
parsedSubjectLocator=createLocator(href);
}
else logger.log("Parse exception: Expecting "+TAG_SUBJECTINDICATORREF+" or "+TAG_RESOURCEREF);
// TODO: topicRef
break;
case STATE_BASENAME:
if(qName.equals(TAG_BASENAMESTRING)){
stateStack.push(state);
state=STATE_BASENAMESTRING;
parsedBaseName="";
}
else if(qName.equals(TAG_VARIANT)){
stateStack.push(state);
state=STATE_VARIANT;
parsedParameters=new LinkedHashSet<>();
parsedVariantName=null;
}
else if(qName.equals(TAG_SCOPE)){
stateStack.push(state);
state=STATE_SCOPE;
}
else logger.log("Parse exception: Expecting "+TAG_BASENAMESTRING+", "+TAG_VARIANT+" or "+TAG_SCOPE);
break;
case STATE_BASENAMESTRING:
logger.log("Parse exception: Expecting char data!");
break;
case STATE_VARIANT:
if(qName.equals(TAG_PARAMETERS)){
stateStack.push(state);
state=STATE_PARAMETERS;
}
else if(qName.equals(TAG_VARIANTNAME)){
stateStack.push(state);
state=STATE_VARIANTNAME;
}
else logger.log("Parse exception: Expecting "+TAG_PARAMETERS+" or "+TAG_VARIANTNAME);
break;
case STATE_PARAMETERS:
if(qName.equals(TAG_TOPICREF)){
String href=attributes.getValue(XMLNS_XLINK,"href");
parsedParameters.add(getOrCreateTopic(href));
}
else if(qName.equals(TAG_SUBJECTINDICATORREF)){
Locator l=createLocator(attributes.getValue(XMLNS_XLINK,"href"));
Topic t=getTopic(l);
if(t==null){
t=createTopic();
t.addSubjectIdentifier(createLocator(attributes.getValue(XMLNS_XLINK,"href")));
}
parsedParameters.add(t);
}
else logger.log("Parse exception: Expecting "+TAG_TOPICREF+" or "+TAG_SUBJECTINDICATORREF);
break;
case STATE_VARIANTNAME:
if(qName.equals(TAG_RESOURCEDATA)){
stateStack.push(state);
state=STATE_VARIANTRESOURCEDATA;
parsedVariantName="";
}
else logger.log("Parse exception: Expecting "+TAG_RESOURCEDATA);
break;
case STATE_VARIANTRESOURCEDATA:
logger.log("Parse exception: Expecting char data");
break;
case STATE_SCOPE:
if(qName.equals(TAG_TOPICREF)){
String href=attributes.getValue(XMLNS_XLINK,"href");
parsedScope.add(getOrCreateTopic(href));
}
else if(qName.equals(TAG_SUBJECTINDICATORREF)){
Locator l=createLocator(attributes.getValue(XMLNS_XLINK,"href"));
Topic t=getTopic(l);
if(t==null){
t=createTopic();
t.addSubjectIdentifier(createLocator(attributes.getValue(XMLNS_XLINK,"href")));
}
parsedScope.add(t);
}
else logger.log("Parse exception: Expecting "+TAG_TOPICREF+" or "+TAG_SUBJECTINDICATORREF);
//TODO: resourceRef
break;
case STATE_OCCURRENCE:
if(qName.equals(TAG_SCOPE)){
stateStack.push(state);
state=STATE_SCOPE;
}
else if(qName.equals(TAG_INSTANCEOF)){
stateStack.push(state);
state=STATE_OCCURRENCEINSTANCEOF;
}
else if(qName.equals(TAG_RESOURCEREF)){
parsedOccurrenceRef=attributes.getValue(XMLNS_XLINK,"href");
}
else if(qName.equals(TAG_RESOURCEDATA)){
stateStack.push(state);
state=STATE_RESOURCEDATA;
parsedOccurrenceData="";
}
else logger.log("Parse exception: Expecting "+TAG_SCOPE+", "+TAG_INSTANCEOF+" or "+TAG_RESOURCEDATA+" got "+qName);
break;
case STATE_OCCURRENCEINSTANCEOF:
if(qName.equals(TAG_TOPICREF)){
String href=attributes.getValue(XMLNS_XLINK,"href");
parsedOccurrenceType=getOrCreateTopic(href);
}
else if(qName.equals(TAG_SUBJECTINDICATORREF)){
Locator l=createLocator(attributes.getValue(XMLNS_XLINK,"href"));
Topic t=getTopic(l);
if(t==null){
t=createTopic();
t.addSubjectIdentifier(createLocator(attributes.getValue(XMLNS_XLINK,"href")));
}
parsedOccurrenceType=t;
}
else logger.log("Parse exception: Expecting "+TAG_TOPICREF+" or "+TAG_SUBJECTINDICATORREF);
break;
case STATE_RESOURCEDATA:
logger.log("Parse exception: Expecting char data!");
break;
case STATE_ASSOCIATION:
if(qName.equals(TAG_INSTANCEOF)){
stateStack.push(state);
state=STATE_INSTANCEOF;
}
else if(qName.equals(TAG_SCOPE)){
stateStack.push(state);
state=STATE_SCOPE;
logger.log("Warning: Scope not supported in associations. AssociationID=\""+associationID+"\"");
}
else if(qName.equals(TAG_MEMBER)){
stateStack.push(state);
state=STATE_MEMBER;
parsedRole=null;
parsedPlayers=new LinkedHashSet<>();
}
else logger.log("Parse exception: Expecting "+TAG_INSTANCEOF+", "+TAG_SCOPE+" or "+TAG_MEMBER+" got "+qName);
break;
case STATE_MEMBER:
if(qName.equals(TAG_TOPICREF)){
String href=attributes.getValue(XMLNS_XLINK,"href");
parsedPlayers.add(getOrCreateTopic(href));
}
else if(qName.equals(TAG_SUBJECTINDICATORREF)){
Locator l=createLocator(attributes.getValue(XMLNS_XLINK,"href"));
Topic t=getTopic(l);
if(t==null){
t=createTopic();
t.addSubjectIdentifier(createLocator(attributes.getValue(XMLNS_XLINK,"href")));
}
parsedPlayers.add(t);
}
else if(qName.equals(TAG_ROLESPEC)){
stateStack.push(state);
state=STATE_ROLESPEC;
}
else logger.log("Parse exception: Expecting "+TAG_TOPICREF+", "+TAG_SUBJECTINDICATORREF+" or "+TAG_ROLESPEC);
break;
case STATE_ROLESPEC:
if(qName.equals(TAG_TOPICREF)){
String href=attributes.getValue(XMLNS_XLINK,"href");
parsedRole=getOrCreateTopic(href);
}
else if(qName.equals(TAG_SUBJECTINDICATORREF)){
Locator l=createLocator(attributes.getValue(XMLNS_XLINK,"href"));
Topic t=getTopic(l);
if(t==null){
t=createTopic();
t.addSubjectIdentifier(createLocator(attributes.getValue(XMLNS_XLINK,"href")));
}
parsedRole=t;
}
else logger.log("Parse exception: Expecting "+TAG_TOPICREF+" or "+TAG_SUBJECTINDICATORREF);
break;
}
}
catch(Exception e){
logger.log(e);
}
if(count++ % 10000 == 9999) {
logger.hlog("Importing XTM topic map.\nFound " + topicCount + " topics, " + associationCount + " associations and "+ occurrenceCount + " occurrences.");
}
}
@Override
public void endElement(String uri, String localName, String qName) throws org.xml.sax.SAXException {
if(logger.forceStop()) {
throw new org.xml.sax.SAXException("user_interrupt");
}
Topic topic;
try {
switch(state){
case STATE_TOPICMAP:
if(qName.equals(TAG_TOPIC_MAP)){
state=stateStack.pop();
Locator eloc=createLocator(EDITTIME_SI);
Iterator<Map.Entry<Topic,Collection<Occurrence>>> iter=allOccurrences.entrySet().iterator();
while(iter.hasNext()){
Map.Entry<Topic,Collection<Occurrence>> e=iter.next();
topic=(Topic)e.getKey();
if(topic.isRemoved()){
logger.log("Warning: Occurrence topic is removed (probably merged), topic map was inconsistent!");
topic=getTopic(topic.getOneSubjectIdentifier());
if(topic==null){
logger.log("Error: Couldn't find other version of topic, skipping occurrence!");
break;
}
}
Collection<Occurrence> c=e.getValue();
Iterator<Occurrence> iter2=c.iterator();
while(iter2.hasNext()){
Occurrence o=iter2.next();
if(o.type==null) logger.log("Warning: Occurrence has no type!");
if(o.type.getSubjectIdentifiers().contains(eloc)){
topic.setEditTime(Long.parseLong(o.data));
}
else{
if(o.version==null) {
logger.log("Warning: Occurrence has no version, adding a generic one!");
o.version=getTopic(TMBox.LANGINDEPENDENT_SI);
if(o.version==null){
o.version=createTopic();
o.version.addSubjectIdentifier(createLocator(TMBox.LANGINDEPENDENT_SI));
o.version.setBaseName("Language independent");
}
}
if(o.version!=null){
if(o.data!=null){
if(o.type.isRemoved()) logger.log("!!!! type is removed");
if(o.version.isRemoved()) logger.log("!!!! version is removed");
topic.setData(o.type,o.version, o.data);
}
if(o.ref!=null){
logger.log("Converting resourceRef occurrence to new topic and an association");
Topic t=createTopic();
t.addSubjectIdentifier(createLocator(makeSubjectIndicator()));
t.setBaseName("Occurrence file: "+o.ref);
t.setSubjectLocator(createLocator(o.ref));
Topic orole=getTopic("http://wandora.org/si/compatibility/occurrence-role-reference");
if(orole==null){
orole=createTopic();
orole.addSubjectIdentifier(createLocator("http://wandora.org/si/compatibility/occurrence-role-reference"));
orole.setBaseName("Occurrence role reference");
}
Topic trole=getTopic("http://wandora.org/si/compatibility/occurrence-role-topic");
if(trole==null){
trole=createTopic();
trole.addSubjectIdentifier(createLocator("http://wandora.org/si/compatibility/occurrence-role-topic"));
trole.setBaseName("Occurrence role topic");
}
Association a=createAssociation(o.type);
a.addPlayer(topic,trole);
a.addPlayer(t,orole);
}
if(o.data==null && o.ref==null){
logger.log("Warning: Occurrence has no data and no reference!");
}
}
else logger.log("Warning: Occurrence still has no version (weird)!");
}
}
}
// this is for debugging
Iterator<Map.Entry<String,Topic>> diter=idmapping.entrySet().iterator();
while(diter.hasNext()){
Map.Entry<String,Topic> e=diter.next();
String key=e.getKey();
Topic t=e.getValue();
if(t.isRemoved()){
logger.log("Topic was removed, XTM file was probably inconsistent, id was \""+key+"\".");
}
else if(t.getOneSubjectIdentifier()==null){
logger.log("No subject identifier for topic, id was \""+key+"\".");
}
}
}
else logger.log("Parse exception: Expecting end of "+TAG_TOPIC_MAP+" but got "+qName);
break;
case STATE_TOPIC:
if(qName.equalsIgnoreCase(TAG_TOPIC)){
if(topicID==null) topic=createTopic();
else topic=getOrCreateTopic("#"+topicID);
Iterator<Topic> titer=parsedType.iterator();
while(titer.hasNext()){
Topic t=titer.next();
topic.addType(t);
}
// if(parsedSubjectIdentifiers.size()==0) logger.log("Warning, couldn't find any subject identifiers for topic "+parsedBaseName);
Iterator<Locator> liter=parsedSubjectIdentifiers.iterator();
while(liter.hasNext()){
Locator l=liter.next();
topic.addSubjectIdentifier(l);
}
if(parsedSubjectIdentifiers.isEmpty()){
// logger.log("Warning topic has no subject identifiers, creating one.");
topic.addSubjectIdentifier(createLocator(makeSubjectIndicator()));
}
Iterator<VariantName> viter=parsedVariants.iterator();
while(viter.hasNext()){
VariantName v=viter.next();
topic.setVariant(v.scope,v.name);
}
if(parsedSubjectLocator!=null) topic.setSubjectLocator(parsedSubjectLocator);
if(parsedBaseName!=null && parsedBaseName.length()>0) topic.setBaseName(parsedBaseName);
allOccurrences.put(topic,parsedOccurrences);
state=stateStack.pop();
}
else logger.log("Parse exception: Expecting end of "+TAG_TOPIC+" but got "+qName);
break;
case STATE_ASSOCIATION:
if(qName.equalsIgnoreCase(TAG_ASSOCIATION)){
if(parsedType.isEmpty()) logger.log("No association type");
else{
if(parsedType.size()>1) logger.log("Multiple types for association, using first!");
topic = parsedType.iterator().next();
Association a=createAssociation(topic);
Iterator<Member> miter=parsedMembers.iterator();
// TODO: check that no multiple members with same role
while(miter.hasNext()){
Member m=miter.next();
a.addPlayer(m.player,m.role);
}
}
state=stateStack.pop();
}
else logger.log("Parse exception: Expecting end of "+TAG_ASSOCIATION+" but got "+qName);
break;
case STATE_INSTANCEOF:
if(qName.equals(TAG_INSTANCEOF)){
state=stateStack.pop();
}
else if(qName.equals(TAG_TOPICREF)){}
else if(qName.equals(TAG_SUBJECTINDICATORREF)){}
else logger.log("Parse exception: Expecting end of "+TAG_INSTANCEOF+" but got "+qName);
break;
case STATE_SUBJECTIDENTITY:
if(qName.equals(TAG_SUBJECTIDENTITY)){
state=stateStack.pop();
}
else if(qName.equals(TAG_SUBJECTINDICATORREF)){}
else if(qName.equals(TAG_RESOURCEREF)){}
else logger.log("Parse exception: Expecting end of "+TAG_SUBJECTIDENTITY+" but got "+qName);
break;
case STATE_BASENAME:
if(qName.equals(TAG_BASENAME)){
Iterator<VariantName> viter=parsedBaseNameVariants.iterator();
while(viter.hasNext()){
VariantName v=viter.next();
v.scope.addAll(parsedScope);
}
parsedVariants.addAll(parsedBaseNameVariants);
state=stateStack.pop();
}
else logger.log("Parse exception: Expecting end of "+TAG_BASENAME+" but got "+qName);
break;
case STATE_BASENAMESTRING:
if(qName.equals(TAG_BASENAMESTRING)){
state=stateStack.pop();
}
else logger.log("Parse exception: Expecting end of "+TAG_BASENAMESTRING+" but got "+qName);
break;
case STATE_VARIANT:
if(qName.equals(TAG_VARIANT)){
if(parsedVariantName != null) {
parsedBaseNameVariants.add(new VariantName(parsedVariantName,parsedParameters));
}
else {
logger.log("parsedVariantName == " + parsedVariantName + "(topic " + topicID + ")");
}
state=stateStack.pop();
}
else logger.log("Parse exception: Expecting end of "+TAG_VARIANT+" but got "+qName);
break;
case STATE_PARAMETERS:
if(qName.equals(TAG_PARAMETERS)){
state=stateStack.pop();
}
else if(qName.equals(TAG_TOPICREF)){}
else if(qName.equals(TAG_SUBJECTINDICATORREF)){}
else logger.log("Parse exception: Expecting end of "+TAG_PARAMETERS+" but got "+qName);
break;
case STATE_VARIANTNAME:
if(qName.equals(TAG_VARIANTNAME)){
state=stateStack.pop();
}
else logger.log("Parse exception: Expecting end of "+TAG_VARIANTNAME+" but got "+qName);
break;
case STATE_VARIANTRESOURCEDATA:
if(qName.equals(TAG_RESOURCEDATA)){
state=stateStack.pop();
}
else logger.log("Parse exception: Expecting end of "+TAG_RESOURCEDATA+" but got "+qName);
break;
case STATE_OCCURRENCE:
if(qName.equals(TAG_OCCURRENCE)){
if(parsedOccurrenceType==null) logger.log("No occurrence type");
else{
if(parsedScope.size()>1) logger.log("Occurrence scope contains more than one topic, using only first!");
Occurrence o=new Occurrence(parsedOccurrenceType,(parsedScope.size()>=1?(Topic)parsedScope.iterator().next():null),parsedOccurrenceData,parsedOccurrenceRef);
parsedOccurrences.add(o);
}
state=stateStack.pop();
}
else if(qName.equals(TAG_RESOURCEREF)){}
else logger.log("Parse exception: Expecting end of "+TAG_OCCURRENCE+" but got "+qName);
break;
case STATE_OCCURRENCEINSTANCEOF:
if(qName.equals(TAG_INSTANCEOF)){
state=stateStack.pop();
}
else if(qName.equals(TAG_TOPICREF)){}
else if(qName.equals(TAG_SUBJECTINDICATORREF)){}
else logger.log("Parse exception: Expecting end of "+TAG_INSTANCEOF+" but got "+qName);
break;
case STATE_RESOURCEDATA:
if(qName.equals(TAG_RESOURCEDATA)){
state=stateStack.pop();
}
else logger.log("Parse exception: Expecting end of "+TAG_RESOURCEDATA+" but got "+qName);
break;
case STATE_SCOPE:
if(qName.equals(TAG_SCOPE)){
state=stateStack.pop();
}
else if(qName.equals(TAG_TOPICREF)){}
else if(qName.equals(TAG_SUBJECTINDICATORREF)){}
else logger.log("Parse exception: Expecting end of "+TAG_SCOPE+" but got "+qName);
break;
case STATE_MEMBER:
if(qName.equals(TAG_MEMBER)){
if(parsedPlayers.size()>0){
if(parsedPlayers.size()>1) logger.log("Warning: Only one player per member. Association id=\""+associationID+"\"!");
parsedMembers.add(new Member((Topic)parsedPlayers.iterator().next(),parsedRole));
}
else logger.log("No players found"); // TODO: warning no player found
state=stateStack.pop();
}
else if(qName.equals(TAG_TOPICREF)){}
else if(qName.equals(TAG_SUBJECTINDICATORREF)){}
else logger.log("Parse exception: Expecting end of "+TAG_MEMBER+" but got "+qName);
break;
case STATE_ROLESPEC:
if(qName.equals(TAG_ROLESPEC)){
state=stateStack.pop();
}
else if(qName.equals(TAG_TOPICREF)){}
else if(qName.equals(TAG_SUBJECTINDICATORREF)){}
else logger.log("Parse exception: Expecting end of "+TAG_ROLESPEC+" but got "+qName);
break;
default:
logger.log("Parse exception: Not expecting end of tag but got "+qName);
break;
}
}
catch(Exception e){
logger.log(e);
}
}
public Topic getOrCreateTopic(String href) throws TopicMapException {
Topic t=idmapping.get(href);
if(t!=null) {
if(t.isRemoved()) {
logger.log("ID mapping found for \""+href+"\" but topic has been deleted (or merged). XTM is probably inconsistent. Getting new version of the topic.");
Locator l=t.getOneSubjectIdentifier();
if(l==null) t=null;
else t=getTopic(l);
if(t!=null){
idmapping.put(href,t);
}
else{
logger.log("Couldn't find new version of deleted topic. This will probably cause problems. Creating new.");
t=createTopic();
idmapping.put(href,t);
}
}
return t;
}
else {
t=createTopic();
idmapping.put(href,t);
return t;
}
}
@Override
public void endDocument() throws SAXException {
logger.log("Found total " + topicCount + " topics, " + associationCount + " associations and "+ occurrenceCount + " occurrences.");
}
@Override
public void endPrefixMapping(String prefix) throws SAXException {
}
@Override
public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
}
@Override
public void processingInstruction(String target, String data) throws SAXException {
}
@Override
public void setDocumentLocator(org.xml.sax.Locator locator) {
}
@Override
public void skippedEntity(String name) throws SAXException {
}
@Override
public void startDocument() throws SAXException {
}
@Override
public void startPrefixMapping(String prefix, String uri) throws SAXException {
}
@Override
public void error(SAXParseException e) throws SAXParseException {
throw e;
}
@Override
public void fatalError(SAXParseException e) throws SAXParseException {
throw e;
}
@Override
public void warning(SAXParseException e) {
logger.log(e);
}
public class VariantName {
public String name;
public Set<Topic> scope;
public VariantName(String name, Collection<Topic> c){
this.name=name;
scope = new LinkedHashSet<Topic>();
for(Iterator<Topic> i = c.iterator(); i.hasNext();) {
scope.add(i.next());
}
}
public VariantName(String name, Set<Topic> scope){
this.name=name;
this.scope=scope;
}
}
public class Member {
public Topic player;
public Topic role;
public Member(Topic player,Topic role){
this.player=player;
this.role=role;
}
}
public class Occurrence {
public Topic type;
public Topic version;
public String data;
public String ref;
public Occurrence(Topic type,Topic version,String data,String ref){
this.type=type; this.version=version; this.data=data; this.ref=ref;
}
}
public class IntegerStack {
private Stack<Integer> stack;
public IntegerStack(){
this.stack=new Stack<>();
}
public int pop(){
return stack.pop().intValue();
}
public void push(int i){
stack.push(Integer.valueOf(i));
}
public int peek(){
return stack.peek().intValue();
}
}
}
}
| 104,304 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TopicHashSet.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/TopicHashSet.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* TopicHashSet.java
*
* Created on 30. toukokuuta 2007, 14:15
*
*/
package org.wandora.topicmap;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
/**
*
* @author olli
*/
public class TopicHashSet implements Set<Topic> {
private TopicHashMap<TopicHashSet> map;
/** Creates a new instance of TopicHashSet */
public TopicHashSet() {
map=new TopicHashMap<>();
}
public TopicHashSet(Collection<? extends Topic> c){
this();
addAll(c);
}
public void clear() {
map.clear();
}
public boolean isEmpty() {
return map.isEmpty();
}
public Iterator<Topic> iterator() {
return map.keySet().iterator();
}
public int size() {
return map.size();
}
public Object[] toArray() {
return map.keySet().toArray();
}
public boolean contains(Object o) {
return map.containsKey(o);
}
public boolean remove(Object o) {
return (map.remove(o)!=null);
}
public <T> T[] toArray(T[] a) {
return (T[])map.keySet().toArray(a);
}
public boolean addAll(Collection<? extends Topic> c) {
boolean ret=false;
for(Topic t : c){
if(map.put(t,this)==null) ret=true;
}
return ret;
}
public boolean containsAll(Collection<?> c) {
for(Object t : c){
if(!map.containsKey(t)) return false;
}
return true;
}
public boolean removeAll(Collection<?> c) {
boolean ret=false;
for(Object t : c){
if(map.remove(t)!=null) ret=true;
}
return ret;
}
public boolean retainAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
public boolean add(Topic e) {
return (map.put(e,this)==null);
}
}
| 2,675 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TopicRemovedException.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/TopicRemovedException.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* TopicRemovedException.java
*
* Created on 19. toukokuuta 2006, 14:55
*
*/
package org.wandora.topicmap;
/**
* Topic becomes removed whenever it has been merged into another topic.
*
* @author olli
*/
public class TopicRemovedException extends TopicMapException {
/** Creates a new instance of TopicRemovedException */
public TopicRemovedException() {
}
}
| 1,197 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TopicMapStatData.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/TopicMapStatData.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* TopicMapStatData.java
*
* Created on 25. toukokuuta 2006, 18:26
*
*/
package org.wandora.topicmap;
/**
*
* @author akivela
*/
public class TopicMapStatData {
Object[] data = null;
/** Creates a new instance of TopicMapStatData */
public TopicMapStatData() {
}
public TopicMapStatData(int intData) {
data = new Object[] { Integer.valueOf(intData) };
}
public TopicMapStatData(int intData1, int intData2) {
data = new Object[] { Integer.valueOf(intData1), Integer.valueOf(intData2) };
}
public TopicMapStatData(TopicMapStatData newData) {
data = new Object[] { newData };
}
public TopicMapStatData(TopicMapStatData newData1, TopicMapStatData newData2) {
data = new Object[] { newData1, newData2 };
}
// -------------------------------------------------------------------------
@Override
public String toString() {
if(data != null && data.length > 0) {
StringBuilder sb = new StringBuilder("");
for(int i=0; i<data.length; i++) {
sb.append( data[i].toString() );
if(i+1<data.length) sb.append("/");
}
return sb.toString();
}
else {
return "n.a.";
}
}
}
| 2,140 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TopicIterator.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/TopicIterator.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*/
package org.wandora.topicmap;
import java.util.Iterator;
/**
*
* An iterator with a mechanism to dispose of it cleanly. When iterating
* topics, some implementations need to dispose of the iterator properly.
* Previously this was done when the iterator had been completely iterated
* through. But in some cases it may be desirable to stop iterating earlier and
* going through the whole thing could be time consuming. This class is designed
* to address this issue. Whenever a topic map implementation returns a TopicIterator,
* its dispose method may be called to stop the iteration process early. If a
* normal Iterator is returned, then it should be assumed that it must be iterated
* completely or things might not be cleaned up properly.
*
* @author olli
*/
public interface TopicIterator extends Iterator<Topic> {
public void dispose();
}
| 1,669 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TopicMapListener.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/TopicMapListener.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* TopicMapListener.java
*
* Created on July 13, 2004, 9:54 AM
*/
package org.wandora.topicmap;
import java.util.Collection;
/**
* A listener for various changes in a topic map.
*
* @author olli
*/
public interface TopicMapListener {
/* public void topicChanged(Topic t) throws TopicMapException ;
public void topicRemoved(Topic t) throws TopicMapException ;
public void associationChanged(Association a) throws TopicMapException ;
public void associationRemoved(Association a) throws TopicMapException ;
*/
/*
* MergedTopicMap reports general changes with topicSubjectIdentifierChanged(topic,null,null) and
* associationPlayerChanged(association,null,null,null).
*/
/**
* Notification that a subject identifier has changed. Either added or removed is non-null
* and indicates that a subject identifier has been added or removed, respectively.
* The non-null parameter contains the new subject identifier or the removed subject identifier.
*/
public void topicSubjectIdentifierChanged(Topic t,Locator added,Locator removed) throws TopicMapException ;
/**
* Notification that the base name has been changed. Either newName or oldName may
* be null indicating that base name was removed or old name was empty.
*/
public void topicBaseNameChanged(Topic t,String newName,String oldName) throws TopicMapException ;
/**
* Notification that a topic type has changed. Either added or removed is non-null
* and indicates that a type has been added or removed, respectively.
* The non-null parameter contains the new type or the removed type.
*/
public void topicTypeChanged(Topic t,Topic added,Topic removed) throws TopicMapException ;
/**
* Notification that a variant name has been changed. Either newName or oldName may
* be null indicating that the variant name was removed or old name was empty.
*/
public void topicVariantChanged(Topic t,Collection<Topic> scope,String newName,String oldName) throws TopicMapException ;
/**
* Notification that topic occurrence has been changed. Either newValue or oldValue may
* be null indicating that the occurrence was removed or old value was empty.
*/
public void topicDataChanged(Topic t,Topic type,Topic version,String newValue,String oldValue) throws TopicMapException ;
/**
* Notification that the subject locator has been changed. Either newLocator or oldLocator may
* be null indicating that locator was removed or there was no old locator.
*/
public void topicSubjectLocatorChanged(Topic t,Locator newLocator,Locator oldLocator) throws TopicMapException ;
/**
* Notification that a topic has been completely removed.
*/
public void topicRemoved(Topic t) throws TopicMapException ;
/**
* A notification used to report general or large changes in topic, for example when topics are merged.
* Such a large change may consist of any number of smaller changes that are NOT reported
* individually with the other listener methods. This method is used when tracking
* individual changes is hard to implement.
*/
public void topicChanged(Topic t) throws TopicMapException ;
/**
* A notification that association type has changed. Either newType or oldType
* can be null to indicate that old or new type was null. When type
* is changed from one topic to another, both will be non-null.
*/
public void associationTypeChanged(Association a,Topic newType,Topic oldType) throws TopicMapException ;
/**
* A notification that a player in an association with a certain role has
* been changed. Either newPlayer or oldPlayer can be null to indicate that
* the no new player for the role was set or that there was no player
* with the role previously. Both can also be non-null to indicate that
* the player of the role changed.
*/
public void associationPlayerChanged(Association a,Topic role,Topic newPlayer,Topic oldPlayer) throws TopicMapException ;
/**
* A notification that an association has been completely removed.
*/
public void associationRemoved(Association a) throws TopicMapException ;
/**
* A notification used to report general or large changes in association.
* Such a large change may consist of any number of smaller changes that are NOT reported
* individually with the other listener methods. This method is used when tracking
* individual changes is hard to implement.
*/
public void associationChanged(Association a) throws TopicMapException ;
}
| 5,476 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SimpleTopicMapLogger.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/SimpleTopicMapLogger.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.topicmap;
import java.io.PrintStream;
/**
*
* @author olli
*/
public class SimpleTopicMapLogger implements TopicMapLogger{
protected PrintStream out;
public SimpleTopicMapLogger(PrintStream out){
this.out=out;
}
public SimpleTopicMapLogger(){
this(System.out);
}
@Override
public boolean forceStop() {
return false;
}
@Override
public void hlog(String message) {
log(message);
}
@Override
public void log(String message) {
out.println(message);
}
@Override
public void log(String message, Exception e) {
out.println(message);
log(e);
}
@Override
public void log(Exception e) {
e.printStackTrace(out);
}
@Override
public void setLogTitle(String title) {
}
@Override
public void setProgress(int n) {
}
@Override
public void setProgressMax(int maxn) {
}
}
| 1,777 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TMBox.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/TMBox.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* TMBox.java
*
* Created on June 7, 2004, 12:43 PM
*/
package org.wandora.topicmap;
import static org.wandora.utils.Tuples.t2;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.LinkedHashSet;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.Stack;
import org.wandora.application.gui.ConfirmDialog;
import org.wandora.application.gui.ConfirmResult;
import org.wandora.topicmap.layered.Layer;
import org.wandora.topicmap.layered.LayerStack;
import org.wandora.topicmap.layered.LayeredTopic;
import org.wandora.utils.GripCollections;
import org.wandora.utils.Tuples.T2;
/**
* TMBox contains various topic map related tools and utility methods.
*
* @author olli
*/
public class TMBox {
public static final String WANDORACLASS_SI = "http://wandora.org/si/core/wandora-class";
public static final String ASSOCIATIONTYPE_SI = "http://wandora.org/si/core/association-type";
public static final String ASSOCIATIONROLE_SI = "http://wandora.org/si/core/associationrole";
public static final String ROLE_SI = "http://wandora.org/si/core/role";
public static final String LANGINDEPENDENT_SI = "http://wandora.org/si/core/lang-independent";
public static final String ASSOCIATIONROLECATEGORIES_SI = "http://wandora.org/si/core/associationrolecategories";
public static final String OCCURRENCETYPE_SI = "http://wandora.org/si/core/occurrence-type";
public static final String HIDELEVEL_SI = "http://wandora.org/si/core/hidelevel";
public static final String CATEGORYHIERARCHY_SI = "http://wandora.org/si/common/categoryhierarchy";
public static final String SUPERCATEGORY_SI = "http://wandora.org/si/common/supercategory";
public static final String SUBCATEGORY_SI = "http://wandora.org/si/common/subcategory";
public static final String ENTRYTIME_SI = "http://wandora.org/si/common/entrytime";
public static final String VARIANT_NAME_VERSION_SI = "http://wandora.org/si/core/variant-name-version";
public static final String LANGUAGE_SI = "http://wandora.org/si/core/language";
// Language topics, data versions and display scope (moved from WandoraAdminManager)
/**
* Gets a subject identifier for each topic that represents some language in
* the topic map. This is done by getting all topics that are of language type.
* The language topic is assumed to have a subject identifier LANGUAGE_SI.
*/
public static String[] getLanguageSIs(TopicMap tm) throws TopicMapException {
Collection<Topic> languageTopics = TMBox.sortTopics(tm.getTopicsOfType(LANGUAGE_SI), "en");
if(languageTopics != null && languageTopics.size() > 0) {
List<String> languageSIs = new ArrayList<>();
for(Topic languageTopic : languageTopics) {
try {
languageSIs.add( languageTopic.getOneSubjectIdentifier().toExternalForm() );
}
catch (Exception e) {
e.printStackTrace();
}
}
return (String []) languageSIs.toArray(new String[] { } );
}
else {
return new String[] {};
}
}
public static Topic[] getLanguageTopics(TopicMap tm) throws TopicMapException {
Collection<Topic> languageTopics = TMBox.sortTopics(tm.getTopicsOfType(LANGUAGE_SI), "en");
if(languageTopics != null && languageTopics.size() > 0) {
return (Topic []) languageTopics.toArray( new Topic[] { } );
}
else {
return new Topic[] {};
}
}
/**
* Gets a subject identifier for each topic that represents some variant name version in
* the topic map. This is done by getting all topics that are of name version type.
* The name version topic is assumed to have a subject identifier VARIANT_NAME_VERSION_SI.
*/
public static String[] getNameVersionSIs(TopicMap tm) throws TopicMapException {
Collection<Topic> variantNameVersionTopics = TMBox.sortTopics(tm.getTopicsOfType(VARIANT_NAME_VERSION_SI), "en");
if(variantNameVersionTopics != null && variantNameVersionTopics.size() > 0) {
List<String> variantNameVersionSIs = new ArrayList<>();
for( Topic variantNameVersionTopic : variantNameVersionTopics ) {
try {
variantNameVersionSIs.add( variantNameVersionTopic.getOneSubjectIdentifier().toExternalForm() );
}
catch (Exception e) {
e.printStackTrace();
}
}
return (String []) variantNameVersionSIs.toArray(new String[] { } );
}
else {
return new String[]{
// XTMPSI.DISPLAY,
// XTMPSI.SORT
};
}
}
public static Topic[] getNameVersionTopics(TopicMap tm) throws TopicMapException {
Collection<Topic> variantNameVersionTopics = TMBox.sortTopics(tm.getTopicsOfType(VARIANT_NAME_VERSION_SI), "en");
if(variantNameVersionTopics != null && variantNameVersionTopics.size() > 0) {
return (Topic []) variantNameVersionTopics.toArray( new Topic[] { } );
}
else {
return new Topic[] { };
}
}
/**
* Gets display name scope for English language. This scope will contain
* the English language topic and display name topic, if they exist in
* the topic map.
*/
public static Set<Topic> getGUINameScope(TopicMap tm) throws TopicMapException {
Set<Topic> nameScope = new LinkedHashSet<>();
Topic t = tm.getTopic(XTMPSI.getLang("en"));
if(t != null && !t.isRemoved()) nameScope.add(t);
t = tm.getTopic(XTMPSI.DISPLAY);
if(t != null && !t.isRemoved()) nameScope.add(t);
return nameScope;
}
////////////////////////////////////////////////////////////
/**
* <p>
* Creates a user readable message from an integer that encodes merge/split
* information. These kinds of integers are returned by the methods that
* check if a certain operation will result in a merge or split.
* </p>
* <p>
* The integer uses four bits to encode the information. If bit 1 is set,
* changes will be visible in the whole layer stack instead of only in an
* individual layer. For example merge of two topics in the same layer is
* not visible in layer stack if those topics were already merged.
* </p>
* <p>
* If bit 2 is set there will be a real merge in the selected layer. That is,
* two topics, both in the selected layer, will be merged together.
* </p>
* <p>
* If bit 4 is set two topics will be merged virtually.
* There isn't a real merge of topics in any layer but two separate topics
* are going to be visible as only one topic because of the changes. Note
* that the topics may be in the same layer or different layers.
* </p>
* <p>
* If bit 8 is set a topic will be split. There is no operation that would
* cause a single topic in a layer to be split in two (or more) topics
* in the same layer. Splits are always virtual, two topics that were visible
* as one merged topic are going to be visible as separate topics. The topics
* may be in the same layer or different layers.
* </p>
* <p>
* Value 0 means that no split or merge will occur. Value 1 is not possible
* but other values up to and including 15 are possible.
* </p>
*/
public static String buildMergeMessage(int a){
String message="";
if( (a&2)!=0 ) message+="A real merge of two topics in the selected layer.\n";
if( (a&4)!=0 ) message+="A virtual merge of two topics in two different layers.\n";
if( (a&8)!=0 ) message+="A split of two topics in two different layers.\n";
if( (a&1)!=0 ) message+="Changes will be visible in whole layer stack.\n";
else message+="Changes will not be visible in whole layer stack.\n";
return message;
}
public static ConfirmResult checkBaseNameChange(java.awt.Component parent,Topic topic,String value) throws TopicMapException{
return checkBaseNameChange(parent,topic,value,false);
}
/**
* Checks if the base name of the given topic can be changed to the given value.
* Checks if the change will result in merges or splits and in such a case
* warns the user with a dialog. Dialog has buttons to allow the change or
* cancel the operation. If multiple parameter is true, it will also contain
* buttons to allow changes for all or deny for all. Value parameter can be
* null to indicate that current base name is to be removed. Parent parameter
* is only used as the parent of the possible dialog.
*/
public static ConfirmResult checkBaseNameChange(java.awt.Component parent,Topic topic,String value,boolean multiple) throws TopicMapException{
if(value==null) value="";
value=value.trim();
String orig=topic.getBaseName();
if((orig==null && value.length()>0) || (orig!=null && !orig.equals(value))){
int a=checkBaseNameMerge(topic,value);
if(a!=0){
String message="";
if(value.length()>0) message="New base name \""+value+"\" will cause following:\n";
else message="Removing base name will cause following:\n";
message+=buildMergeMessage(a);
ConfirmResult res=ConfirmDialog.showConfirmDialog(parent,"Merge/split confirmation",message,!multiple);
return res;
}
}
return ConfirmResult.yes;
}
public static ConfirmResult checkSubjectLocatorChange(java.awt.Component parent,Topic topic,String value) throws TopicMapException{
return checkSubjectLocatorChange(parent,topic,value,false);
}
/**
* Like checkBaseNameChange, checks if the subject locator of the topic can be changed.
*/
public static ConfirmResult checkSubjectLocatorChange(java.awt.Component parent,Topic topic,String value,boolean multiple) throws TopicMapException{
if(value==null) value="";
value=value.trim();
Locator orig=topic.getSubjectLocator();
if((orig==null && value.length()>0) || (orig!=null && !orig.toExternalForm().equals(value))){
Locator l=null;
if(value.length()>0) l=topic.getTopicMap().createLocator(value);
int a=checkSubjectLocatorMerge(topic,l);
if(a!=0){
String message="";
if(l!=null) message="New subject locator \""+value+"\" will cause following:\n";
else message="Removing subject locator will cause following:\n";
message+=buildMergeMessage(a);
ConfirmResult res=ConfirmDialog.showConfirmDialog(parent,"Merge/split confirmation",message,!multiple);
return res;
}
}
return ConfirmResult.yes;
}
public static ConfirmResult checkSubjectIdentifierChange(java.awt.Component parent,Topic topic,Locator value,boolean add) throws TopicMapException{
return checkSubjectIdentifierChange(parent,topic,value,add,false);
}
/**
* Checks if a subject identifier can be added or removed from a topic. If the
* operation results in merges or splits, warns the user with a dialog like in
* checkBaseNameChange. If add parameter is true then a subject identifier is about
* to be added, otherwise it is to be removed.
*/
public static ConfirmResult checkSubjectIdentifierChange(java.awt.Component parent,Topic topic,Locator value,boolean add,boolean multiple) throws TopicMapException{
int a=checkSubjectIdentifierMerge(topic,value,add);
if(a!=0){
String message="";
String valueString = value.toExternalForm();
if(valueString.length() > 256) {
valueString = valueString.substring(0, 256) + "...";
}
if(add) message="New subject identifier \""+valueString+"\" will cause following:\n";
else message="Removing subject identifier \""+valueString+"\" will cause following:\n";
message+=buildMergeMessage(a);
ConfirmResult res=ConfirmDialog.showConfirmDialog(parent,"Merge/split confirmation",message,!multiple);
return res;
}
return ConfirmResult.yes;
}
public static ConfirmResult checkTopicRemove(java.awt.Component parent,Topic topic) throws TopicMapException {
return checkTopicRemove(parent,topic,false);
}
/**
* Checks if removing a topic will result in a split and warns the user in that case.
* Like checkBaseNameChange, if multiple parameter is true, warning dialog will
* have options for allow all or deny all.
*/
public static ConfirmResult checkTopicRemove(java.awt.Component parent,Topic topic,boolean multiple) throws TopicMapException {
if(checkTopicRemoveSplit(topic)){
ConfirmResult res=ConfirmDialog.showConfirmDialog(parent,"Split confirmation","Removing topic will cause the split of two or more topics\nin different layers. Continue?",!multiple);
return res;
}
return ConfirmResult.yes;
}
// --------
private static int layerSplit(Set<T2<Topic,Topic>> links,Collection<Topic> topics){
Stack<Topic> stack=new Stack<>();
Set<Topic> included=new HashSet<>();
if(topics.isEmpty()) return 0;
stack.add(topics.iterator().next());
included.add(stack.peek());
while(!stack.isEmpty()){
Topic u=stack.pop();
for(Topic i : topics){
if(included.contains(i)) continue;
if(links.contains(t2(u,i))){
stack.push(i);
included.add(i);
}
}
}
return included.size()-topics.size();
}
/*
* Following methods are used by the public check*Change methods.
*
* Returned int has different bits set depending on what kind of merge
* or split occurs. 0 means that no merge or split occurs. 1 is never returned
* but other values up to and including 15 are possible return values. If the
* topic given as parameter is not an instance of LayeredTopic then first
* bit is always set if there are any merges and only other bit that can be
* set is 2. In other words return value will be 0 if no changes or 3
* if two topics will be merged and nothing else.
*
* 1 = visible in layerstack
* 2 = merge in a specific layer
* 4 = merge between topics of different layers
* 8 = split between topics of different layers
*/
public static int checkBaseNameMerge(Topic t,String newBaseName) throws TopicMapException {
if(t instanceof LayeredTopic){
int ret=0;
LayeredTopic lt=(LayeredTopic)t;
LayerStack tm=lt.getLayerStack();
Layer selectedLayer=tm.getSelectedTreeLayer();
Topic et=tm.getTopicForSelectedTreeLayer(lt);
{
LayeredTopic u=(LayeredTopic)tm.getTopicWithBaseName(newBaseName);
if(u!=null){
if(!u.mergesWithTopic(lt)) ret|=1;
}
}
{
// Topic u=tm.getSelectedLayer().getTopicMap().getTopicWithBaseName(newBaseName);
Topic u=selectedLayer.getTopicMap().getTopicWithBaseName(newBaseName);
if(u!=null){
// Topic et=lt.getTopicForSelectedLayer();
if(et==null || !et.mergesWithTopic(u)) ret|=2;
}
}
{
// Topic et=lt.getTopicForSelectedLayer();
// for(Layer l : tm.getLayers()){
for(Layer l : tm.getLeafLayers()){
// if(l==tm.getSelectedLayer()) continue;
if(l==selectedLayer) continue;
Topic u=l.getTopicMap().getTopicWithBaseName(newBaseName);
if(u!=null && (et==null || !u.mergesWithTopic(et))) ret|=4;
}
}
{
// Topic et=lt.getTopicForSelectedLayer();
// Collection<Topic> topics=lt.getTopicsForAllLayers();
Collection<Topic> topics=tm.getTopicsForAllLeafLayers(lt);
Set<T2<Topic,Topic>> links=new HashSet<>();
for(Topic i : topics){
Collection<Locator> isi=i.getSubjectIdentifiers();
Locator isl=i.getSubjectLocator();
String ibn=i.getBaseName();
if(et==i) ibn=newBaseName;
for(Topic j : topics){
if(i==j) continue;
Collection<Locator> jsi=j.getSubjectIdentifiers();
Locator jsl=j.getSubjectLocator();
String jbn=j.getBaseName();
if(et==j) jbn=newBaseName;
boolean merges=false;
if(ibn!=null && jbn!=null && ibn.equals(jbn)) merges=true;
else if(GripCollections.collectionsOverlap(isi,jsi)) merges=true;
else if(isl!=null && jsl!=null && isl.equals(jsl)) merges=true;
if(merges) links.add(t2(i,j));
}
}
String oldName=null;
if(et!=null) oldName=et.getBaseName();
if(oldName!=null){
for(Topic i : topics){
if(tm.getLeafLayer(i)==selectedLayer) continue;
if(i.getBaseName()!=null && i.getBaseName().equals(oldName)){
if(!links.contains(t2(et,i))) ret|=8;
}
}
}
if( (ret&8)!=0 && (ret&1)==0 ){
if(layerSplit(links,topics)!=0) ret|=1;
}
}
return ret;
}
else{
Topic u=t.getTopicMap().getTopicWithBaseName(newBaseName);
if(u!=null && !u.mergesWithTopic(t)) return 3;
else return 0;
}
}
public static int checkSubjectLocatorMerge(Topic t, Locator newSubjectLocator) throws TopicMapException {
if(newSubjectLocator==null) return 0;
if(t instanceof LayeredTopic){
int ret=0;
LayeredTopic lt=(LayeredTopic)t;
LayerStack tm=lt.getLayerStack();
Layer selectedLayer=tm.getSelectedTreeLayer();
Topic et=tm.getTopicForSelectedTreeLayer(lt);
{
LayeredTopic u=(LayeredTopic)tm.getTopicBySubjectLocator(newSubjectLocator);
if(u!=null){
if(!u.mergesWithTopic(lt)) ret|=1;
}
}
{
Topic u=selectedLayer.getTopicMap().getTopicBySubjectLocator(newSubjectLocator);
if(u!=null){
if(et==null || !et.mergesWithTopic(u)) ret|=2;
}
}
{
for(Layer l : tm.getLeafLayers()){
if(l==selectedLayer) continue;
Topic u=l.getTopicMap().getTopicBySubjectLocator(newSubjectLocator);
if(u!=null && (et==null || !u.mergesWithTopic(et))) ret|=4;
}
}
{
Collection<Topic> topics=tm.getTopicsForAllLeafLayers(lt);
Set<T2<Topic,Topic>> links=new HashSet<>();
for(Topic i : topics){
Collection<Locator> isi=i.getSubjectIdentifiers();
Locator isl=i.getSubjectLocator();
String ibn=i.getBaseName();
if(et==i) isl=newSubjectLocator;
for(Topic j : topics){
if(i==j) continue;
Collection<Locator> jsi=j.getSubjectIdentifiers();
Locator jsl=j.getSubjectLocator();
String jbn=j.getBaseName();
if(et==j) jsl=newSubjectLocator;
boolean merges=false;
if(ibn!=null && jbn!=null && ibn.equals(jbn)) merges=true;
else if(GripCollections.collectionsOverlap(isi,jsi)) merges=true;
else if(isl!=null && jsl!=null && isl.equals(jsl)) merges=true;
if(merges) links.add(t2(i,j));
}
}
Locator oldSL=null;
if(et!=null) oldSL=et.getSubjectLocator();
if(oldSL!=null){
for(Topic i : topics){
if(tm.getLeafLayer(i)==selectedLayer) continue;
if(i.getSubjectLocator()!=null && i.getSubjectLocator().equals(oldSL)){
if(!links.contains(t2(et,i))) ret|=8;
}
}
}
if( (ret&8)!=0 && (ret&1)==0 ){
if(layerSplit(links,topics)!=0) ret|=1;
}
}
return ret;
}
else{
Topic u=t.getTopicMap().getTopicBySubjectLocator(newSubjectLocator);
if(u!=null && !u.mergesWithTopic(t)) return 3;
else return 0;
}
}
public static int checkSubjectIdentifierMerge(Topic t, Locator subjectIdentifier,boolean add) throws TopicMapException {
if(t instanceof LayeredTopic){
int ret=0;
LayeredTopic lt=(LayeredTopic)t;
LayerStack tm=lt.getLayerStack();
Layer selectedLayer=tm.getSelectedTreeLayer();
Topic et=tm.getTopicForSelectedTreeLayer(lt);
if(add) {
LayeredTopic u=(LayeredTopic)tm.getTopic(subjectIdentifier);
if(u!=null){
if(!u.mergesWithTopic(lt)) ret|=1;
}
}
if(add){
Topic u=selectedLayer.getTopicMap().getTopic(subjectIdentifier);
if(u!=null){
if(et==null || !et.mergesWithTopic(u)) ret|=2;
}
}
if(add){
for(Layer l : tm.getLeafLayers()){
if(l==selectedLayer) continue;
Topic u=l.getTopicMap().getTopic(subjectIdentifier);
if(u!=null && (et==null || !u.mergesWithTopic(et))) ret|=4;
}
}
if(!add){
Collection<Topic> topics=tm.getTopicsForAllLeafLayers(lt);
Set<T2<Topic,Topic>> links=new HashSet<>();
for(Topic i : topics){
Collection<Locator> isi=i.getSubjectIdentifiers();
Locator isl=i.getSubjectLocator();
String ibn=i.getBaseName();
if(et==i){
Collection<Locator> temp=new ArrayList<>();
temp.addAll(isi);
temp.remove(subjectIdentifier);
isi=temp;
}
for(Topic j : topics){
if(i==j) continue;
Collection<Locator> jsi=j.getSubjectIdentifiers();
Locator jsl=j.getSubjectLocator();
String jbn=j.getBaseName();
if(et==j) {
Collection<Locator> temp=new ArrayList<Locator>();
temp.addAll(jsi);
temp.remove(subjectIdentifier);
jsi=temp;
}
boolean merges=false;
if(ibn!=null && jbn!=null && ibn.equals(jbn)) merges=true;
else if(GripCollections.collectionsOverlap(isi,jsi)) merges=true;
else if(isl!=null && jsl!=null && isl.equals(jsl)) merges=true;
if(merges) links.add(t2(i,j));
}
}
for(Topic i : topics){
if(tm.getLeafLayer(i)==selectedLayer) continue;
if(i.getSubjectIdentifiers().contains(subjectIdentifier)){
if(!links.contains(t2(et,i))) ret|=8;
}
}
if( (ret&8)!=0 && (ret&1)==0 ){
if(layerSplit(links,topics)!=0) ret|=1;
}
}
return ret;
}
else{
if(add){
Topic u=t.getTopicMap().getTopic(subjectIdentifier);
if(u!=null && !u.mergesWithTopic(t)) return 3;
else return 0;
}
else return 0;
}
}
/*
* true if a split occurs
*/
public static boolean checkTopicRemoveSplit(Topic t) throws TopicMapException {
if(t instanceof LayeredTopic){
LayeredTopic lt=(LayeredTopic)t;
LayerStack tm=lt.getLayerStack();
Topic et=lt.getTopicForSelectedLayer();
if(et==null) return false;
Set<T2<Topic,Topic>> links=new HashSet<>();
Collection<Topic> topics=lt.getTopicsForAllLayers();
for(Topic i : topics){
if(tm.getLayer(i)==tm.getSelectedLayer()){
if(et==i) continue;
}
for(Topic j : topics){
if(i==j) continue;
if(tm.getLayer(j)==tm.getSelectedLayer()){
if(et==j) continue;
}
if((i.mergesWithTopic(j))) links.add(t2(i,j));
}
}
ArrayList<Topic> temp=new ArrayList<Topic>();
temp.addAll(topics);
temp.remove(et);
if(layerSplit(links,temp)!=0) return true;
}
return false;
}
// -------------------------------------------------------------------------
/**
* Gets the topic with given subject identifier, if such a topic doesn't
* exists, makes one. If a new topic is created, it will only contain the
* subject identifier, no base name or anything else.
*/
public static Topic getOrCreateTopic(TopicMap tm, String si) throws TopicMapException {
Topic t=tm.getTopic(si);
if(t==null) {
t=tm.createTopic();
t.addSubjectIdentifier(tm.createLocator(si));
}
return t;
}
/**
* Gets the topic with given subject identifier, if such a topic doesn't
* exists, makes one and sets the given base name. If an existing topic is found
* the name parameter is ignored. That is, the existing topic will not be changed
* in any way.
*/
public static Topic getOrCreateTopic(TopicMap tm, String si, String name) throws TopicMapException {
Topic t=tm.getTopic(si);
if(t==null) {
t=tm.createTopic();
t.addSubjectIdentifier(tm.createLocator(si));
t.setBaseName(name);
}
return t;
}
/**
* Gets the topic with given base name, if such a topic doesn't exists,
* makes one. If a new topic is created, it will contain the base name and
* a generic unique subject identifier, nothing else.
*/
public static Topic getOrCreateTopicWithBaseName(TopicMap tm, String name) throws TopicMapException {
Topic t=tm.getTopicWithBaseName(name);
if(t==null) {
t=tm.createTopic();
t.setBaseName(name);
t.addSubjectIdentifier(tm.makeSubjectIndicatorAsLocator());
}
return t;
}
/**
* Merges in a topic map using base names and subject locators from the source
* topic map instead of destination topic map whenever topics merge.
*/
public static void mergeTopicMapInOverwriting(TopicMap dest, TopicMap src) throws TopicMapException {
Iterator<Topic> iter=src.getTopics();
while(iter.hasNext()){
Topic t=iter.next();
Topic c=dest.copyTopicIn(t, false);
dest.copyTopicAssociationsIn(t);
if(t.getBaseName()!=null) c.setBaseName(t.getBaseName());
if(t.getSubjectLocator()!=null) c.setSubjectLocator(t.getSubjectLocator());
}
}
/**
* Checks if topic is visible at visibility level of 1. If topic has
* language independent hide level occurrence with number 1 or greater, it
* is not visible.
*/
public static boolean topicVisible(Topic t) throws TopicMapException {
return topicVisible(t,1);
}
/**
* Checks if topic is visible at given level. Topic is not visible it it has
* occurrence with type HIDELEVEL_SI and version
* LANGINDEPENDENT_SI and the integer it contains is
* smaller than the given visibility level.
*/
public static boolean topicVisible(Topic t, int level) throws TopicMapException {
Topic hidelevel=t.getTopicMap().getTopic(HIDELEVEL_SI);
Topic langI=t.getTopicMap().getTopic(LANGINDEPENDENT_SI);
if(hidelevel==null || langI==null) return true;
String hidden=t.getData(hidelevel,langI);
if(hidden==null) return true;
int i=Integer.parseInt(hidden);
return i<level;
}
/**
* Checks if association is visible at visibility level of 1. This is true
* if its type, all roles and all players are visible at level 1.
* @see #topicVisible(Topic,int)
*/
public static boolean associationVisible(Association a) throws TopicMapException {
return associationVisible(a,1);
}
/**
* Checks if association is visible at given level. For association to be visible
* its type, all roles and all players must be visible at that level.
* @see #topicVisible(Topic,int)
*/
public static boolean associationVisible(Association a, int level) throws TopicMapException {
if(!topicVisible(a.getType(),level)) return false;
Iterator<Topic> roles=a.getRoles().iterator();
while(roles.hasNext()){
Topic role=roles.next();
if(!topicVisible(role,level)) return false;
if(!topicVisible(a.getPlayer(role),level)) return false;
}
return true;
}
public static int countAssociationsInCategories(Topic root,Topic assocType,Topic role) throws TopicMapException {
return countAssociationsInCategories(root,assocType,role,new HashSet<>()).size();
}
public static Set<Topic> countAssociationsInCategories(Topic root,Topic assocType,Topic role,Set<Topic> topics) throws TopicMapException {
Iterator<Association> associationIter=root.getAssociations(assocType,role).iterator();
while(associationIter.hasNext()){
Association a=associationIter.next();
Iterator<Topic> roleIter=a.getRoles().iterator();
while(roleIter.hasNext()){
Topic arole=roleIter.next();
if(arole!=role) topics.add(a.getPlayer(arole));
}
}
Iterator<Topic> subCategoriesIter = getSubCategories(root).iterator();
while(subCategoriesIter.hasNext()){
countAssociationsInCategories(subCategoriesIter.next(),assocType,role,topics);
}
return topics;
}
public static Iterator<TreeIteratorNode> treeIterator(Topic root,String lang){
return new TreeIterator(root,lang);
}
public static class TreeIterator implements Iterator<TreeIteratorNode> {
private Stack<Iterator<Topic>> stack;
private Iterator<Topic> current;
private TreeIteratorNode lastReturned;
private Collection<Topic> children;
private String lang;
public TreeIterator(Topic root,String lang){
this.lang=lang;
List<Topic> al=new ArrayList<>();
al.add(root);
current=al.iterator();
stack=new Stack<>();
}
public boolean hasNext() {
if(current.hasNext()) return true;
if(lastReturned.doChildren() && children.size()>0) return true;
if(stack.isEmpty()) return false;
return true;
}
public TreeIteratorNode next() {
boolean opened=false;
boolean closed=false;
if(lastReturned!=null && lastReturned.doChildren && children.size()>0){
stack.push(current);
current=children.iterator();
opened=true;
}
if(!current.hasNext()){
if(stack.isEmpty()) throw new NoSuchElementException();
current=stack.pop();
closed=true;
}
if(!current.hasNext()){
lastReturned=new TreeIteratorNode(null,false,true);
children=new ArrayList<>();
return lastReturned;
}
Topic t=(Topic)current.next();
try{
children=getSubCategories(t);
}catch(TopicMapException tme){
tme.printStackTrace(); // TODO EXCEPTION
children=new ArrayList<>();
}
children=sortTopics(children,lang);
lastReturned=new TreeIteratorNode(t,opened,closed);
return lastReturned;
}
public void remove() {
}
}
public static class TreeIteratorNode {
private boolean doChildren;
private Topic topic;
private boolean closenode;
private boolean opennode;
public TreeIteratorNode(Topic topic,boolean open,boolean close){
this.topic=topic;
doChildren=false;
this.topic=topic;
this.closenode=close;
this.opennode=open;
}
public boolean open(){
return opennode;
}
public boolean close(){
return closenode;
}
public boolean doChildren(){
return doChildren;
}
public void setIterateChildren(){
doChildren=true;
}
public Topic getTopic(){
return topic;
}
}
public static Stack<Topic> getCategoryPath(Topic t) throws TopicMapException {
Stack<Topic> path=new Stack<>();
Topic walker=t;
Collection<Topic> parents=getSuperCategories(walker);
while(parents.size()>0){
path.push(walker);
walker=(Topic)parents.iterator().next();
parents=getSuperCategories(walker);
}
path.push(walker);
return path;
}
public static Collection<Topic> getSubCategoriesRecursive(Topic t) throws TopicMapException {
return _getSubCategoriesRecursive(t,new HashSet<>());
}
private static Collection<Topic> _getSubCategoriesRecursive(Topic t,Set<Topic> c) throws TopicMapException {
Topic hierarchy=t.getTopicMap().getTopic(CATEGORYHIERARCHY_SI);
Topic supercat=t.getTopicMap().getTopic(SUPERCATEGORY_SI);
Topic subcat=t.getTopicMap().getTopic(SUBCATEGORY_SI);
if(hierarchy==null || supercat==null || subcat==null) return new ArrayList<>();
Collection<Association> as=t.getAssociations(hierarchy,supercat);
Iterator<Association> iter=as.iterator();
while(iter.hasNext()){
Association a=iter.next();
Topic s=a.getPlayer(subcat);
if(!c.contains(s)){
c.add(s);
_getSubCategoriesRecursive(s,c);
}
}
return c;
}
public static Collection<Topic> getSubCategories(Topic t,Set<Topic> c) throws TopicMapException {
Topic hierarchy=t.getTopicMap().getTopic(CATEGORYHIERARCHY_SI);
Topic supercat=t.getTopicMap().getTopic(SUPERCATEGORY_SI);
Topic subcat=t.getTopicMap().getTopic(SUBCATEGORY_SI);
if(hierarchy==null || supercat==null || subcat==null) return new ArrayList<>();
Collection<Association> as=t.getAssociations(hierarchy,supercat);
Iterator<Association> iter=as.iterator();
while(iter.hasNext()){
Association a=iter.next();
Topic s=a.getPlayer(subcat);
c.add(s);
}
return c;
}
public static Collection<Topic> getSubCategories(Topic t) throws TopicMapException {
return getSubCategories(t,new HashSet<>());
}
public static Collection<Topic> getSuperCategories(Topic t) throws TopicMapException {
Set<Topic> c=new HashSet<>();
Topic hierarchy=t.getTopicMap().getTopic(CATEGORYHIERARCHY_SI);
Topic supercat=t.getTopicMap().getTopic(SUPERCATEGORY_SI);
Topic subcat=t.getTopicMap().getTopic(SUBCATEGORY_SI);
if(hierarchy==null || supercat==null || subcat==null) return new ArrayList<>();
Collection<Association> as=t.getAssociations(hierarchy,subcat);
Iterator<Association> iter=as.iterator();
while(iter.hasNext()){
Association a=iter.next();
Topic s=a.getPlayer(supercat);
c.add(s);
}
return c;
}
public static String getTopicSortName(Topic topic,String lang) throws TopicMapException {
String name=getTopicName(topic,getSortNameTopic(topic),getLangTopic(topic,lang),false);
if(name==null || name.length() == 0) return getTopicDisplayName(topic,lang);
else return name;
}
public static String getTopicDisplayName(Topic topic,String lang) throws TopicMapException {
return getTopicName(topic,getDisplayNameTopic(topic),getLangTopic(topic,lang),true);
}
public static String getTopicName(Topic topic,Topic s1,Topic s2,boolean forceSomething) throws TopicMapException {
Set<Topic> scope=new HashSet<>();
if(s1!=null) scope.add(s1);
if(s2!=null) scope.add(s2);
return getTopicName(topic,scope,forceSomething);
}
public static String getTopicName(Topic topic,Set<Topic> scope,boolean forceSomething) throws TopicMapException {
String name=topic.getVariant(scope);
String tempName = null;
if(name==null && forceSomething){
int maxcount=0;
Set<Set<Topic>> scopes=topic.getVariantScopes();
Iterator<Set<Topic>> iter=scopes.iterator();
while(iter.hasNext()){
Set<Topic> s=iter.next();
int count=0;
Iterator<Topic> iter2=scope.iterator();
while(iter2.hasNext()){
Topic t=iter2.next();
if(s.contains(t)) count++;
}
if(count>maxcount){
maxcount=count;
tempName = topic.getVariant(s);
if(tempName != null && tempName.length() != 0) {
name=tempName;
}
}
}
if(name==null) name=topic.getBaseName();
if(name==null){
Collection<Locator> sis=topic.getSubjectIdentifiers();
if(!sis.isEmpty()) name=(sis.iterator().next()).toExternalForm();
}
if(name==null) name="[unnamed]";
}
return name;
}
public static Topic getLangTopic(Topic t,String lang) throws TopicMapException {
return t.getTopicMap().getTopic(XTMPSI.getLang(lang));
}
public static Topic getDisplayNameTopic(Topic t) throws TopicMapException {
return t.getTopicMap().getTopic(XTMPSI.DISPLAY);
}
public static Topic getSortNameTopic(Topic t) throws TopicMapException {
return t.getTopicMap().getTopic(XTMPSI.SORT);
}
public static Collection<Topic> getAssociatedTopics(Topic topic,Topic associationType,Topic topicRole,Topic associatedRole,String sortLang) throws TopicMapException {
Iterator<Association> iter=topic.getAssociations(associationType,topicRole).iterator();
Set<Topic> set=new LinkedHashSet<>();
while(iter.hasNext()){
Association a=iter.next();
Topic p=a.getPlayer(associatedRole);
if(p!=null) set.add(p);
}
if(sortLang==null) return set;
else return sortTopics(set,sortLang);
}
public static boolean isTopicOfType(Topic topic,Topic type) throws TopicMapException {
return topic.isOfType(type);
}
/**
* Sorts an array of topics by occurrence values.
*/
public static Collection<Topic> sortTopicsByData(Collection<Topic> topics, Topic dataType, String lang) throws TopicMapException {
return sortTopicsByData(topics,dataType,lang,false);
}
/**
* Sorts a collection of topics by occurrence values.
*/
public static Collection<Topic> sortTopicsByData(Collection<Topic> topics, Topic dataType, String lang,boolean desc) throws TopicMapException {
List<Topic> al=new ArrayList<>(topics.size());
al.addAll(topics);
Collections.sort(al,new DataValueComparator(dataType,lang,desc));
return al;
}
/**
* Sorts an array of topics by their display names. If a proper sort name
* is not found, other variants, base name or subject identifier is used.
*/
public static Topic[] sortTopics(Topic[] topics,String lang) {
/* TopicAndName[] a=new TopicAndName[topics.length];
for(int i=0;i<topics.length;i++){
a[i]=new TopicAndName(topics[i],lang);
}
quickSortTopics(a,0,a.length-1);
Topic[] ts=new Topic[a.length];
for(int i=0;i<a.length;i++){
ts[i]=a[i].topic;
}
return ts; */
List<Topic> al=new ArrayList<>();
al.addAll(Arrays.asList(topics));
Collections.sort(al,new TopicNameComparator(lang));
Topic[] ts=new Topic[topics.length];
for(int i=0;i<ts.length;i++){
ts[i]=al.get(i);
}
return ts;
}
/**
* Sorts a collection of topics by their display names. If a proper sort name
* is not found, other variants, base name or subject identifier is used.
*/
public static Collection<Topic> sortTopics(Collection<Topic> topics,String lang) {
/* TopicAndName[] a=new TopicAndName[topics.size()];
Iterator iter=topics.iterator();
int counter=0;
while(iter.hasNext()){
a[counter++]=new TopicAndName((Topic)iter.next(),lang);
}
quickSortTopics(a,0,a.length-1);
ArrayList al=new ArrayList(a.length);
for(int i=0;i<a.length;i++){
al.add(a[i].topic);
}
return al;*/
List<Topic> al=new ArrayList<>();
if(topics != null) {
try {
al.addAll(topics);
Collections.sort(al,new TopicNameComparator(lang));
} catch(Exception e){
System.out.println("Exception in sort topics: "+e.toString());
}
}
return al;
}
public static Collection<Association> sortAssociations(Collection<Association> associations, String lang, Topic role) {
List<Association> al=new ArrayList<>();
if(associations != null) {
al.addAll(associations);
Collections.sort(al,new AssociationTypeComparator(lang, role));
}
return al;
}
public static Collection<Association> sortAssociations(Collection<Association> associations, String lang) {
List<Association> al=new ArrayList<>();
if(associations != null) {
al.addAll(associations);
Collections.sort(al,new AssociationTypeComparator(lang));
}
return al;
}
public static Collection<Association> sortAssociations(Collection<Association> associations, Collection<Topic> ignoreTopics, String lang){
if(associations != null) {
try {
List<Association> al=new ArrayList<>(associations.size());
al.addAll(associations);
Collections.sort(al,new AssociationTypeComparator(lang, ignoreTopics));
return al;
}
catch (Exception e) {
return associations;
}
}
return new ArrayList<>();
}
/**
* Associations must be sorted first for this to work!
*/
public static Collection<Association> removeDuplicateAssociations(Collection<Association> associations, Collection<Topic> ignoreTopics) throws TopicMapException {
Iterator<Association> iter=associations.iterator();
Association last=null;
if(iter.hasNext()) last=iter.next();
else return associations;
while(iter.hasNext()){
Association a=iter.next();
boolean duplicate=false;
if(a.getType()==last.getType()){
Iterator<Topic> iter2=last.getRoles().iterator();
duplicate=true;
while(iter2.hasNext()){
Topic role=iter2.next();
Topic player1=last.getPlayer(role);
Topic player2=a.getPlayer(role);
boolean ignore1=ignoreTopics.contains(player1);
boolean ignore2=(player2==null?false:ignoreTopics.contains(player2));
if(player1!=player2 && (!ignore1 || !ignore2) ){
duplicate=false;
break;
}
}
}
if(duplicate){
iter.remove();
}
else{
last=a;
}
}
return associations;
}
public static void clearTopicMap(TopicMap topicMap) throws TopicMapException {
Iterator<Association> associationIter=topicMap.getAssociations();
List<Association> tobeDeletedAssociations=new ArrayList<>();
while(associationIter.hasNext()){
tobeDeletedAssociations.add(associationIter.next());
}
associationIter=tobeDeletedAssociations.iterator();
while(associationIter.hasNext()){
Association a=associationIter.next();
a.remove();
}
// we must do several passes because some topics are in use in other topics and can't be deleted right away
// collect all topics in a new list to avoid ConcurrentModificationException
Iterator<Topic> topicIter=topicMap.getTopics();
List<Topic> tobeDeletedTopics=new ArrayList<>();
while(topicIter.hasNext()){
Topic t=topicIter.next();
tobeDeletedTopics.add(t);
}
topicIter=tobeDeletedTopics.iterator();
while(topicIter.hasNext()){
Topic t=topicIter.next();
if(t.isDeleteAllowed()){
try{
t.remove();
}catch(TopicInUseException e){}
}
else{
Iterator<Set<Topic>> scopeIter=new ArrayList<>(t.getVariantScopes()).iterator();
while(scopeIter.hasNext()){
Set<Topic> c=scopeIter.next();
t.removeVariant(c);
}
Iterator<Topic> typeIter=new ArrayList<>(t.getTypes()).iterator();
while(typeIter.hasNext()){
Topic ty=typeIter.next();
t.removeType(ty);
}
Iterator<Topic> dataTypeIter=new ArrayList<>(t.getDataTypes()).iterator();
while(dataTypeIter.hasNext()){
Topic ty=dataTypeIter.next();
t.removeData(ty);
}
}
}
topicIter=topicMap.getTopics();
tobeDeletedTopics=new ArrayList<>();
while(topicIter.hasNext()){
Topic t=topicIter.next();
tobeDeletedTopics.add(t);
}
topicIter=tobeDeletedTopics.iterator();
while(topicIter.hasNext()){
Topic t=topicIter.next();
if(t.isDeleteAllowed()){
try{
t.remove();
}catch(TopicInUseException e){}
}
}
}
/* private static void quickSortTopics(TopicAndName[] o,int a,int b){
if(a>=b) return;
int pivot=(a+b)/2;
int l=a-1,r=b;
TopicAndName p=o[pivot];
TopicAndName t;
o[pivot]=o[b];
o[b]=p;
while(l<r){
while(o[++l].compareTo(p)<0 && l<r) ;
while(o[--r].compareTo(p)>0 && l<r) ;
if(l<r){
t=o[l];
o[l]=o[r];
o[r]=t;
}
}
t=o[l];
o[l]=o[b];
o[b]=t;
quickSortTopics(o,a,l-1);
quickSortTopics(o,l+1,b);
}
*/
/**
* A topic comparator that orders topics by the lexicographical ordering of
* specified data values. Constructor needs the data type and version to use.
*/
public static class DataValueComparator implements Comparator<Topic> {
private Topic dataType;
private Topic lang;
private Topic langIndep;
private boolean desc;
public DataValueComparator(Topic dataType,String lang,boolean desc) throws TopicMapException {
this(dataType,lang==null?null:dataType.getTopicMap().getTopic(XTMPSI.getLang(lang)),desc);
}
public DataValueComparator(Topic dataType,Topic lang,boolean desc) throws TopicMapException {
this.dataType=dataType;
this.lang=lang;
this.desc=desc;
langIndep=dataType.getTopicMap().getTopic(TMBox.LANGINDEPENDENT_SI);
}
public int compare(Topic t1, Topic t2) {
String d1=null;
String d2=null;
try{
if(lang!=null){
d1=t1.getData(dataType,lang);
d2=t2.getData(dataType,lang);
}
if(d1==null) d1=t1.getData(dataType,langIndep);
if(d2==null) d2=t2.getData(dataType,langIndep);
}catch(TopicMapException tme){tme.printStackTrace();}
int r;
if(d1!=null && d2!=null) r=d1.compareTo(d2);
else if(d1==null && d2!=null) r=1;
else if(d1!=null && d2==null) r=-1;
else r=0;
if(desc) return -r;
else return r;
}
}
/**
* A topic comparator that orders topics by their names. Sort names are
* used when available, otherwise display names are
* used. If no suitable variant names are present base names are used. You can also
* force the use of base names by specifying null language.
*/
public static class TopicNameComparator implements Comparator<Topic> {
private Map<Topic,String> nameCache;
private String lang;
private boolean desc;
public TopicNameComparator(String lang){
this(lang,false);
}
public TopicNameComparator(String lang,boolean desc){
nameCache=new HashMap<>();
this.lang=lang;
this.desc=desc;
}
public String getTopicName(Topic topic) throws TopicMapException {
String name=(String)nameCache.get(topic);
if(name!=null) return name;
if(lang==null) name=topic.getBaseName();
else name=TMBox.getTopicSortName(topic,lang);
if(name!=null) name=name.toLowerCase();
else name="";
nameCache.put(topic,name);
return name;
}
public int compare(Topic t1, Topic t2) {
String n1="";
String n2="";
try{
n1=getTopicName(t1);
n2=getTopicName(t2);
}catch(TopicMapException tme){
tme.printStackTrace(); // TODO EXCEPTION
}
int c=n1.compareTo(n2);
if(c==0) c=(t1.hashCode()<t2.hashCode()?-1:(t1.hashCode()==t2.hashCode()?0:1));
if(desc) return -c;
else return c;
}
}
public static class TopicBNAndSIComparator implements Comparator<Topic> {
private static Locator findLeastLocator(Collection<Locator> c){
Locator least=null;
for(Locator l : c){
if(least==null || l.compareTo(least)<0) least=l;
}
return least;
}
@Override
public int compare(Topic t1, Topic t2) {
try{
String bn1=t1.getBaseName();
String bn2=t2.getBaseName();
if(bn2==null && bn1!=null) return -1;
else if(bn1==null && bn2!=null) return 1;
else if(bn1!=null && bn2!=null){
int c=bn1.compareTo(bn2);
if(c!=0) return c;
}
Locator l1=findLeastLocator(t1.getSubjectIdentifiers());
Locator l2=findLeastLocator(t2.getSubjectIdentifiers());
if(l2==null && l1!=null) return -1;
else if(l1==null && l2!=null) return 1;
else if(l1==null && l2==null) return 0;
else return l1.compareTo(l2);
}
catch(TopicMapException tme){
tme.printStackTrace();
return 0;
}
}
}
public static class TopicSIComparator implements Comparator<Topic> {
@Override
public int compare(Topic t1, Topic t2) {
try{
Locator l1=t1.getFirstSubjectIdentifier();
Locator l2=t2.getFirstSubjectIdentifier();
if(l2==null && l1!=null) return -1;
else if(l1==null && l2!=null) return 1;
else if(l1==null && l2==null) return 0;
else return l1.compareTo(l2);
}
catch(TopicMapException tme){
tme.printStackTrace();
return 0;
}
}
}
/**
* Sorts associations by
* <ul>
* <li>first comparing association types</li>
* <li>then if ignoreTopics was specified, compare players of first roles that are not in ignoreTopics</li>
* <li>then compare role set sizes</li>
* <li>finally compare all roles and players, but only if the fullCompare is set to true, otherwise
* comparison ends at previous step, this last step is fairly computationally expensive
* as the role lists themselves have to be sorted first</li>
* </ul>
* Topic comparisons and player ordering is done with the specified topicComparator.
*/
public static class AssociationTypeComparator implements Comparator<Association> {
private Collection<Topic> ignoreTopics;
private Comparator<Topic> topicComparator;
private Topic compareRole;
private boolean fullCompare=false; // full compare can be a very heavy operation, only do it if specifically asked to
public AssociationTypeComparator(String lang){
this(new TopicNameComparator(lang));
}
public AssociationTypeComparator(String lang,Collection<Topic> ignoreTopics){
this(new TopicNameComparator(lang),ignoreTopics);
}
public AssociationTypeComparator(Comparator<Topic> topicComparator){
this.topicComparator=topicComparator;
}
public AssociationTypeComparator(Comparator<Topic> topicComparator, Collection<Topic> ignoreTopics){
this.topicComparator=topicComparator;
this.ignoreTopics=ignoreTopics;
this.compareRole=null;
}
public AssociationTypeComparator(String lang, Topic roleTopic){
this(new TopicNameComparator(lang),roleTopic);
}
public AssociationTypeComparator(Comparator<Topic> topicComparator, Topic roleTopic){
this.topicComparator=topicComparator;
this.ignoreTopics=null;
this.compareRole=roleTopic;
}
public void setFullCompare(boolean full){
this.fullCompare=full;
}
public int compare(Association a1, Association a2) {
if(compareRole != null) {
try {
Topic p1=a1.getPlayer(compareRole);
Topic p2=a2.getPlayer(compareRole);
if(p1 == null && p2 == null) return 0;
if(p1 == null && p2 != null) return -1;
if(p1 != null && p2 == null) return 1;
return topicComparator.compare(p1,p2);
}
catch(Exception e) {
e.printStackTrace();
return 0;
}
}
else {
try{
Topic t1=a1.getType();
Topic t2=a2.getType();
if(t1==null) return -1;
else if(t2==null) return 1;
int c=topicComparator.compare(t1,t2);
if(c==0){
if(ignoreTopics!=null){
Topic p1=null,p2=null;
Topic minRole=null;
Iterator<Topic> iter=a1.getRoles().iterator();
while(iter.hasNext()){
Topic role=iter.next();
Topic p=a1.getPlayer(role);
if(!ignoreTopics.contains(p) && (minRole==null || topicComparator.compare(role,minRole)<0)) {
minRole=role;
p1=p;
}
}
minRole=null;
iter=a2.getRoles().iterator();
while(iter.hasNext()){
Topic role=iter.next();
Topic p=a2.getPlayer(role);
if(!ignoreTopics.contains(p) && (minRole==null || topicComparator.compare(role,minRole)<0)) {
minRole=role;
p2=p;
}
}
if(p1!=null && p2!=null){
c=topicComparator.compare(p1,p2);
if(c!=0) return c;
}
}
if(a1.getRoles().size()<a2.getRoles().size()) return -1;
else if(a1.getRoles().size()==a2.getRoles().size()) {
if(!this.fullCompare) return 0;
List<Topic> r1=new ArrayList<>(a1.getRoles());
List<Topic> r2=new ArrayList<>(a2.getRoles());
Collections.sort(r1,topicComparator);
Collections.sort(r2,topicComparator);
for(int i=0;i<r1.size();i++){
c=topicComparator.compare(r1.get(i),r2.get(i));
if(c!=0) return c;
}
for(int i=0;i<r1.size();i++){
Topic p1=a1.getPlayer(r1.get(i));
Topic p2=a2.getPlayer(r2.get(i));
c=topicComparator.compare(p1,p2);
if(c!=0) return c;
}
return 0;
}
else return 1;
}
else return c;
}catch(TopicMapException tme){tme.printStackTrace();return 0;} // TODO EXCEPTION
}
}
}
/**
* Topic comparator that compares by comparing topics playing a specified role
* in an association of specified type. The players of topics are compared by
* comparing their sort or display names or base names if no language is specified
* or no other suitable variant name is found. The first player is used for
* ordering if there are multiple associations with suitable players (first player
* when comparing players by their names).
*/
public static class TopicAssociationPlayerComparator implements Comparator<Topic> {
private Topic associationType;
private Topic playerRole;
private Map<Topic,String> nameMap;
private String lang;
public TopicAssociationPlayerComparator(Topic associationType,Topic playerRole,String lang){
this.associationType=associationType;
this.playerRole=playerRole;
this.lang=lang;
nameMap=new HashMap<>();
}
public String getNameFor(Topic t){
String ret=nameMap.get(t);
if(ret==null){
try{
String min=null;
for(Association a : t.getAssociations(associationType)){
Topic p=a.getPlayer(playerRole);
String name=null;
if(lang==null) name=p.getBaseName();
else name=TMBox.getTopicSortName(p,lang);
if(name!=null) name=name.toLowerCase();
else name="";
if(min==null || name.compareTo(min)<0) min=name;
}
if(min==null) min="";
ret=min;
}
catch(TopicMapException tme){
tme.printStackTrace();
ret="";
}
nameMap.put(t,ret);
}
return ret;
}
public int compare(Topic t1,Topic t2){
return getNameFor(t1).compareTo(getNameFor(t2));
}
}
/**
* Association comparator that compares associations by comparing topics of
* the specified role. Topics are compared by comparing their sort or display
* names or base names if language is not specified or no suitable variant
* name is found.
*/
public static class AssociationPlayerComparator implements Comparator<Association> {
private Topic playerRole;
private Map<Association,String> nameMap;
private String lang;
public AssociationPlayerComparator(Topic playerRole,String lang){
this.playerRole=playerRole;
this.lang=lang;
nameMap=new HashMap<>();
}
public String getNameFor(Association a){
String ret=nameMap.get(a);
if(ret==null){
try{
Topic p=a.getPlayer(playerRole);
ret=null;
if(p==null) ret="";
else{
if(lang==null) ret=p.getBaseName();
else ret=TMBox.getTopicSortName(p,lang);
if(ret!=null) ret=ret.toLowerCase();
else ret="";
}
}
catch(TopicMapException tme){
tme.printStackTrace();
ret="";
}
nameMap.put(a,ret);
}
return ret;
}
public int compare(Association a1,Association a2){
return getNameFor(a1).compareTo(getNameFor(a2));
}
}
public static class ScopeComparator implements Comparator<Set<Topic>> {
private Comparator<Topic> topicComparator;
public ScopeComparator(){
this(new TopicNameComparator(null));
}
public ScopeComparator(Comparator<Topic> topicComparator){
this.topicComparator=topicComparator;
}
@Override
public int compare(Set<Topic> o1, Set<Topic> o2) {
if(o1.size()<o2.size()) return -1;
else if(o1.size()>o2.size()) return 1;
ArrayList<Topic> s1=new ArrayList<Topic>(o1);
ArrayList<Topic> s2=new ArrayList<Topic>(o2);
Collections.sort(s1,topicComparator);
Collections.sort(s2,topicComparator);
for(int i=0;i<s1.size();i++){
int c=topicComparator.compare(s1.get(i), s2.get(i));
if(c!=0) return c;
}
return 0;
}
}
}
| 66,578 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
Test.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/Test.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* Test.java
*
* Created on June 10, 2004, 4:28 PM
*/
package org.wandora.topicmap;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import org.wandora.topicmap.memory.TopicMapImpl;
/**
*
* @author olli
*/
public class Test {
/** Creates a new instance of Test */
public Test() {
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws Exception {
TopicMap tm=new TopicMapImpl();
System.out.println("Reading inital topic map from "+args[0]);
InputStream in=new FileInputStream(args[0]);
tm.importXTM(in);
in.close();
for(int i=1;i<args.length-1;i++){
System.out.println("Reading next topic map from "+args[i]);
TopicMap next=new TopicMapImpl();
in=new FileInputStream(args[i]);
next.importXTM(in);
in.close();
System.out.println("Merging");
tm.mergeIn(next);
}
if(args.length>1){
System.out.println("Exporting to "+args[args.length-1]);
OutputStream out=new FileOutputStream(args[args.length-1]);
tm.exportXTM(out);
out.close();
}
}
}
| 2,118 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
Topic.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/Topic.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* Topic.java
*
* Created on June 10, 2004, 11:12 AM
*/
package org.wandora.topicmap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/**
* <p>
* The abstract Topic class. Each topic implementation should extend this class.
* </p><p>
* Note that you should not store Topic objects except for very short times. Topics may be removed or
* merged at any time and the topic objects will become invalid. If you are doing something where this
* can happen, be sure to check if the topic is invalid with the isRemoved method. If it returns true,
* the topic may have been removed from the topic map or it might have been merged with some other topic.
* You can get this possible other topic with TopicMap.getTopic which will need the subject identifier
* of the topic, which means that usually it is better to just store the subject identifiers instead
* of the topics in the first place.
* </p><p>
* Many methods may cause topic merges in the topic map. Such methods include addSubjectIdentifier,
* setBaseName and setSubjectLocator. If a merge occurs, the merge will be handled in such a way that
* the object whose method was called will stay a valid topic object. In other words, other merging
* topics will be merged into it instead of the other way around.
* </p>
* @author olli
*/
public abstract class Topic {
/**
* Gets the topic ID. Topic id is unique in the topic map. It cannot be changed
* after topic creation and is generally not visible to the user. It can be used
* when exporting topic map into XTM or storing it in a database.
*/
public abstract String getID() throws TopicMapException ;
/** Gets all subject identifiers of the topic. */
public abstract Collection<Locator> getSubjectIdentifiers() throws TopicMapException ;
/** Adds a subject identifier for the topic. This may cause a topic merge. */
public abstract void addSubjectIdentifier(Locator l) throws TopicMapException ;
/** Removes a subject identifier. */
public abstract void removeSubjectIdentifier(Locator l) throws TopicMapException ;
/** Gets the topic base name or null if no base name has been set. */
public abstract String getBaseName() throws TopicMapException ;
/** Sets the topic base name. This may cause a topic merge. */
public abstract void setBaseName(String name) throws TopicMapException ;
/** Gets all topic types. */
public abstract Collection<Topic> getTypes() throws TopicMapException ;
/** Adds a topic type. If topic already has that type, does nothing.*/
public abstract void addType(Topic t) throws TopicMapException ;
/** Removes a topic type. If topic is not of the specified type, does nothing. */
public abstract void removeType(Topic t) throws TopicMapException ;
/** Checks if this topic is of the specified type. */
public abstract boolean isOfType(Topic t) throws TopicMapException ;
/**
* Gets a variant with the specified scope. The scope must be a Collection of Topics.
* Returns null if there is no variant with the specified scope.
*/
public abstract String getVariant(Set<Topic> scope) throws TopicMapException ;
/**
* Sets the variant with the specified scope. Will overwrite previous value
* if there already is a variant name with the specified scope.
*/
public abstract void setVariant(Set<Topic> scope,String name) throws TopicMapException ;
/** Gets the scopes of all variant names. */
public abstract Set<Set<Topic>> getVariantScopes() throws TopicMapException ;
/** Removes a variant name with the specified scope. If no such variant exists, does nothing. */
public abstract void removeVariant(Set<Topic> scope) throws TopicMapException ;
/** Gets data with the specified type and version. Returns null if data is not found. */
public abstract String getData(Topic type,Topic version) throws TopicMapException ;
/** Returns a Hashtable mapping data versions to data content. */
public abstract Hashtable<Topic,String> getData(Topic type) throws TopicMapException ;
/** Gets all used data types. */
public abstract Collection<Topic> getDataTypes() throws TopicMapException ;
/** Sets several data values. Each value is set with same type, the other parameter
should contain versions mapped to the actual values. */
public abstract void setData(Topic type,Hashtable<Topic,String> versionData) throws TopicMapException ;
/** Sets data with specified type and version. */
public abstract void setData(Topic type,Topic version,String value) throws TopicMapException ;
/** Removes data with specified type and version. If no such data value is set, does nothing. */
public abstract void removeData(Topic type,Topic version) throws TopicMapException ;
/** Removes all data with the specified type. */
public abstract void removeData(Topic type) throws TopicMapException ;
/** Gets the topic subject locator or null if it has not been set. */
public abstract Locator getSubjectLocator() throws TopicMapException ;
/** Sets the topic subject locator overwriting possible previous value. */
public abstract void setSubjectLocator(Locator l) throws TopicMapException ;
/** Gets the topic map this topic belongs to. */
public abstract TopicMap getTopicMap();
/** Gets all associations where this topic is a player. */
public abstract Collection<Association> getAssociations() throws TopicMapException ;
/** Gets all associations of specified type where this topic is a player. */
public abstract Collection<Association> getAssociations(Topic type) throws TopicMapException ;
/** Gets associations of the specified type where this topic is in the specified role */
public abstract Collection<Association> getAssociations(Topic type,Topic role) throws TopicMapException ;
/**
* Removes this topic. If this topic is used in any association as the association type or role of any member
* or this topic is used in any topic in variant scope, data version, data type or topic type,
* a TopicInUseException is thrown. This topic may however be used as a player of associations. All such
* associations are deleted along with this topic.
*/
public abstract void remove() throws TopicMapException;
public abstract long getEditTime() throws TopicMapException ;
public abstract void setEditTime(long time) throws TopicMapException ;
public abstract long getDependentEditTime() throws TopicMapException ;
public abstract void setDependentEditTime(long time) throws TopicMapException ;
/**
* Returns true if this topic has been removed from the topic map it belonged to. Note that it might
* have been removed as a result of topics being merged and still exists in the topic map but as another
* topic object.
*/
public abstract boolean isRemoved() throws TopicMapException ;
/**
* Returns true if and only if remove() can be called without it throwing TopicInUseException. This
* is exactly when this topic is not used in any association as the association type or role of any member,
* and this topic is not used in any topic in variant scope, data version, data type or topic type.
* This topic may however be used as a player of associations.
*/
public abstract boolean isDeleteAllowed() throws TopicMapException ;
/** Gets topics which have data with this topic as type. */
public abstract Collection<Topic> getTopicsWithDataType() throws TopicMapException ;
/** Gets topics which have data with this topic as version. */
public abstract Collection<Topic> getTopicsWithDataVersion() throws TopicMapException ;
/** Gets associations that have this topic as type. */
public abstract Collection<Association> getAssociationsWithType() throws TopicMapException ;
/** Gets associations that have this topic as role. */
public abstract Collection<Association> getAssociationsWithRole() throws TopicMapException ;
/** Gets topics which have variants with this topic in scope. */
public abstract Collection<Topic> getTopicsWithVariantScope() throws TopicMapException ;
/**
* Gets data with the specified type and language version. If data with the specified language is not found
* tries to get data with language independent version (WandoraManage.LANGINDEPENDENT_SI). If that is not
* found tries to get data of the specified type with any version. Use getData(Topic,Topic) to get the
* data with specified type and version or null if it does not exist.
*/
public String getData(Topic type,String lang) throws TopicMapException {
String langsi=XTMPSI.getLang(lang);
Topic langT=getTopicMap().getTopic(langsi);
String data=null;
if(langT!=null) {
data=getData(type,langT);
}
if(data==null){
langT=getTopicMap().getTopic(TMBox.LANGINDEPENDENT_SI);
if(langT!=null){
data=getData(type,langT);
}
if(data==null){
Hashtable<Topic,String> ht=getData(type);
if(ht==null || ht.isEmpty()) return null;
Iterator<String> iter=ht.values().iterator();
if(iter.hasNext()) data=iter.next();
}
}
return data;
}
/**
* Sets a variant with scope containing the display topic and the language topic of the specified
* language.
*/
public void setDisplayName(String lang,String name) throws TopicMapException {
if(getTopicMap().isReadOnly()) throw new TopicMapReadOnlyException();
String langsi=XTMPSI.getLang(lang);
Topic langT=getTopicMap().getTopic(langsi);
String dispsi=XTMPSI.DISPLAY;
Topic dispT=getTopicMap().getTopic(dispsi);
Set<Topic> scope=new HashSet<>();
if(langT==null) {
langT=getTopicMap().createTopic();
langT.addSubjectIdentifier(getTopicMap().createLocator(langsi));
}
scope.add(langT);
if(dispT==null) {
dispT=getTopicMap().createTopic();
dispT.addSubjectIdentifier(getTopicMap().createLocator(dispsi));
}
scope.add(dispT);
setVariant(scope,name);
}
/**
* Gets a display name for English language. Calls getDisplayName(String) with parameter
* "en".
* @see #getDisplayName(String)
*/
public String getDisplayName() throws TopicMapException {
return getDisplayName("en");
}
/**
* Gets a name suitable for display in the specified language. This method will call getName with
* a scope containing the display topic and the language topic of the specified language. Will first
* try to get a variant with this exact scope but if one is not found, may return a variant with almost
* this scope or base name or subject identifier.
*/
public String getDisplayName(String lang) throws TopicMapException {
String langsi=XTMPSI.getLang(lang);
Topic langT=getTopicMap().getTopic(langsi);
String dispsi=XTMPSI.DISPLAY;
Topic dispT=getTopicMap().getTopic(dispsi);
Set<Topic> scope=new HashSet<>();
if(langT!=null) scope.add(langT);
if(dispT!=null) scope.add(dispT);
return getName(scope);
}
/**
* Gets a name suitable for sorting in the specified language. This method will call getName with
* a scope containing the sort topic and the language topic of the specified language. Will first
* try to get a variant with this exact scope but if one is not found, may return a variant with almost
* this scope or base name or subject identifier.
*/
public String getSortName(String lang) throws TopicMapException {
String langsi=XTMPSI.getLang(lang);
Topic langT=getTopicMap().getTopic(langsi);
String sortsi=XTMPSI.SORT;
Topic sortT=getTopicMap().getTopic(sortsi);
Set<Topic> scope=new HashSet<>();
if(langT!=null) scope.add(langT);
if(sortT!=null) scope.add(sortT);
return getName(scope);
}
/**
* Gets a name for the topic. Tries to get a name that matches the scope as much as possible.
* If a suitable name is not found in variants, returns the base name, if it is null returns
* one of the subject identifiers, if there is none returns "[unnamed]".
*/
public String getName(Set<Topic> scope) throws TopicMapException {
String name=null;
try {
if(scope != null) name=getVariant(scope);
if(name==null || name.trim().length()==0){
int maxcount=0;
Set<Set<Topic>> scopes=getVariantScopes();
if(scopes != null) {
Iterator<Set<Topic>> iter=scopes.iterator();
while(iter.hasNext()){
Set<Topic> s= iter.next();
String vname=getVariant(s);
if(vname==null || vname.trim().length()==0) continue;
int count=0;
if(scope != null) {
Iterator<Topic> iter2=scope.iterator();
while(iter2.hasNext()){
Topic t=iter2.next();
// if(s.contains(t)) count++;
Iterator<Topic> iter3=s.iterator();
while(iter3.hasNext()){
Topic st=iter3.next();
if(st.mergesWithTopic(t)){
count++;
break;
}
}
}
}
if(count>maxcount){
maxcount=count;
name=getVariant(s);
}
}
}
if(name==null || name.trim().length()==0) name=getBaseName();
if(name==null || name.trim().length()==0){
Collection<Locator> sis=getSubjectIdentifiers();
if(!sis.isEmpty()) name=(sis.iterator().next()).toExternalForm();
}
}
}
catch(Exception e) {
e.printStackTrace();
}
if(name==null || name.trim().length()==0) name="[unnamed]";
return name;
}
/** Returns one of the subject identifiers of this topic or null if none exists. */
public Locator getOneSubjectIdentifier() throws TopicMapException {
Collection<Locator> c=getSubjectIdentifiers();
if(c.size()>0) return c.iterator().next();
else return null;
}
/**
* Returns the subject identifier for the topic that is the first in
* lexicographical ordering. This guarantees that you'll always
* get the same subject identifier as long as the subject identifiers of the
* topic have not changed between calls. This can be desirable in some
* situations. However, there is a performance penalty in using this as
* opposed to getOneSubjectIdentifier.
*/
public Locator getFirstSubjectIdentifier() throws TopicMapException {
List<Locator> ls=new ArrayList<>(getSubjectIdentifiers());
if(ls.isEmpty()) return null;
if(ls.size()==1) return ls.get(0);
Locator least=null;
for(Locator l : ls) {
if(least==null || l.compareTo(least)<0) least=l;
}
return least;
}
/**
* Checks if this topic would merge with the topic given as parameter.
* The topic given as parameter may be from this or another topic map.
*/
public boolean mergesWithTopic(Topic topic) throws TopicMapException {
if(topic==null) return false;
if(this==topic) return true;
if(getBaseName()!=null && topic.getBaseName()!=null && getBaseName().equals(topic.getBaseName()))
return true;
Collection<Locator> tsis=topic.getSubjectIdentifiers();
for(Locator l : getSubjectIdentifiers()) {
if(tsis.contains(l)) return true;
}
if(getSubjectLocator()!=null && topic.getSubjectLocator()!=null && getSubjectLocator().equals(topic.getSubjectLocator()))
return true;
return false;
}
/**
* Gets name of this topic suitable for display. Uses getDisplayName to do this.
* @see #getDisplayName()
*/
@Override
public String toString(){
try{
return getDisplayName();
}
catch(TopicMapException tme){
tme.printStackTrace();
return "<Exception>";
}
}
}
| 17,909 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TopicMapListenerAdapter.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/TopicMapListenerAdapter.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* TopicMapListenerAdapter.java
*
* Created on 26. toukokuuta 2006, 13:16
*
*/
package org.wandora.topicmap;
import java.util.Collection;
/**
*
* @author olli
*/
public abstract class TopicMapListenerAdapter implements TopicMapListener {
public void topicChanged(Topic t) throws TopicMapException{
}
public void topicRemoved(Topic t) throws TopicMapException{
}
public void associationChanged(Association a) throws TopicMapException{
}
public void associationRemoved(Association a) throws TopicMapException{
}
public void topicSubjectIdentifierChanged(Topic t,Locator added,Locator removed) throws TopicMapException{
topicChanged(t);
}
public void topicBaseNameChanged(Topic t,String newName,String oldName) throws TopicMapException{
topicChanged(t);
}
public void topicTypeChanged(Topic t,Topic added,Topic removed) throws TopicMapException {
topicChanged(t);
}
public void topicVariantChanged(Topic t,Collection<Topic> scope,String newName,String oldName) throws TopicMapException {
topicChanged(t);
}
public void topicDataChanged(Topic t,Topic type,Topic version,String newValue,String oldValue) throws TopicMapException {
topicChanged(t);
}
public void topicSubjectLocatorChanged(Topic t,Locator newLocator,Locator oldLocator) throws TopicMapException {
topicChanged(t);
}
public void associationTypeChanged(Association a,Topic newType,Topic oldType) throws TopicMapException {
associationChanged(a);
}
public void associationPlayerChanged(Association a,Topic role,Topic newPlayer,Topic oldPlayer) throws TopicMapException {
associationChanged(a);
}
}
| 2,659 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TopicMapSearchOptions.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/TopicMapSearchOptions.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* TopicMapSearchOptions.java
*
* Created on 24. helmikuuta 2006, 20:24
*
*/
package org.wandora.topicmap;
/**
*
* @author akivela
*/
public class TopicMapSearchOptions {
public boolean searchBasenames = false;
public boolean searchVariants = false;
public boolean searchOccurrences = false;
public boolean searchSIs = false;
public boolean searchSL = false;
// different topic map implementations may or may not respect this,
// so if you absolutely don't want more results, do check the size
// of the final result yourself
public int maxResults=-1;
public TopicMapSearchOptions(boolean searchBasenames, boolean searchVariants, boolean searchOccurrences, boolean searchSIs, boolean searchSL) {
this(searchBasenames, searchVariants, searchOccurrences, searchSIs, searchSL, -1);
}
public TopicMapSearchOptions(boolean searchBasenames, boolean searchVariants, boolean searchOccurrences, boolean searchSIs, boolean searchSL,int maxResults) {
this.searchBasenames = searchBasenames;
this.searchVariants = searchVariants;
this.searchOccurrences = searchOccurrences;
this.searchSIs = searchSIs;
this.searchSL = searchSL;
this.maxResults=maxResults;
}
public TopicMapSearchOptions() {
this.searchBasenames = true;
this.searchVariants = true;
this.searchOccurrences = true;
this.searchSIs = true;
this.searchSL = true;
this.maxResults = -1;
}
public TopicMapSearchOptions duplicate(){
return new TopicMapSearchOptions(searchBasenames, searchVariants, searchOccurrences, searchSIs, searchSL, maxResults);
}
}
| 2,519 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
W2TAssociation.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/wandora2tmapi/W2TAssociation.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2013 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.topicmap.wandora2tmapi;
import java.util.HashSet;
import java.util.Set;
import org.tmapi.core.Association;
import org.tmapi.core.Locator;
import org.tmapi.core.ModelConstraintException;
import org.tmapi.core.Role;
import org.tmapi.core.TMAPIRuntimeException;
import org.tmapi.core.Topic;
import org.tmapi.core.TopicMap;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author olli
*/
public class W2TAssociation implements Association {
protected W2TTopicMap tm;
protected org.wandora.topicmap.Association a;
public W2TAssociation(W2TTopicMap tm,org.wandora.topicmap.Association a){
this.tm=tm;
this.a=a;
}
public org.wandora.topicmap.Association getWrapped(){
return a;
}
@Override
public TopicMap getParent() {
return tm;
}
@Override
public Set<Role> getRoles() {
try{
HashSet<Role> ret=new HashSet<Role>();
for(org.wandora.topicmap.Topic role : a.getRoles() ){
org.wandora.topicmap.Topic player=a.getPlayer(role);
ret.add(new W2TRole(this, new W2TTopic(tm,role), new W2TTopic(tm,player)));
}
return ret;
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
@Override
public Set<Topic> getRoleTypes() {
try{
return tm.wrapTopics(a.getRoles());
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
@Override
public Set<Role> getRoles(Topic type) {
try{
org.wandora.topicmap.Topic player=a.getPlayer(((W2TTopic)type).t);
HashSet<Role> ret=new HashSet<Role>();
if(player!=null) ret.add(new W2TRole(this, (W2TTopic)type, new W2TTopic(tm,player)));
return ret;
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
@Override
public Role createRole(Topic type, Topic player) throws ModelConstraintException {
try{
if(a.getPlayer(((W2TTopic)type).getWrapped())!=null)
throw new UnsupportedOperationException("Multiple players with same role in an association are not supported");
a.addPlayer(((W2TTopic)player).getWrapped(), ((W2TTopic)type).getWrapped());
return new W2TRole(this,(W2TTopic)type,(W2TTopic)player);
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
@Override
public Topic getReifier() {
return null;
}
@Override
public void setReifier(Topic topic) throws ModelConstraintException {
throw new UnsupportedOperationException("Reification not supported");
}
@Override
public TopicMap getTopicMap() {
return tm;
}
@Override
public String getId() {
return null;
}
@Override
public Set<Locator> getItemIdentifiers() {
return new HashSet<Locator>();
}
@Override
public void addItemIdentifier(Locator lctr) throws ModelConstraintException {
throw new UnsupportedOperationException("Item identifiers not supported");
}
@Override
public void removeItemIdentifier(Locator lctr) {
// There will never be any item identifiers so nothing needs to be done
}
@Override
public void remove() {
try{
a.remove();
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
@Override
public Topic getType() {
try{
return new W2TTopic(tm,a.getType());
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
@Override
public void setType(Topic topic) {
try{
a.setType(((W2TTopic)topic).getWrapped());
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
@Override
public Set<Topic> getScope() {
return new HashSet<Topic>();
}
@Override
public void addTheme(Topic topic) throws ModelConstraintException {
throw new UnsupportedOperationException("Scoped associations not supported");
}
@Override
public void removeTheme(Topic topic) {
// there is no themes in the scope so nothing needs to be done
}
}
| 5,240 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
W2TName.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/wandora2tmapi/W2TName.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2013 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.topicmap.wandora2tmapi;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.tmapi.core.Locator;
import org.tmapi.core.ModelConstraintException;
import org.tmapi.core.Name;
import org.tmapi.core.TMAPIRuntimeException;
import org.tmapi.core.Topic;
import org.tmapi.core.TopicMap;
import org.tmapi.core.Variant;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author olli
*/
public class W2TName implements Name {
protected W2TTopic t;
protected W2TTopicMap tm;
public W2TName(W2TTopicMap tm,W2TTopic t){
this.tm=tm;
this.t=t;
}
@Override
public Topic getParent() {
return t;
}
@Override
public String getValue() {
try{
return t.t.getBaseName();
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
@Override
public void setValue(String string) throws ModelConstraintException {
try{
t.getWrapped().setBaseName(string);
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
@Override
public Set<Variant> getVariants() {
try{
Set<Set<org.wandora.topicmap.Topic>> scopes=t.t.getVariantScopes();
HashSet<Variant> ret=new HashSet<Variant>();
for(Set<org.wandora.topicmap.Topic> scope : scopes){
ret.add(new W2TVariant(this,scope));
}
return ret;
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
@Override
public Variant createVariant(String string, Topic... scope) throws ModelConstraintException {
return createVariant(string,tm.createLocator(W2TTopicMap.TYPE_STRING_SI),scope);
}
@Override
public Variant createVariant(String string, Collection<Topic> scope) throws ModelConstraintException {
return createVariant(string,tm.createLocator(W2TTopicMap.TYPE_STRING_SI),scope.toArray(new Topic[0]));
}
@Override
public Variant createVariant(Locator lctr, Topic... scope) throws ModelConstraintException {
throw new UnsupportedOperationException("Only string variants are supported");
}
@Override
public Variant createVariant(Locator lctr, Collection<Topic> scope) throws ModelConstraintException {
throw new UnsupportedOperationException("Only string variants are supported");
}
@Override
public Variant createVariant(String string, Locator datatype, Topic... scope) throws ModelConstraintException {
org.wandora.topicmap.Topic _t=t.getWrapped();
HashSet<org.wandora.topicmap.Topic>_scope=new HashSet<>();
for(Topic s : scope){
_scope.add(((W2TTopic)s).getWrapped());
}
try{
_t.setVariant(_scope, string);
return new W2TVariant(this, _scope);
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
@Override
public Variant createVariant(String string, Locator datatype, Collection<Topic> scope) throws ModelConstraintException {
return createVariant(string,datatype,scope.toArray(new Topic[0]));
}
@Override
public Topic getType() {
return tm.getTopicBySubjectIdentifier(W2TTopicMap.TOPIC_NAME_SI);
}
@Override
public void setType(Topic topic) {
throw new UnsupportedOperationException("Name type cannot be changed");
}
@Override
public TopicMap getTopicMap() {
return tm;
}
@Override
public String getId() {
return null;
}
@Override
public Set<Locator> getItemIdentifiers() {
return new HashSet<Locator>();
}
@Override
public void addItemIdentifier(Locator lctr) throws ModelConstraintException {
throw new UnsupportedOperationException("Item identifiers not supported");
}
@Override
public void removeItemIdentifier(Locator lctr) {
}
@Override
public void remove() {
// This doesn't actually remove variants from the wandora model.
// See the notes about variants and null base names in W2TTopic.java
try{
t.getWrapped().setBaseName(null);
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
@Override
public Set<Topic> getScope() {
return new HashSet<Topic>();
}
@Override
public void addTheme(Topic topic) throws ModelConstraintException {
throw new UnsupportedOperationException("Scope not supported in names");
}
@Override
public void removeTheme(Topic topic) {
}
@Override
public Topic getReifier() {
return null;
}
@Override
public void setReifier(Topic topic) throws ModelConstraintException {
throw new UnsupportedOperationException("Reification not supported");
}
}
| 5,859 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
W2TLocator.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/wandora2tmapi/W2TLocator.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2013 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.topicmap.wandora2tmapi;
import org.tmapi.core.Locator;
import org.tmapi.core.MalformedIRIException;
/**
*
* @author olli
*/
public class W2TLocator implements Locator {
protected org.wandora.topicmap.Locator l;
public W2TLocator(org.wandora.topicmap.Locator l){
this.l=l;
}
public W2TLocator(String reference){
this(new org.wandora.topicmap.Locator(reference));
}
@Override
public String getReference() {
return l.getReference();
}
@Override
public String toExternalForm() {
return l.toExternalForm();
}
@Override
public Locator resolve(String string) throws MalformedIRIException {
if(string.startsWith("#")) return new W2TLocator(new org.wandora.topicmap.Locator(l.getNotation(),l.getReference()+string));
else return new W2TLocator(string);
}
// hashCode and equals implementations specified by tmapi
@Override
public int hashCode() {
return this.getReference().hashCode();
}
@Override
public boolean equals(Object other) {
return (other instanceof Locator && this.getReference().equals(((Locator)other).getReference()));
}
}
| 2,040 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
W2TRole.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/wandora2tmapi/W2TRole.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2013 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.topicmap.wandora2tmapi;
import java.util.HashSet;
import java.util.Set;
import org.tmapi.core.Association;
import org.tmapi.core.Locator;
import org.tmapi.core.ModelConstraintException;
import org.tmapi.core.Role;
import org.tmapi.core.TMAPIRuntimeException;
import org.tmapi.core.Topic;
import org.tmapi.core.TopicMap;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author olli
*/
public class W2TRole implements Role {
protected W2TAssociation association;
protected W2TTopic type;
protected W2TTopic player;
public W2TRole(W2TAssociation association,W2TTopic type,W2TTopic player){
this.association=association;
this.type=type;
this.player=player;
}
@Override
public Association getParent() {
return association;
}
@Override
public Topic getPlayer() {
return player;
}
@Override
public void setPlayer(Topic topic) {
org.wandora.topicmap.Association _a=association.getWrapped();
org.wandora.topicmap.Topic _type=type.getWrapped();
try{
// this replaces the old player
_a.addPlayer(_type, ((W2TTopic)topic).getWrapped());
player=(W2TTopic)topic;
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
@Override
public Topic getReifier() {
return null;
}
@Override
public void setReifier(Topic topic) throws ModelConstraintException {
throw new UnsupportedOperationException("Reification not supported");
}
@Override
public TopicMap getTopicMap() {
return type.tm;
}
@Override
public String getId() {
return null;
}
@Override
public Set<Locator> getItemIdentifiers() {
return new HashSet<Locator>();
}
@Override
public void addItemIdentifier(Locator lctr) throws ModelConstraintException {
throw new UnsupportedOperationException("Item identifiers not supported");
}
@Override
public void removeItemIdentifier(Locator lctr) {
}
@Override
public void remove() {
org.wandora.topicmap.Association _a=association.getWrapped();
org.wandora.topicmap.Topic _type=type.getWrapped();
try{
_a.removePlayer(_type);
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
@Override
public Topic getType() {
return type;
}
@Override
public void setType(Topic topic) {
org.wandora.topicmap.Association _a=association.getWrapped();
try{
_a.setType(((W2TTopic)topic).getWrapped());
type=(W2TTopic)topic;
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
}
| 3,665 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
W2TOccurrence.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/wandora2tmapi/W2TOccurrence.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2013 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.topicmap.wandora2tmapi;
import java.util.HashSet;
import java.util.Set;
import org.tmapi.core.Locator;
import org.tmapi.core.ModelConstraintException;
import org.tmapi.core.Occurrence;
import org.tmapi.core.TMAPIRuntimeException;
import org.tmapi.core.Topic;
import org.tmapi.core.TopicMap;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author olli
*/
public class W2TOccurrence extends AbstractDatatypeAware implements Occurrence {
protected W2TTopic t;
protected W2TTopic type;
protected W2TTopic language;
public W2TOccurrence(W2TTopic t,W2TTopic type,W2TTopic language){
this.t=t;
this.type=type;
this.language=language;
}
@Override
public Topic getParent() {
return t;
}
@Override
public Topic getType() {
return type;
}
@Override
public void setType(Topic topic) {
org.wandora.topicmap.Topic _topic=((W2TTopic)topic).getWrapped();
org.wandora.topicmap.Topic _t=t.getWrapped();
org.wandora.topicmap.Topic _type=type.getWrapped();
org.wandora.topicmap.Topic _language=(language==null?null:language.getWrapped());
try{
String value=_t.getData(_type,_language);
_t.removeData(_type, _language);
_t.setData(_topic, _language, value);
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
this.type=(W2TTopic)topic;
}
@Override
public TopicMap getTopicMap() {
return t.tm;
}
@Override
public String getId() {
return null;
}
@Override
public Set<Locator> getItemIdentifiers() {
return new HashSet<Locator>();
}
@Override
public void addItemIdentifier(Locator lctr) throws ModelConstraintException {
throw new UnsupportedOperationException("Item identifiers not supported");
}
@Override
public void removeItemIdentifier(Locator lctr) {
throw new UnsupportedOperationException("Item identifiers not supported");
}
@Override
public void remove() {
org.wandora.topicmap.Topic _t=t.getWrapped();
org.wandora.topicmap.Topic _type=type.getWrapped();
org.wandora.topicmap.Topic _language=(language==null?null:language.getWrapped());
try{
_t.removeData(_type, _language);
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
@Override
public Topic getReifier() {
return null;
}
@Override
public void setReifier(Topic topic) throws ModelConstraintException {
throw new UnsupportedOperationException("Reification not supported");
}
@Override
public Set<Topic> getScope() {
HashSet<Topic> ret=new HashSet<Topic>();
if(language!=null) ret.add(language);
return ret;
}
/*
Add Theme actually replaces the language topic instead of adding it. Remove
theme does nothing if the topic isn't the language topic and throws an exception
if it is. This guarantees that there is only a single topic in the scope at
all times but still allows the topic to be changed. addTheme and removeTheme
can still be called in succession as if to change a theme to another because
after addTheme removeTheme will do nothing.
*/
@Override
public void addTheme(Topic theme) throws ModelConstraintException {
org.wandora.topicmap.Topic _theme=((W2TTopic)theme).getWrapped();
org.wandora.topicmap.Topic _t=t.getWrapped();
org.wandora.topicmap.Topic _type=type.getWrapped();
org.wandora.topicmap.Topic _language=(language==null?null:language.getWrapped());
try{
String value=_t.getData(_type,_language);
_t.removeData(_type, _language);
_t.setData(_type, _theme, value);
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
this.language=(W2TTopic)theme;
}
@Override
public void removeTheme(Topic topic) {
try{
if(this.language!=null && this.language.getWrapped().mergesWithTopic(((W2TTopic)topic).getWrapped())){
throw new UnsupportedOperationException("Occurrences must have one theme topic");
}
// else do nothing, the topic isn't in the scope in the first place
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
@Override
public String getValue() {
try{
return t.t.getData(type.t, language!=null?language.t:null);
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
@Override
public void setValue(String s){
try {
t.t.setData(type.t, language!=null?language.t:null, s);
}catch(TopicMapException tme){
throw new RuntimeException(tme);
}
}
}
| 5,888 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AbstractDatatypeAware.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/wandora2tmapi/AbstractDatatypeAware.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2013 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.topicmap.wandora2tmapi;
import java.math.BigDecimal;
import java.math.BigInteger;
import org.tmapi.core.DatatypeAware;
import org.tmapi.core.Locator;
import org.tmapi.core.ModelConstraintException;
/**
*
* @author olli
*/
public abstract class AbstractDatatypeAware implements DatatypeAware {
@Override
public Locator getDatatype() {
return new W2TLocator(W2TTopicMap.TYPE_STRING_SI);
}
@Override
public abstract String getValue();
@Override
public abstract void setValue(String s);
@Override
public void setValue(Locator lctr) throws ModelConstraintException {
setValue(lctr.toString());
}
@Override
public void setValue(String string, Locator lctr) throws ModelConstraintException {
setValue(string);
}
@Override
public void setValue(BigDecimal bd) throws ModelConstraintException {
setValue(bd.toString());
}
@Override
public void setValue(BigInteger bi) throws ModelConstraintException {
setValue(bi.toString());
}
@Override
public void setValue(long l) {
setValue(Long.toString(l));
}
@Override
public void setValue(float f) {
setValue(Float.toString(f));
}
@Override
public void setValue(int i) {
setValue(Integer.toString(i));
}
@Override
public int intValue() {
return Integer.parseInt(getValue());
}
@Override
public BigInteger integerValue() {
return new BigInteger(getValue());
}
@Override
public float floatValue() {
return Float.parseFloat(getValue());
}
@Override
public BigDecimal decimalValue() {
return new BigDecimal(getValue());
}
@Override
public long longValue() {
return Long.parseLong(getValue());
}
@Override
public Locator locatorValue() {
throw new IllegalArgumentException();
}
}
| 2,757 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
W2TVariant.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/wandora2tmapi/W2TVariant.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2013 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.topicmap.wandora2tmapi;
import java.util.HashSet;
import java.util.Set;
import org.tmapi.core.Locator;
import org.tmapi.core.ModelConstraintException;
import org.tmapi.core.Name;
import org.tmapi.core.Topic;
import org.tmapi.core.TopicMap;
import org.tmapi.core.Variant;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author olli
*/
public class W2TVariant extends AbstractDatatypeAware implements Variant {
protected W2TName name;
protected W2TTopic t;
protected Set<org.wandora.topicmap.Topic> scope;
public W2TVariant(W2TName name,Set<org.wandora.topicmap.Topic> scope){
this.name=name;
this.t=name.t;
this.scope=scope;
}
@Override
public Name getParent() {
return name;
}
@Override
public Set<Topic> getScope() {
return t.tm.wrapTopics(scope);
}
@Override
public Topic getReifier() {
return null;
}
@Override
public void setReifier(Topic topic) throws ModelConstraintException {
throw new UnsupportedOperationException("Reification not supported");
}
@Override
public TopicMap getTopicMap() {
return t.getTopicMap();
}
@Override
public String getId() {
return null;
}
@Override
public Set<Locator> getItemIdentifiers() {
return new HashSet<Locator>();
}
@Override
public void addItemIdentifier(Locator lctr) throws ModelConstraintException {
throw new UnsupportedOperationException("Item identfiers not supported");
}
@Override
public void removeItemIdentifier(Locator lctr) {
throw new UnsupportedOperationException("Item identifiers not supported");
}
@Override
public void remove() {
try{
t.getWrapped().removeVariant(scope);
}catch(TopicMapException tme){
throw new RuntimeException(tme);
}
}
@Override
public void addTheme(Topic topic) throws ModelConstraintException {
try{
org.wandora.topicmap.Topic _topic=((W2TTopic)topic).getWrapped();
boolean found=false;
for(org.wandora.topicmap.Topic s : scope){
if(s.mergesWithTopic(_topic)) {
found=true;
break;
}
}
if(found) return;
HashSet<org.wandora.topicmap.Topic> newScope=new HashSet<>(scope);
newScope.add(_topic);
String value=t.getWrapped().getVariant(scope);
t.getWrapped().removeVariant(scope);
t.getWrapped().setVariant(newScope, value);
scope=newScope;
}catch(TopicMapException tme){
throw new RuntimeException(tme);
}
}
@Override
public void removeTheme(Topic topic) {
try{
HashSet<org.wandora.topicmap.Topic> newScope=new HashSet<>(scope);
org.wandora.topicmap.Topic _topic=((W2TTopic)topic).getWrapped();
boolean found=false;
for(org.wandora.topicmap.Topic s : scope){
if(s.mergesWithTopic(_topic)) {
found=true;
}
else newScope.add(s);
}
if(!found) return;
String value=t.getWrapped().getVariant(scope);
t.getWrapped().removeVariant(scope);
t.getWrapped().setVariant(newScope, value);
scope=newScope;
}catch(TopicMapException tme){
throw new RuntimeException(tme);
}
}
@Override
public String getValue() {
try{
return t.t.getVariant(scope);
}catch(TopicMapException tme){
throw new RuntimeException(tme);
}
}
@Override
public void setValue(String s){
try {
t.t.setVariant(scope, s);
}catch(TopicMapException tme){
throw new RuntimeException(tme);
}
}
}
| 4,826 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
W2TTopic.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/wandora2tmapi/W2TTopic.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2013 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.topicmap.wandora2tmapi;
import java.util.Collection;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Map;
import java.util.Set;
import org.tmapi.core.IdentityConstraintException;
import org.tmapi.core.Locator;
import org.tmapi.core.ModelConstraintException;
import org.tmapi.core.Name;
import org.tmapi.core.Occurrence;
import org.tmapi.core.Reifiable;
import org.tmapi.core.Role;
import org.tmapi.core.TMAPIRuntimeException;
import org.tmapi.core.Topic;
import org.tmapi.core.TopicInUseException;
import org.tmapi.core.TopicMap;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author olli
*/
public class W2TTopic implements Topic {
protected W2TTopicMap tm;
protected org.wandora.topicmap.Topic t;
protected boolean strictFailure=true;
public W2TTopic(W2TTopicMap tm,org.wandora.topicmap.Topic t){
this.tm=tm;
this.t=t;
}
public boolean isStrictFailure() {
return strictFailure;
}
public void setStrictFailure(boolean strictFailure) {
if(strictFailure==false) throw new RuntimeException("not implemented yet");
this.strictFailure = strictFailure;
}
public org.wandora.topicmap.Topic getWrapped(){
return t;
}
@Override
public TopicMap getParent() {
return tm;
}
@Override
public void addItemIdentifier(Locator lctr) {
throw new UnsupportedOperationException("Item identifiers not supported");
}
@Override
public Set<Locator> getSubjectIdentifiers() {
try{
return tm.wrapLocators(t.getSubjectIdentifiers());
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
/*
The tmapi specifies an autoMerge feature which can be set off or on when
creating the topic map. If off, merges should not happen automatically in
addSubjectIdentifier etc, instead an exception should be thrown in such a
case. Currently there is no way to change this setting however and automerge
is assumed to be turned on always.
*/
@Override
public void addSubjectIdentifier(Locator lctr) throws IdentityConstraintException, ModelConstraintException {
try{
t.addSubjectIdentifier(tm.tm.createLocator(lctr.toExternalForm()));
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
@Override
public void removeSubjectIdentifier(Locator lctr) {
try{
t.removeSubjectIdentifier(tm.tm.createLocator(lctr.toExternalForm()));
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
@Override
public Set<Locator> getSubjectLocators() {
try{
org.wandora.topicmap.Locator l=t.getSubjectLocator();
HashSet<Locator> ret=new HashSet<Locator>();
if(l!=null) ret.add(new W2TLocator(l));
return ret;
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
@Override
public void addSubjectLocator(Locator lctr) throws IdentityConstraintException, ModelConstraintException {
try{
if(t.getSubjectLocator()==null) t.setSubjectLocator(tm.tm.createLocator(lctr.toExternalForm()));
else throw new UnsupportedOperationException("Multiple subject locators in a topic not supported");
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
@Override
public void removeSubjectLocator(Locator lctr) {
try{
if(t.getSubjectLocator()!=null && lctr!=null){
if(t.getSubjectLocator().toExternalForm().equals(lctr.toExternalForm())) t.setSubjectLocator(null);
}
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
public Name _getName(){
try{
if(t.getBaseName()!=null) return new W2TName(tm,this);
else return null;
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
/*
If the base name of a topic is null, then it will not have any Names
and thus no variant names. But Wandora topic map model does allow variant
names without a base name. TMAPI doesn't allow null value in the name but
empty string would be allowed. This however might cause problems with
merge handling.
*/
@Override
public Set<Name> getNames() {
HashSet<Name> ret=new HashSet<Name>();
Name name=_getName();
if(name!=null) ret.add(name);
return ret;
}
@Override
public Set<Name> getNames(Topic topic) {
// all names have the default type so this is either equal to getNames or an empty set
if(topic.getSubjectIdentifiers().contains(tm.createLocator(W2TTopicMap.TOPIC_NAME_SI))) return getNames();
else return new HashSet<Name>();
}
/*
The name methods are violating the specification slightly when it comes ot Name
type. Each Name must have a type instead of the type being null. The createName
methods that don't take a type should automatically use the default name type
http://psi.topicmaps.org/iso13250/model/topic-name
*/
@Override
public Name createName(Topic type, String value, Topic... scope) throws ModelConstraintException {
if(_getName()!=null) throw new UnsupportedOperationException("Only one name per topic is supported");
else {
if(scope.length>0) throw new UnsupportedOperationException("Scoped names are not supported");
if(!type.getSubjectIdentifiers().contains(tm.createLocator(W2TTopicMap.TOPIC_NAME_SI)))
throw new UnsupportedOperationException("only default name type is supported");
try{
t.setBaseName(value);
return _getName();
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
}
@Override
public Name createName(Topic type, String value, Collection<Topic> scope) throws ModelConstraintException {
return createName(type,value,scope.toArray(new Topic[0]));
}
@Override
public Name createName(String value, Topic... scope) throws ModelConstraintException {
return createName(tm.getTopicBySubjectIdentifier(W2TTopicMap.TOPIC_NAME_SI),value,scope);
}
@Override
public Name createName(String value, Collection<Topic> scope) throws ModelConstraintException {
return createName(tm.getTopicBySubjectIdentifier(W2TTopicMap.TOPIC_NAME_SI),value,scope.toArray(new Topic[0]));
}
@Override
public Set<Occurrence> getOccurrences() {
try{
HashSet<Occurrence> ret=new HashSet<Occurrence>();
for(org.wandora.topicmap.Topic _type : t.getDataTypes()){
W2TTopic type=new W2TTopic(tm,_type);
Hashtable<org.wandora.topicmap.Topic,String> occs=t.getData(_type);
for(Map.Entry<org.wandora.topicmap.Topic,String> e : occs.entrySet()){
org.wandora.topicmap.Topic lang=e.getKey();
ret.add(new W2TOccurrence(this,type,lang!=null?new W2TTopic(tm,lang):null));
}
}
return ret;
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
@Override
public Set<Occurrence> getOccurrences(Topic type) {
try{
Hashtable<org.wandora.topicmap.Topic,String> occs=t.getData(((W2TTopic)type).t);
HashSet<Occurrence> ret=new HashSet<Occurrence>();
for(Map.Entry<org.wandora.topicmap.Topic,String> e : occs.entrySet()){
org.wandora.topicmap.Topic lang=e.getKey();
ret.add(new W2TOccurrence(this,(W2TTopic)type,lang!=null?new W2TTopic(tm,lang):null));
}
return ret;
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
/*
Datatypes aren't supported in Wandora. It should automatically be assigned
a value xsd:string or xsd:anyURI but a null is used here instead.
*/
@Override
public Occurrence createOccurrence(Topic type, String value, Topic... scope) throws ModelConstraintException {
return createOccurrence(type,value,tm.createLocator(W2TTopicMap.TYPE_STRING_SI),scope);
}
@Override
public Occurrence createOccurrence(Topic type, String value, Collection<Topic> scope) throws ModelConstraintException {
return createOccurrence(type,value,tm.createLocator(W2TTopicMap.TYPE_STRING_SI),scope);
}
@Override
public Occurrence createOccurrence(Topic type, Locator value, Topic... scope) throws ModelConstraintException {
throw new UnsupportedOperationException("Only string occurrences are supported");
//return createOccurrence(type,value.toExternalForm(),null,scope);
}
@Override
public Occurrence createOccurrence(Topic type, Locator value, Collection<Topic> scope) throws ModelConstraintException {
throw new UnsupportedOperationException("Only string occurrences are supported");
// return createOccurrence(type,value.toExternalForm(),null,scope);
}
@Override
public Occurrence createOccurrence(Topic type, String value, Locator dataType, Topic... scope) throws ModelConstraintException {
if(!dataType.toExternalForm().equals(W2TTopicMap.TYPE_STRING_SI)) throw new UnsupportedOperationException("Only string occurrences are supported");
if(scope.length!=1) throw new UnsupportedOperationException("The scope must have exactly one topic indicating the language");
Topic version=scope[0];
try{
String data=t.getData(((W2TTopic)type).getWrapped(), ((W2TTopic)version).getWrapped());
if(data!=null) throw new UnsupportedOperationException("Only one occurrence for each type/language pair allowed");
t.setData(((W2TTopic)type).getWrapped(), ((W2TTopic)version).getWrapped(), value);
return new W2TOccurrence(this,(W2TTopic)type,(W2TTopic)version);
}
catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
@Override
public Occurrence createOccurrence(Topic type, String value, Locator dataType, Collection<Topic> scope) throws ModelConstraintException {
return createOccurrence(type,value,dataType,scope.toArray(new Topic[0]));
}
protected Set<Role> _getRolesPlayed(Topic type, Topic associationType){
try{
HashSet<Role> ret=new HashSet<Role>();
Collection<org.wandora.topicmap.Association> as;
if(associationType==null) as=t.getAssociations();
else as=t.getAssociations(((W2TTopic)associationType).t);
for(org.wandora.topicmap.Association a : as){
W2TAssociation w2ta=new W2TAssociation(tm,a);
for(org.wandora.topicmap.Topic role : a.getRoles()){
if(type!=null && !((W2TTopic)type).t.mergesWithTopic(role)) continue;
W2TTopic w2trole=new W2TTopic(tm, role);
org.wandora.topicmap.Topic player=a.getPlayer(role);
if(player.mergesWithTopic(this.t)){
ret.add(new W2TRole(w2ta, w2trole, this));
}
}
}
return ret;
}
catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
@Override
public Set<Role> getRolesPlayed() {
return _getRolesPlayed(null,null);
}
@Override
public Set<Role> getRolesPlayed(Topic type) {
return _getRolesPlayed(type,null);
}
@Override
public Set<Role> getRolesPlayed(Topic type, Topic associationType) {
return _getRolesPlayed(type,associationType);
}
@Override
public Set<Topic> getTypes() {
try{
return tm.wrapTopics(t.getTypes());
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
@Override
public void addType(Topic topic) throws ModelConstraintException {
try{
t.addType(((W2TTopic)topic).getWrapped());
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
@Override
public void removeType(Topic topic) {
try{
t.removeType(((W2TTopic)topic).getWrapped());
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
@Override
public Reifiable getReified() {
return null;
}
@Override
public void mergeIn(Topic topic) throws ModelConstraintException {
try{
org.wandora.topicmap.Topic w=((W2TTopic)topic).getWrapped();
org.wandora.topicmap.Locator si=w.getOneSubjectIdentifier();
if(si==null){
si=t.getTopicMap().makeSubjectIndicatorAsLocator();
w.addSubjectIdentifier(si);
t.addSubjectIdentifier(si);
t.removeSubjectIdentifier(si);
}
else {
t.addSubjectIdentifier(si);
}
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
@Override
public void remove() throws TopicInUseException {
try{
if(!t.isDeleteAllowed()) throw new TopicInUseException(this,"Topic in use");
else t.remove();
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
@Override
public TopicMap getTopicMap() {
return tm;
}
@Override
public String getId() {
try{
return t.getID();
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
@Override
public Set<Locator> getItemIdentifiers() {
return new HashSet<Locator>();
}
@Override
public void removeItemIdentifier(Locator lctr) {
// there will never be any item identifiers so nothing needs to be done
}
}
| 15,391 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
W2TTopicMap.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/wandora2tmapi/W2TTopicMap.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2013 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.topicmap.wandora2tmapi;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.tmapi.core.Association;
import org.tmapi.core.Construct;
import org.tmapi.core.IdentityConstraintException;
import org.tmapi.core.Locator;
import org.tmapi.core.MalformedIRIException;
import org.tmapi.core.ModelConstraintException;
import org.tmapi.core.Name;
import org.tmapi.core.Occurrence;
import org.tmapi.core.Role;
import org.tmapi.core.TMAPIRuntimeException;
import org.tmapi.core.Topic;
import org.tmapi.core.TopicMap;
import org.tmapi.core.Variant;
import org.tmapi.index.Index;
import org.tmapi.index.ScopedIndex;
import org.tmapi.index.TypeInstanceIndex;
import org.wandora.topicmap.TopicHashSet;
import org.wandora.topicmap.TopicMapException;
import org.wandora.topicmap.layered.Layer;
import org.wandora.topicmap.layered.LayerStack;
import org.wandora.topicmap.tmapi2wandora.T2WTopicMap;
import org.wandora.topicmap.undowrapper.UndoException;
/**
* This is a TMAPI topic map implementation which wraps inside it a
* Wandora TopicMap. The implementation does support both reading and writing,
* but there are several restrictions in how the topic map can be written to.
* These have to do with restrictions in Wandora's topic map model compared to the
* standard TMDM used by TMAPI. Some structures allowed in TMDM cannot be easily
* converted to Wandora's data model, UnsupportedOperationExceptions are thrown
* in such cases.
*
* @author olli
*/
public class W2TTopicMap implements TopicMap {
public static final String DEFAULT_TM_LOCATOR="http://wandora.org/si/tmapi/defaultTMLocator";
protected org.wandora.topicmap.TopicMap original;
protected org.wandora.topicmap.layered.LayerStack tm;
protected W2TLocator locator;
public W2TTopicMap(org.wandora.topicmap.TopicMap tm) throws TopicMapException {
original=tm;
this.tm=new LayerStack();
try{
this.tm.setUseUndo(false);
}catch(UndoException ue){}
this.tm.addLayer(new Layer(original, "original", this.tm));
addCompatibilityLayer();
}
public static final String TOPIC_NAME_SI="http://psi.topicmaps.org/iso13250/model/topic-name";
public static final String TYPE_STRING_SI="http://www.w3.org/TR/xmlschema-2/#string";
/*
This wrapper requires a couple of topics to exist in the topic map to work.
These are added in a separate layers for minimum interference with everything
else.
*/
protected void addCompatibilityLayer() throws TopicMapException {
org.wandora.topicmap.memory.TopicMapImpl c=new org.wandora.topicmap.memory.TopicMapImpl();
c.createTopic().addSubjectIdentifier(c.createLocator(TOPIC_NAME_SI));
c.createTopic().addSubjectIdentifier(c.createLocator(TYPE_STRING_SI));
Layer l=new Layer(c, "compatibility", this.tm);
l.setReadOnly(true);
this.tm.addLayer(l);
}
public Set<Topic> wrapTopics(Collection<org.wandora.topicmap.Topic> topics){
HashSet<Topic> ret=new LinkedHashSet<Topic>();
for(org.wandora.topicmap.Topic t : topics){
ret.add(new W2TTopic(this,t));
}
return ret;
}
public Set<Locator> wrapLocators(Collection<org.wandora.topicmap.Locator> locators){
HashSet<Locator> ret=new LinkedHashSet<Locator>();
for(org.wandora.topicmap.Locator l : locators){
ret.add(new W2TLocator(l));
}
return ret;
}
public Set<Association> wrapAssociations(Collection<org.wandora.topicmap.Association> associations){
HashSet<Association> ret=new LinkedHashSet<Association>();
for(org.wandora.topicmap.Association a : associations){
ret.add(new W2TAssociation(this,a));
}
return ret;
}
@Override
public Construct getParent() {
return null;
}
@Override
public Set<Topic> getTopics() {
HashSet<Topic> ret=new LinkedHashSet<Topic>();
try{
Iterator<org.wandora.topicmap.Topic> iter=tm.getTopics();
while(iter.hasNext()){
org.wandora.topicmap.Topic t=iter.next();
ret.add(new W2TTopic(this,t));
}
return ret;
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
@Override
public Locator getLocator() {
if(locator!=null) return locator;
else return new W2TLocator(DEFAULT_TM_LOCATOR);
}
public void setLocator(W2TLocator locator){
this.locator=locator;
}
@Override
public Set<Association> getAssociations() {
HashSet<Association> ret=new LinkedHashSet<Association>();
try{
Iterator<org.wandora.topicmap.Association> iter=tm.getAssociations();
while(iter.hasNext()){
org.wandora.topicmap.Association a=iter.next();
ret.add(new W2TAssociation(this,a));
}
return ret;
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
@Override
public Topic getTopicBySubjectIdentifier(Locator lctr) {
try{
org.wandora.topicmap.Topic t=tm.getTopic(lctr.toExternalForm());
if(t==null) return null;
return new W2TTopic(this,t);
}catch(TopicMapException tme) {
throw new TMAPIRuntimeException(tme);
}
}
public Topic getTopicBySubjectIdentifier(String si) {
try{
org.wandora.topicmap.Topic t=tm.getTopic(si);
if(t==null) return null;
return new W2TTopic(this,t);
}catch(TopicMapException tme) {
throw new TMAPIRuntimeException(tme);
}
}
@Override
public Topic getTopicBySubjectLocator(Locator lctr) {
try{
org.wandora.topicmap.Topic t=tm.getTopicBySubjectLocator(lctr.toExternalForm());
if(t==null) return null;
return new W2TTopic(this,t);
}catch(TopicMapException tme) {
throw new TMAPIRuntimeException(tme);
}
}
@Override
public Construct getConstructByItemIdentifier(Locator lctr) {
return null;
}
@Override
public Construct getConstructById(String string) {
return null;
}
@Override
public Locator createLocator(String string) throws MalformedIRIException {
return new W2TLocator(string);
}
@Override
public Topic createTopicBySubjectIdentifier(Locator lctr) throws ModelConstraintException {
try{
org.wandora.topicmap.Topic t=tm.getTopic(lctr.toExternalForm());
if(t==null) {
t=tm.createTopic();
t.addSubjectIdentifier(tm.createLocator(lctr.toExternalForm()));
}
return new W2TTopic(this,t);
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
@Override
public Topic createTopicBySubjectLocator(Locator lctr) throws ModelConstraintException {
try{
org.wandora.topicmap.Topic t=tm.getTopicBySubjectLocator(lctr.toExternalForm());
if(t==null) {
t=tm.createTopic();
t.addSubjectIdentifier(tm.makeSubjectIndicatorAsLocator());
t.setSubjectLocator(tm.createLocator(lctr.toExternalForm()));
}
return new W2TTopic(this,t);
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
@Override
public Topic createTopicByItemIdentifier(Locator lctr) throws IdentityConstraintException, ModelConstraintException {
// no topics have item identifiers ever so this is essentially same as just creating a new one
return createTopic();
}
@Override
public Topic createTopic() {
try{
org.wandora.topicmap.Topic t=tm.createTopic();
t.addSubjectIdentifier(tm.makeSubjectIndicatorAsLocator());
return new W2TTopic(this,t);
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
@Override
public Association createAssociation(Topic type, Topic... scope) throws ModelConstraintException {
if(scope!=null && scope.length>0) throw new UnsupportedOperationException("Scope not supported in associations");
try{
org.wandora.topicmap.Association a=tm.createAssociation(((W2TTopic)type).getWrapped());
return new W2TAssociation(this,a);
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
@Override
public Association createAssociation(Topic type, Collection<Topic> scope) throws ModelConstraintException {
if(scope!=null && scope.size()>0) throw new UnsupportedOperationException("Scope not supported in associations");
else return createAssociation(type);
}
@Override
public void close() {
}
@Override
public void mergeIn(TopicMap tm) throws ModelConstraintException {
try{
T2WTopicMap wrapped=new T2WTopicMap(tm);
this.tm.mergeIn(wrapped);
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
@Override
public <I extends Index> I getIndex(Class<I> type) {
if(type.isAssignableFrom(TypeInstanceIndex.class)) return (I)(new W2TTypeInstanceIndex());
else if(type.isAssignableFrom(ScopedIndex.class)) return (I)(new W2TScopedIndex());
else throw new UnsupportedOperationException("Index not supported.");
}
@Override
public Topic getReifier() {
return null;
}
@Override
public void setReifier(Topic topic) throws ModelConstraintException {
throw new UnsupportedOperationException("Reification not supported");
}
@Override
public TopicMap getTopicMap() {
return this;
}
@Override
public String getId() {
return null;
}
@Override
public Set<Locator> getItemIdentifiers() {
return new HashSet<Locator>();
}
@Override
public void addItemIdentifier(Locator lctr) throws ModelConstraintException {
throw new UnsupportedOperationException("Item identifiers not supported");
}
@Override
public void removeItemIdentifier(Locator lctr) {
}
@Override
public void remove() {
}
public void clear() {
try{
tm.clearTopicMap();
}catch(TopicMapException tme){
throw new TMAPIRuntimeException(tme);
}
}
private class W2TTypeInstanceIndex implements TypeInstanceIndex {
@Override
public Collection<Topic> getTopics(Topic topic) {
try{
return wrapTopics(tm.getTopicsOfType(((W2TTopic)topic).getWrapped()));
}catch(TopicMapException tme) {
throw new TMAPIRuntimeException(tme);
}
}
@Override
public Collection<Topic> getTopics(Topic[] topics, boolean matchAll) {
try{
TopicHashSet work=new TopicHashSet();
for(int i=0;i<topics.length;i++){
Collection<org.wandora.topicmap.Topic> ts=tm.getTopicsOfType(((W2TTopic)topics[i]).getWrapped());
if(matchAll){
if(i==0) work.addAll(ts);
else {
TopicHashSet test=new TopicHashSet(ts);
ArrayList<org.wandora.topicmap.Topic> remove=new ArrayList<org.wandora.topicmap.Topic>();
for(org.wandora.topicmap.Topic t : ts){
if(!test.contains(t)) remove.add(t);
}
ts.removeAll(remove);
}
}
else {
work.addAll(ts);
}
}
return wrapTopics(work);
}catch(TopicMapException tme) {
throw new TMAPIRuntimeException(tme);
}
}
@Override
public Collection<Topic> getTopicTypes() {
try{
// Go through all topics, not very efficient.
TopicHashSet types=new TopicHashSet();
Iterator<org.wandora.topicmap.Topic> iter=tm.getTopics();
while(iter.hasNext()){
org.wandora.topicmap.Topic t=iter.next();
types.addAll(t.getTypes());
}
return wrapTopics(types);
}catch(TopicMapException tme) {
throw new TMAPIRuntimeException(tme);
}
}
@Override
public Collection<Association> getAssociations(Topic topic) {
try{
return wrapAssociations(tm.getAssociationsOfType(((W2TTopic)topic).getWrapped()));
}catch(TopicMapException tme) {
throw new TMAPIRuntimeException(tme);
}
}
@Override
public Collection<Topic> getAssociationTypes() {
try{
// Go through all topics, not very efficient.
TopicHashSet types=new TopicHashSet();
Iterator<org.wandora.topicmap.Association> iter=tm.getAssociations();
while(iter.hasNext()){
org.wandora.topicmap.Association a=iter.next();
types.add(a.getType());
}
return wrapTopics(types);
}catch(TopicMapException tme) {
throw new TMAPIRuntimeException(tme);
}
}
@Override
public Collection<Role> getRoles(Topic topic) {
try{
ArrayList<Role> ret=new ArrayList<Role>();
Collection<org.wandora.topicmap.Association> as=((W2TTopic)topic).getWrapped().getAssociationsWithRole();
for(org.wandora.topicmap.Association a : as){
org.wandora.topicmap.Topic p=a.getPlayer(((W2TTopic)topic).getWrapped());
ret.add(new W2TRole(new W2TAssociation(W2TTopicMap.this, a), (W2TTopic)topic, new W2TTopic(W2TTopicMap.this, p)));
}
return ret;
}catch(TopicMapException tme) {
throw new TMAPIRuntimeException(tme);
}
}
@Override
public Collection<Topic> getRoleTypes() {
try{
// Go through all topics, not very efficient.
TopicHashSet types=new TopicHashSet();
Iterator<org.wandora.topicmap.Association> iter=tm.getAssociations();
while(iter.hasNext()){
org.wandora.topicmap.Association a=iter.next();
types.addAll(a.getRoles());
}
return wrapTopics(types);
}catch(TopicMapException tme) {
throw new TMAPIRuntimeException(tme);
}
}
@Override
public Collection<Occurrence> getOccurrences(Topic topic) {
if(topic==null) return new ArrayList<Occurrence>(); // occurrences without type are not supported in Wandora so this is always empty
try{
ArrayList<Occurrence> ret=new ArrayList<Occurrence>();
org.wandora.topicmap.Topic _topic=((W2TTopic)topic).getWrapped();
Collection<org.wandora.topicmap.Topic> ts=_topic.getTopicsWithDataType();
for(org.wandora.topicmap.Topic t : ts){
W2TTopic w2tt=new W2TTopic(W2TTopicMap.this,t);
Hashtable<org.wandora.topicmap.Topic,String> data=t.getData(_topic);
for(Map.Entry<org.wandora.topicmap.Topic,String> e : data.entrySet()){
ret.add(new W2TOccurrence(w2tt,(W2TTopic)topic,new W2TTopic(W2TTopicMap.this,e.getKey())));
}
}
return ret;
}catch(TopicMapException tme) {
throw new TMAPIRuntimeException(tme);
}
}
@Override
public Collection<Topic> getOccurrenceTypes() {
try{
// Go through all topics, not very efficient.
TopicHashSet types=new TopicHashSet();
Iterator<org.wandora.topicmap.Topic> iter=tm.getTopics();
while(iter.hasNext()){
org.wandora.topicmap.Topic t=iter.next();
types.addAll(t.getDataTypes());
}
return wrapTopics(types);
}catch(TopicMapException tme) {
throw new TMAPIRuntimeException(tme);
}
}
@Override
public Collection<Name> getNames(Topic topic) {
if(topic!=null) return new ArrayList<Name>(); // all names in wandora are typeless
else {
try{
ArrayList<Name> ret=new ArrayList<Name>();
Iterator<org.wandora.topicmap.Topic> iter=tm.getTopics();
while(iter.hasNext()){
org.wandora.topicmap.Topic t=iter.next();
if(t.getBaseName()!=null) ret.add(new W2TName(W2TTopicMap.this, new W2TTopic(W2TTopicMap.this, t)));
}
return ret;
}catch(TopicMapException tme) {
throw new TMAPIRuntimeException(tme);
}
}
}
@Override
public Collection<Topic> getNameTypes() {
// names in wandora are not typed, in the wrapper they all use the default name
Collection<Topic> ret=new ArrayList<Topic>();
ret.add(W2TTopicMap.this.getTopicBySubjectIdentifier(TOPIC_NAME_SI));
return ret;
}
@Override
public void open() {
}
@Override
public void close() {
}
@Override
public boolean isOpen() {
return true;
}
@Override
public boolean isAutoUpdated() {
return true;
}
@Override
public void reindex() {
}
}
private class W2TScopedIndex implements ScopedIndex {
@Override
public Collection<Association> getAssociations(Topic topic) {
if(topic!=null) return new ArrayList<Association>();
else return W2TTopicMap.this.getAssociations();
}
@Override
public Collection<Association> getAssociations(Topic[] topics, boolean matchAll) {
if(topics.length==0 && matchAll) return W2TTopicMap.this.getAssociations();
else return new ArrayList<Association>();
}
@Override
public Collection<Topic> getAssociationThemes() {
return new ArrayList<Topic>();
}
@Override
public Collection<Occurrence> getOccurrences(Topic topic) {
if(topic==null) throw new UnsupportedOperationException("Not supported yet."); // should return all occurrences
org.wandora.topicmap.Topic _topic=((W2TTopic)topic).getWrapped();
try{
ArrayList<Occurrence> ret=new ArrayList<Occurrence>();
Collection<org.wandora.topicmap.Topic> ts=((W2TTopic)topic).getWrapped().getTopicsWithDataVersion();
for(org.wandora.topicmap.Topic t : ts){
W2TTopic w2tt=new W2TTopic(W2TTopicMap.this, t);
for(org.wandora.topicmap.Topic dataType : t.getDataTypes()){
W2TTopic w2ttype=new W2TTopic(W2TTopicMap.this, dataType);
for(Map.Entry<org.wandora.topicmap.Topic,String> o : t.getData(dataType).entrySet()){
if(o.getKey().mergesWithTopic(_topic)) {
ret.add(new W2TOccurrence(w2tt, w2ttype, (W2TTopic)topic));
}
}
}
}
return ret;
}catch(TopicMapException tme) {
throw new TMAPIRuntimeException(tme);
}
}
@Override
public Collection<Occurrence> getOccurrences(Topic[] topics, boolean matchAll) {
if(topics.length==0){
if(matchAll) return getOccurrences(null); // for now this throws an exception but this should do the right thing when implemented
else return new ArrayList<Occurrence>();
}
else if(topics.length==1) return getOccurrences(topics[0]);
else { // .length>1
if(matchAll) return new ArrayList<Occurrence>(); // no occurrence in wandora has two versions so this is always empty
// assuming the topics array contains unique topics,
// there should not be duplicates as each occurrence
// in wandora only has a single version
ArrayList<Occurrence> ret=new ArrayList<Occurrence>();
for (Topic topic : topics) {
ret.addAll(getOccurrences(topic));
}
return ret;
}
}
@Override
public Collection<Topic> getOccurrenceThemes() {
return new ArrayList<Topic>();
}
@Override
public Collection<Name> getNames(Topic topic) {
if(topic==null) throw new UnsupportedOperationException("Not supported yet."); // should return all names
else return new ArrayList<Name>();
}
@Override
public Collection<Name> getNames(Topic[] topics, boolean matchAll) {
if(topics.length==0 && matchAll) return getNames(null);
else return new ArrayList<Name>();
}
@Override
public Collection<Topic> getNameThemes() {
return new ArrayList<Topic>(); // names in Wandora are not scoped, only variants
}
@Override
public Collection<Variant> getVariants(Topic topic) {
if(topic==null) return getVariants(new Topic[0],false);
else return getVariants(new Topic[]{topic},false);
}
@Override
public Collection<Variant> getVariants(Topic[] topics, boolean matchAll) {
if(topics.length==0){
if(matchAll) throw new UnsupportedOperationException("Not supported yet."); // should return all names
else return new ArrayList<Variant>();
}
else {
if(topics.length<2 || !matchAll){
try{
Collection<org.wandora.topicmap.Topic> ts;
if(topics.length==1) ts=((W2TTopic)topics[0]).getWrapped().getTopicsWithVariantScope();
else {
ts=new TopicHashSet();
for(Topic topic : topics){
ts.addAll( ((W2TTopic)topic).getWrapped().getTopicsWithVariantScope() );
}
}
ArrayList<Variant> ret=new ArrayList<Variant>();
for(org.wandora.topicmap.Topic t : ts){
W2TTopic w2tt=new W2TTopic(W2TTopicMap.this, t);
W2TName name=new W2TName(W2TTopicMap.this, w2tt);
for(Set<org.wandora.topicmap.Topic> scope : t.getVariantScopes()){
ScopeLoop: for(org.wandora.topicmap.Topic scopeTopic : scope){
for(Topic topic : topics){
if(scopeTopic.mergesWithTopic( ((W2TTopic)topic).getWrapped() )){
ret.add(new W2TVariant(name, scope));
break ScopeLoop;
}
}
}
}
}
return ret;
}catch(TopicMapException tme) {
throw new TMAPIRuntimeException(tme);
}
}
else {
throw new UnsupportedOperationException("Not supported yet.");
// should do an intersection of calling getVariants individually on each topic
}
}
}
@Override
public Collection<Topic> getVariantThemes() {
throw new UnsupportedOperationException("Not supported yet."); // should return all topics used in any variant scope
}
@Override
public void open() {
}
@Override
public void close() {
}
@Override
public boolean isOpen() {
return true;
}
@Override
public boolean isAutoUpdated() {
return true;
}
@Override
public void reindex() {
}
}
}
| 26,407 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
T2WAssociation.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/tmapi2wandora/T2WAssociation.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.topicmap.tmapi2wandora;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author olli
*/
public class T2WAssociation implements Association {
protected T2WTopicMap tm;
protected org.tmapi.core.Association a;
public T2WAssociation(T2WTopicMap tm,org.tmapi.core.Association a){
this.tm=tm;
this.a=a;
}
@Override
public Topic getType() throws TopicMapException {
return new T2WTopic(tm,a.getType());
}
@Override
public void setType(Topic t) throws TopicMapException {
throw new UnsupportedOperationException("Editing not supported");
}
@Override
public Topic getPlayer(Topic role) throws TopicMapException {
org.tmapi.core.Topic _role=((T2WTopic)role).getWrapped();
Set<org.tmapi.core.Role> rs=a.getRoles(_role);
if(rs.isEmpty()) return null;
if(rs.size()==1){
org.tmapi.core.Topic _player=rs.iterator().next().getPlayer();
return new T2WTopic(tm,_player);
}
else {
// The association has several players with the same role type.
// We could return just one of them but maybe it's better to ignore
// them all.
return null;
}
}
@Override
public void addPlayer(Topic player, Topic role) throws TopicMapException {
throw new UnsupportedOperationException("Editing not supported");
}
@Override
public void addPlayers(Map<Topic, Topic> players) throws TopicMapException {
throw new UnsupportedOperationException("Editing not supported");
}
@Override
public void removePlayer(Topic role) throws TopicMapException {
throw new UnsupportedOperationException("Editing not supported");
}
@Override
public Collection<Topic> getRoles() throws TopicMapException {
// See the comment in getPlayer about duplicate role types.
// We ignore completely those role types here which complicates this
// method a little bit.
HashSet<org.tmapi.core.Topic> _roles=new HashSet<org.tmapi.core.Topic>();
HashSet<org.tmapi.core.Topic> _ret=new HashSet<org.tmapi.core.Topic>();
for(org.tmapi.core.Role r : a.getRoles()) {
if(!_roles.add(r.getType())){
_ret.remove(r.getType()); // if the role was already there then ignore it completely
}
else _ret.add(r.getType());
}
return tm.wrapTopics(_ret);
}
@Override
public TopicMap getTopicMap() {
return tm;
}
@Override
public void remove() throws TopicMapException {
throw new UnsupportedOperationException("Editing not supported");
}
@Override
public boolean isRemoved() throws TopicMapException {
return false;
}
}
| 3,880 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
T2WTopic.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/tmapi2wandora/T2WTopic.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.topicmap.tmapi2wandora;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Set;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author olli
*/
/*
This currently trusts equals check to identify equal topics for the
tmapi part. The spec says that tmapi equals method must just compare
objects with ==. Tmapi doesn't provide other starightforward ways to
check topic map equality of two topics so it is assumed that each topic
is represented by only one java object.
*/
public class T2WTopic extends Topic {
protected T2WTopicMap tm;
protected org.tmapi.core.Topic t;
public T2WTopic(T2WTopicMap tm,org.tmapi.core.Topic t){
this.tm=tm;
this.t=t;
}
public org.tmapi.core.Topic getWrapped(){
return t;
}
@Override
public String getID() throws TopicMapException {
String s=t.getId();
if(s!=null) return s;
else return ""+t.hashCode();
}
@Override
public Collection<Locator> getSubjectIdentifiers() throws TopicMapException {
Set<org.tmapi.core.Locator> ls=t.getSubjectIdentifiers();
return tm.wrapLocators(ls);
}
@Override
public void addSubjectIdentifier(Locator l) throws TopicMapException {
throw new UnsupportedOperationException("Editing not supported");
}
@Override
public void removeSubjectIdentifier(Locator l) throws TopicMapException {
throw new UnsupportedOperationException("Editing not supported");
}
protected org.tmapi.core.Name _getBaseName() {
org.tmapi.core.TopicMap _tm=t.getParent();
org.tmapi.core.Topic type=_tm.getTopicBySubjectIdentifier(_tm.createLocator(T2WTopicMap.TOPIC_NAME_SI));
if(type==null) return null;
Set<org.tmapi.core.Name> ns=t.getNames(type);
for(org.tmapi.core.Name n : ns){
if(n.getScope().isEmpty()) return n;
}
return null;
}
@Override
public String getBaseName() throws TopicMapException {
org.tmapi.core.Name n=_getBaseName();
if(n==null) return null;
else return n.getValue();
}
@Override
public void setBaseName(String name) throws TopicMapException {
throw new UnsupportedOperationException("Editing not supported");
}
@Override
public Collection<Topic> getTypes() throws TopicMapException {
return tm.wrapTopics(t.getTypes());
}
@Override
public void addType(Topic t) throws TopicMapException {
throw new UnsupportedOperationException("Editing not supported");
}
@Override
public void removeType(Topic t) throws TopicMapException {
throw new UnsupportedOperationException("Editing not supported");
}
@Override
public boolean isOfType(Topic type) throws TopicMapException {
return t.getTypes().contains(((T2WTopic)type).getWrapped());
}
@Override
public String getVariant(Set<Topic> scope) throws TopicMapException {
org.tmapi.core.Name name=_getBaseName();
if(name==null) return null;
Set<org.tmapi.core.Topic> _scope=new HashSet<org.tmapi.core.Topic>();
for(Topic t : scope){
_scope.add(((T2WTopic)t).getWrapped());
}
for(org.tmapi.core.Variant v : name.getVariants()){
if(name.getScope().equals(_scope)) return v.getValue();
}
return null;
}
@Override
public void setVariant(Set<Topic> scope, String name) throws TopicMapException {
throw new UnsupportedOperationException("Editing not supported");
}
@Override
public Set<Set<Topic>> getVariantScopes() throws TopicMapException {
org.tmapi.core.Name name=_getBaseName();
if(name==null) return new HashSet<Set<Topic>>();
HashSet<Set<Topic>> ret=new HashSet<Set<Topic>>();
for(org.tmapi.core.Variant variant : name.getVariants()){
Set<org.tmapi.core.Topic> _scope=variant.getScope();
HashSet<Topic> scope=new HashSet<Topic>();
for(org.tmapi.core.Topic _theme : _scope){
scope.add(new T2WTopic(tm,_theme));
}
ret.add(scope);
}
return ret;
}
@Override
public void removeVariant(Set<Topic> scope) throws TopicMapException {
throw new UnsupportedOperationException("Editing not supported");
}
@Override
public String getData(Topic type, Topic version) throws TopicMapException {
Set<org.tmapi.core.Occurrence> os=t.getOccurrences(((T2WTopic)type).getWrapped());
for(org.tmapi.core.Occurrence o : os){
Set<org.tmapi.core.Topic> scope=o.getScope();
if(scope.size()==1){
org.tmapi.core.Topic _version=scope.iterator().next();
if(_version==((T2WTopic)version).getWrapped()) {
return o.getValue();
}
}
}
return null;
}
@Override
public Hashtable<Topic, String> getData(Topic type) throws TopicMapException {
Hashtable<Topic,String> ret=new Hashtable<Topic,String>();
Set<org.tmapi.core.Occurrence> os=t.getOccurrences(((T2WTopic)type).getWrapped());
for(org.tmapi.core.Occurrence o : os){
Set<org.tmapi.core.Topic> scope=o.getScope();
if(scope.size()==1){
org.tmapi.core.Topic _version=scope.iterator().next();
ret.put(new T2WTopic(tm,_version),o.getValue());
}
}
return ret;
}
@Override
public Collection<Topic> getDataTypes() throws TopicMapException {
HashSet<org.tmapi.core.Topic> _ret=new HashSet<org.tmapi.core.Topic>();
Set<org.tmapi.core.Occurrence> os=t.getOccurrences();
for(org.tmapi.core.Occurrence o : os){
Set<org.tmapi.core.Topic> scope=o.getScope();
if(scope.size()==1){
org.tmapi.core.Topic _type=o.getType();
_ret.add(_type);
}
}
return tm.wrapTopics(_ret);
}
@Override
public void setData(Topic type, Hashtable<Topic, String> versionData) throws TopicMapException {
throw new UnsupportedOperationException("Editing not supported");
}
@Override
public void setData(Topic type, Topic version, String value) throws TopicMapException {
throw new UnsupportedOperationException("Editing not supported");
}
@Override
public void removeData(Topic type, Topic version) throws TopicMapException {
throw new UnsupportedOperationException("Editing not supported");
}
@Override
public void removeData(Topic type) throws TopicMapException {
throw new UnsupportedOperationException("Editing not supported");
}
@Override
public Locator getSubjectLocator() throws TopicMapException {
Set<org.tmapi.core.Locator> ls=t.getSubjectLocators();
if(ls.isEmpty()) return null;
else if(ls.size()==1) return tm.createLocator(ls.iterator().next().toExternalForm());
else {
ArrayList<String> sort=new ArrayList<String>();
for(org.tmapi.core.Locator l : ls){
sort.add(l.toExternalForm());
}
Collections.sort(sort);
return tm.createLocator(sort.get(0));
}
}
@Override
public void setSubjectLocator(Locator l) throws TopicMapException {
throw new UnsupportedOperationException("Editing not supported");
}
@Override
public TopicMap getTopicMap() {
return tm;
}
@Override
public Collection<Association> getAssociations() throws TopicMapException {
Set<org.tmapi.core.Role> rs=t.getRolesPlayed();
HashSet<org.tmapi.core.Association> _ret=new HashSet<org.tmapi.core.Association>();
for(org.tmapi.core.Role r : rs){
_ret.add(r.getParent());
}
return tm.wrapAssociations(_ret);
}
@Override
public Collection<Association> getAssociations(Topic type) throws TopicMapException {
Set<org.tmapi.core.Role> rs=t.getRolesPlayed();
HashSet<org.tmapi.core.Association> _ret=new HashSet<org.tmapi.core.Association>();
for(org.tmapi.core.Role r : rs){
org.tmapi.core.Association _a=r.getParent();
if(_a.getType().equals(((T2WTopic)type).getWrapped()))
_ret.add(_a);
}
return tm.wrapAssociations(_ret);
}
@Override
public Collection<Association> getAssociations(Topic type, Topic role) throws TopicMapException {
HashSet<org.tmapi.core.Association> _ret=new HashSet<org.tmapi.core.Association>();
for(org.tmapi.core.Role r : t.getRolesPlayed(((T2WTopic)role).getWrapped(), ((T2WTopic)type).getWrapped())) {
_ret.add(r.getParent());
}
return tm.wrapAssociations(_ret);
}
@Override
public void remove() throws TopicMapException {
throw new UnsupportedOperationException("Editing not supported");
}
@Override
public long getEditTime() throws TopicMapException {
return 0; // should we still maybe keep track of editing time even though editing is not supported?
}
@Override
public void setEditTime(long time) throws TopicMapException {
}
@Override
public long getDependentEditTime() throws TopicMapException {
return 0;
}
@Override
public void setDependentEditTime(long time) throws TopicMapException {
}
@Override
public boolean isRemoved() throws TopicMapException {
return false;
}
@Override
public boolean isDeleteAllowed() throws TopicMapException {
return false; // editing not supported so delete not allowed either
}
@Override
public Collection<Topic> getTopicsWithDataType() throws TopicMapException {
Collection<org.tmapi.core.Occurrence> os=tm.getTypeIndex().getOccurrences(t);
HashSet<org.tmapi.core.Topic> _ret=new HashSet<org.tmapi.core.Topic>();
for(org.tmapi.core.Occurrence o : os){
if(o.getScope().size()==1)
_ret.add(o.getParent());
}
return tm.wrapTopics(_ret);
}
@Override
public Collection<Topic> getTopicsWithDataVersion() throws TopicMapException {
Collection<org.tmapi.core.Occurrence> os=tm.getScopedIndex().getOccurrences(t);
HashSet<org.tmapi.core.Topic> _ret=new HashSet<org.tmapi.core.Topic>();
for(org.tmapi.core.Occurrence o : os){
if(o.getScope().size()==1)
_ret.add(o.getParent());
}
return tm.wrapTopics(_ret);
}
@Override
public Collection<Association> getAssociationsWithType() throws TopicMapException {
Collection<org.tmapi.core.Association> as=tm.getTypeIndex().getAssociations(t);
HashSet<org.tmapi.core.Association> _ret=new HashSet<org.tmapi.core.Association>();
for(org.tmapi.core.Association a : as){
_ret.add(a);
}
return tm.wrapAssociations(_ret);
}
@Override
public Collection<Association> getAssociationsWithRole() throws TopicMapException {
Collection<org.tmapi.core.Role> rs=tm.getTypeIndex().getRoles(t);
HashSet<org.tmapi.core.Association> _ret=new HashSet<org.tmapi.core.Association>();
for(org.tmapi.core.Role r : rs){
_ret.add(r.getParent());
}
return tm.wrapAssociations(_ret);
}
@Override
public Collection<Topic> getTopicsWithVariantScope() throws TopicMapException {
org.tmapi.core.TopicMap _tm=t.getParent();
org.tmapi.core.Topic nameType=_tm.getTopicBySubjectIdentifier(_tm.createLocator(T2WTopicMap.TOPIC_NAME_SI));
if(nameType==null) return new ArrayList<Topic>();
Collection<org.tmapi.core.Variant> vs=tm.getScopedIndex().getVariants(t);
HashSet<org.tmapi.core.Topic> _ret=new HashSet<org.tmapi.core.Topic>();
for(org.tmapi.core.Variant v : vs){
org.tmapi.core.Name _name=v.getParent();
if(_name.getType().equals(nameType))
_ret.add(_name.getParent());
}
return tm.wrapTopics(_ret);
}
}
| 13,355 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
T2WTopicMap.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/tmapi2wandora/T2WTopicMap.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.topicmap.tmapi2wandora;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.tmapi.index.LiteralIndex;
import org.tmapi.index.ScopedIndex;
import org.tmapi.index.TypeInstanceIndex;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.topicmap.TopicMapListener;
import org.wandora.topicmap.TopicMapSearchOptions;
import org.wandora.topicmap.TopicMapStatData;
import org.wandora.topicmap.TopicMapStatOptions;
/**
* This is a Wandora TopicMap that wraps inside it a TMAPI topic map.
* This is a read-only implementation, you cannot edit the TMAPI topic map
* through this. However, you can always create a new Wandora topic map,
* then merge in a TMAPI topic map using this wrapper, after which you have the
* same topic map in a Wandora implementation which you can then edit.
*
* @author olli
*/
public class T2WTopicMap extends TopicMap {
public static final String TOPIC_NAME_SI="http://psi.topicmaps.org/iso13250/model/topic-name";
public static final String TYPE_STRING_SI="http://www.w3.org/TR/xmlschema-2/#string";
protected org.tmapi.core.TopicMap tm;
protected TypeInstanceIndex typeIndex;
protected LiteralIndex literalIndex;
protected ScopedIndex scopedIndex;
public T2WTopicMap(org.tmapi.core.TopicMap tm){
this.tm=tm;
typeIndex=tm.getIndex(TypeInstanceIndex.class);
literalIndex=tm.getIndex(LiteralIndex.class);
scopedIndex=tm.getIndex(ScopedIndex.class);
}
@Override
public void close() {
}
public TypeInstanceIndex getTypeIndex(){
return typeIndex;
}
public LiteralIndex getLiteralIndex(){
return literalIndex;
}
public ScopedIndex getScopedIndex(){
return scopedIndex;
}
public Collection<Topic> wrapTopics(Collection<org.tmapi.core.Topic> ts){
ArrayList<Topic> ret=new ArrayList<Topic>();
for(org.tmapi.core.Topic t : ts){
ret.add(new T2WTopic(this,t));
}
return ret;
}
public Collection<Association> wrapAssociations(Collection<org.tmapi.core.Association> as){
ArrayList<Association> ret=new ArrayList<Association>();
for(org.tmapi.core.Association a : as){
ret.add(new T2WAssociation(this,a));
}
return ret;
}
public Collection<Locator> wrapLocators(Collection<org.tmapi.core.Locator> ls) throws TopicMapException {
ArrayList<Locator> ret=new ArrayList<Locator>();
for(org.tmapi.core.Locator l : ls){
ret.add(createLocator(l.toExternalForm()));
}
return ret;
}
@Override
public Topic getTopic(Locator si) throws TopicMapException {
org.tmapi.core.Topic t=tm.getTopicBySubjectIdentifier(tm.createLocator(si.toExternalForm()));
if(t==null) return null;
return new T2WTopic(this,t);
}
@Override
public Topic getTopicBySubjectLocator(Locator sl) throws TopicMapException {
org.tmapi.core.Topic t=tm.getTopicBySubjectLocator(tm.createLocator(sl.toExternalForm()));
if(t==null) return null;
return new T2WTopic(this,t);
}
@Override
public Topic createTopic(String id) throws TopicMapException {
throw new UnsupportedOperationException("Editing not supported");
}
@Override
public Topic createTopic() throws TopicMapException {
throw new UnsupportedOperationException("Editing not supported");
}
@Override
public Association createAssociation(Topic type) throws TopicMapException {
throw new UnsupportedOperationException("Editing not supported");
}
@Override
public Collection<Topic> getTopicsOfType(Topic type) throws TopicMapException {
Collection<org.tmapi.core.Topic> ts=typeIndex.getTopics(((T2WTopic)type).getWrapped());
return wrapTopics(ts);
}
@Override
public Topic getTopicWithBaseName(String name) throws TopicMapException {
Collection<org.tmapi.core.Name> ns=literalIndex.getNames(name);
for(org.tmapi.core.Name n : ns){
org.tmapi.core.Topic type=n.getType();
for(org.tmapi.core.Locator l : type.getSubjectIdentifiers()){
if(l.toExternalForm().equals(TOPIC_NAME_SI)){
return new T2WTopic(this,n.getParent());
}
}
}
return null;
}
@Override
public Iterator<Topic> getTopics() throws TopicMapException {
final Iterator<org.tmapi.core.Topic> iter=tm.getTopics().iterator();
return new Iterator<Topic>(){
@Override
public boolean hasNext() {
return iter.hasNext();
}
@Override
public Topic next() {
return new T2WTopic(T2WTopicMap.this,iter.next());
}
@Override
public void remove() { throw new UnsupportedOperationException(); }
};
}
@Override
public Topic[] getTopics(String[] sis) throws TopicMapException {
ArrayList<Topic> ret=new ArrayList<Topic>();
for(String si : sis){
ret.add(getTopic(si));
}
return ret.toArray(new Topic[ret.size()]);
}
@Override
public Iterator<Association> getAssociations() throws TopicMapException {
final Iterator<org.tmapi.core.Association> iter=tm.getAssociations().iterator();
return new Iterator<Association>(){
@Override
public boolean hasNext() {
return iter.hasNext();
}
@Override
public Association next() {
return new T2WAssociation(T2WTopicMap.this,iter.next());
}
@Override
public void remove() { throw new UnsupportedOperationException(); }
};
}
@Override
public Collection<Association> getAssociationsOfType(Topic type) throws TopicMapException {
Collection<org.tmapi.core.Association> as=typeIndex.getAssociations(((T2WTopic)type).getWrapped());
return wrapAssociations(as);
}
@Override
public int getNumTopics() throws TopicMapException {
return tm.getTopics().size();
}
@Override
public int getNumAssociations() throws TopicMapException {
return tm.getAssociations().size();
}
@Override
public Topic copyTopicIn(Topic t, boolean deep) throws TopicMapException {
throw new UnsupportedOperationException("Editing not supported");
}
@Override
public Association copyAssociationIn(Association a) throws TopicMapException {
throw new UnsupportedOperationException("Editing not supported");
}
@Override
public void copyTopicAssociationsIn(Topic t) throws TopicMapException {
throw new UnsupportedOperationException("Editing not supported");
}
@Override
public void setTrackDependent(boolean v) throws TopicMapException {
}
@Override
public boolean trackingDependent() throws TopicMapException {
return true;
}
@Override
public void addTopicMapListener(TopicMapListener listener) {
// topic map isn't edited so no method of the listener ever need be called
}
@Override
public void removeTopicMapListener(TopicMapListener listener) {
}
@Override
public List<TopicMapListener> getTopicMapListeners() {
return new ArrayList<TopicMapListener>();
// this should really return the list
}
@Override
public void disableAllListeners() {
}
@Override
public void enableAllListeners() {
// listeners aren't used anyway because editing isn't supported
}
@Override
public boolean isTopicMapChanged() throws TopicMapException {
return false; // no editing, never changed
}
@Override
public boolean resetTopicMapChanged() throws TopicMapException {
return false;
}
@Override
public Collection<Topic> search(String query, TopicMapSearchOptions options) throws TopicMapException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public TopicMapStatData getStatistics(TopicMapStatOptions options) throws TopicMapException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void clearTopicMap() throws TopicMapException {
throw new UnsupportedOperationException("Editing not supported");
}
@Override
public void clearTopicMapIndexes() throws TopicMapException {
}
}
| 9,679 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
XTMParser2.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/parser/XTMParser2.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.wandora.topicmap.parser;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Stack;
import org.wandora.application.Wandora;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.topicmap.TopicMapLogger;
import org.wandora.topicmap.XTMPSI;
import org.wandora.utils.Options;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
/**
*
* @author olli
*/
public class XTMParser2 implements org.xml.sax.ContentHandler, org.xml.sax.ErrorHandler {
public static final String OCCURRENCE_RESOURCE_REF_KEY = "topicmap.xtm2.convertOccurrenceResourceRefsToResourceDatas";
public static final String IMPORT_XML_IDENTIFIERS_KEY = "topicmap.xtm2.importIdentifiers";
public static final String ENSURE_UNIQUE_BASENAMES_KEY = "topicmap.xtm2.ensureUniqueBasenames";
public static final int STATE_ROOT=0;
public static final int STATE_TOPICMAP=1;
public static final int STATE_TOPIC=2;
public static final int STATE_NAME=3;
public static final int STATE_VALUE=4;
public static final int STATE_VARIANT=5;
public static final int STATE_SCOPE=6;
public static final int STATE_INSTANCEOF=7;
public static final int STATE_TYPE=8;
public static final int STATE_OCCURRENCE=9;
public static final int STATE_RESOURCEDATA=10;
public static final int STATE_ASSOCIATION=11;
public static final int STATE_ROLE=12;
public static final String E_TOPICMAP = "topicMap";
public static final String E_VERSION = "versoin";
public static final String E_TOPIC = "topic";
public static final String E_NAME = "name";
public static final String E_VALUE = "value";
public static final String E_VARIANT = "variant";
public static final String E_SCOPE = "scope";
public static final String E_INSTANCEOF = "instanceOf";
public static final String E_TYPE = "type";
public static final String E_OCCURRENCE = "occurrence";
public static final String E_RESOURCEDATA = "resourceData";
public static final String E_ASSOCIATION = "association";
public static final String E_ROLE = "role";
public static final String E_TOPICREF = "topicRef";
public static final String E_RESOURCEREF = "resourceRef";
public static final String E_SUBJECTLOCATOR = "subjectLocator";
public static final String E_SUBJECTIDENTIFIER = "subjectIdentifier";
public static final String E_SUBJECTIDENTITY = "subjectIdentity";
public static final String E_MERGEMAP = "mergeMap";
public static final String E_ITEMIDENTITY = "itemIdentity";
public static boolean CONVERT_OCCURRENCE_RESOURCE_REF_TO_RESOURCE_DATA = true;
public static boolean ENSURE_UNIQUE_BASENAMES = false;
public static boolean IMPORT_XML_IDENTIFIERS = true;
protected TopicMap tm;
protected TopicMapLogger logger;
protected HashMap<String,String> idmapping;
protected Stack<Integer> stateStack;
protected int state;
protected int topicCount;
protected int associationCount;
protected int occurrenceCount;
protected int elementCount;
public XTMParser2(TopicMap tm,TopicMapLogger logger){
this.tm=tm;
this.logger=logger;
state=STATE_ROOT;
stateStack=new Stack<Integer>();
idmapping=new HashMap<String,String>();
Wandora w = Wandora.getWandora();
if(w != null) {
Options options = w.getOptions();
setOccurrenceResourceRef2ResourceData(options.getBoolean(OCCURRENCE_RESOURCE_REF_KEY, CONVERT_OCCURRENCE_RESOURCE_REF_TO_RESOURCE_DATA));
setImportXmlIdentifiers(options.getBoolean(IMPORT_XML_IDENTIFIERS_KEY, IMPORT_XML_IDENTIFIERS));
setEnsureUniqueBasenames(options.getBoolean(ENSURE_UNIQUE_BASENAMES_KEY, ENSURE_UNIQUE_BASENAMES));
}
}
public void setOccurrenceResourceRef2ResourceData(boolean f) {
CONVERT_OCCURRENCE_RESOURCE_REF_TO_RESOURCE_DATA = f;
}
public void setImportXmlIdentifiers(boolean f) {
IMPORT_XML_IDENTIFIERS = f;
}
public void setEnsureUniqueBasenames(boolean f) {
ENSURE_UNIQUE_BASENAMES = f;
}
protected void handleRoot(String uri, String localName, String qName, Attributes atts){
if(qName.equals(E_TOPICMAP)){
startTopicMap();
}
else logger.log("Expecting root element "+E_TOPICMAP+", got "+qName);
}
protected void endRoot(String uri, String localName, String qName) {
}
protected void startTopicMap(){
stateStack.push(state);
state=STATE_TOPICMAP;
}
protected void handleTopicMap(String uri, String localName, String qName, Attributes atts){
if(qName.equals(E_VERSION)){
logger.log("Encountered "+E_VERSION+", ignoring");
}
else if(qName.equals(E_MERGEMAP)){
logger.log("Encountered unsupported "+E_MERGEMAP+", ignoring");
}
else if(qName.equals(E_TOPIC)){
startTopic(atts);
}
else if(qName.equals(E_ASSOCIATION)){
startAssociation();
}
else logger.log("Expecting one of "+E_VERSION+", "+E_MERGEMAP+", "+E_TOPIC+", "+E_ASSOCIATION+", got "+qName);
}
protected void endTopicMap(String uri, String localName, String qName){
if(qName.equals(E_TOPICMAP)){
postProcessTopicMap();
}
}
/**
* Remove temporary subject identifiers created during parse. This is
* necessary as temporary identifiers are reused during next parse.
* If a topic has only temporary subject identifier, a permanent
* subject identifier is created for the topic.
*/
protected void postProcessTopicMap(){
try {
// remove temporary subject identifiers
Iterator<Topic> topics=tm.getTopics();
Collection topicCollection = new ArrayList<Topic>();
while(topics.hasNext()) {
Topic t=topics.next();
topicCollection.add(t);
}
topics = topicCollection.iterator();
while(topics.hasNext()) {
Topic t=topics.next();
ArrayList<Locator> sis = new ArrayList<Locator>(t.getSubjectIdentifiers());
int sisSize = sis.size();
for(Locator si : sis) {
if(si.toExternalForm().startsWith(temporarySI)) {
if(sisSize < 2) {
// create permanent subject identifier before temporary can be removed.
String permanentSI = "http://wandora.org/si/xtm2/permanent/" + System.currentTimeMillis() + "-" + Math.round(Math.random()*999999);
// System.out.println("adding si "+permanentSI);
t.addSubjectIdentifier(new Locator( permanentSI ));
}
// System.out.println("Removing si "+si.toExternalForm());
t.removeSubjectIdentifier(si);
}
}
}
}
catch(TopicMapException tme){
logger.log(tme);
}
}
protected ParsedTopic parsedTopic;
protected void startTopic(Attributes atts) {
stateStack.push(state);
state=STATE_TOPIC;
parsedTopic=new ParsedTopic();
parsedTopic.id=atts.getValue("id");
topicCount++;
}
protected void handleTopic(String uri, String localName, String qName, Attributes atts){
if(qName.equals(E_ITEMIDENTITY)) {
String href=handleHRef(qName, atts);
if(href!=null) parsedTopic.itemIdentities.add(href);
}
else if(qName.equals(E_SUBJECTLOCATOR)) {
String href=handleHRef(qName, atts);
if(href!=null) parsedTopic.subjectLocators.add(href);
}
else if(qName.equals(E_SUBJECTIDENTIFIER)) {
String href=handleHRef(qName, atts);
if(href!=null) parsedTopic.subjectIdentifiers.add(href);
}
else if(qName.equals(E_INSTANCEOF)) startInstanceOf();
else if(qName.equals(E_NAME)) startName();
else if(qName.equals(E_OCCURRENCE)) startOccurrence();
else logger.log("Expecting one of "+E_ITEMIDENTITY+", "+E_SUBJECTLOCATOR+", "+E_SUBJECTIDENTIFIER+", "+E_INSTANCEOF+", "+E_NAME+", "+E_OCCURRENCE+", got "+qName);
}
protected void endTopic(String uri, String localName, String qName){
if(qName.equals(E_TOPIC)){
state=stateStack.pop();
processTopic();
}
}
protected void processTopic(){
try{
Topic t=null;
if(parsedTopic.id!=null) {
t=getOrCreateTopicID("#"+parsedTopic.id);
}
else {
t=tm.createTopic();
}
if(parsedTopic.types!=null){
ArrayList<Topic> types=processTopicRefs(parsedTopic.types);
for(Topic type : types){
t.addType(type);
}
}
for(String si : parsedTopic.subjectIdentifiers){
t.addSubjectIdentifier(tm.createLocator(si));
}
if(parsedTopic.itemIdentities.size()>0){
logger.log("Warning, converting item identities to subject identifiers");
for(String si : parsedTopic.itemIdentities){
t.addSubjectIdentifier(tm.createLocator(si));
}
}
if(parsedTopic.subjectLocators.size()>1)
logger.log("Warning, more than one subject locator found, ignoring all but one");
if(parsedTopic.subjectLocators.size()>0){
t.setSubjectLocator(tm.createLocator(parsedTopic.subjectLocators.get(0)));
}
for(ParsedName name : parsedTopic.names){
ArrayList<Topic> scope=processTopicRefs(name.scope);
if(name.type!=null) {
logger.log("Warning, name has type, moving to scope");
// if(name.scope==null) name.scope=new ArrayList<Topic>();
if(scope==null) scope=new ArrayList<Topic>();
scope.add(getOrCreateTopicRef(name.type));
}
if(name.value!=null && name.value.length()>0){
// if(name.scope==null || name.scope.size()==0){
if(scope==null || scope.isEmpty()){
if(ENSURE_UNIQUE_BASENAMES) {
int i = 2;
if(tm.getTopicWithBaseName(name.value) != null) {
while(tm.getTopicWithBaseName(name.value+" ("+i+")") != null) i++;
name.value = name.value+" ("+i+")";
}
}
t.setBaseName(name.value);
}
else {
// t.setVariant(new HashSet<Topic>(name.scope), name.value);
t.setVariant(new LinkedHashSet<Topic>(scope), name.value);
}
}
for(ParsedVariant v : name.variants) {
HashSet<Topic> s=new LinkedHashSet<Topic>();
// if(name.scope!=null) s.addAll(name.scope);
if(name.scope!=null) s.addAll(scope);
// if(v.scope!=null) s.addAll(v.scope);
if(v.scope!=null) s.addAll(processTopicRefs(v.scope));
t.setVariant(s,v.data);
}
}
for(ParsedOccurrence o : parsedTopic.occurrences){
if(o.type==null) {
logger.log("Warning, occurrence has no type, skipping.");
continue;
}
if(o.ref!=null) {
if(CONVERT_OCCURRENCE_RESOURCE_REF_TO_RESOURCE_DATA) {
logger.log("Converting resource ref occurrence to resource data occurrence");
Topic version=null;
if(o.scope==null || o.scope.isEmpty()) {
logger.log("Warning, occurrence has no scope, using lang independent");
version=getOrCreateTopic(XTMPSI.getLang(null));
}
else {
if(o.scope.size()>1) logger.log("Warning, variant scope has more than one topic, ignoring all but one.");
version=getOrCreateTopicRef(o.scope.get(0));
}
t.setData(getOrCreateTopicRef(o.type), version, o.ref);
}
else {
logger.log("Converting resource ref occurrence to association");
Topic t2=tm.createTopic();
t2.addSubjectIdentifier(tm.makeSubjectIndicatorAsLocator());
t2.setBaseName("Occurrence file: "+o.ref);
t2.setSubjectLocator(tm.createLocator(o.ref));
Topic orole=getOrCreateTopic("http://wandora.org/si/compatibility/occurrencerolereference");
Topic trole=getOrCreateTopic("http://wandora.org/si/compatibility/occurrenceroletopic");
// Association a=tm.createAssociation(o.type);
Association a=tm.createAssociation(getOrCreateTopicRef(o.type));
a.addPlayer(t,trole);
a.addPlayer(t2,orole);
}
}
else if(o.data==null){
logger.log("Warning, occurrence has no data or resource ref, skipping.");
continue;
}
else{
Topic version=null;
if(o.scope==null || o.scope.isEmpty()) {
logger.log("Warning, occurrence has no scope, using lang independent");
version=getOrCreateTopic(XTMPSI.getLang(null));
}
else {
if(o.scope.size()>1) logger.log("Warning, variant scope has more than one topic, ignoring all but one.");
// version=o.scope.get(0);
version=getOrCreateTopicRef(o.scope.get(0));
}
// t.setData(o.type, version, o.data);
t.setData(getOrCreateTopicRef(o.type), version, o.data);
}
}
}
catch(TopicMapException tme){
logger.log(tme);
}
}
protected ParsedName parsedName;
protected void startName(){
stateStack.push(state);
state=STATE_NAME;
parsedName=new ParsedName();
}
protected void handleName(String uri, String localName, String qName, Attributes atts){
if(qName.equals(E_TYPE)) startType();
else if(qName.equals(E_SCOPE)) startScope();
else if(qName.equals(E_VALUE)) startValue();
else if(qName.equals(E_RESOURCEREF)){
logger.log("Unsupported resourceRef in name, skipping.");
}
else if(qName.equals(E_VARIANT)) startVariant();
else logger.log("Expecting one of "+E_TYPE+", "+E_SCOPE+", "+E_RESOURCEDATA+", "+E_RESOURCEREF+", got "+qName);
}
protected void endName(String uri, String localName, String qName){
if(qName.equals(E_NAME)){
state=stateStack.pop();
if(state==STATE_TOPIC) parsedTopic.names.add(parsedName);
}
}
protected String parsedCharacters;
protected String parsedValue;
protected void startValue(){
stateStack.push(state);
state=STATE_VALUE;
parsedCharacters="";
parsedValue=null;
}
protected void handleValue(String uri, String localName, String qName, Attributes atts){
}
protected void endValue(String uri, String localName, String qName){
if(qName.equals(E_VALUE)){
parsedValue=parsedCharacters;
state=stateStack.pop();
if(state==STATE_NAME) parsedName.value=parsedValue;
}
}
protected ParsedVariant parsedVariant;
protected void startVariant(){
stateStack.push(state);
state=STATE_VARIANT;
parsedVariant=new ParsedVariant();
}
protected void handleVariant(String uri, String localName, String qName, Attributes atts){
if(qName.equals(E_SCOPE)) startScope();
else if(qName.equals(E_RESOURCEREF)){
logger.log("Unsupported variant element "+E_RESOURCEDATA);
}
else if(qName.equals(E_RESOURCEDATA)) startResourceData();
else logger.log("Expecting one of "+E_SCOPE+", "+E_RESOURCEREF+", "+E_RESOURCEDATA+", got "+qName);
}
protected void endVariant(String uri, String localName, String qName){
if(qName.equals(E_VARIANT)){
state=stateStack.pop();
if(state==STATE_NAME) parsedName.variants.add(parsedVariant);
}
}
protected String handleHRef(String qName, Attributes atts) {
String href=atts.getValue("href");
if(href==null) logger.log("Expecting attribute href in "+qName);
return href;
}
// protected ArrayList<Topic> parsedScope;
protected ArrayList<String> parsedScope;
protected void startScope(){
stateStack.push(state);
state=STATE_SCOPE;
// parsedScope=new ArrayList<Topic>();
parsedScope=new ArrayList<String>();
}
protected void handleScope(String uri, String localName, String qName, Attributes atts){
if(qName.equals(E_TOPICREF)){
// try{
String href=handleHRef(qName,atts);
if(href!=null){
// Topic t=getOrCreateTopicRef(href);
// if(t!=null) parsedScope.add(t);
parsedScope.add(href);
}
// }catch(TopicMapException tme){logger.log(tme);}
}
else logger.log("Expecting "+E_TOPICREF+", got "+qName);
}
protected void endScope(String uri, String localName, String qName){
if(qName.equals(E_SCOPE)){
state=stateStack.pop();
if(state==STATE_VARIANT) parsedVariant.scope=parsedScope;
else if(state==STATE_OCCURRENCE) parsedOccurrence.scope=parsedScope;
else if(state==STATE_ASSOCIATION) parsedAssociation.scope=parsedScope;
else if(state==STATE_NAME) parsedName.scope=parsedScope;
}
}
// protected ArrayList<Topic> parsedInstances;
protected ArrayList<String> parsedInstances;
protected void startInstanceOf(){
stateStack.push(state);
state=STATE_INSTANCEOF;
// parsedInstances=new ArrayList<Topic>();
parsedInstances=new ArrayList<String>();
}
protected void handleInstanceOf(String uri, String localName, String qName, Attributes atts){
if(qName.equals(E_TOPICREF)){
// try{
String href=handleHRef(qName,atts);
if(href!=null){
// Topic t=getOrCreateTopicRef(href);
// if(t!=null) parsedInstances.add(t);
parsedInstances.add(href);
}
// }catch(TopicMapException tme){logger.log(tme);}
}
else logger.log("Expecting "+E_TOPICREF+", got "+qName);
}
protected void endInstanceOf(String uri, String localName, String qName){
if(qName.equals(E_INSTANCEOF)){
state=stateStack.pop();
if(state==STATE_TOPIC) parsedTopic.types=parsedInstances;
}
}
// protected Topic parsedType;
protected String parsedType;
protected void startType(){
stateStack.push(state);
state=STATE_TYPE;
parsedType=null;
}
protected void handleType(String uri, String localName, String qName, Attributes atts){
if(qName.equals(E_TOPICREF)){
if(parsedType!=null) logger.log("Encountered another topicRef in type, overwriting previous.");
String href=handleHRef(qName,atts);
if(href!=null){
// try{
// parsedType=getOrCreateTopicRef(href);
parsedType=href;
// }catch(TopicMapException tme){logger.log(tme);}
}
}
else logger.log("Expecting "+E_TOPICREF+", got "+qName);
}
protected void endType(String uri, String localName, String qName){
if(qName.equals(E_TYPE)){
state=stateStack.pop();
if(state==STATE_OCCURRENCE) parsedOccurrence.type=parsedType;
else if(state==STATE_ROLE) parsedRole.type=parsedType;
else if(state==STATE_ASSOCIATION) parsedAssociation.type=parsedType;
else if(state==STATE_NAME) parsedName.type=parsedType;
}
}
protected ParsedOccurrence parsedOccurrence;
protected void startOccurrence(){
stateStack.push(state);
state=STATE_OCCURRENCE;
parsedOccurrence=new ParsedOccurrence();
occurrenceCount++;
}
protected void handleOccurrence(String uri, String localName, String qName, Attributes atts){
if(qName.equals(E_TYPE)) startType();
else if(qName.equals(E_SCOPE)) startScope();
else if(qName.equals(E_RESOURCEREF)){
String href=handleHRef(qName,atts);
if(href!=null) parsedOccurrence.ref=href;
}
else if(qName.equals(E_RESOURCEDATA)) startResourceData();
else logger.log("Expecting one of "+E_TYPE+", "+E_SCOPE+", "+E_RESOURCEREF+", "+E_RESOURCEDATA+", got "+qName);
}
protected void endOccurrence(String uri, String localName, String qName){
if(qName.equals(E_OCCURRENCE)){
state=stateStack.pop();
if(state==STATE_TOPIC) parsedTopic.occurrences.add(parsedOccurrence);
}
}
protected String parsedResourceData;
protected void startResourceData(){
stateStack.push(state);
state=STATE_RESOURCEDATA;
parsedCharacters="";
parsedResourceData=null;
}
protected void handleResourceData(String uri, String localName, String qName, Attributes atts){
}
protected void endResourceData(String uri, String localName, String qName){
if(qName.equals(E_RESOURCEDATA)){
parsedResourceData=parsedCharacters;
state=stateStack.pop();
if(state==STATE_VARIANT) parsedVariant.data=parsedResourceData;
else if(state==STATE_OCCURRENCE) parsedOccurrence.data=parsedResourceData;
}
}
protected ParsedAssociation parsedAssociation;
protected void startAssociation(){
stateStack.push(state);
state=STATE_ASSOCIATION;
parsedAssociation=new ParsedAssociation();
associationCount++;
}
protected void handleAssociation(String uri, String localName, String qName, Attributes atts){
if(qName.equals(E_TYPE)) startType();
else if(qName.equals(E_SCOPE)) {
logger.log("Warning, scope not supported in association");
startScope();
}
else if(qName.equals(E_ROLE)) startRole();
else logger.log("Expecting one of "+E_TYPE+", "+E_SCOPE+", "+E_ROLE+", got "+qName);
}
protected void endAssociation(String uri, String localName, String qName){
if(qName.equals(E_ASSOCIATION)){
state=stateStack.pop();
processAssociation();
}
}
protected void processAssociation() {
if(parsedAssociation.type==null) logger.log("No type in association");
else if(parsedAssociation.roles.isEmpty()) logger.log("No players in association");
else {
try {
// Association a=tm.createAssociation(parsedAssociation.type);
Association a=tm.createAssociation(getOrCreateTopicRef(parsedAssociation.type));
for(ParsedRole r : parsedAssociation.roles) {
// a.addPlayer(r.topic,r.type);
a.addPlayer(getOrCreateTopicRef(r.topic),getOrCreateTopicRef(r.type));
}
}
catch(TopicMapException tme){logger.log(tme);}
}
}
protected ParsedRole parsedRole;
protected void startRole() {
stateStack.push(state);
state=STATE_ROLE;
parsedRole=new ParsedRole();
}
protected void handleRole(String uri, String localName, String qName, Attributes atts){
if(qName.equals(E_TYPE)){
startType();
}
else if(qName.equals(E_TOPICREF)){
String href=handleHRef(qName,atts);
if(href!=null){
// try{
// Topic t=getOrCreateTopicRef(href);
// if(t!=null) parsedRole.topic=t;
parsedRole.topic=href;
// } catch(TopicMapException tme){logger.log(tme);}
}
}
else logger.log("Expecting one of "+E_TYPE+", "+E_TOPICREF+", got "+qName);
}
protected void endRole(String uri, String localName, String qName){
if(qName.equals(E_ROLE)) {
state=stateStack.pop();
if(state==STATE_ASSOCIATION) parsedAssociation.roles.add(parsedRole);
}
}
protected static class ParsedTopic{
public String id;
public ArrayList<String> itemIdentities;
public ArrayList<String> subjectLocators;
public ArrayList<String> subjectIdentifiers;
// public ArrayList<Topic> types;
public ArrayList<String> types;
public ArrayList<ParsedName> names;
public ArrayList<ParsedOccurrence> occurrences;
public ParsedTopic(){
itemIdentities=new ArrayList<String>();
subjectLocators=new ArrayList<String>();
subjectIdentifiers=new ArrayList<String>();
names=new ArrayList<ParsedName>();
occurrences=new ArrayList<ParsedOccurrence>();
}
}
protected static class ParsedAssociation{
public ArrayList<ParsedRole> roles;
// public ArrayList<Topic> scope;
public ArrayList<String> scope;
// public Topic type;
public String type;
public ParsedAssociation(){
roles=new ArrayList<ParsedRole>();
}
}
protected static class ParsedName{
// public Topic type;
public String type;
// public ArrayList<Topic> scope;
public ArrayList<String> scope;
public String value;
public ArrayList<ParsedVariant> variants;
public ParsedName(){
variants=new ArrayList<ParsedVariant>();
}
}
protected static class ParsedOccurrence{
// public Topic type;
public String type;
// public ArrayList<Topic> scope;
public ArrayList<String> scope;
public String ref;
public String data;
public ParsedOccurrence(){
}
}
protected static class ParsedVariant{
// public ArrayList<Topic> scope;
public ArrayList<String> scope;
public String data;
public ParsedVariant(){
}
}
protected static class ParsedRole {
// public Topic type;
public String type;
// public Topic topic;
public String topic;
public ParsedRole(){
}
}
//////////////////////////////
protected ArrayList<Topic> processTopicRefs(ArrayList<String> hrefs) throws TopicMapException {
if(hrefs==null) return null;
ArrayList<Topic> ret=new ArrayList<Topic>();
for(String href : hrefs) {
ret.add(getOrCreateTopicRef(href));
}
return ret;
}
protected Topic getOrCreateTopicRef(String ref) throws TopicMapException {
String si=idmapping.get(ref);
if(si!=null) return getOrCreateTopic(si);
Topic t=tm.getTopic(ref);
if(t!=null) return t;
si=temporarySI+ref;
idmapping.put(ref,si);
return getOrCreateTopic(si, hrefToId(ref));
}
protected String hrefToId(String ref) {
if(ref != null) {
if(ref.startsWith("#")) {
return ref.substring(1);
}
}
return ref;
}
protected Topic getOrCreateTopic(String si) throws TopicMapException {
Topic t=tm.getTopic(si);
if(t==null) {
t=tm.createTopic();
t.addSubjectIdentifier(tm.createLocator(si));
}
return t;
}
protected Topic getOrCreateTopic(String si, String id) throws TopicMapException {
Topic t=tm.getTopic(si);
if(t==null) {
if(id != null && IMPORT_XML_IDENTIFIERS) {
t = tm.createTopic(hrefToId(id));
}
else {
t = tm.createTopic();
}
t.addSubjectIdentifier(tm.createLocator(si));
}
return t;
}
/*
* TemporarySI should *NOT* be same as the default temporary subject identifier
* path. XTMParser2 removes subject identifiers based on the temporarySI
* after parse. Wandora removes temporary subject identifiers after parse.
* Look at the method postProcessTopicMap above.
*/
protected String temporarySI="http://wandora.org/si/xtm2/temp/";
protected Topic getOrCreateTopicID(String id) throws TopicMapException {
String si=idmapping.get(id);
if(si!=null) {
return getOrCreateTopic(si, hrefToId(id));
}
si=temporarySI+id;
idmapping.put(id,si);
return getOrCreateTopic(si, hrefToId(id));
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
switch(state){
case STATE_RESOURCEDATA: case STATE_VALUE:
parsedCharacters+=new String(ch,start,length);
break;
}
}
@Override
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
if(logger.forceStop()) {
throw new org.xml.sax.SAXException("user_interrupt");
}
// logger.log("Start element "+qName+" state="+state);
switch(state){
case STATE_ROOT:
handleRoot(uri, localName, qName, atts);
break;
case STATE_TOPICMAP:
handleTopicMap(uri, localName, qName, atts);
break;
case STATE_TOPIC:
handleTopic(uri, localName, qName, atts);
break;
case STATE_NAME:
handleName(uri, localName, qName, atts);
break;
case STATE_VALUE:
handleValue(uri, localName, qName, atts);
break;
case STATE_VARIANT:
handleVariant(uri, localName, qName, atts);
break;
case STATE_SCOPE:
handleScope(uri, localName, qName, atts);
break;
case STATE_INSTANCEOF:
handleInstanceOf(uri, localName, qName, atts);
break;
case STATE_TYPE:
handleType(uri, localName, qName, atts);
break;
case STATE_OCCURRENCE:
handleOccurrence(uri, localName, qName, atts);
break;
case STATE_RESOURCEDATA:
handleResourceData(uri, localName, qName, atts);
break;
case STATE_ASSOCIATION:
handleAssociation(uri, localName, qName, atts);
break;
case STATE_ROLE:
handleRole(uri, localName, qName, atts);
break;
}
// logger.log(" state="+state);
if( (elementCount++ % 10000) == 9999) {
logger.hlog("Importing XTM (2.0) topic map.\nFound " + topicCount + " topics, " + associationCount + " associations and "+ occurrenceCount + " occurrences.");
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
// logger.log("End element "+qName+" state="+state);
switch(state){
case STATE_ROOT:
endRoot(uri, localName, qName);
break;
case STATE_TOPICMAP:
endTopicMap(uri, localName, qName);
break;
case STATE_TOPIC:
endTopic(uri, localName, qName);
break;
case STATE_NAME:
endName(uri, localName, qName);
break;
case STATE_VALUE:
endValue(uri, localName, qName);
break;
case STATE_VARIANT:
endVariant(uri, localName, qName);
break;
case STATE_SCOPE:
endScope(uri, localName, qName);
break;
case STATE_INSTANCEOF:
endInstanceOf(uri, localName, qName);
break;
case STATE_TYPE:
endType(uri, localName, qName);
break;
case STATE_OCCURRENCE:
endOccurrence(uri, localName, qName);
break;
case STATE_RESOURCEDATA:
endResourceData(uri, localName, qName);
break;
case STATE_ASSOCIATION:
endAssociation(uri, localName, qName);
break;
case STATE_ROLE:
endRole(uri, localName, qName);
break;
}
// logger.log(" state="+state);
}
@Override
public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
}
@Override
public void processingInstruction(String target, String data) throws SAXException {
}
@Override
public void setDocumentLocator(org.xml.sax.Locator locator) {
}
@Override
public void skippedEntity(String name) throws SAXException {
}
@Override
public void startDocument() throws SAXException {
}
@Override
public void endDocument() throws SAXException {
logger.log("Importing XTM (2.0) topic map.\nFound " + topicCount + " topics, " + associationCount + " associations and "+ occurrenceCount + " occurrences.");
}
@Override
public void startPrefixMapping(String prefix, String uri) throws SAXException {
}
@Override
public void endPrefixMapping(String prefix) throws SAXException {
}
@Override
public void error(SAXParseException exception) throws SAXException {
throw exception;
}
@Override
public void fatalError(SAXParseException exception) throws SAXException {
throw exception;
}
@Override
public void warning(SAXParseException exception) throws SAXException {
logger.log(exception);
}
}
| 36,817 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
XTMAdaptiveParser.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/parser/XTMAdaptiveParser.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.wandora.topicmap.parser;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapLogger;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
/**
*
* @author olli
*/
public class XTMAdaptiveParser implements ContentHandler, ErrorHandler {
protected ContentHandler xtm1parser;
protected ContentHandler xtm2parser;
protected ErrorHandler xtm1errorHandler;
protected ErrorHandler xtm2errorHandler;
protected ContentHandler selectedContentHandler;
protected ErrorHandler selectedErrorHandler;
protected TopicMapLogger logger;
public XTMAdaptiveParser(TopicMap tm,TopicMapLogger logger,ContentHandler xtm1parser){
this.xtm1parser=xtm1parser;
this.xtm1errorHandler=(ErrorHandler)xtm1parser;
this.xtm2parser=new XTMParser2(tm,logger);
this.xtm2errorHandler=(ErrorHandler)xtm2parser;
this.logger=logger;
}
public void selectXTM2(){
logger.log("Using XTM 2.0 parser");
selectedContentHandler=xtm2parser;
selectedErrorHandler=xtm2errorHandler;
}
public void selectXTM1(){
logger.log("Using XTM 1.0 parser");
selectedContentHandler=xtm1parser;
selectedErrorHandler=xtm1errorHandler;
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if(selectedContentHandler!=null) selectedContentHandler.characters(ch,start,length);
}
@Override
public void endDocument() throws SAXException {
if(selectedContentHandler!=null) selectedContentHandler.endDocument();
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if(selectedContentHandler!=null) selectedContentHandler.endElement(uri,localName,qName);
}
@Override
public void endPrefixMapping(String prefix) throws SAXException {
if(selectedContentHandler!=null) selectedContentHandler.endPrefixMapping(prefix);
}
@Override
public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
if(selectedContentHandler!=null) selectedContentHandler.ignorableWhitespace(ch,start,length);
}
@Override
public void processingInstruction(String target, String data) throws SAXException {
if(selectedContentHandler!=null) selectedContentHandler.processingInstruction(target,data);
}
@Override
public void setDocumentLocator(org.xml.sax.Locator locator) {
if(selectedContentHandler!=null) selectedContentHandler.setDocumentLocator(locator);
}
@Override
public void skippedEntity(String name) throws SAXException {
if(selectedContentHandler!=null) selectedContentHandler.skippedEntity(name);
}
@Override
public void startDocument() throws SAXException {
if(selectedContentHandler!=null) selectedContentHandler.startDocument();
}
@Override
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
if(selectedContentHandler==null && qName.equals("topicMap")){
String version=atts.getValue("version");
if(version!=null && version.startsWith("2")) selectXTM2();
else selectXTM1();
}
if(selectedContentHandler!=null) selectedContentHandler.startElement(uri,localName,qName,atts);
}
@Override
public void startPrefixMapping(String prefix, String uri) throws SAXException {
/* if(selectedContentHandler==null){
if(prefix==null || prefix.length()==0){
if(uri.equals("http://www.topicmaps.org/xtm/")) selectXTM2();
else if(uri.equals("http://www.topicmaps.org/xtm/1.0")) selectXTM1();
}
}*/
if(selectedContentHandler!=null) selectedContentHandler.startPrefixMapping(prefix,uri);
}
@Override
public void error(SAXParseException exception) throws SAXException {
if(selectedErrorHandler!=null) selectedErrorHandler.error(exception);
}
@Override
public void fatalError(SAXParseException exception) throws SAXException {
if(selectedErrorHandler!=null) selectedErrorHandler.fatalError(exception);
}
@Override
public void warning(SAXParseException exception) throws SAXException {
if(selectedErrorHandler!=null) selectedErrorHandler.warning(exception);
}
}
| 5,362 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
LTMParser.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/parser/LTMParser.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* JTMParser.java
*
* Created on May 18, 2009, 10:38 AM
*/
package org.wandora.topicmap.parser;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.wandora.application.Wandora;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.TMBox;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.topicmap.TopicMapLogger;
import org.wandora.topicmap.XTMPSI;
import org.wandora.utils.Options;
/**
*
* @author akivela
*/
public class LTMParser {
public static final String OPTIONS_BASE_KEY = "topicmap.ltm";
public static final String OPTIONS_KEY_ALLOW_SPECIAL_CHARS_IN_QNAMES = OPTIONS_BASE_KEY+"allowSpecialCharsInQNames";
public static final String OPTIONS_KEY_NEW_OCCURRENCE_FOR_EACH_SCOPE = OPTIONS_BASE_KEY+"newOccurrenceForEachScope";
public static final String OPTIONS_KEY_REJECT_ROLELESS_MEMBERS = OPTIONS_BASE_KEY+"rejectRolelessMembers";
public static final String OPTIONS_KEY_PREFER_CLASS_AS_ROLE = OPTIONS_BASE_KEY+"preferClassAsRole";
public static final String OPTIONS_KEY_FORCE_UNIQUE_BASENAMES = OPTIONS_BASE_KEY+"forceUniqueBasenames";
public static final String OPTIONS_KEY_TRIM_BASENAMES = OPTIONS_BASE_KEY+"trimBasenames";
public static final String OPTIONS_KEY_OVERWRITE_VARIANTS = OPTIONS_BASE_KEY+"overwriteVariants";
public static final String OPTIONS_KEY_OVERWRITE_BASENAME = OPTIONS_BASE_KEY+"overwriteBasename";
public static final String OPTIONS_KEY_DEBUG = OPTIONS_BASE_KEY+"debug";
public static final String OPTIONS_KEY_MAKE_SUBJECT_IDENTIFIER_FROM_ID = OPTIONS_BASE_KEY+"makeSIfromID";
public static final String OPTIONS_KEY_MAKE_TOPIC_ID_FROM_ID = OPTIONS_BASE_KEY+"makeTopicIDfromID";
public static boolean ALLOW_SPECIAL_CHARS_IN_QNAMES = false;
public static boolean NEW_OCCURRENCE_FOR_EACH_SCOPE = true;
public static boolean REJECT_ROLELESS_MEMBERS = false;
public static boolean PREFER_CLASS_AS_ROLE = false; // true;
public static boolean MAKE_SUBJECT_IDENTIFIER_FROM_ID = false;
public static boolean MAKE_BASENAME_FROM_ID = false;
//public static boolean MAKE_VARIANT_FROM_BASENAME = false; // TODO
public static boolean FORCE_UNIQUE_BASENAMES = false;
public static boolean TRIM_BASENAMES = true;
public static boolean OVERWRITE_VARIANTS = true;
public static boolean OVERWRITE_BASENAME = true;
public static boolean OVERWRITE_SUBJECT_LOCATORS = false;
public static boolean MAKE_TOPIC_ID_FROM_ID = true;
public static int MAX_SI_LEN = 99999;
public static int MAX_NAME_LEN = 99999;
public static int MAX_STRING_LEN = 99999;
public static String DEFAULT_ROLE_IDENTIFIER = "role";
public static String DEFAULT_SCOPE_FOR_OCCURRENCES = TMBox.LANGINDEPENDENT_SI;
public static String DEFAULT_SCOPE_FOR_VARIANTS = TMBox.LANGINDEPENDENT_SI;
public static String DEFAULT_TYPE_FOR_VARIANTS = "http://www.topicmaps.org/xtm/1.0/core.xtm#display";
public static String STATIC_BASE_URI = "http://wandora.org/si/ltm-import/generated/";
public static String DEFAULT_BASE_URI = "http://wandora.org/si/ltm-import/";
public static String TEMP_SI_PREFIX = "http://wandora.org/si/temp/ltm-import/";
private Topic defaultRoleForAssociations = null;
private Topic defaultScopeForOccurrences = null;
private Topic defaultScopeForVariants = null;
private Topic defaultTypeForVariants = null;
private File currentFile = null;
private String ltmuri = null;
private String baseuri = null;
private String encoding = null;
private String version = null;
private HashMap<String,String> indicatorPrefixes = new HashMap();
private HashMap<String,String> locatorPrefixes = new HashMap();
private ArrayList includes = new ArrayList();
private Pattern prefixPattern = Pattern.compile("[a-zA-Z][a-zA-Z0-9]*\\:.+");
private int numberOfTopics = 0;
private int numberOfAssociations = 0;
private int numberOfOccurrences = 0;
private int numberOfFailedTopics = 0;
private int numberOfFailedAssociations = 0;
private int numberOfFailedOccurrences = 0;
private int lineCounter = 0;
private BufferedReader in = null;
private TopicMapLogger logger = null;
public static boolean debug = false;
private boolean proceed = true;
private TopicMap topicMap = null;
public LTMParser(TopicMap tm, TopicMapLogger logger) {
this.topicMap = tm;
if(logger != null) this.logger = logger;
else this.logger = topicMap;
Wandora w = Wandora.getWandora();
if(w != null) {
Options o = w.getOptions();
if(o != null) {
loadOptions(o);
}
}
}
public void loadOptions(Options o) {
ALLOW_SPECIAL_CHARS_IN_QNAMES = o.getBoolean(OPTIONS_KEY_ALLOW_SPECIAL_CHARS_IN_QNAMES, ALLOW_SPECIAL_CHARS_IN_QNAMES);
NEW_OCCURRENCE_FOR_EACH_SCOPE = o.getBoolean(OPTIONS_KEY_NEW_OCCURRENCE_FOR_EACH_SCOPE, NEW_OCCURRENCE_FOR_EACH_SCOPE);
REJECT_ROLELESS_MEMBERS = o.getBoolean(OPTIONS_KEY_REJECT_ROLELESS_MEMBERS, REJECT_ROLELESS_MEMBERS);
PREFER_CLASS_AS_ROLE = o.getBoolean(OPTIONS_KEY_PREFER_CLASS_AS_ROLE, PREFER_CLASS_AS_ROLE);
FORCE_UNIQUE_BASENAMES = o.getBoolean(OPTIONS_KEY_FORCE_UNIQUE_BASENAMES, FORCE_UNIQUE_BASENAMES);
TRIM_BASENAMES = o.getBoolean(OPTIONS_KEY_TRIM_BASENAMES, TRIM_BASENAMES);
OVERWRITE_VARIANTS = o.getBoolean(OPTIONS_KEY_OVERWRITE_VARIANTS, OVERWRITE_VARIANTS);
OVERWRITE_BASENAME = o.getBoolean(OPTIONS_KEY_OVERWRITE_BASENAME, OVERWRITE_BASENAME);
MAKE_SUBJECT_IDENTIFIER_FROM_ID = o.getBoolean(OPTIONS_KEY_MAKE_SUBJECT_IDENTIFIER_FROM_ID, MAKE_SUBJECT_IDENTIFIER_FROM_ID);
debug = o.getBoolean(OPTIONS_KEY_DEBUG, debug);
}
public void prepare() {
encoding = null;
}
public void init() {
indicatorPrefixes = new HashMap();
locatorPrefixes = new HashMap();
lineCounter = 1;
}
public void parse(File file) {
long startTime = System.currentTimeMillis();
try {
if(file != null) {
if(!(file.exists() || file.canRead()) && currentFile != null) {
String absParentPath = currentFile.getParentFile().getAbsolutePath();
log("Using path from previous file: " + absParentPath + File.separator + file.getName());
file = new File(absParentPath + File.separator + file.getName());
}
if(file.exists() && file.canRead()) {
if(currentFile == null) currentFile = file;
File previousFile = currentFile;
BufferedReader previousIn = in;
String previousBaseuri = baseuri;
String previousLtmuri = ltmuri;
// ltmuri = "file:/" + file.getAbsolutePath();
ltmuri = file.toURI().toString();
InputStream is=new FileInputStream(file);
parse(is);
if(previousIn != null) in = previousIn;
if(ltmuri != null) ltmuri = previousLtmuri;
if(baseuri != null) baseuri = previousBaseuri;
if(previousFile != null) currentFile = previousFile;
}
else {
log("Warning: LTM import is unable to read file: " + file.getAbsolutePath());
}
}
}
catch(Exception e) {
log(e);
}
long endTime = System.currentTimeMillis();
long duration = endTime-startTime;
if(duration > 1000) log("LTM import of '"+file.getAbsolutePath()+"' took "+duration+" ms.");
}
public void parse(InputStream is) throws IOException {
parse(is, "UTF-8");
}
public void parse(InputStream is, String enc) throws IOException {
if(enc == null || enc.equals("")) enc = "UTF-8";
prepare();
InputStreamReader isr = new InputStreamReader(is, enc);
in = new BufferedReader(isr);
eat('\ufeff'); // skip BOM
parseEncodind();
if(encoding != null) {
if(!"utf-8".equalsIgnoreCase(encoding)) {
log("Warning: Wandora's LTM import supports UTF-8 encoding only! Imported LTM document has '"+encoding+"' as encoding.");
}
}
parseVersion();
parseDirectives();
parseTopicElements();
postProcess();
if(logger.forceStop()) {
log("User has stopped LTM import!");
}
}
private void parseEncodind() throws IOException {
eatMeaningless();
if(eat('@')) {
encoding = parseString();
}
}
private void parseVersion() throws IOException {
eatMeaningless();
if(eat("#VERSION")) {
version = parseString();
log("Found LTM version info: "+version);
}
}
private void parseDirectives() throws IOException {
boolean directiveFound = true;
while(directiveFound) {
eatMeaningless();
if(eat("#TOPICMAP")) {
log("Warning: Wandora's LTM import does not handle #TOPICMAP directives!");
}
else if(eat("#MERGEMAP")) {
log("Warning: Wandora's LTM import does not handle #MERGEMAP directives!");
}
else if(eat("#BASEURI")) {
eatMeaningless();
String uri = parseString();
if(uri != null && uri.length()>0) {
log("Base URI found '"+uri+"'.");
baseuri = uri;
}
}
else if(eat("#INCLUDE")) {
eatMeaningless();
String filename = parseString();
if(! includes.contains(filename) ) {
includes.add(filename);
debug("Including '" + filename + "' starts.");
int oldLineCounter = lineCounter;
lineCounter = 1;
parse(new File(filename));
proceed = true;
lineCounter = oldLineCounter;
debug("Including '" + filename + "' ends.");
}
}
else if(eat("#PREFIX")) {
eatMeaningless();
String name = parseName();
eatMeaningless();
if(eat('@')) {
String locator = parseString();
indicatorPrefixes.put(name, locator);
log("Prefix found '" + name + "' = '" + locator + "'");
}
else if(eat('%')) {
String identier = parseString();
locatorPrefixes.put(name, identier);
log("Prefix found '" + name + "' = '" + identier + "'");
}
}
else {
directiveFound = false;
}
}
if(baseuri == null) {
baseuri = DEFAULT_BASE_URI;
log("Found no base URI for topic map. Using default base '"+baseuri+"'.");
}
}
private void parseTopicElements() throws IOException {
int TOPIC = 1;
int ASSOCIATION = 2;
int OCCURRENCE = 3;
int NONE = 0;
int exceptionLimit = 100;
int previousFailed = NONE;
int n=0;
eatMeaningless();
while(proceed && !logger.forceStop()) {
try {
if(previousFailed != NONE) {
syncParse();
previousFailed = NONE;
}
if(eat('[')) {
Topic topic = parseTopic();
if(eat(']') == false) {
debug("Warning: Parse error while processing topic '"+ topic +"'!");
parseUntil(']');
}
if(topic != null) {
numberOfTopics++;
previousFailed = NONE;
}
else {
numberOfFailedTopics++;
previousFailed = TOPIC;
}
}
else if(eat('{')) {
if(parseOccurrence()) {
numberOfOccurrences++;
previousFailed = NONE;
}
else {
numberOfFailedOccurrences++;
previousFailed = OCCURRENCE;
}
}
else {
if( parseAssociation() != null ) {
numberOfAssociations++;
previousFailed = NONE;
}
else {
numberOfFailedAssociations++;
previousFailed = ASSOCIATION;
}
}
}
catch(Exception e) {
e.printStackTrace();
if(--exceptionLimit < 0) {
logger.log("Too many errors occurred while parsing the LTM file. Aborting...");
proceed = false;
}
if(proceed) syncParse();
}
eatMeaningless();
if(n++ % 1000 == 0) logger.hlog("Importing LTM topic map. Imported " + numberOfTopics + " topics, " + numberOfAssociations + " associations and " + numberOfOccurrences +" occurrences.");
}
log("Found total " + numberOfTopics + " topics, " + numberOfAssociations + " associations and " + numberOfOccurrences +" occurrences.");
log("Real number of topics, associations and occurrences in topic map may be smaller due to merges.");
if(numberOfFailedTopics > 0) log("Found also " + numberOfFailedTopics + " broken topics.");
if(numberOfFailedAssociations > 0) log("Found also " + numberOfFailedAssociations + " broken associations.");
if(numberOfFailedOccurrences > 0) log("Found also " + numberOfFailedOccurrences + " broken occurrences.");
}
private void syncParse() throws IOException {
try {
String unrecognized = parseUntil('\n');
eatMeaningless();
log("Warning: Unrecognized element: \"" + unrecognized + "\" near line number "+lineCounter+", after topic number "+numberOfTopics+" and association number " + numberOfAssociations);
}
catch (Exception e) {
e.printStackTrace();
}
}
private void postProcess() {
debug("Post processing topics. Removing temporary subject identifiers.");
if(topicMap != null) {
try {
Iterator<Topic> topics = topicMap.getTopics();
Collection topicCollection = new ArrayList<Topic>();
while(topics.hasNext()) {
Topic t=topics.next();
topicCollection.add(t);
}
topics = topicCollection.iterator();
Topic t = null;
while(topics.hasNext()) {
t = topics.next();
if(t != null && !t.isRemoved()) {
ArrayList<Locator> subjects = new ArrayList();
subjects.addAll(t.getSubjectIdentifiers());
for(Locator si : subjects) {
if(si != null) {
if(si.toExternalForm().startsWith(TEMP_SI_PREFIX)) {
t.removeSubjectIdentifier(si);
}
}
}
}
}
}
catch(Exception e) {
logger.log(e);
}
}
}
// ---------------------------------------------------------------------
// ---------------------------------------------------------- TOPICS ---
// ---------------------------------------------------------------------
private Topic parseTopic() throws IOException, TopicMapException {
Topic topic = null;
LTMQName topicQName = parseQName();
if(topicQName != null) {
boolean foundWithBasename = false;
boolean foundWithSI = false;
boolean foundWithSL = false;
boolean foundWithQName = false;
debug("Topic found: " + topicQName.qname);
ArrayList<Topic> topicTypes = null;
ArrayList<Locator> topicTypeSIs = null;
if(eat(':')) {
topicTypes = parseQTopics();
topicTypeSIs = new ArrayList();
for(Topic topicType : topicTypes) {
topicTypeSIs.add(topicType.getOneSubjectIdentifier());
}
}
ArrayList baseNames = parseBasenames();
Locator subjectLocator = parseSubjectLocator();
ArrayList subjectIdentifiers = parseSubjectIdentifiers();
topic = getOrCreateTopic(topicQName.qname);
if(topic != null) foundWithQName = true;
if(topic == null && baseNames != null) {
Basename basename = null;
if(baseNames.size() > 0) {
basename = (Basename) baseNames.iterator().next();
if(baseNames.size() > 1) {
debug("Warning: Wandora supports only one base name per topic!");
}
if(basename != null) {
if(basename.basename != null) {
topic = topicMap.getTopicWithBaseName(basename.basename);
if(topic != null) foundWithBasename = true;
}
}
}
}
if(topic == null && subjectIdentifiers != null) {
Locator identifier = null;
Iterator identifiers = subjectIdentifiers.iterator();
while(topic == null && identifiers.hasNext()) {
identifier = (Locator) identifiers.next();
if(identifier != null) topic = topicMap.getTopic(identifier);
}
if(topic != null) foundWithSI = true;
}
if(topic == null && subjectLocator != null) {
topic = topicMap.getTopicBySubjectLocator(subjectLocator);
if(topic != null) foundWithSL = true;
}
// ----- TOPIC SOLVED HERE | PROCESS NOW -----
if(!foundWithQName && MAKE_SUBJECT_IDENTIFIER_FROM_ID) {
topic.addSubjectIdentifier(buildLocator(topicQName.qname));
}
if(!foundWithSL && subjectLocator != null) {
if(topic.getSubjectLocator() == null || OVERWRITE_SUBJECT_LOCATORS) {
topic.setSubjectLocator(subjectLocator);
}
}
// PROCESS SUBJECT IDENTIFIERS...
Locator newSI = null;
if(subjectIdentifiers != null && subjectIdentifiers.size() > 0) {
Iterator indicators = subjectIdentifiers.iterator();
while(indicators.hasNext()) {
newSI = (Locator) indicators.next();
if(newSI!=null) {
topic.addSubjectIdentifier(newSI);
}
}
}
else {
if(topic != null && topic.getOneSubjectIdentifier() == null) {
topic.addSubjectIdentifier(new Locator(STATIC_BASE_URI+System.currentTimeMillis()+"-"+Math.floor(Math.random()*999999)));
log("Warning: Missing subject identifier. Adding temporary subject identifier to topic.");
}
}
// PROCESS BASENAMES AND IT'S VARIANTS...
if(baseNames != null && baseNames.size() > 0) {
Basename basename = null;
basename = (Basename) baseNames.iterator().next();
if(basename != null) {
if(basename.basename != null) {
Topic baseNameTopic = topicMap.getTopicWithBaseName(basename.basename);
if(topic.getBaseName() != null || OVERWRITE_BASENAME) {
if(!foundWithBasename && basename.basename != null) {
topic.setBaseName(basename.basename);
}
}
}
if(basename.displayname != null) {
topic.setDisplayName(XTMPSI.getLang(null), basename.displayname); // LANG INDEPENDENT DISPLAYNAME
// logger.log("found displayname name '" + basename.sortname+"'");
}
if(basename.sortname != null) {
HashSet nameScope=new LinkedHashSet();
nameScope.add(getOrCreateTopic(XTMPSI.getLang(null)));
nameScope.add(getOrCreateTopic(XTMPSI.SORT));
topic.setVariant(nameScope, basename.sortname);
// logger.log("found sort name '" + basename.sortname+"'");
}
if(basename.variantNames != null) {
for(Iterator variants = basename.variantNames.iterator(); variants.hasNext(); ) {
VariantName variant = (VariantName) variants.next();
if(variant != null) {
//logger.log("found variant '" + variant.name+"' with scope '"+variant.scope+"'.");
if(variant.name != null && variant.scope != null && variant.scope.size() > 0) {
if(topic.getVariant(variant.scope) != null || OVERWRITE_VARIANTS) {
topic.setVariant(variant.scope, variant.name);
}
}
}
}
}
}
}
// PROCESS TOPIC TYPES...
if(topicTypes != null && topicTypeSIs != null) {
Topic topicType = null;
for( Locator topicTypeSI : topicTypeSIs ) {
try {
if(topicTypeSI != null) {
topicType = topicMap.getTopic(topicTypeSI);
if(topicType != null && !topic.isOfType(topicType)) {
topic.addType(topicType);
debug("Found type for " + topic);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
return topic;
}
private Locator parseSubjectLocator() throws IOException {
Locator locator = null;
if(eat('%')) {
locator = buildLocator(parseString());
}
return locator;
}
private ArrayList parseSubjectIdentifiers() throws IOException {
ArrayList locators = new ArrayList();
boolean ready = false;
do {
String locator = null;
if(eat('@')) {
locator = parseString();
if(locator != null && locator.length() > 0) {
locators.add(buildLocator(locator));
}
}
else {
ready = true;
}
}
while(! ready);
return locators;
}
private ArrayList parseBasenames() throws IOException, TopicMapException {
String basename = null;
String sortname = null;
String displayname = null;
ArrayList variantNames = new ArrayList();
VariantName variantName = null;
ArrayList basenames = new ArrayList();
while(eat('=')) {
basename = parseString();
//logger.log("Basename '"+ basename +"' found for topic!");
if(TRIM_BASENAMES) basename = basename.trim();
if(eat(';')) {
sortname = parseString();
if(eat(';')) {
displayname = parseString();
}
}
ArrayList scopes = parseScope();
//if(scopes != null) logger.log(" Found scope for base name "+scopes);
if(eat('~')) {
LTMQName reifyId = parseQName();
// TODO: Handler for reifiers!
}
while(eat('(')) {
variantName = parseVariantName();
if(variantName != null) variantNames.add(variantName);
eat(')');
}
if(basename != null && basename.length() > 0) {
if(FORCE_UNIQUE_BASENAMES) {
Topic t = topicMap.getTopicWithBaseName(basename);
int n = 0;
while( t != null ) {
n++;
t = topicMap.getTopicWithBaseName(basename + " " + n);
}
if(n > 0) basename = basename + " " + n;
}
//logger.log(" Basename '"+ basename +"'");
}
if(basename != null || !variantNames.isEmpty()) {
basenames.add( new Basename(basename, variantNames, displayname, sortname) );
}
}
//logger.log("Found total "+basenames.size()+" basenames for topic!");
return basenames;
}
private VariantName parseVariantName() throws IOException, TopicMapException {
String variantName = parseString();
ArrayList scope = parseScope();
LTMQName reifyId = parseQName();
if(scope == null) { scope = new ArrayList(); }
/*
if(scope.size() == 0) {
defaultTypeForVariants = getOrCreateMappedTopic(DEFAULT_TYPE_FOR_VARIANTS);
if(defaultTypeForVariants != null && !scope.contains(defaultTypeForVariants)) {
scope.add(defaultTypeForVariants);
}
defaultScopeForVariants = getOrCreateMappedTopic(DEFAULT_SCOPE_FOR_VARIANTS);
if(defaultScopeForVariants != null) {
scope.add(defaultScopeForVariants);
}
}
*/
if(variantName != null) {
if(scope != null && scope.size() > 0) {
return new VariantName(variantName, scope);
}
}
return null;
}
// ---------------------------------------------------------------------
// ---------------------------------------------------- ASSOCIATIONS ---
// ---------------------------------------------------------------------
private Association parseAssociation() throws IOException, TopicMapException {
Association association = null;
LTMQName associationTypeName = parseQName();
if(associationTypeName != null) {
LTMQName reifyId = null;
ArrayList members = new ArrayList();
Member member = null;
Topic associationType = null;
if(eat('(')) {
int memberCounter = 0;
do {
member = parseAssociationMember(memberCounter++, associationTypeName);
if(member != null) {
members.add(member);
}
}
while(eat(','));
// System.out.println("found "+memberCounter+" members.");
eat(')');
}
ArrayList scopes = parseScope();
if(eat('~')) {
reifyId = parseQName();
// TODO: Handler for reifiers!
}
if(members.size() > 0) {
associationType = getOrCreateTopic(associationTypeName);
if(associationType != null) {
//logger.log("Association type is: "+associationType+ " ---- "+associationTypeName.qname);
association = topicMap.createAssociation(associationType);
if(association != null) {
HashMap<Topic,Topic> players=new LinkedHashMap<Topic,Topic>();
for(Iterator memberIter = members.iterator(); memberIter.hasNext(); ) {
member = (Member) memberIter.next();
//if(member != null) association.addPlayer(member.role,member.player);
if(member != null && member.role != null && member.player != null) {
players.put(member.role, member.player);
//logger.log(" Adding association: "+associationType+" player '"+member.player+"' with role '"+member.role+"'." );
}
}
association.addPlayers(players);
}
/*
Iterator i = topicMap.getAssociations();
int c = 0;
while(i.hasNext()) {
i.next();
c++;
}
logger.log("A-count: "+c);
*
*/
}
}
}
return association;
}
private Member parseAssociationMember(int memberNumber, LTMQName associationTypeQName) throws IOException, TopicMapException {
Topic role = null;
Topic player = null;
LTMQName reifyId = null;
if(eat('[')) {
player = parseTopic();
eat(']');
}
else {
player = parseQTopic();
}
if(player != null) {
if(eat(':')) role = parseQTopic();
if(role == null && !REJECT_ROLELESS_MEMBERS) {
//logger.log("role == "+role);
Collection<Topic> types = player.getTypes();
if(types != null && types.size() > 0 && PREFER_CLASS_AS_ROLE) {
role = types.iterator().next();
// System.out.println("found role '"+role+"' ("+role.getOneSubjectIdentifier().toExternalForm()+")");
}
else {
String associationTypeName = "";
if(associationTypeQName != null) {
associationTypeName = associationTypeQName.qname;
}
String roleID = associationTypeName + "_" + DEFAULT_ROLE_IDENTIFIER + "_" + memberNumber;
role = getOrCreateTopic(roleID);
}
}
if(eat('~')) {
reifyId = parseQName();
// TODO: Handler for reifiers!
}
}
if(role != null && player != null) {
return new Member(player, role);
}
return null;
}
// ---------------------------------------------------------------------
// ----------------------------------------------------- OCCURRENCES ---
// ---------------------------------------------------------------------
private boolean parseOccurrence() throws IOException, TopicMapException {
debug("Parsing occurrence");
Topic occurrenceTopic = null;
ArrayList scope = null;
Topic occurrenceType = null;
LTMQName reifyId = null;
boolean occurrenceSucceed = false;
occurrenceTopic = parseQTopic();
debug("Parsed occurrence topic: "+occurrenceTopic);
eat(',');
occurrenceType = parseQTopic();
debug("Parsed occurrence type: "+occurrenceType);
eat(',');
String resource = parseResource();
eat('}');
scope = parseScope();
debug("Parsed occurrence scope: "+scope);
if(eat('~')) {
reifyId = parseQName();
// TODO: Handler for reifiers!
}
if(scope == null) scope = new ArrayList();
if(scope.isEmpty()) {
defaultScopeForOccurrences = getOrCreateTopic(DEFAULT_SCOPE_FOR_OCCURRENCES);
if(defaultScopeForOccurrences != null) {
scope.add(defaultScopeForOccurrences);
}
}
if(occurrenceTopic != null && occurrenceType != null) {
if(resource != null) {
if(scope != null && scope.size() > 0) {
//logger.log("Occurrence found");
Topic scopeTopic = null;
if(NEW_OCCURRENCE_FOR_EACH_SCOPE) {
for(Iterator iter = scope.iterator(); iter.hasNext(); ) {
scopeTopic = (Topic) iter.next();
if(scopeTopic != null) {
// System.out.println("CREATING OCCURRENCE: " +occurrenceType + " --- " + scopeTopic + " --- " + resource);
occurrenceTopic.setData(occurrenceType, scopeTopic, resource);
//logger.log(" Occurrence type: "+ occurrenceType);
//logger.log(" Occurrence scope: "+ scopeTopic);
//logger.log(" Occurrence resource: "+ resource);
occurrenceSucceed = true;
}
}
}
else {
scopeTopic = (Topic) scope.iterator().next();
if(scopeTopic != null) {
occurrenceTopic.setData(occurrenceType, scopeTopic, resource);
occurrenceSucceed = true;
}
}
}
}
}
return occurrenceSucceed;
}
private String parseResource() throws IOException {
String locator = parseString();
if(locator != null && locator.length() >= 1) {
return locator;
}
else {
if(eat('[')) {
if(eatOnly('[')) {
String data = parseUntil("]]");
int unicodeLocation = -1;
String unicodeNumberStr = null;
int unicodeNumber = 0;
do {
unicodeLocation = data.indexOf("\\u");
if(unicodeLocation != -1) {
try {
unicodeNumberStr = data.substring(unicodeLocation+2, unicodeLocation+6);
unicodeNumber = Integer.parseInt(unicodeNumberStr, 16);
data = data.substring(0, unicodeLocation) + ((char) unicodeNumber) + data.substring(unicodeLocation+6);
}
catch(Exception e) {
e.printStackTrace();
}
}
}
while( unicodeLocation != -1 );
return data;
}
}
else {
String data = parseString();
return data;
}
}
return "";
}
// ---------------------------------------------------------------------
// --------------------------------------------------- MISC ELEMENTS ---
// ---------------------------------------------------------------------
private ArrayList parseScope() throws IOException, TopicMapException {
if(eat('/')) {
return parseQTopics();
}
return null;
}
private Topic parseQTopic() throws IOException, TopicMapException {
return getOrCreateTopic(parseQName());
}
private ArrayList parseQTopics() throws IOException, TopicMapException {
ArrayList qtopics = new ArrayList();
Topic qtopic = null;
boolean ready = false;
do {
qtopic = parseQTopic();
if(qtopic != null) qtopics.add(qtopic);
else ready = true;
}
while(!ready);
return qtopics;
}
private ArrayList parseQNames() throws IOException {
ArrayList qnames = new ArrayList();
LTMQName qname = null;
boolean ready = false;
do {
qname = parseQName();
if(qname != null) qnames.add(qname);
else ready = true;
debug("Found qname \"" + qname.qname + "\"");
}
while(!ready);
return qnames;
}
private LTMQName parseQName() throws IOException {
String qname = parseName();
String locatorPrefix = null;
String indicatorPrefix = null;
if(qname != null && qname.length() > 0) {
if(false && eatOnly(':')) {
locatorPrefix = locatorPrefixes.get(qname);
indicatorPrefix = indicatorPrefixes.get(qname);
qname = parseName();
}
return new LTMQName(qname, locatorPrefix, indicatorPrefix);
}
return null;
}
// ---------------------------------------------------------------------
// ------------------------------------------------------ PRIMITIVES ---
// ---------------------------------------------------------------------
private String parseName() throws IOException {
if(ALLOW_SPECIAL_CHARS_IN_QNAMES) return parseExtendedName();
else return parseStrictName();
}
private String parseExtendedName() throws IOException {
StringBuilder sb = new StringBuilder("");
int len = 0;
if(proceed) {
boolean ready = false;
int c = 0;
eatMeaningless(false);
do {
in.mark(1);
c = in.read();
if(c == -1) {
ready = true;
proceed = false;
}
else if(isSpace(c) || "=()[]{}/,:;".indexOf(c) != -1) {
ready = true;
in.reset();
}
else {
if(!isQNameExtendedCharacter(c)) c = '_';
sb.append((char) c);
len++;
}
} while(!ready && len < MAX_NAME_LEN);
}
if(sb.length() > 0) debug("Name found \"" + sb.toString() + "\"");
if(len >= MAX_NAME_LEN) log("Warning: Name length > "+ MAX_NAME_LEN);
return sb.toString();
}
private String parseStrictName() throws IOException {
StringBuilder sb = new StringBuilder("");
int len = 0;
if(proceed) {
boolean ready = false;
int c = 0;
eatMeaningless(false);
do {
in.mark(1);
c = in.read();
if(c == -1) {
ready = true;
proceed = false;
}
else if((len == 0 && isQNameCharacter(c)) || (len > 0 && isQNameExtendedCharacter(c))) {
sb.append((char) c);
len++;
}
else {
ready = true;
in.reset();
}
}
while(!ready && len < MAX_NAME_LEN);
}
if(sb.length() > 0) debug("Name found \"" + sb.toString() + "\"");
if(len >= MAX_NAME_LEN) log("Warning: Name length > "+ MAX_NAME_LEN);
return sb.toString();
}
private String parseString() throws IOException {
StringBuilder sb = new StringBuilder("");
int c = 0;
char ch = 0;
int len = 0;
if(proceed) {
if(eat('"')) {
boolean ready = false;
while(!ready && len < MAX_STRING_LEN && proceed) {
if(eatOnly('"')) {
if(eatOnly('"')) {
sb.append('"');
len++;
}
else {
//System.out.println("found string end.");
ready = true;
}
}
else if(eatOnly('\\')) {
if(eatOnly('u')) {
char[] unicode = new char[4];
int c3 = in.read(unicode);
int uc = Integer.parseInt(new String(unicode), 16);
sb.append((char) uc);
//System.out.println("escaped unicode char found '" + ((char) uc) + "' ("+new String(unicode)+")");
len++;
}
else {
// TODO: MORE COMPLEX SLASH CHARACTERS
c = in.read();
if(c == -1) proceed = false;
else {
ch = (char) c;
//System.out.println("escaped char found '" + ch + "'");
sb.append(ch);
len++;
}
}
}
else {
c = in.read();
if(c == -1) proceed = false;
else {
ch = (char) c;
//System.out.println("char found '" + ch + "'");
sb.append(ch);
len++;
}
}
}
}
}
debug("String found \"" + sb.toString() + "\"");
if(len >= MAX_STRING_LEN) log("Warning: String length > "+ MAX_STRING_LEN);
return sb.toString();
}
private String parseUntil(int ch) throws IOException {
if(!proceed) return null;
StringBuilder sb = new StringBuilder("");
int c = -1;
int maxlen = 99999;
do {
if(c != -1) sb.append((char) c);
c = in.read();
if(c == '\n') lineCounter++;
}
while(c != ch && c != -1 && --maxlen > 0);
if(c == -1) {
proceed = false;
}
return sb.toString();
}
private String parseUntil(String str) throws IOException {
if(!proceed) return null;
StringBuilder sb = new StringBuilder("");
boolean ready = false;
int c = -1;
int strLen = str.length();
char[] charStr = new char[strLen];
for(int i=0; i<strLen; i++) {
charStr[i] = 0;
}
do {
if(charStr[0] != -1 && charStr[0] != 0) sb.append(charStr[0]);
c = in.read();
if(c == '\n') lineCounter++;
ready = true;
for(int i=1; i<strLen; i++) {
charStr[i-1] = charStr[i];
if(ready && str.charAt(i-1) != charStr[i]) ready = false;
//System.out.println("TEST: " + str.charAt(i-1) + " == " + charStr[i]);
}
charStr[strLen-1] = (char) c;
//System.out.println("TEST: " + str.charAt(strLen-1) + " == " + charStr[strLen-1]);
//System.out.println("--");
if(ready && str.charAt(strLen-1) != charStr[strLen-1]) ready = false;
}
while(!ready && c != -1);
if(c == -1) {
debug("Warning: Unexpected end of occurrence data.");
proceed = false;
}
return sb.toString();
}
private boolean parseComment() throws IOException {
if(!proceed) return false;
in.mark(2);
int c1 = in.read();
int c2 = in.read();
if(c1 == '/' && c2 == '*') {
try {
c2 = in.read();
do {
c1 = c2;
c2 = in.read();
if(c2 == '\n') lineCounter++;
}
while(c1 != '*' || c2 != '/');
return true;
}
catch(Exception e) {
debug("Warning: Unexpected end of comment. Missing ending.");
proceed = false;
return true;
}
}
else {
in.reset();
}
return false;
}
// ---------------------------------------------------------------------
private boolean eatOnly(int ch) throws IOException {
if(!proceed) return false;
in.mark(1);
int c = in.read();
if(c == -1) {
proceed = false;
return false;
}
if(c != ch) {
in.reset();
return false;
}
else {
if(ch == '\n') lineCounter++;
}
return true;
}
private boolean eat(int [] str) throws IOException {
if(!proceed) return false;
eatMeaningless();
in.mark(str.length);
char[] chars = new char[str.length];
int c = in.read(chars);
if(c <= 0) {
in.reset();
proceed = false;
return false;
}
int i=0;
while(i < str.length) {
if(str[i] != chars[i]) {
in.reset();
return false;
}
i++;
}
return true;
}
private boolean eat(int ch) throws IOException {
eatMeaningless();
if(!proceed) return false;
in.mark(1);
int c = in.read();
if(c == -1) {
proceed = false;
return false;
}
if(c != ch) {
in.reset();
return false;
}
return true;
}
private boolean eat(String str) throws IOException {
if(!proceed) return false;
eatMeaningless();
in.mark(str.length());
char[] chars = new char[str.length()];
int c = in.read(chars);
if(c <= 0) {
in.reset();
proceed = false;
return false;
}
String byteString = new String(chars);
if(! str.equals(byteString)) {
in.reset();
return false;
}
return true;
}
private boolean eatMeaningless() throws IOException {
return eatMeaningless(true);
}
private boolean eatMeaningless(boolean eatAlsoNewlines) throws IOException {
boolean meaninglessAvailable = false;
boolean anyMeaningless = false;
boolean spacesFound = false;
boolean commentsFound = false;
do {
spacesFound = eatSpaces(eatAlsoNewlines);
commentsFound = parseComment();
meaninglessAvailable = spacesFound || commentsFound;
anyMeaningless = anyMeaningless || meaninglessAvailable;
}
while(meaninglessAvailable);
return anyMeaningless;
}
private boolean eatSpaces() throws IOException {
return eatSpaces(true);
}
private boolean eatSpaces(boolean eatAlsoNewlines) throws IOException {
if(!proceed) return false;
int c = 0;
boolean cont = false;
boolean spacesFound = false;
int n = 0;
do {
in.mark(1);
c = in.read();
if(c == -1) {
cont = false;
proceed = false;
break;
}
else {
cont = ( c == ' ' || c == '\t' );
if(eatAlsoNewlines) {
cont = cont || isSpace(c);
if(c == '\n') lineCounter++;
}
if(cont) {
spacesFound = true;
n++;
}
}
}
while(cont);
// if(n>0) debug(" Number of eaten meaningless: " + n);
in.reset();
return spacesFound;
}
// private String WHITE_SPACE_CHARACTERS = " \t\n\r"; // SEE METHOD isSpace(int c)
private String QNAME_CHARACTERS = "qwertyuioplkjhgfdsazxcvbnmMNBVCXZLKJHGFDSAPOIUYTREWQ_";
private String EXTENDED_QNAME_CHARACTERS = "qwertyuioplkjhgfdsazxcvbnmMNBVCXZLKJHGFDSAPOIUYTREWQ1234567890_-.";
private boolean isSpace(int c) {
if(c == ' ' || c == 0x00A0 || c == 0x2007 || c == 0x202F || c == 0x0009 ||
c == 0x000A || c == 0x000B || c == 0x000C || c == 0x000D) return true;
return false;
}
private boolean isQNameCharacter(int c) {
return (QNAME_CHARACTERS.indexOf(c) != -1);
}
private boolean isQNameExtendedCharacter(int c) {
return (EXTENDED_QNAME_CHARACTERS.indexOf(c) != -1);
}
// ---------------------------------------------------------------------
public int read() throws IOException {
return in.read();
}
public Locator buildTempLocator(String id) {
if(id == null) id = "null";
return new Locator(TEMP_SI_PREFIX + id);
}
public Locator buildLocator(String id) {
if(id == null) return null;
String locatorString = id;
Locator locator = null;
if(locatorString.charAt(0) == '#' && ltmuri != null) {
locatorString = ltmuri + locatorString;
locator = new Locator(locatorString);
}
else {
Matcher prefixPatternMatcher = prefixPattern.matcher(locatorString);
if(prefixPatternMatcher.matches()) {
try {
locator = new Locator(locatorString);
}
catch(Exception e) { }
}
else {
if(baseuri != null) {
if(baseuri.endsWith("/"))
locatorString = baseuri + locatorString;
else
locatorString = baseuri + "/" + locatorString;
}
locator = new Locator(locatorString);
}
}
if(locator != null) {
if(locator.toExternalForm().length() > MAX_SI_LEN) {
locator = new Locator(locator.toExternalForm().substring(0, MAX_SI_LEN));
}
debug("New locator: "+locator.toExternalForm());
}
else {
debug("Warning: Returning null as a locator.");
}
return locator;
}
public Topic getOrCreateTopic(LTMQName qname) throws TopicMapException {
if(qname == null) return null;
return getOrCreateTopic(qname.qname);
}
public Topic getOrCreateTopic(String qname) throws TopicMapException {
if(qname == null) return null;
Topic t = topicMap.getTopic(buildTempLocator(qname));
if(t==null) {
t = topicMap.getTopic(buildLocator(qname));
}
if(t==null) {
if(MAKE_TOPIC_ID_FROM_ID) {
t=topicMap.createTopic(qname);
}
else {
t=topicMap.createTopic();
}
t.addSubjectIdentifier(buildTempLocator(qname));
if(MAKE_SUBJECT_IDENTIFIER_FROM_ID) {
t.addSubjectIdentifier(buildLocator(qname));
}
if(MAKE_BASENAME_FROM_ID && t.getBaseName() == null) {
t.setBaseName(qname);
}
debug("New topic created: " +t);
}
return t;
}
// ---------------------------------------------------------------------
// ---------------------------------------------- LOGS AND DEBUGGING ---
// ---------------------------------------------------------------------
protected void debug(String msg) {
if(debug && logger != null) {
logger.log(msg);
}
}
protected void log(String msg) {
if(logger != null) {
logger.log(msg);
}
}
protected void log(Exception e) {
if(logger != null) {
logger.log(e);
}
}
// ---------------------------------------------------------------------
// ----------------------------------------------- HELPER STRUCTURES ---
// ---------------------------------------------------------------------
public class LTMQName {
public String qname;
public String locatorPrefix;
public String indicatorPrefix;
public LTMQName(String qname, String locatorPrefix, String indicatorPrefix) {
this.qname = qname;
this.locatorPrefix = locatorPrefix;
this.indicatorPrefix = indicatorPrefix;
}
}
public class Basename {
public String basename;
public Collection variantNames;
public String sortname;
public String displayname;
public Basename(String basename, Collection variantNames, String displayName, String sortName){
this.basename=basename;
this.variantNames=variantNames;
this.displayname=displayName;
this.sortname=sortName;
}
}
public class VariantName {
public String name;
public Set scope;
public VariantName(String name, Collection s){
this.name=name;
this.scope=new LinkedHashSet();
for(Iterator i=s.iterator(); i.hasNext(); ) {
scope.add(i.next());
}
}
public VariantName(String name, Set scope){
this.name=name;
this.scope=scope;
}
}
public class Member {
public Topic player;
public Topic role;
public Member(Topic player,Topic role){
this.player=player;
this.role=role;
}
}
}
| 55,707 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
JTMParser.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/parser/JTMParser.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* JTMParser.java
*
* Created on May 18, 2009, 10:38 AM
*/
package org.wandora.topicmap.parser;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import org.json.JSONArray;
import org.json.JSONObject;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapLogger;
import org.wandora.topicmap.TopicTools;
import org.wandora.utils.Tuples.T2;
/**
* This class implements a JSON Topic Maps 1.0 (JTM) parser. Class reads given
* input stream or file and converts serialization to topics and associations.
* As Wandora's Topic Maps model is limited, some parts of JTM serialization
* are skipped.
*
* About JTM see: http://www.cerny-online.com/jtm/1.0/
*
* @author akivela
*/
public class JTMParser {
private static final String STATIC_SI_BODY = "http://wandora.org/si/jtm-parser/generated/";
private static boolean ASSOCIATION_TO_TYPE = true;
private static boolean MAKE_TOPIC_ID_WITH_II = false;
private static boolean MAKE_SUBJECT_IDENTIFIER_WITH_II = true;
private TopicMap topicMap = null;
private TopicMapLogger logger = null;
public JTMParser(TopicMap tm, TopicMapLogger logger) {
this.topicMap = tm;
if(logger != null) {
this.logger = logger;
}
else {
this.logger = tm;
}
}
public void parse(File file) {
try {
FileInputStream fis = new FileInputStream(file);
parse(fis, "UTF-8");
fis.close();
}
catch(Exception e) {
logger.log(e);
}
}
public void parse(InputStream ins) {
parse(ins, "UTF-8");
}
public void parse(InputStream ins, String enc) {
if(topicMap == null) {
log("Warning: JTM parser has no Topic Map object for topics and associations. Aborting.");
return;
}
try {
StringBuilder input = new StringBuilder("");
InputStreamReader insr = new InputStreamReader(ins, enc);
BufferedReader in = new BufferedReader(insr);
String line = null;
do {
line = in.readLine();
if(line != null) {
input.append(line);
}
} while(line != null);
in.close();
parse(new JSONObject(input.toString()));
postProcess();
}
catch(Exception e) {
logger.log(e);
}
}
public boolean areEqual(String key, Object o) {
if(key == null || o == null) return false;
return key.equalsIgnoreCase(o.toString());
}
public void postProcess() throws Exception {
Iterator<Topic> topics = topicMap.getTopics();
Collection topicCollection = new ArrayList<Topic>();
while(topics.hasNext()) {
Topic t=topics.next();
topicCollection.add(t);
}
topics = topicCollection.iterator();
Topic t;
HashMap<Topic,Locator> toBeRemoved = new HashMap();
while(topics.hasNext()) {
t = topics.next();
if(t != null && !t.isRemoved()) {
Collection<Locator> subjectIdentifiers = t.getSubjectIdentifiers();
for(Locator subjectIdentifier : t.getSubjectIdentifiers()) {
if(subjectIdentifier.toExternalForm().startsWith(STATIC_SI_BODY)) {
if(subjectIdentifiers.size() > 1) {
toBeRemoved.put(t, subjectIdentifier);
}
else {
log("Warning: Can't remove temporary subject identifier. Probably the topic had no subject identifier in jtm.");
}
}
}
}
}
for(Topic topic : toBeRemoved.keySet()) {
topic.removeSubjectIdentifier(toBeRemoved.get(topic));
}
}
public void parse(JSONObject inputJSON) throws Exception {
if(topicMap == null) {
log("Warning: JTM parser has no Topic Map object for topics and associations. Aborting.");
return;
}
Iterator keys = inputJSON.keys();
Object key = null;
Object value = null;
logCount = 0;
while(keys.hasNext()) {
key = keys.next();
if(key != null) {
value = inputJSON.get(key.toString());
if("version".equals(key)) {
if(!"1.0".equals(value)) {
log("Warning: JTM version number is not equal to 1.0! Trying anyway...");
}
}
else if("item_type".equals(key)) {
if(areEqual("topicmap", value)) {
// IGNORE SILENTY
}
else if(areEqual("topic", value)) {
parseTopic(inputJSON);
}
else if(areEqual("association", value)) {
parseAssociation(inputJSON);
}
else {
log("Warning: Wandora's JTM parser does not support item_type '"+value.toString()+"'. Skipping.");
}
}
else if("topics".equals(key)) {
if(value != null && value instanceof JSONArray) {
JSONArray topicJSONArray = (JSONArray) value;
int length = topicJSONArray.length();
Object topicJSON = null;
for(int i=0; i<length; i++) {
topicJSON = topicJSONArray.get(i);
if(topicJSON != null && topicJSON instanceof JSONObject) {
parseTopic((JSONObject) topicJSON);
}
}
}
}
else if("associations".equals(key)) {
if(value != null && value instanceof JSONArray) {
JSONArray associationJSONArray = (JSONArray) value;
int length = associationJSONArray.length();
Object associationJSON = null;
for(int i=0; i<length; i++) {
associationJSON = associationJSONArray.get(i);
if(associationJSON != null && associationJSON instanceof JSONObject) {
parseAssociation((JSONObject) associationJSON);
}
}
}
}
}
}
}
public void parseTopic(JSONObject topicJSON) throws Exception {
Iterator keys = topicJSON.keys();
Object key = null;
Object value = null;
Topic t = topicMap.createTopic();
t.addSubjectIdentifier(new Locator(STATIC_SI_BODY+System.currentTimeMillis()+"-"+Math.floor(Math.random()*9999999)));
while(keys.hasNext()) {
key = keys.next();
if(key != null) {
value = topicJSON.get(key.toString());
if("subject_identifiers".equals(key)) {
if(value != null && value instanceof JSONArray) {
JSONArray siArray = (JSONArray) value;
Object si = null;
int length = siArray.length();
for(int i=0; i<length; i++) {
si = siArray.get(i);
if(si != null) {
String sis = si.toString();
if(sis != null && sis.length() > 0) {
t.addSubjectIdentifier(new Locator(sis));
}
}
}
}
}
else if("subject_locators".equals(key)) {
if(value != null && value instanceof JSONArray) {
JSONArray slArray = (JSONArray) value;
Object sl = null;
int length = slArray.length();
for(int i=0; i<length; i++) {
sl = slArray.get(i);
if(sl != null) {
String sls = sl.toString();
if(sls != null && sls.length() > 0) {
if(i<1) {
t.setSubjectLocator(new Locator(sls));
}
else {
log("Warning: Wandora supports only one subject locator in topic. Skipping subject locator '"+sl+"'.");
}
}
}
}
}
}
else if("item_identifiers".equals(key)) {
if(value != null && value instanceof JSONArray) {
JSONArray iiArray = (JSONArray) value;
Object ii = null;
int length = iiArray.length();
for(int i=0; i<length; i++) {
ii = iiArray.get(i);
if(ii != null) {
String iis = ii.toString();
if(iis != null && iis.length() > 0) {
log("Warning: Wandora doesn't support item identifiers. Making subject identifier out of item identifier '"+ii+"'.");
t.addSubjectIdentifier(new Locator(iis));
}
}
}
}
}
}
}
keys = topicJSON.keys();
while(keys.hasNext()) {
key = keys.next();
if(key != null) {
value = topicJSON.get(key.toString());
if("names".equals(key)) {
if(value != null && value instanceof JSONArray) {
JSONArray nameArray = (JSONArray) value;
Object name = null;
int length = nameArray.length();
for(int i=0; i<length; i++) {
name = nameArray.get(i);
if(name!= null && name instanceof JSONObject) {
parseTopicName((JSONObject) name, t);
}
}
}
}
else if("occurrences".equals(key)) {
if(value != null && value instanceof JSONArray) {
JSONArray occurrenceArray = (JSONArray) value;
Object occurrence = null;
int length = occurrenceArray.length();
for(int i=0; i<length; i++) {
occurrence = occurrenceArray.get(i);
if(occurrence!= null && occurrence instanceof JSONObject) {
parseOccurrence((JSONObject) occurrence, t);
}
}
}
}
}
}
}
public void parseTopicName(JSONObject topicNameJSON, Topic t) throws Exception {
Iterator keys = topicNameJSON.keys();
Object key = null;
Object value = null;
boolean hasSetBasename = false;
while(keys.hasNext()) {
key = keys.next();
if(key != null) {
value = topicNameJSON.get(key.toString());
if("value".equals(key)) {
if(hasSetBasename) {
log("Warning: Wandora supports only one base name. Skipping name '"+value+"'.");
}
else {
String bn = value.toString();
if(bn != null && bn.length() > 0) {
t.setBaseName(fixString(bn));
hasSetBasename = true;
}
}
}
else if("variants".equals(key)) {
if(value != null && value instanceof JSONArray) {
JSONArray variantArray = (JSONArray) value;
Object variant = null;
int length = variantArray.length();
for(int i=0; i<length; i++) {
variant = variantArray.get(i);
if(variant!= null && variant instanceof JSONObject) {
parseVariant((JSONObject) variant, t);
}
}
}
}
else if("type".equals(key)) {
log("Warning: Wandora doesn't support typed base names. Skipping.");
}
else if("scope".equals(key)) {
log("Warning: Wandora doesn't support scopes in base names. Skipping.");
}
else if("reifier".equals(key)) {
log("Warning: Wandora doesn't support reifiers in topic names. Skipping.");
}
else if("item_identifiers".equals(key)) {
log("Warning: Wandora doesn't support item identifiers in topic names. Skipping.");
}
}
}
}
public void parseVariant(JSONObject variantJSON, Topic t) throws Exception {
String variantName = null;
HashSet<Topic> scope = new LinkedHashSet();
Iterator keys = variantJSON.keys();
Object key = null;
Object value = null;
while(keys.hasNext()) {
key = keys.next();
if(key != null) {
value = variantJSON.get(key.toString());
if("value".equals(key)) {
variantName = fixString(value.toString());
}
else if("scope".equals(key)) {
if( value instanceof JSONArray ) {
JSONArray scopeArray = (JSONArray) value;
int length = scopeArray.length();
for(int i=0; i<length; i++) {
scope.add(getOrCreateTopic(scopeArray.get(i).toString()));
}
}
else {
scope.add(getOrCreateTopic(value.toString()));
}
}
else if("datatype".equals(key)) {
log("Warning: Wandora doesn't support datatypes in variant names. Skipping.");
}
else if("reifier".equals(key)) {
log("Warning: Wandora doesn't support reifiers in variant names. Skipping.");
}
else if("item_identifiers".equals(key)) {
log("Warning: Wandora doesn't support item_identifiers in variant names. Skipping.");
}
}
}
if(variantName != null && variantName.length() > 0 && scope.size() > 0) {
if(t == null) {
t = topicMap.createTopic();
Locator l = TopicTools.createDefaultLocator();
log("Warning: Adding topic default subject identifier '"+l.toExternalForm()+"'.");
t.addSubjectIdentifier(l);
}
t.setVariant(scope, variantName);
}
}
public void parseOccurrence(JSONObject occurrenceJSON, Topic t) throws Exception {
String occurrenceText = null;
Topic scope = null;
Topic type = null;
Iterator keys = occurrenceJSON.keys();
Object key = null;
Object value = null;
while(keys.hasNext()) {
key = keys.next();
if(key != null) {
value = occurrenceJSON.get(key.toString());
if("value".equals(key)) {
occurrenceText = fixString(value.toString());
}
else if("type".equals(key)) {
type = getOrCreateTopic(value.toString());
}
else if("scope".equals(key)) {
if( value instanceof JSONArray ) {
JSONArray scopeArray = (JSONArray) value;
int length = scopeArray.length();
for(int i=0; i<length; i++) {
if(scope != null) {
log("Warning: Wandora supports only one scope topic in occurrences. Skipping scope '"+scopeArray.getString(i));
}
else {
scope = getOrCreateTopic(scopeArray.get(i).toString());
}
}
}
else {
scope = getOrCreateTopic(value.toString());
}
}
else if("datatype".equals(key)) {
log("Warning: Wandora doesn't support datatypes in occurrences. Skipping.");
}
else if("reifier".equals(key)) {
log("Warning: Wandora doesn't support reifiers in occurrences. Skipping.");
}
else if("item_identifiers".equals(key)) {
log("Warning: Wandora doesn't support item_identifiers in occurrences. Skipping.");
}
}
}
if(occurrenceText != null && occurrenceText.length() > 0 && type != null && scope != null) {
if(t == null) {
t = topicMap.createTopic();
Locator l = TopicTools.createDefaultLocator();
log("Warning: Adding topic default subject identifier '"+l.toExternalForm()+"'.");
t.addSubjectIdentifier(l);
}
t.setData(type, scope, occurrenceText);
}
}
// -------------------------------------------------------- ASSOCIATIONS ---
public void parseAssociation(JSONObject topicJSON) throws Exception {
Association a = null;
ArrayList<T2<String,String>> roles = new ArrayList<T2<String,String>>();
String type = null;
Iterator keys = topicJSON.keys();
Object key = null;
Object value = null;
while(keys.hasNext()) {
key = keys.next();
if(key != null) {
value = topicJSON.get(key.toString());
if("type".equals(key)) {
type = value.toString();
}
else if("roles".equals(key)) {
if(value != null && value instanceof JSONArray) {
JSONArray roleArray = (JSONArray) value;
T2<String,String> role = null;
Object roleObject = null;
int length = roleArray.length();
for(int i=0; i<length; i++) {
roleObject = roleArray.get(i);
if(roleObject != null && roleObject instanceof JSONObject) {
role = parseRoles((JSONObject) roleObject);
if(role != null) {
roles.add(role);
}
}
}
}
}
else if("scope".equals(key)) {
log("Warning: Wandora doesn't support scopes in associations. Skipping.");
}
else if("reifier".equals(key)) {
log("Warning: Wandora doesn't support reifiers in associations. Skipping.");
}
else if("item_identifiers".equals(key)) {
log("Warning: Wandora doesn't support item_identifiers in associations. Skipping.");
}
}
}
if(type != null && roles.size() > 0) {
if(ASSOCIATION_TO_TYPE && roles.size() == 2 &&
(type.endsWith("http://psi.topicmaps.org/iso13250/model/type-instance") ||
type.endsWith("http://www.topicmaps.org/xtm/1.0/core.xtm#class-instance"))) {
Topic instanceTopic = null;
Topic typeTopic = null;
String player1 = roles.get(0).e1;
String roleType1 = roles.get(0).e2;
String player2 = roles.get(1).e1;
String roleType2 = roles.get(1).e2;
if(roleType1 != null &&
(roleType1.endsWith("http://psi.topicmaps.org/iso13250/model/instance") ||
roleType1.endsWith("http://www.topicmaps.org/xtm/1.0/core.xtm#instance"))) {
instanceTopic = getOrCreateTopic(player1);
typeTopic = getOrCreateTopic(player2);
instanceTopic.addType(typeTopic);
}
else {
instanceTopic = getOrCreateTopic(player2);
typeTopic = getOrCreateTopic(player1);
instanceTopic.addType(typeTopic);
}
}
else {
Topic typeTopic = getOrCreateTopic(type);
Topic roleType = null;
Topic rolePlayer = null;
a = topicMap.createAssociation(typeTopic);
for( T2<String,String> role : roles ) {
roleType = getOrCreateTopic(role.e2);
rolePlayer = getOrCreateTopic(role.e1);
a.addPlayer(rolePlayer, roleType);
}
}
}
}
public T2<String,String> parseRoles(JSONObject rolesJSON) throws Exception {
Iterator keys = rolesJSON.keys();
String type = null;
String player = null;
Object key = null;
Object value = null;
while(keys.hasNext()) {
key = keys.next();
if(key != null) {
value = rolesJSON.get(key.toString());
if("type".equals(key)) {
type = value.toString();
}
else if("player".equals(key)) {
player = value.toString();
}
else if("reifier".equals(key)) {
log("Warning: Wandora doesn't support reifiers in roles. Skipping.");
}
else if("item_identifiers".equals(key)) {
log("Warning: Wandora doesn't support item_identifiers in roles. Skipping.");
}
}
}
if(type != null && player != null) {
return new T2(player, type);
}
else {
return null;
}
}
// -------------------------------------------------------------- TOPICS ---
public Topic getOrCreateTopic(String i) {
Topic t = null;
try {
if(i.startsWith("si:")) {
String si = i.substring(3);
t = topicMap.getTopic(si);
if(t == null) {
t = topicMap.createTopic();
if(t != null) {
t.addSubjectIdentifier(new Locator(si));
}
}
}
else if(i.startsWith("sl:")) {
String sl = i.substring(3);
t = topicMap.getTopicBySubjectLocator(sl);
if(t == null) {
t = topicMap.createTopic();
if(t != null) {
t.setSubjectLocator(new Locator(sl));
}
}
}
else if(i.startsWith("ii:")) {
String ii = i.substring(3);
t = topicMap.getTopic(ii);
if(t == null) {
if(MAKE_TOPIC_ID_WITH_II) {
t = topicMap.createTopic(ii);
}
if(MAKE_SUBJECT_IDENTIFIER_WITH_II) {
if(t == null) {
t = topicMap.createTopic();
}
if(t != null) {
t.addSubjectIdentifier(new Locator(ii));
}
}
}
}
else {
t = topicMap.getTopic(i);
if(t == null) {
if(MAKE_TOPIC_ID_WITH_II) {
t = topicMap.createTopic(i);
}
else {
t = topicMap.createTopic();
}
if(t != null) {
t.addSubjectIdentifier(new Locator(i));
}
}
}
}
catch(Exception e) {
logger.log(e);
}
return t;
}
public String fixString(String str) {
return str;
/*
// LOOKS LIKE JAVA HANDLES STRING FIXING AUTOMATICALLY. THUS COMMENTED!
if(str == null || str.length()==0) return str;
else {
System.out.println("Fixing "+str);
StringBuffer sb = new StringBuffer("");
int length = str.length();
int c0 = -1;
int c1 = -1;
for(int i=0; i<length; i++) {
c0 = str.charAt(i);
if(c0=='\\') {
if(i+1<length) {
c1 = str.charAt(i+1);
if(c1=='n') sb.append('\n');
else if(c1=='f') sb.append('\f');
else if(c1=='r') sb.append('\r');
else if(c1=='t') sb.append('\t');
else if(c1=='b') sb.append('\b');
else if(c1=='"') sb.append('"');
else if(c1=='\\') sb.append('\\');
else if(c1=='/') sb.append('/');
else if(c1=='u') {
if(i+5<length) {
try {
String hexstr = str.substring(i+2,i+6);
System.out.println("Found 'u"+hexstr+"'");
int hex = -1;
hex = Integer.parseInt(hexstr, 16);
sb.append((char) hex);
}
catch(Exception e) {
logger.log(e);
}
i+=4;
}
}
else {
sb.append((char) c1);
}
i++;
}
}
else {
sb.append((char) c0);
}
}
return sb.toString();
}
*/
}
// ---------------------------------------------------------------- LOGS ---
private int maxLogs = 1000;
private int logCount = 0;
private void log(String str) {
if(logCount<maxLogs) {
logCount++;
logger.log(str);
if(logCount>=maxLogs) {
logger.log("Silently ignoring rest of the logs...");
}
}
}
}
| 29,340 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
DatabaseTopicMap.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/database2/DatabaseTopicMap.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* DatabaseTopicMap.java
*
* Created on 7. marraskuuta 2005, 11:28
*/
package org.wandora.topicmap.database2;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.topicmap.TopicMapListener;
import org.wandora.topicmap.TopicMapLogger;
import org.wandora.topicmap.TopicMapReadOnlyException;
import org.wandora.topicmap.TopicMapSearchOptions;
import org.wandora.topicmap.TopicMapStatData;
import org.wandora.topicmap.TopicMapStatOptions;
import org.wandora.topicmap.TopicTools;
/**
*
* @author olli, akivela
*/
public class DatabaseTopicMap extends AbstractDatabaseTopicMap {
protected boolean changed;
/** The WeakTopicIndex used to index topics. Note that index needs information
* about changes in topic map and should also be used to construct new
* topics to make sure that there are not two different instances of the same topic.
* @see WeakTopicIndex
*/
protected WeakTopicIndex topicIndex;
protected List<TopicMapListener> topicMapListeners;
protected List<TopicMapListener> disabledListeners;
/**
* <p>
* A flag indicating that the <code>topicIndex</code> is a full index of
* everything existing in this topic map. Normally it is not. However, when
* you import something in an empty topic map, you can stop the index
* cleaner thread that is normally deleting rarely used topics from
* index. Because all created topics and associations are added to the index, this will
* result in an index containing everything in the topic map.
* </p><p>
* The index is done with weak references so the actual objects might not
* be found in the index but even if this is the case, the index will contain
* the information if such an object exists in the actual database or not.
* </p>
*/
protected boolean completeIndexes=false;
protected Object indexLock=new Object();
/** Creates a new instance of DatabaseTopicMap */
public DatabaseTopicMap(String dbDriver, String dbConnectionString, String dbUser, String dbPassword) throws SQLException {
this(dbDriver, dbConnectionString, dbUser, dbPassword, null);
}
public DatabaseTopicMap(String dbDriver, String dbConnectionString, String dbUser, String dbPassword, Object connectionParams) throws SQLException {
this(dbDriver, dbConnectionString, dbUser, dbPassword, null, connectionParams);
}
public DatabaseTopicMap(String dbDriver, String dbConnectionString, String dbUser, String dbPassword, String initScript) throws SQLException {
this(dbDriver, dbConnectionString, dbUser, dbPassword, initScript, null);
}
public DatabaseTopicMap(String dbDriver, String dbConnectionString, String dbUser, String dbPassword, String initScript, Object connectionParams) throws SQLException {
super(dbDriver, dbConnectionString, dbUser, dbPassword, initScript, connectionParams);
topicMapListeners=new ArrayList<TopicMapListener>();
topicIndex=new WeakTopicIndex();
changed=false;
}
/**
* Deletes everything in the topic map by clearing the database tables.
*/
@Override
public void clearTopicMap() throws TopicMapException {
if(isReadOnly()) throw new TopicMapReadOnlyException();
topicIndex.stopCleanerThread();
executeUpdate("delete from MEMBER");
executeUpdate("delete from ASSOCIATION");
executeUpdate("delete from VARIANTSCOPE");
executeUpdate("delete from VARIANT");
executeUpdate("delete from DATA");
executeUpdate("delete from TOPICTYPE");
executeUpdate("delete from SUBJECTIDENTIFIER");
executeUpdate("delete from TOPIC");
topicIndex=new WeakTopicIndex();
changed=true;
}
/**
* Clears the topic index (cache) containing recently accessed database topics.
* Any topic found in the index is not retrieved from the database and it is
* impossible for DatabaseTopicMap to detect any changes in the database. Thus
* the index may contain outdated information and you will need to manually
* clear the index to force retrieving of topics directly from the database.
*/
@Override
public void clearTopicMapIndexes() {
topicIndex.stopCleanerThread();
topicIndex = new WeakTopicIndex();
}
public void printIndexDebugInfo(){
topicIndex.printDebugInfo();
}
/*
* Method checks if database topic map contains topics without subject
* identifiers and inserts default SI to each such topic.
*
* These unindentified topics occur rarely if a tool or import fails for
* example. As unidentified topics cause serious problems if used in
* Wandora application user should have a back door to make database
* topic map consistent.
*/
public void checkSIConsistency() throws TopicMapException {
checkSIConsistency(getLogger());
}
public void checkSIConsistency(TopicMapLogger logger) throws TopicMapException {
if(unconnected) return;
if(isReadOnly()) throw new TopicMapReadOnlyException();
logger.log("Finding topic's without SIs!");
String query = "select TOPICID from TOPIC left join SUBJECTIDENTIFIER on SUBJECTIDENTIFIER.TOPIC=TOPIC.TOPICID where SI is NULL";
Collection<Map<String,Object>> res = executeQuery(query);
String topicID = null;
String defaultSI = null;
logger.log("Found total "+res.size()+" topics without SIs!");
for(Map<String,Object> row : res) {
topicID = row.get("TOPICID").toString();
defaultSI = TopicTools.createDefaultLocator().toExternalForm();
logger.log("Inserting SI '"+defaultSI+" to topic with id '"+topicID+"'.");
if(topicID != null && defaultSI != null) {
executeUpdate("insert into SUBJECTIDENTIFIER (TOPIC, SI) values ('"+escapeSQL(topicID)+"', '"+escapeSQL(defaultSI)+"')");
}
}
}
@Override
public void checkAssociationConsistency(TopicMapLogger logger) throws TopicMapException {
if(unconnected) return;
if(isReadOnly()) throw new TopicMapReadOnlyException();
// if(true) return; // consistency disabled
if(logger != null) logger.log("Checking association consistency!");
int counter=0;
int deleted=0;
Collection<Map<String,Object>> res=executeQuery("select distinct PLAYER from MEMBER");
for(Map<String,Object> row : res){
String player=row.get("PLAYER").toString();
HashSet<ArrayList<String>> associations=new LinkedHashSet<>(500);
Collection<Map<String,Object>> res2=executeQuery(
"select ASSOCIATION.*,M2.* from ASSOCIATION,MEMBER as M1, MEMBER as M2 "+
"where M1.PLAYER='"+escapeSQL(player)+"' and M1.ASSOCIATION=ASSOCIATIONID and "+
"M2.ASSOCIATION=ASSOCIATION.ASSOCIATIONID order by ASSOCIATION.ASSOCIATIONID,M2.ROLE"
);
String associationid="";
ArrayList<String> v=new ArrayList<>(9);
for(Map<String,Object> row2 : res2) {
String id=row2.get("ASSOCIATIONID").toString();
if(!associationid.equals(id)){
if(!associationid.equals("")) {
if(!associations.add(v)) {
logger.hlog("Deleting association with id "+associationid);
executeUpdate("delete from MEMBER where ASSOCIATION='"+escapeSQL(associationid)+"'");
executeUpdate("delete from ASSOCIATION where ASSOCIATIONID='"+escapeSQL(associationid)+"'");
deleted++;
}
v=new ArrayList<>(9);
String type=row2.get("TYPE").toString();
v.add(type);
}
associationid=id;
}
String r=row2.get("ROLE").toString();
String p=row2.get("PLAYER").toString();
v.add(r); v.add(p);
}
if(!associations.add(v)) {
logger.hlog("Deleting association with id "+associationid);
executeUpdate("delete from MEMBER where ASSOCIATION='"+escapeSQL(associationid)+"'");
executeUpdate("delete from ASSOCIATION where ASSOCIATIONID='"+escapeSQL(associationid)+"'");
deleted++;
}
counter++;
// System.out.println("Counter "+counter);
}
if(logger != null) logger.log("Association consistency deleted "+deleted+" associations!");
}
/**
* Closes the topic map. This closes the topic index freeing some resources
* and closes the database connection. Topic map cannot be used or reopened
* after it has been closed.
*/
@Override
public void close(){
topicIndex.destroy();
super.close();
}
// --------------------------------------------------------- BUILD TOPIC ---
/**
* Builds a database topic from a database query result row. The row should contain
* (at least) three columns with names "TOPICID", "BASENAME" and "SUBJECTLOCATOR"
* that are used to build the topic.
*/
public DatabaseTopic buildTopic(Map<String,Object> row) throws TopicMapException {
return buildTopic(row.get("TOPICID"), row.get("BASENAME"), row.get("SUBJECTLOCATOR"));
}
/**
* Builds a database topic when given the topic id, basename and subject locator.
*/
public DatabaseTopic buildTopic(Object id, Object baseName, Object subjectLocator) throws TopicMapException {
return buildTopic((String)id, (String)baseName, (String)subjectLocator);
}
/**
* Builds a database topic when given the topic id, basename and subject locator.
*/
public DatabaseTopic buildTopic(String id, String baseName, String subjectLocator) throws TopicMapException {
DatabaseTopic dbt = topicIndex.getTopicWithID(id);
if(dbt == null) {
dbt = topicIndex.createTopic(id,this);
dbt.initialize(baseName,subjectLocator);
}
else {
if(baseName != null) {
dbt.setBaseName(baseName);
}
if(subjectLocator != null) {
dbt.setSubjectLocator(new Locator(subjectLocator));
}
}
return dbt;
}
// --------------------------------------------------- BUILD ASSOCIATION ---
/**
* Builds a database association from a database query result row. The row should contain
* (at least) four columns with names "ASSOCIATIONID", "TOPICID", "BASENAME" and "SUBJECTLOCATOR"
* where all but the "ASSOCIATIONID" are the core properties of the association type topic.
*/
public DatabaseAssociation buildAssociation(Map<String,Object> row) throws TopicMapException {
return buildAssociation(row.get("ASSOCIATIONID"), row.get("TOPICID"), row.get("BASENAME"), row.get("SUBJECTLOCATOR"));
}
public DatabaseAssociation buildAssociation(Object associationId,Object typeId,Object typeName,Object typeSL) throws TopicMapException {
return buildAssociation((String)associationId, (String)typeId, (String)typeName, (String)typeSL);
}
public DatabaseAssociation buildAssociation(String associationId, String typeId, String typeName, String typeSL) throws TopicMapException {
DatabaseAssociation dba = topicIndex.getAssociation(associationId,this);
if(dba!=null) return dba;
DatabaseTopic type = buildTopic(typeId,typeName,typeSL);
return buildAssociation(associationId,type);
}
public DatabaseAssociation buildAssociation(String associationId, DatabaseTopic type){
DatabaseAssociation dba=topicIndex.getAssociation(associationId,this);
if(dba==null){
dba=topicIndex.createAssociation(associationId,this);
dba.initialize(type);
}
return dba;
}
// --------------------------------------------------------- QUERY TOPIC ---
/**
* Executes a database query and returns results as a collection of topics.
* The result set must have the same columns used by buildTopic method.
*/
public Collection<Topic> queryTopic(String query) throws TopicMapException {
Collection<Map<String,Object>> res = executeQuery(query);
Collection<Topic> ret = new ArrayList<>();
for(Map<String,Object> row : res){
ret.add(buildTopic(row));
}
return ret;
}
/**
* Same as queryTopic but only returns the first topic in the result set or
* null if the result set is empty.
*/
public Topic querySingleTopic(String query) throws TopicMapException {
Collection<Topic> c=queryTopic(query);
if(c.isEmpty()) return null;
else return c.iterator().next();
}
/**
* Executes a database query and returns results as a collection of associations.
* The result set must have the same columns used by buildAssociation method.
*/
public Collection<Association> queryAssociation(String query) throws TopicMapException {
Collection<Map<String,Object>> res = executeQuery(query);
ArrayList<Association> ret = new ArrayList<>();
for(Map<String,Object>row : res){
ret.add(buildAssociation(row));
}
return ret;
}
// -------------------------------------------------------------------------
public Topic getTopic(Collection<Locator> SIs) throws TopicMapException {
for(Locator l : SIs){
Topic t=getTopic(l);
if(t!=null) return t;
}
return null;
}
public void topicSIChanged(DatabaseTopic t,Locator deleted,Locator added){
topicIndex.topicSIChanged(t,deleted,added);
}
public void topicBNChanged(Topic t,String old) throws TopicMapException {
topicIndex.topicBNChanged(t,old);
}
@Override
public Topic getTopic(Locator si) throws TopicMapException {
if(unconnected) return null;
if(topicIndex.containsKeyWithSI(si)) {
Topic t=topicIndex.getTopicWithSI(si);
// may return null if, A) has mapping that no topic with si exists or
// B) there is a mapping but the weak referenc has been cleared
if(t!=null) return t; // clear case, return
else if(topicIndex.isNullSI(si)) {
// if no topic exists, return null, otherwise refetch the topic
return null;
}
}
else if(completeIndexes) return null; // index is complete so if nothing is mentioned then there is no such topic
Topic t=querySingleTopic("select TOPIC.* "
+ "from TOPIC,SUBJECTIDENTIFIER "
+ "where TOPIC=TOPICID "
+ "and SI='"+escapeSQL(si.toExternalForm())+"'");
if(t==null) {
topicIndex.addNullSI(si);
}
return t;
}
@Override
public Topic getTopicBySubjectLocator(Locator sl) throws TopicMapException {
if(unconnected) return null;
return querySingleTopic("select * from TOPIC "
+"where SUBJECTLOCATOR='"
+escapeSQL(sl.toExternalForm())+"'");
}
@Override
public Topic createTopic(String id) throws TopicMapException {
if(unconnected) return null;
if(isReadOnly()) throw new TopicMapReadOnlyException();
DatabaseTopic t = topicIndex.newTopic(id, this);
return t;
}
@Override
public Topic createTopic() throws TopicMapException {
if(unconnected) return null;
if(isReadOnly()) throw new TopicMapReadOnlyException();
DatabaseTopic t=topicIndex.newTopic(this);
return t;
}
@Override
public Association createAssociation(Topic type) throws TopicMapException {
if(unconnected) return null;
if(isReadOnly()) throw new TopicMapReadOnlyException();
DatabaseAssociation a=topicIndex.newAssociation((DatabaseTopic)type,this);
return a;
}
@Override
public Collection<Topic> getTopicsOfType(Topic type) throws TopicMapException {
if(unconnected) return new ArrayList<Topic>();
Collection<Topic> res=queryTopic("select TOPIC.* "
+"from TOPIC,TOPICTYPE "
+"where TOPIC=TOPICID "
+"and TYPE='"+escapeSQL(type.getID())+"'");
Map<String,DatabaseTopic> collected=new LinkedHashMap<>();
for(Topic t : res){
collected.put(t.getID(),(DatabaseTopic)t);
}
DatabaseTopic.fetchAllSubjectIdentifiers(
executeQuery("select SUBJECTIDENTIFIER.* "
+"from SUBJECTIDENTIFIER,TOPIC,TOPICTYPE "
+"where SUBJECTIDENTIFIER.TOPIC=TOPIC.TOPICID "
+"and TOPIC.TOPICID=TOPICTYPE.TOPIC "
+"and TOPICTYPE.TYPE='"+escapeSQL(type.getID())+"' "
+"order by SUBJECTIDENTIFIER.TOPIC"),
collected, this);
return res;
}
@Override
public Topic getTopicWithBaseName(String name) throws TopicMapException {
if(unconnected) return null;
if(topicIndex.containsKeyWithBN(name)) {
// see notes in getTopic(Locator)
Topic t=topicIndex.getTopicWithBN(name);
if(t!=null) return t;
else if(topicIndex.isNullBN(name)) return null;
}
else if(completeIndexes) return null;
Topic t=querySingleTopic("select * from TOPIC where BASENAME='"+escapeSQL(name)+"'");
if(t==null) topicIndex.addNullBN(name);
return t;
}
@Override
public Iterator<Topic> getTopics() {
final Iterator<Map<String,Object>> rowIterator = getRowIterator("select * from TOPIC", "TOPICID");
return new Iterator<>() {
@Override
public boolean hasNext() {
return rowIterator.hasNext();
}
@Override
public Topic next() {
if(!hasNext()) {
throw new NoSuchElementException();
}
Map<String,Object> row = rowIterator.next();
try {
return buildTopic(row);
}
catch(TopicMapException tme) {
tme.printStackTrace(); // TODO EXCEPTION
return null;
}
}
@Override
public void remove() {
rowIterator.remove();
}
};
}
@Override
public Topic[] getTopics(String[] sis) throws TopicMapException {
if(unconnected) {
return new Topic[0];
}
Topic[] ret=new Topic[sis.length];
for(int i=0;i<sis.length;i++){
ret[i]=getTopic(sis[i]);
}
return ret;
}
/**
* Note that you must iterate through all rows because statement and result set
* will only be closed after last row has been fetched.
*/
@Override
public Iterator<Association> getAssociations() {
final Iterator<Map<String,Object>> rowIterator = getRowIterator("select * from ASSOCIATION,TOPIC where TOPICID=TYPE", "TOPIC.TOPICID");
return new Iterator<>() {
@Override
public boolean hasNext() {
return rowIterator.hasNext();
}
@Override
public Association next() {
if(!hasNext()) {
throw new NoSuchElementException();
}
Map<String,Object> row = rowIterator.next();
try {
return buildAssociation(row);
}
catch(TopicMapException tme) {
tme.printStackTrace(); // TODO EXCEPTION
return null;
}
}
@Override
public void remove() {
rowIterator.remove();
}
};
}
@Override
public Collection<Association> getAssociationsOfType(Topic type) throws TopicMapException {
if(unconnected) {
return new ArrayList<>();
}
return queryAssociation("select * "
+ "from ASSOCIATION,TOPIC "
+ "where TYPE=TOPICID "
+ "and TOPICID='"+escapeSQL(type.getID())+"'");
}
@Override
public int getNumTopics() {
int count = executeCountQuery("select count(*) from TOPIC");
return count;
}
@Override
public int getNumAssociations() {
int count = executeCountQuery("select count(*) from ASSOCIATION");
return count;
}
// -------------------------------------------------------------------------
// ---------------------------------------- COPY TOPICIN / ASSOCIATIONIN ---
// -------------------------------------------------------------------------
private Topic _copyTopicIn(Topic t, boolean deep, Map<Topic,Locator> copied) throws TopicMapException {
return _copyTopicIn(t,deep,false,copied);
}
private Topic _copyTopicIn(Topic t, boolean deep, boolean stub, Map<Topic,Locator> copied) throws TopicMapException {
if(copied.containsKey(t)) {
// Don't return the topic that was created when t was copied because it might have been merged with something
// since then. Instead get the topic with one of the subject identifiers of the topic.
Locator l=(Locator)copied.get(t);
return getTopic(l);
}
// first check if the topic would be merged, if so, edit the equal topic directly instead of creating new
// and letting them merge later
Topic nt=getTopic(t.getSubjectIdentifiers());
if(nt==null && t.getBaseName()!=null) nt=getTopicWithBaseName(t.getBaseName());
if(nt==null && t.getSubjectLocator()!=null) nt=getTopicBySubjectLocator(t.getSubjectLocator());
if(nt==null) {
nt=createTopic();
}
for(Locator l : t.getSubjectIdentifiers()){
nt.addSubjectIdentifier(l);
}
if(nt.getSubjectIdentifiers().isEmpty()) {
System.out.println("Warning no subject indicators in topic. Creating default SI.");
long randomNumber = System.currentTimeMillis() + Math.round(Math.random() * 99999);
nt.addSubjectIdentifier(new Locator("http://wandora.org/si/temp/" + randomNumber));
}
copied.put(t,(Locator)nt.getSubjectIdentifiers().iterator().next());
if(nt.getSubjectLocator()==null && t.getSubjectLocator()!=null){
nt.setSubjectLocator(t.getSubjectLocator()); // TODO: raise error if different?
}
if(nt.getBaseName()==null && t.getBaseName()!=null){
nt.setBaseName(t.getBaseName());
}
if( (!stub) || deep) {
for(Topic type : t.getTypes()){
Topic ntype=_copyTopicIn(type,deep,true,copied);
nt.addType(ntype);
}
for(Set<Topic> scope : t.getVariantScopes()) {
Set<Topic> nscope=new LinkedHashSet<>();
for(Topic st : scope){
Topic nst=_copyTopicIn(st,deep,true,copied);
nscope.add(nst);
}
nt.setVariant(nscope, t.getVariant(scope));
}
for(Topic type : t.getDataTypes()) {
Topic ntype=_copyTopicIn(type,deep,true,copied);
Hashtable<Topic,String> versiondata=t.getData(type);
for(Map.Entry<Topic,String> e : versiondata.entrySet()){
Topic version=e.getKey();
String data=e.getValue();
Topic nversion=_copyTopicIn(version,deep,true,copied);
nt.setData(ntype,nversion,data);
}
}
}
return nt;
}
private Association _copyAssociationIn(Association a) throws TopicMapException {
Topic type=a.getType();
Topic ntype=null;
if(type.getSubjectIdentifiers().isEmpty()) {
System.out.println("Warning, topic has no subject identifiers.");
}
else {
ntype=getTopic(type.getSubjectIdentifiers().iterator().next());
}
if(ntype==null) ntype=copyTopicIn(type,false);
Association na=createAssociation(ntype);
for(Topic role : a.getRoles()) {
Topic nrole = null;
if(role.getSubjectIdentifiers().isEmpty()) {
System.out.println("Warning, topic has no subject identifiers. Creating default SI!");
//role.addSubjectIdentifier(new Locator("http://wandora.org/si/temp/" + System.currentTimeMillis()));
}
else {
nrole=getTopic((Locator)role.getSubjectIdentifiers().iterator().next());
}
if(nrole==null) nrole=copyTopicIn(role,false);
Topic player=a.getPlayer(role);
Topic nplayer = null;
if(player.getSubjectIdentifiers().isEmpty()) {
System.out.println("Warning, topic has no subject identifiers. Creating default SI!");
//player.addSubjectIdentifier(new Locator("http://wandora.org/si/temp/" + System.currentTimeMillis()));
}
else {
nplayer=getTopic((Locator)player.getSubjectIdentifiers().iterator().next());
}
if(nplayer==null) nplayer=copyTopicIn(player,false);
na.addPlayer(nplayer,nrole);
}
return na;
}
@Override
public Association copyAssociationIn(Association a) throws TopicMapException {
if(unconnected) return null;
if(isReadOnly()) throw new TopicMapReadOnlyException();
Association n = _copyAssociationIn(a);
Topic minTopic = null;
int minCount = Integer.MAX_VALUE;
for(Topic role : n.getRoles()) {
Topic t = n.getPlayer(role);
if(t.getAssociations().size()<minCount){
minCount = t.getAssociations().size();
minTopic = t;
}
}
if(minTopic != null) {
((DatabaseTopic)minTopic).removeDuplicateAssociations();
}
return n;
}
@Override
public Topic copyTopicIn(Topic t, boolean deep) throws TopicMapException {
if(unconnected) return null;
if(isReadOnly()) throw new TopicMapReadOnlyException();
return _copyTopicIn(t, deep, false, new LinkedHashMap<>());
}
@Override
public void copyTopicAssociationsIn(Topic t) throws TopicMapException {
if(unconnected) return;
if(isReadOnly()) throw new TopicMapReadOnlyException();
Topic nt=getTopic((Locator)t.getSubjectIdentifiers().iterator().next());
if(nt==null) nt=copyTopicIn(t,false);
for(Association a : t.getAssociations()) {
_copyAssociationIn(a);
}
((DatabaseTopic)nt).removeDuplicateAssociations();
}
// -------------------------------------------------------------------------
// ------------------------------------------------------ IMPORT / MERGE ---
// -------------------------------------------------------------------------
@Override
public void importXTM(java.io.InputStream in, TopicMapLogger logger) throws java.io.IOException,TopicMapException {
if(unconnected) return;
if(isReadOnly()) throw new TopicMapReadOnlyException();
int numTopics=getNumTopics();
if(numTopics==0) {
System.out.println("Merging to empty topic map");
topicIndex.stopCleanerThread();
completeIndexes=topicIndex.isFullIndex();
}
else {
System.out.println("Merging to non-empty topic map (numTopcis="+numTopics+")");
}
boolean old=getConsistencyCheck();
setConsistencyCheck(false);
boolean check=!getConsistencyCheck();
super.importXTM(in, logger);
topicIndex.clearTopicCache();
topicIndex.startCleanerThread();
completeIndexes=false;
if(check && old) checkAssociationConsistency();
setConsistencyCheck(old);
}
@Override
public void importLTM(java.io.InputStream in, TopicMapLogger logger) throws java.io.IOException,TopicMapException {
if(unconnected) return;
if(isReadOnly()) throw new TopicMapReadOnlyException();
int numTopics=getNumTopics();
if(numTopics==0) {
System.out.println("Merging to empty topic map");
topicIndex.stopCleanerThread();
completeIndexes=topicIndex.isFullIndex();
}
else {
System.out.println("Merging to non-empty topic map (numTopcis="+numTopics+")");
}
boolean old=getConsistencyCheck();
setConsistencyCheck(false);
boolean check=!getConsistencyCheck();
super.importLTM(in, logger);
topicIndex.clearTopicCache();
topicIndex.startCleanerThread();
completeIndexes=false;
if(check && old) checkAssociationConsistency();
setConsistencyCheck(old);
}
@Override
public void importLTM(java.io.File in) throws java.io.IOException,TopicMapException {
if(unconnected) return;
if(isReadOnly()) throw new TopicMapReadOnlyException();
int numTopics=getNumTopics();
if(numTopics==0) {
System.out.println("Merging to empty topic map");
topicIndex.stopCleanerThread();
completeIndexes=topicIndex.isFullIndex();
}
else System.out.println("Merging to non-empty topic map (numTopcis="+numTopics+")");
boolean old=getConsistencyCheck();
setConsistencyCheck(false);
boolean check=!getConsistencyCheck();
super.importLTM(in);
topicIndex.clearTopicCache();
topicIndex.startCleanerThread();
completeIndexes=false;
if(check && old) checkAssociationConsistency();
setConsistencyCheck(old);
}
// -------------------------------------------------------------------------
@Override
public void mergeIn(TopicMap tm, TopicMapLogger tmLogger) throws TopicMapException {
if(unconnected) return;
if(isReadOnly()) throw new TopicMapReadOnlyException();
int numTopics=getNumTopics();
if(numTopics==0) {
tmLogger.log("Merging to empty topic map");
topicIndex.stopCleanerThread();
completeIndexes=topicIndex.isFullIndex();
}
else tmLogger.log("Merging to non-empty topic map (numTopics="+numTopics+")");
int targetNumTopics=tm.getNumTopics();
int targetNumAssociations=tm.getNumAssociations();
int tcount=0;
Map<Topic,Locator> copied=new LinkedHashMap<>();
{
// note that in some topic map implementations (DatabaseTopicMap specifically)
// you must always iterate through all topics to close the result set thus
// don't break the while loop even after forceStop
Iterator<Topic> iter=tm.getTopics();
while(iter.hasNext()) {
Topic t = null;
try {
t=iter.next();
if(!tmLogger.forceStop()) {
_copyTopicIn(t,true,false,copied);
}
tcount++;
}
catch (Exception e) {
tmLogger.log("Unable to copy topic (" + t + ").",e);
}
if((tcount%1000)==0) tmLogger.hlog("Copied "+tcount+"/"+targetNumTopics+" topics and 0/"+targetNumAssociations+" associations");
}
}
if(!tmLogger.forceStop()){
Set<Topic> endpoints=new LinkedHashSet<>();
int acount=0;
Iterator<Association> iter=tm.getAssociations();
while(iter.hasNext()) {
try {
Association a=iter.next();
if(!tmLogger.forceStop()) {
Association na=_copyAssociationIn(a);
Topic minTopic=null;
int minCount=Integer.MAX_VALUE;
Iterator<Topic> iter2=na.getRoles().iterator();
while(iter2.hasNext()){
Topic role=iter2.next();
Topic t=na.getPlayer(role);
if(t.getAssociations().size()<minCount){
minCount=t.getAssociations().size();
minTopic=t;
}
}
endpoints.add(minTopic);
}
acount++;
if((acount%1000)==0) tmLogger.hlog("Copied "+tcount+"/"+targetNumTopics+" topics and "+acount+"/"+targetNumAssociations+" associations");
}
catch (Exception e) {
tmLogger.log("Unable to copy association.",e);
}
}
tmLogger.log("merged "+tcount+" topics and "+acount+" associations");
tmLogger.log("cleaning associations");
for(Topic t : endpoints){
((DatabaseTopic)t).removeDuplicateAssociations();
}
}
topicIndex.startCleanerThread();
completeIndexes=false;
}
// -------------------------------------------------------------------------
// --------------------------------------------------------------- INDEX ---
// -------------------------------------------------------------------------
/**
* Tries to set complete index attribute. This is only possible if the topic map is
* empty (getNumTopics returns 0). If this is the case, will stop index cleaner
* thread and set the completeIndexes attribute to true.
* @see #completeIndexes
*/
public void setCompleteIndex(){
if(getNumTopics()==0) {
topicIndex.stopCleanerThread();
completeIndexes=topicIndex.isFullIndex();
}
}
/**
* Restarts the topic index cleaner thread. You need to call this at some point
* if you stopped it with setCompleteIndex.
*/
public void resetCompleteIndex(){
topicIndex.clearTopicCache();
topicIndex.startCleanerThread();
completeIndexes=false;
}
// ------------------------------------------------------------ TRACKING ---
@Override
public boolean trackingDependent(){
return false;
}
@Override
public void setTrackDependent(boolean v){
// TODO: dependent times and tracking dependent
}
// -------------------------------------------------------------------------
// --------------------------------------------------- TOPIC MAP CHANGED ---
// -------------------------------------------------------------------------
@Override
public boolean isTopicMapChanged(){
return changed;
}
@Override
public boolean resetTopicMapChanged(){
boolean old=changed;
changed=false;
return old;
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------- SEARCH ---
// -------------------------------------------------------------------------
@Override
public Collection<Topic> search(String query, TopicMapSearchOptions options) {
if(unconnected) return new ArrayList<Topic>();
ArrayList<Topic> searchResult = new ArrayList<Topic>();
int MAX_SEARCH_RESULTS = 999;
if(options.maxResults>=0 && options.maxResults<MAX_SEARCH_RESULTS) MAX_SEARCH_RESULTS=options.maxResults;
if(query == null || query.length()<4) {
return searchResult;
}
String dbquery = "%" + escapeSQL(query) + "%";
System.out.println("Search starts");
String union="";
// --- Basename ---
if(options.searchBasenames) {
if(union.length()>0) union+=" union ";
union+=" select TOPIC.* from TOPIC where BASENAME like '"+dbquery+"'";
}
// --- Variant names ---
if(options.searchVariants) {
if(union.length()>0) union+=" union ";
union+=" select TOPIC.* from TOPIC,VARIANT where TOPICID=VARIANT.TOPIC and VARIANT.VALUE like '"+dbquery+"'";
}
// --- text occurrences ---
if(options.searchOccurrences) {
if(union.length()>0) union+=" union ";
union+=" select TOPIC.* from TOPIC,DATA where DATA.TOPIC=TOPICID and DATA.DATA like '"+dbquery+"'";
}
// --- locator ---
if(options.searchSL) {
if(union.length()>0) union+=" union ";
union+=" select TOPIC.* from TOPIC where SUBJECTLOCATOR like '"+dbquery+"'";
}
// --- sis ---
if(options.searchSIs) {
if(union.length()>0) union+=" union ";
union+=" select TOPIC.* from TOPIC,SUBJECTIDENTIFIER where TOPICID=SUBJECTIDENTIFIER.TOPIC and SUBJECTIDENTIFIER.SI like '"+dbquery+"'";
}
try{
Collection<Topic> res=queryTopic(union);
int counter=0;
for(Topic t : res){
if(t.getOneSubjectIdentifier() == null) {
System.out.println("Warning: Topic '"+t.getBaseName()+"' has no SI!");
}
else {
searchResult.add(t);
counter++;
if(counter>=MAX_SEARCH_RESULTS) break;
}
}
}
catch(Exception e){e.printStackTrace();}
System.out.println("Search ends with " + searchResult.size() + " hits.");
return searchResult;
}
// -------------------------------------------------------------------------
// ---------------------------------------------------------- STATISTICS ---
// -------------------------------------------------------------------------
@Override
public TopicMapStatData getStatistics(TopicMapStatOptions options) throws TopicMapException {
if(options == null) return null;
int option = options.getOption();
int count = 0;
switch(option) {
case TopicMapStatOptions.NUMBER_OF_TOPICS: {
return new TopicMapStatData(this.getNumTopics());
}
case TopicMapStatOptions.NUMBER_OF_TOPIC_CLASSES: {
count = executeCountQuery("select count(DISTINCT TYPE) from TOPICTYPE");
return new TopicMapStatData(count);
}
case TopicMapStatOptions.NUMBER_OF_ASSOCIATIONS: {
return new TopicMapStatData(this.getNumAssociations());
}
case TopicMapStatOptions.NUMBER_OF_ASSOCIATION_PLAYERS: {
count = executeCountQuery("select count(DISTINCT MEMBER.PLAYER) from MEMBER");
return new TopicMapStatData(count);
}
case TopicMapStatOptions.NUMBER_OF_ASSOCIATION_ROLES: {
count = executeCountQuery("select count(DISTINCT MEMBER.ROLE) from MEMBER");
return new TopicMapStatData(count);
}
case TopicMapStatOptions.NUMBER_OF_ASSOCIATION_TYPES: {
count = executeCountQuery("select count(DISTINCT ASSOCIATION.TYPE) from ASSOCIATION");
return new TopicMapStatData(count);
}
case TopicMapStatOptions.NUMBER_OF_BASE_NAMES: {
count = executeCountQuery("select count(*) from TOPIC where BASENAME is not null");
return new TopicMapStatData(count);
}
case TopicMapStatOptions.NUMBER_OF_OCCURRENCES: {
count = executeCountQuery("select count(*) from DATA");
return new TopicMapStatData(count);
}
case TopicMapStatOptions.NUMBER_OF_SUBJECT_IDENTIFIERS: {
count = executeCountQuery("select count(*) from SUBJECTIDENTIFIER");
return new TopicMapStatData(count);
}
case TopicMapStatOptions.NUMBER_OF_SUBJECT_LOCATORS: {
count = executeCountQuery("select count(*) from TOPIC where SUBJECTLOCATOR is not null");
return new TopicMapStatData(count);
}
}
return new TopicMapStatData();
}
// -------------------------------------------------------------------------
// --------------------------------------------------- TOPICMAP LISTENER ---
// -------------------------------------------------------------------------
@Override
public List<TopicMapListener> getTopicMapListeners(){
return topicMapListeners;
}
@Override
public void addTopicMapListener(TopicMapListener listener){
topicMapListeners.add(listener);
}
@Override
public void removeTopicMapListener(TopicMapListener listener){
topicMapListeners.remove(listener);
}
@Override
public void disableAllListeners(){
if(disabledListeners==null){
disabledListeners=topicMapListeners;
topicMapListeners=new ArrayList<TopicMapListener>();
}
}
@Override
public void enableAllListeners(){
if(disabledListeners!=null){
topicMapListeners=disabledListeners;
disabledListeners=null;
}
}
/*
public TopicMapListener setTopicMapListener(TopicMapListener listener){
TopicMapListener old=topicMapListener;
topicMapListener=listener;
return old;
}
*/
// ----------------------------------------- TOPICMAP LISTENER INTERFACE ---
void topicRemoved(Topic t) throws TopicMapException {
topicIndex.topicRemoved(t);
changed=true;
for(TopicMapListener listener : topicMapListeners){
listener.topicRemoved(t);
}
}
void associationRemoved(Association a) throws TopicMapException {
changed=true;
for(TopicMapListener listener : topicMapListeners){
listener.associationRemoved(a);
}
}
public void topicSubjectIdentifierChanged(Topic t,Locator added,Locator removed) throws TopicMapException{
changed=true;
for(TopicMapListener listener : topicMapListeners){
listener.topicSubjectIdentifierChanged(t,added,removed);
}
}
public void topicBaseNameChanged(Topic t,String newName,String oldName) throws TopicMapException{
changed=true;
for(TopicMapListener listener : topicMapListeners){
listener.topicBaseNameChanged(t,newName,oldName);
}
}
public void topicTypeChanged(Topic t,Topic added,Topic removed) throws TopicMapException {
changed=true;
for(TopicMapListener listener : topicMapListeners){
listener.topicTypeChanged(t,added,removed);
}
}
public void topicVariantChanged(Topic t,Collection<Topic> scope,String newName,String oldName) throws TopicMapException {
changed=true;
for(TopicMapListener listener : topicMapListeners){
listener.topicVariantChanged(t,scope,newName,oldName);
}
}
public void topicDataChanged(Topic t,Topic type,Topic version,String newValue,String oldValue) throws TopicMapException {
changed=true;
for(TopicMapListener listener : topicMapListeners){
listener.topicDataChanged(t,type,version,newValue,oldValue);
}
}
public void topicSubjectLocatorChanged(Topic t,Locator newLocator,Locator oldLocator) throws TopicMapException {
changed=true;
for(TopicMapListener listener : topicMapListeners){
listener.topicSubjectLocatorChanged(t,newLocator,oldLocator);
}
}
public void topicChanged(Topic t) throws TopicMapException {
changed=true;
for(TopicMapListener listener : topicMapListeners){
listener.topicChanged(t);
}
}
public void associationTypeChanged(Association a,Topic newType,Topic oldType) throws TopicMapException {
changed=true;
for(TopicMapListener listener : topicMapListeners){
listener.associationTypeChanged(a,newType,oldType);
}
}
public void associationPlayerChanged(Association a,Topic role,Topic newPlayer,Topic oldPlayer) throws TopicMapException {
changed=true;
for(TopicMapListener listener : topicMapListeners){
listener.associationPlayerChanged(a,role,newPlayer,oldPlayer);
}
}
public void associationChanged(Association a) throws TopicMapException{
changed=true;
for(TopicMapListener listener : topicMapListeners){
listener.associationChanged(a);
}
}
// -------------------------------------------------------------------------
public void commit() throws SQLException, TopicMapException {
super.commit();
}
}
| 48,027 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
DatabaseAssociation.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/database2/DatabaseAssociation.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* DatabaseAssociation.java
*
* Created on 7. marraskuuta 2005, 11:28
*/
package org.wandora.topicmap.database2;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.topicmap.TopicMapReadOnlyException;
import org.wandora.topicmap.TopicRemovedException;
/**
*
* @author olli
*/
public class DatabaseAssociation implements Association {
protected DatabaseTopicMap topicMap;
protected String id;
protected boolean full;
protected DatabaseTopic type;
protected Map<Topic,Topic> players;
protected boolean removed=false;
/** Creates a new instance of DatabaseAssociation */
public DatabaseAssociation(DatabaseTopic type,DatabaseTopicMap topicMap) {
this.type=type;
this.topicMap=topicMap;
full=false;
}
public DatabaseAssociation(DatabaseTopic type,String id,DatabaseTopicMap topicMap) {
this(type,topicMap);
this.id=id;
}
public DatabaseAssociation(String id,DatabaseTopicMap topicMap) {
this.topicMap=topicMap;
this.id=id;
full=false;
}
public DatabaseAssociation(Map<String,Object> row,DatabaseTopicMap topicMap) throws TopicMapException {
this(topicMap.buildTopic(row),topicMap);
this.id=row.get("ASSOCIATIONID").toString();
}
void initialize(DatabaseTopic type){
this.type=type;
}
protected String escapeSQL(String s){
return topicMap.escapeSQL(s);
}
private static int idcounter=0;
protected static synchronized String makeID(){
if(idcounter>=100000) idcounter=0;
return "A"+System.currentTimeMillis()+"-"+(idcounter++);
}
public String getID(){
return id;
}
void create() throws TopicMapException {
players=new LinkedHashMap<>();
full=true;
id=makeID();
topicMap.executeUpdate("insert into ASSOCIATION (ASSOCIATIONID,TYPE) values ('"+escapeSQL(id)+"','"+escapeSQL(type.getID())+"')");
}
static Map<String,DatabaseTopic> makeFullAll(Collection<Map<String,Object>> res,Map<String,DatabaseAssociation> associations,DatabaseTopicMap topicMap) throws TopicMapException {
HashMap<String,DatabaseTopic> collected = new LinkedHashMap<>();
String associationID = null;
Map<Topic,Topic> players = null;
for(Map<String,Object> row : res) {
if(associationID==null || !associationID.equals(row.get("ASSOCIATION"))) {
if(associationID != null) {
DatabaseAssociation dba = associations.get(associationID);
if(dba!=null && !dba.full){
dba.full=true;
dba.players=players;
}
}
players = new LinkedHashMap<>();
if(row.get("ASSOCIATION") != null) {
associationID = row.get("ASSOCIATION").toString();
}
}
DatabaseTopic player=topicMap.buildTopic(row.get("PLAYERID"),row.get("PLAYERBN"),row.get("PLAYERSL"));
DatabaseTopic role=topicMap.buildTopic(row.get("ROLEID"),row.get("ROLEBN"),row.get("ROLESL"));
collected.put(player.getID(),player);
collected.put(role.getID(),role);
players.put(role,player);
}
if(associationID != null) {
DatabaseAssociation dba=associations.get(associationID);
if(dba!=null && !dba.full){
dba.full=true;
dba.players=players;
}
}
return collected;
}
void makeFull() throws TopicMapException {
full=true;
Collection<Map<String,Object>> res=
topicMap.executeQuery("select P.TOPICID as PLAYERID, P.BASENAME as PLAYERNAME, P.SUBJECTLOCATOR as PLAYERSL, "+
"R.TOPICID as ROLEID, R.BASENAME as ROLENAME, R.SUBJECTLOCATOR as ROLESL from "+
"TOPIC as P,TOPIC as R, MEMBER as M where P.TOPICID=M.PLAYER and "+
"R.TOPICID=M.ROLE and M.ASSOCIATION='"+escapeSQL(id)+"'");
players=new LinkedHashMap<>();
for(Map<String,Object> row : res){
Topic role=topicMap.buildTopic(row.get("ROLEID"),row.get("ROLENAME"),row.get("ROLESL"));
Topic player=topicMap.buildTopic(row.get("PLAYERID"),row.get("PLAYERNAME"),row.get("PLAYERSL"));
players.put(role,player);
}
}
@Override
public Topic getType() throws TopicMapException {
return type;
}
@Override
public void setType(Topic t) throws TopicMapException {
if( removed ) throw new TopicRemovedException();
if(!full) makeFull();
for(Map.Entry<Topic,Topic> e : players.entrySet()){
Topic role=e.getKey();
Topic player=e.getValue();
((DatabaseTopic)player).associationChanged(this, t, type, role, role);
}
Topic old=type;
type=(DatabaseTopic)t;
topicMap.executeUpdate("update ASSOCIATION set TYPE='"+escapeSQL(type.getID())+"' where ASSOCIATIONID='"+escapeSQL(id)+"'");
topicMap.associationTypeChanged(this,t,old);
}
@Override
public Topic getPlayer(Topic role) throws TopicMapException {
if(!full) makeFull();
return players.get(role);
}
@Override
public void addPlayer(Topic player,Topic role) throws TopicMapException {
if( removed ) throw new TopicRemovedException();
if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException();
if(!full) makeFull();
Topic old=players.get(role);
if(old!=null){
((DatabaseTopic)old).associationChanged(this, null, type,null, role);
topicMap.executeUpdate("update MEMBER set PLAYER='"+escapeSQL(player.getID())+"' where "+
"ASSOCIATION='"+escapeSQL(id)+"' and ROLE='"+escapeSQL(role.getID())+"'");
}
else{
topicMap.executeUpdate("insert into MEMBER (ASSOCIATION,PLAYER,ROLE) values "+
"('"+escapeSQL(id)+"','"+escapeSQL(player.getID())+"','"+escapeSQL(role.getID())+"')");
}
((DatabaseTopic)player).associationChanged(this,type,null,role,null);
players.put(role,player);
if(topicMap.getConsistencyCheck()) checkRedundancy();
topicMap.associationPlayerChanged(this,role,player,old);
}
@Override
public void addPlayers(Map<Topic,Topic> players) throws TopicMapException {
if( removed ) throw new TopicRemovedException();
if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException();
boolean changed=false;
for(Map.Entry<Topic,Topic> e : players.entrySet()){
DatabaseTopic role=(DatabaseTopic)e.getKey();
DatabaseTopic player=(DatabaseTopic)e.getValue();
Topic old=this.players.get(role);
if(old!=null){
((DatabaseTopic)old).associationChanged(this, null, type,null, role);
topicMap.executeUpdate("update MEMBER set PLAYER='"+escapeSQL(player.getID())+"' where "+
"ASSOCIATION='"+escapeSQL(id)+"' and ROLE='"+escapeSQL(role.getID())+"'");
}
else{
topicMap.executeUpdate("insert into MEMBER (ASSOCIATION,PLAYER,ROLE) values "+
"('"+escapeSQL(id)+"','"+escapeSQL(player.getID())+"','"+escapeSQL(role.getID())+"')");
}
((DatabaseTopic)player).associationChanged(this,type,null,role,null);
this.players.put(role,player);
topicMap.associationPlayerChanged(this,role,player,old);
}
if(topicMap.getConsistencyCheck()) checkRedundancy();
}
@Override
public void removePlayer(Topic role) throws TopicMapException {
if( removed ) throw new TopicRemovedException();
if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException();
if(!full) makeFull();
Topic old=players.get(role);
if(old!=null){
((DatabaseTopic)old).associationChanged(this, null, type,null, role);
topicMap.executeUpdate("delete from MEMBER where "+
"ASSOCIATION='"+escapeSQL(id)+"' and ROLE='"+escapeSQL(role.getID())+"'");
}
players.remove(role);
checkRedundancy();
topicMap.associationPlayerChanged(this,role,null,old);
}
@Override
public Collection<Topic> getRoles() throws TopicMapException {
if(!full) makeFull();
return players.keySet();
}
@Override
public TopicMap getTopicMap(){
return topicMap;
}
@Override
public void remove() throws TopicMapException {
if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException();
if(!full) makeFull();
removed=true;
for(Map.Entry<Topic,Topic> e : players.entrySet()){
Topic role=e.getKey();
Topic player=e.getValue();
((DatabaseTopic)player).associationChanged(this, null, type, null, role);
}
topicMap.executeUpdate("delete from MEMBER where ASSOCIATION='"+escapeSQL(id)+"'");
topicMap.executeUpdate("delete from ASSOCIATION where ASSOCIATIONID='"+escapeSQL(id)+"'");
topicMap.associationRemoved(this);
}
@Override
public boolean isRemoved() throws TopicMapException {
return removed;
}
public void checkRedundancy() throws TopicMapException {
if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException();
if(players.isEmpty()) return;
if(type==null) return;
Collection<Association> smallest=null;
for(Topic role : players.keySet()){
Topic player=players.get(role);
Collection<Association> c=player.getAssociations(type,role);
if(smallest==null || c.size()<smallest.size()) smallest=c;
// getAssociations may be a timeconsuming method so don't check everything if not necessary
if(smallest!=null && smallest.size()<50) break;
}
Set<Association> delete=new HashSet<>();
for(Association a : smallest){
if(a==this) continue;
if(((DatabaseAssociation)a)._equals(this)){
delete.add(a);
}
}
for(Association a : delete){
a.remove();
}
}
boolean _equals(DatabaseAssociation a){
if(a == null) return false;
return (players.equals(a.players)&&(type==a.type));
}
int _hashCode(){
return players.hashCode()+type.hashCode();
}
}
| 11,851 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
DatabaseTopic.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/database2/DatabaseTopic.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* DatabaseTopic.java
*
* Created on 7. marraskuuta 2005, 11:28
*/
package org.wandora.topicmap.database2;
import static org.wandora.utils.Tuples.t2;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicInUseException;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.topicmap.TopicMapReadOnlyException;
import org.wandora.topicmap.TopicRemovedException;
import org.wandora.utils.Tuples.T2;
/**
*
* @author olli
*/
public class DatabaseTopic extends Topic {
protected boolean full;
// flags indicating what kind of data has been fecthed from the database
protected boolean sisFetched;
protected boolean dataFetched;
protected boolean variantsFetched;
protected boolean typesFetched;
// protected boolean associationsFetched;
protected DatabaseTopicMap topicMap;
protected String baseName;
protected String id;
protected Locator subjectLocator;
protected Set<Locator> subjectIdentifiers;
protected Map<Topic,Map<Topic,String>> data;
// scope value ,variantid
protected Map<Set<Topic>,T2<String,String>> variants;
protected Set<Topic> types;
// type , role of this topic
//protected Hashtable<Topic,Hashtable<Topic,Collection<Association>>> associations;
protected WeakReference<Map<Topic,Map<Topic,Collection<Association>>>> storedAssociations;
protected boolean removed=false;
/** Creates a new instance of DatabaseTopic */
public DatabaseTopic(DatabaseTopicMap tm) {
this.topicMap=tm;
full=false;
sisFetched=false;
dataFetched=false;
variantsFetched=false;
typesFetched=false;
id=null;
// associationsFetched=false;
}
public DatabaseTopic(String id, DatabaseTopicMap tm) {
this(tm);
this.id=id;
}
public DatabaseTopic(Map<String,Object> row, DatabaseTopicMap tm) throws TopicMapException {
this(tm);
Object o=row.get("BASENAME");
if(o!=null) {
internalSetBaseName(o.toString());
}
o=row.get("SUBJECTLOCATOR");
if(o!=null) {
subjectLocator=topicMap.createLocator(o.toString());
}
o=row.get("TOPICID");
if(o!=null) {
id=o.toString();
}
}
public DatabaseTopic(Object baseName, Object subjectLocator, Object id, DatabaseTopicMap tm) throws TopicMapException {
this(tm);
if(baseName!=null) {
internalSetBaseName(baseName.toString());
}
if(subjectLocator!=null) {
this.subjectLocator=topicMap.createLocator(subjectLocator.toString());
}
if(id!=null) {
this.id=id.toString();
}
else {
System.out.println("Warning: DatabaseTopic id is not set: "+this.id+" != "+id);
}
}
void initialize(Object baseName, Object subjectLocator) throws TopicMapException {
initialize((String)baseName, (String)subjectLocator);
}
/**
* Initializes this DatabaseTopic object setting the basename and subject locator
* but does not modify the actual database.
*/
void initialize(String baseName, String subjectLocator) throws TopicMapException {
internalSetBaseName(baseName);
if(subjectLocator!=null) {
this.subjectLocator=topicMap.createLocator(subjectLocator);
}
}
/**
* Sets the base name in this DatabaseTopic object but does not modify the database.
*/
protected void internalSetBaseName(String bn) throws TopicMapException {
String old=baseName;
baseName=bn;
topicMap.topicBNChanged(this, old);
}
private static int idcounter=0;
/**
* Makes an ID string that can be used as an identifier in the database.
* It will be unique if all identifiers are generated using the same Java
* virtual machine but if they are being generated by several virtual machine
* collisions may occur, however they will be extremely unlikely.
*/
protected static synchronized String makeID(){
if(idcounter>=100000) idcounter=0;
return "T"+System.currentTimeMillis()+"-"+(idcounter++);
}
/**
* Inserts a new topic in the database with the data currently set in this
* DatabaseTopic object. A new DatabaseTopic is not inserted in the database
* until this method is called.
*/
void create() throws TopicMapException {
subjectIdentifiers=Collections.synchronizedSet(new LinkedHashSet<>());
data=Collections.synchronizedMap(new LinkedHashMap<>());
variants=new HashMap<>();
types=Collections.synchronizedSet(new LinkedHashSet<>());
// associations=new Hashtable<Topic,Hashtable<Topic,Collection<Association>>>();
full=true;
sisFetched=true;
dataFetched=true;
variantsFetched=true;
typesFetched=true;
if(id == null) {
id=makeID();
}
topicMap.executeUpdate("insert into TOPIC (TOPICID) values ('"+escapeSQL(id)+"')");
}
protected String escapeSQL(String s){
return topicMap.escapeSQL(s);
}
/**
* Sets subject identifiers in this DatabaseTopic but does not modify
* the underlying database.
*/
protected void setSubjectIdentifiers(Set<Locator> sis) {
Set<Locator> oldSIs = subjectIdentifiers;
subjectIdentifiers = sis;
if(oldSIs!=null && !oldSIs.isEmpty()) {
Set<Locator> removed = new LinkedHashSet<>();
removed.addAll(oldSIs);
removed.removeAll(subjectIdentifiers);
for(Locator l : removed){
topicMap.topicSIChanged(this,l,null);
}
Set<Locator> added = new LinkedHashSet<>();
added.addAll(subjectIdentifiers);
added.removeAll(oldSIs);
for(Locator l : added){
topicMap.topicSIChanged(this,null,l);
}
}
else{
for(Locator l : subjectIdentifiers){
topicMap.topicSIChanged(this,null,l);
}
}
}
// -------------------------------------------------------------------------
// --------------------------------------------------------------- FETCH ---
// -------------------------------------------------------------------------
protected void fetchSubjectIdentifiers() throws TopicMapException {
if(id == null) {
System.out.println("topic's id is null.");
System.out.println(this.baseName);
//System.out.println(this);
}
Collection<Map<String,Object>> res=topicMap.executeQuery("select * from SUBJECTIDENTIFIER where TOPIC='"+escapeSQL(id)+"'");
Set<Locator> newSIs=new LinkedHashSet<>();
for(Map<String,Object> row : res){
newSIs.add(topicMap.createLocator(row.get("SI").toString()));
}
setSubjectIdentifiers(newSIs);
sisFetched=true;
}
protected void fetchData() throws TopicMapException {
Collection<Map<String,Object>> res=topicMap.executeQuery(
"select DATA.*, " +
"Y.TOPICID as TYPEID, Y.BASENAME as TYPEBN, Y.SUBJECTLOCATOR as TYPESL," +
"V.TOPICID as VERSIONID, V.BASENAME as VERSIONBN, V.SUBJECTLOCATOR as VERSIONSL " +
"from DATA,TOPIC as Y,TOPIC as V where "+
"DATA.TYPE=Y.TOPICID and DATA.VERSION=V.TOPICID and "+
"DATA.TOPIC='"+escapeSQL(id)+"'");
data=new LinkedHashMap<>();
for(Map<String,Object> row : res){
Topic type=topicMap.buildTopic(row.get("TYPEID"),row.get("TYPEBN"),row.get("TYPESL"));
Topic version=topicMap.buildTopic(row.get("VERSIONID"),row.get("VERSIONBN"),row.get("VERSIONSL"));
Map<Topic,String> td=data.get(type);
if(td==null){
td=new LinkedHashMap<>();
data.put(type,td);
}
td.put(version,row.get("DATA").toString());
}
dataFetched=true;
}
protected void fetchVariants() throws TopicMapException {
Collection<Map<String,Object>> res=topicMap.executeQuery(
"select TOPIC.*,VARIANT.* from TOPIC,VARIANT,VARIANTSCOPE where "+
"TOPICID=VARIANTSCOPE.TOPIC and VARIANTSCOPE.VARIANT=VARIANTID and "+
"VARIANT.TOPIC='"+escapeSQL(id)+"' order by VARIANTID");
variants=new HashMap<>();
HashSet<Topic> scope=null;
String lastVariant=null;
String lastName=null;
for(Map<String,Object> row : res) {
if(lastVariant==null || !lastVariant.equals(row.get("VARIANTID"))){
if(lastVariant!=null){
variants.put(scope,t2(lastName,lastVariant));
}
scope=new LinkedHashSet<>();
lastVariant=row.get("VARIANTID").toString();
lastName=row.get("VALUE").toString();
}
scope.add(topicMap.buildTopic(row));
}
if(lastVariant!=null){
variants.put(scope,t2(lastName,lastVariant));
}
variantsFetched=true;
}
protected void fetchTypes() throws TopicMapException {
Collection<Map<String,Object>> res=topicMap.executeQuery(
"select TOPIC.* from TOPIC,TOPICTYPE where TYPE=TOPICID and "+
"TOPIC='"+escapeSQL(id)+"'");
types=new LinkedHashSet<>();
for(Map<String,Object> row : res){
types.add(topicMap.buildTopic(row));
}
typesFetched=true;
}
static void fetchAllSubjectIdentifiers(Collection<Map<String,Object>> res, Map<String,DatabaseTopic> topics,DatabaseTopicMap topicMap) throws TopicMapException {
String topicID = null;
HashSet<Locator> subjectIdentifiers = new LinkedHashSet<>();
for(Map<String,Object> row : res) {
if(topicID == null || !topicID.equals(row.get("TOPIC"))) {
if(topicID != null) {
DatabaseTopic dbt=topics.get(topicID);
if(dbt != null && !dbt.sisFetched){
dbt.sisFetched = true;
dbt.setSubjectIdentifiers(subjectIdentifiers);
}
}
subjectIdentifiers = new LinkedHashSet<>();
if(row.get("TOPIC") != null) {
topicID = row.get("TOPIC").toString();
}
}
if(row.get("SI") != null) {
subjectIdentifiers.add(topicMap.createLocator(row.get("SI").toString()));
}
}
if(topicID != null) {
DatabaseTopic dbt=topics.get(topicID);
if(dbt != null && !dbt.sisFetched) {
dbt.sisFetched = true;
dbt.setSubjectIdentifiers(subjectIdentifiers);
}
}
}
protected Map<Topic,Map<Topic,Collection<Association>>> fetchAssociations() throws TopicMapException {
if(storedAssociations != null) {
Map<Topic,Map<Topic,Collection<Association>>> associations = storedAssociations.get();
if(associations != null) return associations;
}
Collection<Map<String,Object>> res = topicMap.executeQuery(
"select R.TOPICID as ROLEID,R.BASENAME as ROLEBN,R.SUBJECTLOCATOR as ROLESL," +
"T.TOPICID as TYPEID,T.BASENAME as TYPEBN,T.SUBJECTLOCATOR as TYPESL,ASSOCIATIONID " +
"from MEMBER,ASSOCIATION,TOPIC as T,TOPIC as R where "+
"R.TOPICID=MEMBER.ROLE and MEMBER.ASSOCIATION=ASSOCIATION.ASSOCIATIONID and "+
"ASSOCIATION.TYPE=T.TOPICID and MEMBER.PLAYER='"+escapeSQL(id)+"' "+
"order by R.TOPICID"
);
Map<Topic,Map<Topic,Collection<Association>>> associations = new HashMap<>();
Map<String,DatabaseTopic> collectedTopics = new LinkedHashMap<>();
Map<String,DatabaseAssociation> collectedAssociations = new LinkedHashMap<>();
for(Map<String,Object> row : res) {
DatabaseTopic type=topicMap.buildTopic(row.get("TYPEID"),row.get("TYPEBN"),row.get("TYPESL"));
DatabaseTopic role=topicMap.buildTopic(row.get("ROLEID"),row.get("ROLEBN"),row.get("ROLESL"));
Map<Topic,Collection<Association>> as = associations.get(type);
if(as == null) {
as = new HashMap<>();
associations.put(type,as);
}
Collection<Association> c = as.get(role);
if(c == null) {
c = new ArrayList<>();
as.put(role,c);
}
Object associationId = row.get("ASSOCIATIONID");
if(associationId != null) {
DatabaseAssociation da = topicMap.buildAssociation(associationId.toString(),type);
c.add(da);
collectedAssociations.put(da.getID(),da);
collectedTopics.put(type.getID(),type);
collectedTopics.put(role.getID(),role);
}
}
{
collectedTopics.putAll(DatabaseAssociation.makeFullAll(topicMap.executeQuery(
"select R.TOPICID as ROLEID,R.BASENAME as ROLEBN,R.SUBJECTLOCATOR as ROLESL," +
"P.TOPICID as PLAYERID,P.BASENAME as PLAYERBN,P.SUBJECTLOCATOR as PLAYERSL, OM.ASSOCIATION " +
"from MEMBER as LM,MEMBER as OM,TOPIC as P,TOPIC as R where "+
"R.TOPICID=OM.ROLE and P.TOPICID=OM.PLAYER and OM.ASSOCIATION=LM.ASSOCIATION and "+
"LM.PLAYER='"+escapeSQL(id)+"' order by OM.ASSOCIATION"
),collectedAssociations,topicMap));
/* DatabaseTopic.fetchAllSubjectIdentifiers(topicMap.executeQuery(
"select * from SUBJECTIDENTIFIER where TOPIC in (select TYPE "+
"from MEMBER as LM,ASSOCIATION where "+
"ASSOCIATIONID=LM.ASSOCIATION and "+
"LM.PLAYER='"+escapeSQL(id)+"' "+
"union "+
"select OM.ROLE "+
"from MEMBER as LM,MEMBER as OM where "+
"OM.ASSOCIATION=LM.ASSOCIATION and "+
"LM.PLAYER='"+escapeSQL(id)+"' "+
"union "+
"select OM.PLAYER "+
"from MEMBER as LM,MEMBER as OM where "+
"OM.ASSOCIATION=LM.ASSOCIATION and "+
"LM.PLAYER='"+escapeSQL(id)+"') order by TOPIC"
),collectedTopics,topicMap);
*/
DatabaseTopic.fetchAllSubjectIdentifiers(topicMap.executeQuery(
"select SUBJECTIDENTIFIER.* from SUBJECTIDENTIFIER, ("+
"select TOPIC.TOPICID "+
"from MEMBER as LM,ASSOCIATION,TOPIC where "+
"ASSOCIATIONID=LM.ASSOCIATION and "+
"LM.PLAYER='"+escapeSQL(id)+"' and TOPIC.TOPICID=ASSOCIATION.TYPE "+
"union "+
"select TOPIC.TOPICID "+
"from MEMBER as LM,MEMBER as OM,TOPIC where "+
"OM.ASSOCIATION=LM.ASSOCIATION and "+
"LM.PLAYER='"+escapeSQL(id)+"' and TOPIC.TOPICID=OM.ROLE "+
"union "+
"select TOPIC.TOPICID "+
"from MEMBER as LM,MEMBER as OM,TOPIC where "+
"OM.ASSOCIATION=LM.ASSOCIATION and "+
"LM.PLAYER='"+escapeSQL(id)+"' and TOPIC.TOPICID=OM.PLAYER "+
") as TEMP where SUBJECTIDENTIFIER.TOPIC=TEMP.TOPICID order by TOPIC"
),collectedTopics,topicMap);
}
// associationsFetched=true;
storedAssociations=new WeakReference(associations);
return associations;
}
/**
* Fetch all information from database that hasn't already been fetched.
*/
void makeFull() throws TopicMapException {
if(!sisFetched) {
fetchSubjectIdentifiers();
}
if(!dataFetched) {
fetchData();
}
if(!variantsFetched) {
fetchVariants();
}
if(!typesFetched) {
fetchTypes();
}
// if(!associationsFetched) fetchAssociations();
full=true;
}
// -------------------------------------------------------------------------
@Override
public String getID() {
return id;
}
@Override
public Collection<Locator> getSubjectIdentifiers() throws TopicMapException {
if(!sisFetched) {
fetchSubjectIdentifiers();
}
return subjectIdentifiers;
}
@Override
public void addSubjectIdentifier(Locator l) throws TopicMapException {
if( removed ) throw new TopicRemovedException();
if( topicMap.isReadOnly() ) throw new TopicMapReadOnlyException();
if( l == null ) return;
if(!sisFetched) fetchSubjectIdentifiers();
if(!subjectIdentifiers.contains(l)) {
Topic t=topicMap.getTopic(l);
if(t!=null) {
mergeIn(t);
}
else {
subjectIdentifiers.add(l);
// System.out.println("Inserting si "+l.toExternalForm());
boolean ok = topicMap.executeUpdate("insert into SUBJECTIDENTIFIER (TOPIC,SI) values ('"+
escapeSQL(id)+"','"+escapeSQL(l.toExternalForm())+"')");
if(!ok) System.out.println("Failed to add si "+l.toExternalForm());
topicMap.topicSIChanged(this, null,l);
topicMap.topicSubjectIdentifierChanged(this,l,null);
}
}
// topicMap.topicChanged(this);
}
public void mergeIn(Topic t) throws TopicMapException {
if( removed ) throw new TopicRemovedException();
if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException();
if( t == null ) return;
Collection<Map<String,Object>> tempRes;
DatabaseTopic ti=(DatabaseTopic)t;
// add data
tempRes=topicMap.executeQuery("select D1.* from DATA as D1,DATA as D2 where D1.VERSION=D2.VERSION and "+
"D1.TYPE=D2.TYPE and D1.TOPIC='"+escapeSQL(t.getID())+"' and D2.TOPIC='"+escapeSQL(id)+"'");
for(Map<String,Object> row : tempRes){
topicMap.executeUpdate("delete from DATA where TOPIC='"+escapeSQL((String)row.get("TOPIC"))+"' and "+
"TYPE='"+escapeSQL((String)row.get("TYPE"))+"' and "+
"VERSION='"+escapeSQL((String)row.get("VERSION"))+"'");
}
topicMap.executeUpdate("update DATA set TOPIC='"+escapeSQL(id)+"' where "+
"TOPIC='"+escapeSQL(t.getID())+"'");
// set base name
if(ti.getBaseName()!=null) {
String name=ti.getBaseName();
ti.setBaseName(null);
this.setBaseName(name);
}
// set subject locator
if(ti.getSubjectLocator()!=null){
Locator l=ti.getSubjectLocator();
ti.setSubjectLocator(null);
this.setSubjectLocator(l);
}
// for now just update all associations,roles,types etc and remove duplicates later
// set types
tempRes=topicMap.executeQuery("select T1.* from TOPICTYPE as T1,TOPICTYPE as T2 where T1.TYPE=T2.TYPE and "+
"T1.TOPIC='"+escapeSQL(t.getID())+"' and T2.TOPIC='"+escapeSQL(id)+"'");
for(Map<String,Object> row : tempRes){
topicMap.executeUpdate("delete from TOPICTYPE where TOPIC='"+escapeSQL((String)row.get("TOPIC"))+"' and "+
"TYPE='"+escapeSQL((String)row.get("TYPE"))+"'");
}
topicMap.executeUpdate("update TOPICTYPE set TOPIC='"+escapeSQL(id)+"' where "+
"TOPIC='"+escapeSQL(t.getID())+"'");
tempRes=topicMap.executeQuery("select T1.* from TOPICTYPE as T1,TOPICTYPE as T2 where T1.TOPIC=T2.TOPIC and "+
"T1.TYPE='"+escapeSQL(t.getID())+"' and T2.TYPE='"+escapeSQL(id)+"'");
for(Map<String,Object> row : tempRes){
topicMap.executeUpdate("delete from TOPICTYPE where TOPIC='"+escapeSQL((String)row.get("TOPIC"))+"' and "+
"TYPE='"+escapeSQL((String)row.get("TYPE"))+"'");
}
topicMap.executeUpdate("update TOPICTYPE set TYPE='"+escapeSQL(id)+"' where "+
"TYPE='"+escapeSQL(t.getID())+"'");
// set variant names
topicMap.executeUpdate("update VARIANT set TOPIC='"+escapeSQL(id)+"' where "+
"TOPIC='"+escapeSQL(t.getID())+"'");
// set subject identifiers
topicMap.executeUpdate("update SUBJECTIDENTIFIER set TOPIC='"+escapeSQL(id)+"' where "+
"TOPIC='"+escapeSQL(t.getID())+"'");
// change association players
topicMap.executeUpdate("update MEMBER set PLAYER='"+escapeSQL(id)+"' where "+
"PLAYER='"+escapeSQL(t.getID())+"'");
// change association types
topicMap.executeUpdate("update ASSOCIATION set TYPE='"+escapeSQL(id)+"' where "+
"TYPE='"+escapeSQL(t.getID())+"'");
// change data types
tempRes=topicMap.executeQuery("select D1.* from DATA as D1,DATA as D2 where D1.VERSION=D2.VERSION and "+
"D1.TOPIC=D2.TOPIC and D1.TYPE='"+escapeSQL(t.getID())+"' and D2.TYPE='"+escapeSQL(id)+"'");
for(Map<String,Object> row : tempRes){
topicMap.executeUpdate("delete from DATA where TOPIC='"+escapeSQL((String)row.get("TOPIC"))+"' and "+
"TYPE='"+escapeSQL((String)row.get("TYPE"))+"' and "+
"VERSION='"+escapeSQL((String)row.get("VERSION"))+"'");
}
topicMap.executeUpdate("update DATA set TYPE='"+escapeSQL(id)+"' where "+
"TYPE='"+escapeSQL(t.getID())+"'");
// change data versions
tempRes=topicMap.executeQuery("select D1.* from DATA as D1,DATA as D2 where D1.TYPE=D2.TYPE and "+
"D1.TOPIC=D2.TOPIC and D1.VERSION='"+escapeSQL(t.getID())+"' and D2.VERSION='"+escapeSQL(id)+"'");
for(Map<String,Object> row : tempRes){
topicMap.executeUpdate("delete from DATA where TOPIC='"+escapeSQL((String)row.get("TOPIC"))+"' and "+
"TYPE='"+escapeSQL((String)row.get("TYPE"))+"' and "+
"VERSION='"+escapeSQL((String)row.get("VERSION"))+"'");
}
topicMap.executeUpdate("update DATA set VERSION='"+escapeSQL(id)+"' where "+
"VERSION='"+escapeSQL(t.getID())+"'");
// change role types
tempRes=topicMap.executeQuery("select M1.* from MEMBER as M1,MEMBER as M2 where M1.ASSOCIATION=M2.ASSOCIATION and "+
"M1.ROLE='"+escapeSQL(t.getID())+"' and M2.ROLE='"+escapeSQL(id)+"'");
for(Map<String,Object> row : tempRes){
topicMap.executeUpdate("delete from MEMBER where ASSOCIATION='"+escapeSQL((String)row.get("ASSOCIATION"))+"' and "+
"ROLE='"+escapeSQL((String)row.get("ROLE"))+"'");
}
topicMap.executeUpdate("update MEMBER set ROLE='"+escapeSQL(id)+"' where "+
"ROLE='"+escapeSQL(t.getID())+"'");
// change variant scopes
tempRes=topicMap.executeQuery("select V1.* from VARIANTSCOPE as V1,VARIANTSCOPE as V2 where "+
"V1.VARIANT=V2.VARIANT and V1.TOPIC='"+escapeSQL(t.getID())+"' and V2.TOPIC='"+escapeSQL(id)+"'");
for(Map<String,Object> row : tempRes){
topicMap.executeUpdate("delete from VARIANTSCOPE where VARIANT='"+escapeSQL((String)row.get("VARIANT"))+"' and "+
"TOPIC='"+escapeSQL((String)row.get("TOPIC"))+"'");
}
topicMap.executeUpdate("update VARIANTSCOPE set TOPIC='"+escapeSQL(id)+"' where "+
"TOPIC='"+escapeSQL(t.getID())+"'");
// remove everything where old topic is still used (these are duplicates)
topicMap.executeUpdate("delete from TOPICTYPE where TOPIC='"+escapeSQL(t.getID())+"'");
topicMap.executeUpdate("delete from DATA where TOPIC='"+escapeSQL(t.getID())+"'");
topicMap.executeUpdate("delete from DATA where TYPE='"+escapeSQL(t.getID())+"'");
topicMap.executeUpdate("delete from DATA where VERSION='"+escapeSQL(t.getID())+"'");
topicMap.executeUpdate("delete from MEMBER where ROLE='"+escapeSQL(t.getID())+"'");
topicMap.executeUpdate("delete from VARIANTSCOPE where TOPIC='"+escapeSQL(t.getID())+"'");
{ // check for duplicate associations
Collection<Map<String,Object>> res=topicMap.executeQuery(
"select M1.*,ASSOCIATION.TYPE from MEMBER as M1, ASSOCIATION, MEMBER as M2 where "+
"M1.ASSOCIATION=ASSOCIATIONID and ASSOCIATIONID=M2.ASSOCIATION and "+
"M2.PLAYER='"+escapeSQL(id)+"' order by M1.ASSOCIATION");
// type ,associations{ role ,player}
HashSet<T2<String,Collection<T2<String,String>>>> associations=new LinkedHashSet<>();
HashSet<String> delete=new LinkedHashSet<>();
String oldAssociation="dummy";
String oldType="";
Collection<T2<String,String>> association=null;
for(Map<String,Object> row : res){
String aid=(String)row.get("ASSOCIATION");
if(!aid.equals(oldAssociation)){
if(association!=null){
if(associations.contains(t2(oldType,association))) delete.add(oldAssociation);
else associations.add(t2(oldType,association));
}
association=new LinkedHashSet<>();
oldAssociation=aid;
oldType=(String)row.get("TYPE");
}
association.add(t2((String)row.get("ROLE"),(String)row.get("PLAYER")));
}
if(association!=null){
if(associations.contains(t2(oldType,association))) delete.add(oldAssociation);
}
if(delete.size()>0){
String col=topicMap.collectionToSQL(delete);
topicMap.executeUpdate("delete from MEMBER where ASSOCIATION in "+col);
topicMap.executeUpdate("delete from ASSOCIATION where ASSOCIATIONID in "+col);
}
}
{ // check for duplicate variants
Collection<Map<String,Object>> res=topicMap.executeQuery(
"select VARIANTSCOPE.* from VARIANT,VARIANTSCOPE where "+
"VARIANT.TOPIC='"+escapeSQL(id)+"' and VARIANTID=VARIANT order by VARIANTID");
Set<Collection<String>> scopes=new LinkedHashSet<>();
Set<String> delete=new LinkedHashSet<>();
String oldVariant="dummy";
Collection<String> scope=null;
for(Map<String,Object> row : res){
String vid=(String)row.get("VARIANT");
if(!vid.equals(oldVariant)){
if(scope!=null){
if(scopes.contains(scope)) delete.add(oldVariant);
else scopes.add(scope);
}
scope=new LinkedHashSet<>();
oldVariant=vid;
}
scope.add((String)row.get("TOPIC"));
}
if(scope!=null){
if(scopes.contains(scope)) delete.add(oldVariant);
}
if(!delete.isEmpty()){
String col=topicMap.collectionToSQL(delete);
topicMap.executeUpdate("delete from VARIANTSCOPE where VARIANT in "+col);
topicMap.executeUpdate("delete from VARIANT where VARIANTID in "+col);
}
}
// remove merged topic
try{
t.remove();
}catch(TopicInUseException e){
System.out.println("ERROR couldn't delete merged topic, topic in use. There is a bug in the code if this happens. "+e.getReason());
}
sisFetched=false;
full=false;
makeFull();
topicMap.topicChanged(this);
}
@Override
public void removeSubjectIdentifier(Locator l) throws TopicMapException {
if( removed ) throw new TopicRemovedException();
if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException();
if(l == null) return;
subjectIdentifiers.remove(l);
topicMap.executeUpdate("delete from SUBJECTIDENTIFIER where SI='"+escapeSQL(l.toExternalForm())+"'");
topicMap.topicSubjectIdentifierChanged(this,null,l);
topicMap.topicSIChanged(this, l,null);
}
@Override
public String getBaseName(){
return baseName;
}
@Override
public void setBaseName(String name) throws TopicMapException {
if( removed ) throw new TopicRemovedException();
if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException();
if(name==null){
if(baseName!=null){
String old=baseName;
internalSetBaseName(null);
topicMap.executeUpdate("update TOPIC "
+"set BASENAME=null "
+"where TOPICID='"+escapeSQL(id)+"'");
topicMap.topicBaseNameChanged(this,null,old);
}
return;
}
if(baseName==null || !baseName.equals(name)){
Topic t=topicMap.getTopicWithBaseName(name);
if(t!=null){
mergeIn(t);
}
String old=baseName;
internalSetBaseName(name);
topicMap.executeUpdate("update TOPIC "
+"set BASENAME='"+escapeSQL(name)+"' "
+"where TOPICID='"+escapeSQL(id)+"'");
topicMap.topicBaseNameChanged(this,name,old);
}
}
@Override
public Collection<Topic> getTypes() throws TopicMapException {
if(!full) makeFull();
return types;
}
@Override
public void addType(Topic t) throws TopicMapException {
if( removed ) throw new TopicRemovedException();
if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException();
if(t == null) return;
if(!full) makeFull();
if(!types.contains(t)){
types.add(t);
topicMap.executeUpdate("insert into TOPICTYPE (TOPIC,TYPE) values ('"+
escapeSQL(id)+"','"+escapeSQL(t.getID())+"')");
topicMap.topicTypeChanged(this,t,null);
}
}
@Override
public void removeType(Topic t) throws TopicMapException {
if( removed ) throw new TopicRemovedException();
if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException();
if(t == null) return;
if(!full) makeFull();
if(types.contains(t)){
types.remove(t);
topicMap.executeUpdate("delete from TOPICTYPE "
+"where TOPIC='"+escapeSQL(id)+"' "
+"and TYPE='"+escapeSQL(t.getID())+"'");
topicMap.topicTypeChanged(this,null,t);
}
}
@Override
public boolean isOfType(Topic t) throws TopicMapException {
if(t == null) return false;
if(!full) makeFull();
return types.contains(t);
}
@Override
public String getVariant(Set<Topic> scope) throws TopicMapException {
if(!full) makeFull();
T2<String,String> variant = variants.get(scope);
if(variant != null) return variant.e1;
return null;
}
@Override
public void setVariant(Set<Topic> scope,String name) throws TopicMapException {
if( removed ) throw new TopicRemovedException();
if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException();
if(!full) makeFull();
String old=null;
if(variants.get(scope)!=null){
String vid=variants.get(scope).e2;
topicMap.executeUpdate("update VARIANT set VALUE='"+escapeSQL(name)+"' where VARIANTID='"+escapeSQL(vid)+"'");
old=variants.put(scope,t2(name,vid)).e1;
}
else{
String vid=makeID();
topicMap.executeUpdate("insert into VARIANT (VARIANTID,TOPIC,VALUE) values ('"+
escapeSQL(vid)+"','"+escapeSQL(id)+"','"+escapeSQL(name)+"')");
for(Topic s : scope){
topicMap.executeUpdate("insert into VARIANTSCOPE (VARIANT,TOPIC) values ('"+
escapeSQL(vid)+"','"+escapeSQL(s.getID())+"')");
}
variants.put(scope,t2(name,vid));
}
topicMap.topicVariantChanged(this,scope,name,old);
}
@Override
public Set<Set<Topic>> getVariantScopes() throws TopicMapException {
if(!full) makeFull();
return variants.keySet();
}
@Override
public void removeVariant(Set<Topic> scope) throws TopicMapException {
if( removed ) throw new TopicRemovedException();
if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException();
if(!full) makeFull();
T2<String,String> v=variants.get(scope);
if(v!=null){
topicMap.executeUpdate("delete from VARIANTSCOPE where VARIANT='"+escapeSQL(v.e2)+"'");
topicMap.executeUpdate("delete from VARIANT where VARIANTID='"+escapeSQL(v.e2)+"'");
variants.remove(scope);
topicMap.topicVariantChanged(this,scope,null,v.e1);
}
}
@Override
public String getData(Topic type,Topic version) throws TopicMapException {
if(type == null || version == null) return null;
if(!full) makeFull();
Map<Topic,String> td=data.get(type);
if(td==null) return null;
return td.get(version);
}
@Override
public Hashtable<Topic,String> getData(Topic type) throws TopicMapException {
if(!full) makeFull();
if(data.containsKey(type)) {
Hashtable<Topic,String> ht = new Hashtable<>();
Map<Topic,String> m = data.get(type);
ht.putAll(m);
return ht;
}
else {
return new Hashtable<>();
}
}
@Override
public Collection<Topic> getDataTypes() throws TopicMapException {
if(!full) makeFull();
return data.keySet();
}
@Override
public void setData(Topic type,Hashtable<Topic,String> versionData) throws TopicMapException {
if( removed ) throw new TopicRemovedException();
if( topicMap.isReadOnly() ) throw new TopicMapReadOnlyException();
for(Map.Entry<Topic,String> e : versionData.entrySet()){
setData(type,e.getKey(),e.getValue());
}
}
@Override
public void setData(Topic type,Topic version,String value) throws TopicMapException {
if( removed ) throw new TopicRemovedException();
if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException();
if(!dataFetched) {
fetchData();
}
if(getData(type,version)!=null){
topicMap.executeUpdate("update DATA set DATA='"+escapeSQL(value)+"' "
+"where TOPIC='"+escapeSQL(id)+"' "
+"and TYPE='"+escapeSQL(type.getID())+"' "
+"and VERSION='"+escapeSQL(version.getID())+"'");
}
else{
topicMap.executeUpdate("insert into DATA (DATA,TOPIC,TYPE,VERSION) values ("+
"'"+escapeSQL(value)+"','"+escapeSQL(id)+"','"+escapeSQL(type.getID())+"','"+
escapeSQL(version.getID())+"')");
}
Map<Topic,String> dt=data.get(type);
if(dt==null) {
dt=new LinkedHashMap<>();
data.put(type,dt);
}
String old=dt.put(version,value);
topicMap.topicDataChanged(this,type,version,value,old);
}
@Override
public void removeData(Topic type,Topic version) throws TopicMapException {
if( removed ) throw new TopicRemovedException();
if( topicMap.isReadOnly() ) throw new TopicMapReadOnlyException();
if(type == null || version == null) return;
if(!full) makeFull();
if(getData(type,version) != null) {
topicMap.executeUpdate("delete from DATA "
+"where TOPIC='"+escapeSQL(id)+"' "
+"and TYPE='"+escapeSQL(type.getID())+"' "
+"and VERSION='"+escapeSQL(version.getID())+"'");
String old=data.get(type).remove(version);
Map<Topic,String> datas = data.get(type);
if(datas != null && datas.isEmpty()) {
data.remove(type);
}
topicMap.topicDataChanged(this,type,version,null,old);
}
}
@Override
public void removeData(Topic type) throws TopicMapException {
if( removed ) throw new TopicRemovedException();
if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException();
if(type == null) return;
if(!full) makeFull();
if(getData(type) != null) {
topicMap.executeUpdate("delete from DATA "
+"where TOPIC='"+escapeSQL(id)+"' "
+"and TYPE='"+escapeSQL(type.getID())+"'");
Map<Topic,String> old = data.remove(type);
for(Map.Entry<Topic,String> e : old.entrySet()){
topicMap.topicDataChanged(this,type,e.getKey(),null,e.getValue());
}
}
}
@Override
public Locator getSubjectLocator(){
return subjectLocator;
}
@Override
public void setSubjectLocator(Locator l) throws TopicMapException {
if( removed ) throw new TopicRemovedException();
if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException();
if(l==null){
if(subjectLocator!=null){
Locator old=subjectLocator;
subjectLocator=null;
topicMap.executeUpdate("update TOPIC set SUBJECTLOCATOR=null where TOPICID='"+escapeSQL(id)+"'");
topicMap.topicSubjectLocatorChanged(this,l,old);
}
return;
}
if(subjectLocator==null || !subjectLocator.equals(l)){
Topic t=topicMap.getTopicBySubjectLocator(l);
if(t!=null){
mergeIn(t);
}
Locator old=subjectLocator;
subjectLocator=l;
topicMap.executeUpdate("update TOPIC set SUBJECTLOCATOR='"+escapeSQL(l.toExternalForm())+"' where TOPICID='"+escapeSQL(id)+"'");
topicMap.topicSubjectLocatorChanged(this,l,old);
}
}
@Override
public TopicMap getTopicMap(){
return topicMap;
}
@Override
public Collection<Association> getAssociations() throws TopicMapException {
// if(!full) makeFull();
Set<Association> ret=new LinkedHashSet<>();
Map<Topic,Map<Topic,Collection<Association>>> associations=fetchAssociations();
for(Map.Entry<Topic,Map<Topic,Collection<Association>>> e : associations.entrySet()){
for(Map.Entry<Topic,Collection<Association>> e2 : e.getValue().entrySet()){
for(Association a : e2.getValue()){
ret.add(a);
}
}
}
return ret;
}
@Override
public Collection<Association> getAssociations(Topic type) throws TopicMapException {
if(type == null) return null;
// if(!full) makeFull();
Set<Association> ret=new LinkedHashSet<>();
Map<Topic,Map<Topic,Collection<Association>>> associations=fetchAssociations();
if(associations.get(type)==null) {
return new ArrayList<Association>();
}
for(Map.Entry<Topic,Collection<Association>> e2 : associations.get(type).entrySet()){
for(Association a : e2.getValue()){
ret.add(a);
}
}
return ret;
}
@Override
public Collection<Association> getAssociations(Topic type,Topic role) throws TopicMapException {
if(type == null || role == null) return null;
// if(!full) makeFull();
Map<Topic,Map<Topic,Collection<Association>>> associations=fetchAssociations();
Map<Topic,Collection<Association>> as=associations.get(type);
if(as==null) {
return new ArrayList<Association>();
}
Collection<Association> ret=as.get(role);
if(ret==null) {
return new ArrayList<Association>();
}
return ret;
}
@Override
public void remove() throws TopicMapException {
if( removed ) throw new TopicRemovedException();
if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException();
if(!isDeleteAllowed()) throw new TopicInUseException(this);
String eid=escapeSQL(id);
Collection<Map<String,Object>> res=topicMap.executeQuery("select distinct ASSOCIATIONID "
+"from ASSOCIATION,MEMBER "
+"where MEMBER.PLAYER='"+eid+"' "
+"and MEMBER.ASSOCIATION=ASSOCIATION.ASSOCIATIONID");
String[] aid=new String[res.size()];
int counter=0;
for(Map<String,Object> row : res){
aid[counter++]=row.get("ASSOCIATIONID").toString();
}
topicMap.executeUpdate("delete from VARIANTSCOPE where VARIANT in (select VARIANTID from VARIANT where TOPIC='"+eid+"')");
topicMap.executeUpdate("delete from VARIANT where VARIANTID='"+eid+"'");
topicMap.executeUpdate("delete from DATA where TOPIC='"+eid+"'");
topicMap.executeUpdate("delete from TOPICTYPE where TOPIC='"+eid+"'");
topicMap.executeUpdate("delete from SUBJECTIDENTIFIER where TOPIC='"+eid+"'");
for(int i=0;i<aid.length;i+=50){
String c="";
for(int j=i;j<aid.length && j<i+50;j++){
if(c.length()>0) c+=",";
c+="'"+escapeSQL(aid[j])+"'";
}
topicMap.executeUpdate("delete from MEMBER where ASSOCIATION in ("+c+")");
topicMap.executeUpdate("delete from ASSOCIATION where ASSOCIATIONID in ("+c+")");
}
topicMap.executeUpdate("delete from TOPIC where TOPICID='"+eid+"'");
removed=true;
topicMap.topicRemoved(this);
}
@Override
public long getEditTime(){
return 0; // TODO: what to do with edittimes? store in db?
}
@Override
public void setEditTime(long time){
}
@Override
public long getDependentEditTime(){
return 0;
}
@Override
public void setDependentEditTime(long time){
}
@Override
public boolean isRemoved(){
return removed;
}
@Override
public boolean isDeleteAllowed() throws TopicMapException {
String eid=escapeSQL(id);
Collection<Map<String,Object>> res=topicMap.executeQuery(
"select TOPICID from TOPIC where TOPICID='"+eid+"' and ("+
"exists (select * from VARIANTSCOPE where TOPIC='"+eid+"') or "+
"exists (select * from DATA where TYPE='"+eid+"' or VERSION='"+eid+"') or "+
"exists (select * from TOPICTYPE where TYPE='"+eid+"') or "+
// "exists (select * from MEMBER where PLAYER='"+eid+"' or ROLE='"+eid+"') or "+
"exists (select * from MEMBER where ROLE='"+eid+"') or "+
"exists (select * from ASSOCIATION where TYPE='"+eid+"') )");
if(!res.isEmpty()) return false;
return true;
}
@Override
public Collection<Topic> getTopicsWithDataType() throws TopicMapException {
return topicMap.queryTopic("select TOPIC.* "
+ "from TOPIC,DATA "
+ "where TOPICID=TOPIC "
+ "and TYPE='"+escapeSQL(id)+"'");
}
@Override
public Collection<Association> getAssociationsWithType() throws TopicMapException {
return topicMap.queryAssociation("select ASSOCIATION.* "
+ "from ASSOCIATION "
+ "where TYPE='"+escapeSQL(id)+"'");
}
@Override
public Collection<Association> getAssociationsWithRole() throws TopicMapException {
return topicMap.queryAssociation("select ASSOCIATION.* "
+"from ASSOCIATION,MEMBER "
+"where ASSOCIATION=ASSOCIATIONID "
+"and ROLE='"+escapeSQL(id)+"'");
}
@Override
public Collection<Topic> getTopicsWithDataVersion() throws TopicMapException {
return topicMap.queryTopic("select TOPIC.* "
+"from TOPIC,DATA "
+"where TOPICID=TOPIC "
+"and VERSION='"+escapeSQL(id)+"'");
}
@Override
public Collection<Topic> getTopicsWithVariantScope() throws TopicMapException {
return topicMap.queryTopic("select distinct TOPIC.* "
+"from TOPIC,VARIANT,VARIANTSCOPE "
+"where TOPIC.TOPICID=VARIANT.TOPIC "
+"and VARIANT.VARIANTID=VARIANTSCOPE.VARIANT "
+"and VARIANTSCOPE.TOPIC='"+escapeSQL(id)+"'");
}
void associationChanged(DatabaseAssociation a,Topic type,Topic oldType,Topic role,Topic oldRole){
Map<Topic,Map<Topic,Collection<Association>>> associations=null;
if(storedAssociations!=null){
associations=storedAssociations.get();
if(associations==null) return;
}
else return;
Map<Topic,Collection<Association>> t=null;
Collection<Association> c=null;
if(oldType!=null){
t=associations.get(oldType);
c=t.get(oldRole);
c.remove(a);
// remove c from t if it becomes empty?
}
if(type!=null){
t=associations.get(type);
if(t==null){
t=new HashMap<>();
associations.put(type,t);
}
c=t.get(role);
if(c==null){
c=new LinkedHashSet<>();
t.put(role,c);
}
c.add(a);
}
storedAssociations=new WeakReference<>(associations);
}
void removeDuplicateAssociations() throws TopicMapException {
if(topicMap.isReadOnly()) throw new TopicMapReadOnlyException();
Set<EqualAssociationWrapper> as=new LinkedHashSet<>();
Set<Association> delete=new LinkedHashSet<>();
for(Association a : getAssociations()) {
if(!as.add(new EqualAssociationWrapper((DatabaseAssociation)a))){
delete.add(a);
}
}
for(Association a : delete) a.remove();
}
/*
public int hashCode(){
return id.hashCode();
}
public boolean equals(Object o){
if(o instanceof DatabaseTopic){
return ((DatabaseTopic)o).id.equals(id);
}
else return false;
}*/
private class EqualAssociationWrapper {
public DatabaseAssociation a;
private int hashCode=0;
public EqualAssociationWrapper(DatabaseAssociation a){
this.a=a;
}
@Override
public boolean equals(Object o){
if(o==null) return false;
if(hashCode()!=o.hashCode()) return false;
return a._equals(((EqualAssociationWrapper)o).a);
}
@Override
public int hashCode(){
if(hashCode!=0) return hashCode;
else {
hashCode=a._hashCode();
return hashCode;
}
}
}
}
| 49,757 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TopicMapSQLException.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/database2/TopicMapSQLException.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* TopicMapSQLException.java
*
* Created on 15. toukokuuta 2006, 14:47
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package org.wandora.topicmap.database2;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author olli
*/
public class TopicMapSQLException extends TopicMapException {
private static final long serialVersionUID = 1L;
/** Creates a new instance of TopicMapSQLException */
public TopicMapSQLException() {
}
public TopicMapSQLException(String s) {
super(s);
}
public TopicMapSQLException(Throwable cause){
super(cause);
}
public TopicMapSQLException(String s,Throwable cause){
super(s,cause);
}
}
| 1,576 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
WeakTopicIndex.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/database2/WeakTopicIndex.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* WeakTopicIndex.java
*
* Created on 14. marraskuuta 2005, 13:54
*/
package org.wandora.topicmap.database2;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
import org.wandora.utils.MultiHashMap;
/**
* <p>
* WeakTopicIndex keeps an index of every topic and association created with it.
* Database topic map creates all topics and associations with it instead of
* creating them directly. The index is done
* with <code>WeakReference</code>s so that Java garbage collector can collect
* the indexed topics at any time if there are no strong references to them
* elsewhere. With this kind of index, it is possible to make sure that
* at any time there is at most one topic object for each individual topic in the
* database but at the same time allow garbage collector to clean topics that are
* not referenced anywhere else than the index.
* </p>
* <p>
* WeakTopicIndex needs to have a cleaner thread running that cleans the WeakReferences
* when garbage collector has collected the referred objects.
* </p>
* <p>
* In addition, a strong reference to 2000 most used topics is maintained. This
* acts as a sort of cache to keep frequently accessed topics in memory even if
* strong references are not kept outside the index. This cache is maintained with
* the <code>WeakTopicIndex.CacheList</code> class.
* </p>
*
* @author olli
*/
public class WeakTopicIndex implements Runnable {
/**
* <p>
* Cache list is a list of objects where the most used objects are at the top
* of the list and least used objects are at the bottom. New objects are
* added somewhere in the middle but near the bottom. Objects are accessed
* which either moves them up in the list or adds them at the specified
* add point if they are not in the list allready.
* </p><p>
* The idea is that a limited number of objects from a very large object pool
* are kept in memeory and it is prefered that objects that are used the most
* stay in the list while objects that are used little fall off the list.
* Objects are not added right at the bottom to avoid them being falling off
* the list straight away and not having any chance of moving up.
* </p><p>
* List is implemented as a linked list with pointers to the top, bottom
* and the marked add position.
* </p>
*/
public static class CacheList<E> {
private static class ListItem<E> {
public ListItem<E> next=null;
public ListItem<E> prev=null;
public E item;
public ListItem(E item){
this.item=item;
}
}
/** The maximum size of the list */
public static final int cacheSize=2000;
/** The position at which new objects are added */
public static final int markPos=200;
private int size=0;
private ListItem<E> last=null;
private ListItem<E> first=null;
private ListItem<E> mark=null;
private HashMap<E,ListItem<E>> map;
public CacheList(){
map=new HashMap<E,ListItem<E>>(cacheSize);
}
private void addAtMark(E e){
ListItem<E> item=new ListItem<E>(e);
if(size<=markPos){
if(last==null) last=first=item;
else{
last.next=item;
item.prev=last;
last=item;
}
if(size==markPos) mark=item;
size++;
}
else if(size<cacheSize){
item.prev=mark.prev;
mark.prev.next=item;
mark.prev=item;
item.next=mark;
mark=item;
size++;
}
else{
item.next=mark.next;
mark.next.prev=item;
mark.next=item;
item.prev=mark;
mark=item;
map.remove(first.item);
first=first.next;
first.prev=null;
}
map.put(e,item);
}
private void moveUp(ListItem<E> item){
if(item.next==null) return;
/* Order before | order after
* a a <- may be null
* b c=item
* c=item b
* d d <- may be null
*/
ListItem<E> a=item.next.next;
ListItem<E> b=item.next;
ListItem<E> c=item;
ListItem<E> d=item.prev;
if(a!=null) a.prev=c;
c.prev=b;
b.prev=d;
c.next=a;
b.next=c;
if(d!=null) d.next=b;
if(b==mark) mark=c;
else if(c==mark) mark=b;
if(b==last) last=c;
if(c==first) first=b;
}
/**
* Accesses an object moving it up in the list or adding it to the
* list if it isn't in it yet.
*/
public void access(E e){
ListItem<E> item=map.get(e);
if(item!=null) {
moveUp(item);
// System.out.println("CACHE move up "+size);
}
else {
// System.out.println("CACHE add at mark "+size);
addAtMark(e);
}
}
public int size(){
return size;
}
public void printDebugInfo(){
ListItem<E> prev=null;
ListItem<E> item=first;
int counter1=0;
HashSet<E> uniqTest=new HashSet<E>();
while(item!=null){
uniqTest.add(item.item);
prev=item;
item=item.next;
counter1++;
}
boolean check1=(prev==last);
item=last;
int counter2=0;
while(item!=null){
prev=item;
item=item.prev;
counter2++;
}
boolean check2=(prev==first);
System.out.println("Cachelist size "+counter1+", "+counter2+", "+size+", "+uniqTest.size()+", "+check1+", "+check2+")");
}
}
private boolean running;
private Thread thread;
// reference queue for topics to receive notifications when topics are garbage collected
private ReferenceQueue<DatabaseTopic> topicRefQueue;
// map to get topics with their IDs
private HashMap<String,WeakReference<DatabaseTopic>> topicIDIndex;
// map to get topics with their subject identifiers
private HashMap<Locator,WeakReference<DatabaseTopic>> topicSIIndex;
// map to get topics with their base names
private HashMap<String,WeakReference<DatabaseTopic>> topicBNIndex;
/* Inverse indexes are needed to get the id/si/base name of previously stored
* topics with the WeakReferenc after the reference has been cleared and the
* actual topic is not anymore available.
*/
private HashMap<WeakReference<DatabaseTopic>,String> topicInvIDIndex;
private MultiHashMap<WeakReference<DatabaseTopic>,Locator> topicInvSIIndex;
private HashMap<WeakReference<DatabaseTopic>,String> topicInvBNIndex;
// reference queue for associations to receive notifications when associations are garbage collected
private ReferenceQueue<DatabaseAssociation> associationRefQueue;
// map to get oassociationns with their IDs
private HashMap<String,WeakReference<DatabaseAssociation>> associationIDIndex;
// inverse index for associations
private HashMap<WeakReference<DatabaseAssociation>,String> associationInvIDIndex;
/**
* A CacheList that keeps (strong) references to topics so they do not get
* carbage collected. This keeps (roughly speaking) the 2000 most used
* topics in memory at all times and allows them to be retrieved quickly
* from the weak indexes. Without keeping strong references to them they
* would be garbage collected and the indexes would be of little use.
*/
private CacheList<DatabaseTopic> topicCache;
/**
* if references queues are being used, that is if we are keeping track
* of topics/associations that have been garbage collected
*/
private boolean useRefQueue=true;
/** Creates a new instance of WeakTopicIndex */
public WeakTopicIndex() {
useRefQueue=true;
topicIDIndex=new HashMap<String,WeakReference<DatabaseTopic>>();
topicSIIndex=new HashMap<Locator,WeakReference<DatabaseTopic>>();
topicBNIndex=new HashMap<String,WeakReference<DatabaseTopic>>();
topicInvIDIndex=new HashMap<WeakReference<DatabaseTopic>,String>();
topicInvSIIndex=new MultiHashMap<WeakReference<DatabaseTopic>,Locator>();
topicInvBNIndex=new HashMap<WeakReference<DatabaseTopic>,String>();
associationIDIndex=new HashMap<String,WeakReference<DatabaseAssociation>>();
associationInvIDIndex=new HashMap<WeakReference<DatabaseAssociation>,String>();
topicCache=new CacheList<DatabaseTopic>();
if(useRefQueue){
running=true;
thread=new Thread(this);
topicRefQueue=new ReferenceQueue<DatabaseTopic>();
associationRefQueue=new ReferenceQueue<DatabaseAssociation>();
thread.start();
}
else{
running=false;
topicRefQueue=null;
associationRefQueue=null;
}
}
/**
* Clears the topic cache allowing any topic that isn't (strongly) referenced
* elsewhere to be gargbage collected and removed from the index.
* Note that this does not actually clear the index.
*/
public void clearTopicCache(){
topicCache=new CacheList<DatabaseTopic>();
}
/**
* Stops the thread that is cleaning indexes of topics/associations that have
* been garbage collected.
*/
public void stopCleanerThread(){
if(useRefQueue){
System.out.println("Stopping index cleaner");
useRefQueue=false;
topicInvIDIndex=null;
topicInvSIIndex=null;
topicInvBNIndex=null;
associationInvIDIndex=null;
running=false;
if(thread!=null) thread.interrupt();
thread=null;
topicRefQueue=null;
associationRefQueue=null;
}
}
/**
* Restarts the thread that is cleaning indexes of topics/associations that
* have been garbage collected.
*/
public void startCleanerThread(){
if(!useRefQueue){
System.out.println("Starting index cleaner");
useRefQueue=true;
running=false;
if(thread!=null) thread.interrupt();
HashMap<String,WeakReference<DatabaseTopic>> newTopicIDIndex=new HashMap<String,WeakReference<DatabaseTopic>>();
HashMap<WeakReference<DatabaseTopic>,String> newTopicInvIDIndex=new HashMap<WeakReference<DatabaseTopic>,String>();
HashMap<String,WeakReference<DatabaseAssociation>> newAssociationIDIndex=new HashMap<String,WeakReference<DatabaseAssociation>>();
HashMap<WeakReference<DatabaseAssociation>,String> newAssociationInvIDIndex=new HashMap<WeakReference<DatabaseAssociation>,String>();
topicRefQueue=new ReferenceQueue<DatabaseTopic>();
associationRefQueue=new ReferenceQueue<DatabaseAssociation>();
for(WeakReference<DatabaseTopic> ref : topicIDIndex.values()){
DatabaseTopic t=ref.get();
if(t==null) continue;
WeakReference<DatabaseTopic> r=new WeakReference<DatabaseTopic>(t,topicRefQueue);
newTopicIDIndex.put(t.getID(),r);
newTopicInvIDIndex.put(r,t.getID());
}
for(WeakReference<DatabaseAssociation> ref : associationIDIndex.values()){
DatabaseAssociation a=ref.get();
if(a==null) continue;
WeakReference<DatabaseAssociation> r=new WeakReference<DatabaseAssociation>(a,associationRefQueue);
newAssociationIDIndex.put(a.getID(),r);
newAssociationInvIDIndex.put(r,a.getID());
}
topicIDIndex=newTopicIDIndex;
topicInvIDIndex=newTopicInvIDIndex;
associationIDIndex=newAssociationIDIndex;
associationInvIDIndex=newAssociationInvIDIndex;
topicSIIndex=new HashMap<Locator,WeakReference<DatabaseTopic>>();
topicBNIndex=new HashMap<String,WeakReference<DatabaseTopic>>();
topicInvSIIndex=new MultiHashMap<WeakReference<DatabaseTopic>,Locator>();
topicInvBNIndex=new HashMap<WeakReference<DatabaseTopic>,String>();
thread=new Thread(this);
running=true;
thread.start();
}
}
/**
* If the indexes are complete. Note that even though they are complete some
* of the indexed topics/associations may have been garbage collected and
* index only contains information that something has been in there.
* This makes it possible to determine if some topic exists but isn't
* anymore in the index or if it doesn't exist.
*/
public boolean isFullIndex(){
return !useRefQueue;
}
public void destroy(){
running=false;
}
/**
* Creates a new topic and adds it to the index.
*/
public synchronized DatabaseTopic newTopic(String id, DatabaseTopicMap tm) throws TopicMapException {
if(topicIDIndex.containsKey(id)) {
WeakReference<DatabaseTopic> ref = topicIDIndex.get(id);
return topicAccessed(ref.get());
}
else {
DatabaseTopic t=new DatabaseTopic(id,tm);
t.create();
WeakReference<DatabaseTopic> ref=new WeakReference<DatabaseTopic>(t,topicRefQueue);
topicIDIndex.put(t.getID(),ref);
if(useRefQueue) topicInvIDIndex.put(ref,t.getID());
return topicAccessed(t);
}
}
/**
* Creates a new topic and adds it to the index.
*/
public synchronized DatabaseTopic newTopic(DatabaseTopicMap tm) throws TopicMapException {
DatabaseTopic t=new DatabaseTopic(tm);
t.create();
WeakReference<DatabaseTopic> ref=new WeakReference<DatabaseTopic>(t,topicRefQueue);
topicIDIndex.put(t.getID(),ref);
if(useRefQueue) topicInvIDIndex.put(ref,t.getID());
return topicAccessed(t);
}
/**
* Accesses a topic moving it up or adding it to the CacheList.
*/
private synchronized DatabaseTopic topicAccessed(DatabaseTopic topic){
if(topic==null) return null;
topicCache.access(topic);
// topicCache.printDebugInfo();
return topic;
}
/**
* Constructs a DatabaseTopic with the given ID.
*/
public synchronized DatabaseTopic createTopic(String id, DatabaseTopicMap tm) {
if(id == null) {
System.out.println("Warning: DatabaseTopic's id will be null. This will cause problems.");
}
DatabaseTopic t=getTopicWithID(id);
if(t!=null) return topicAccessed(t);
t = new DatabaseTopic(id, tm);
id = t.getID();
WeakReference<DatabaseTopic> ref=new WeakReference<DatabaseTopic>(t,topicRefQueue);
topicIDIndex.put(id,ref);
if(useRefQueue) topicInvIDIndex.put(ref,id);
return topicAccessed(t);
}
/* The containsKey method check if the appropriate index contains an entry
* with the given key. The isNull methods check if the index returns null
* for the key, that is either they don't have an entry for the key or they
* have a null entry. Use containsKey methods to distinguish between the two.
* The getTopicWith methods get a topic from the appropriate index and
* return null if the index doesn't have an entry for the key, the entry
* is null or the entry is a WeakReference that has been cleared but not
* yet cleaned by the cleaner thread.
*/
/* addNull methods can be used to add null entries in the index. These should
* be interpreted to mean that a topic does not exist with the given key.
*/
/* topic*Changed and topicRemoved methods are used to update indexes according
* to changes in the topic map.
*/
public synchronized DatabaseTopic getTopicWithID(String id){
WeakReference<DatabaseTopic> ref=topicIDIndex.get(id);
if(ref!=null) {
return topicAccessed(ref.get());
}
else return null;
}
public synchronized boolean containsKeyWithID(String id){
return topicIDIndex.containsKey(id);
}
public synchronized boolean containsKeyWithSI(Locator si){
return topicSIIndex.containsKey(si);
}
public synchronized boolean containsKeyWithBN(String bn){
return topicBNIndex.containsKey(bn);
}
public synchronized boolean isNullSI(Locator si){
return topicSIIndex.get(si)==null;
}
public synchronized boolean isNullBN(String bn){
return topicBNIndex.get(bn)==null;
}
public synchronized DatabaseTopic getTopicWithSI(Locator si){
WeakReference<DatabaseTopic> ref=topicSIIndex.get(si);
if(ref!=null) {
return topicAccessed(ref.get());
}
else return null;
}
public synchronized DatabaseTopic getTopicWithBN(String bn){
WeakReference<DatabaseTopic> ref=topicBNIndex.get(bn);
if(ref!=null) {
return topicAccessed(ref.get());
}
else return null;
}
public synchronized void topicSIChanged(DatabaseTopic t,Locator deleted,Locator added){
if(deleted!=null && topicSIIndex.containsKey(deleted) && (topicSIIndex.get(deleted)==null || topicSIIndex.get(deleted).get()==t)) {
WeakReference<DatabaseTopic> tref=topicSIIndex.get(deleted);
if(tref!=null && useRefQueue) topicInvSIIndex.remove(tref);
topicSIIndex.remove(deleted);
}
if(added!=null) {
WeakReference<DatabaseTopic> ref=topicIDIndex.get(t.getID());
topicSIIndex.put(added,ref);
if(useRefQueue) topicInvSIIndex.addUniq(ref,added);
}
}
public synchronized void addNullSI(Locator si){
topicSIIndex.put(si,null);
}
public synchronized void addNullBN(String bn){
topicBNIndex.put(bn,null);
}
public synchronized void topicBNChanged(Topic t,String old) throws TopicMapException {
if(old!=null && topicBNIndex.containsKey(old) && (topicBNIndex.get(old)==null || topicBNIndex.get(old).get()==t)) {
WeakReference<DatabaseTopic> tref=topicBNIndex.get(old);
if(tref!=null && useRefQueue) topicInvBNIndex.remove(tref);
topicBNIndex.remove(old);
}
if(t.getBaseName()!=null) {
WeakReference<DatabaseTopic> ref=topicIDIndex.get(t.getID());
topicBNIndex.put(t.getBaseName(),ref);
if(useRefQueue) topicInvBNIndex.put(ref,t.getBaseName());
}
}
public synchronized void topicRemoved(Topic t) throws TopicMapException {
for(Locator l : t.getSubjectIdentifiers()){
if(topicSIIndex.containsKey(l) && (topicSIIndex.get(l)==null || topicSIIndex.get(l).get()==t)){
WeakReference<DatabaseTopic> tref=topicSIIndex.get(l);
if(tref!=null && useRefQueue) topicInvSIIndex.remove(tref);
topicSIIndex.remove(l);
}
}
String old=t.getBaseName();
if(old!=null && topicBNIndex.containsKey(old) && (topicBNIndex.get(old)==null || topicBNIndex.get(old).get()==t)) {
WeakReference<DatabaseTopic> tref=topicBNIndex.get(old);
if(tref!=null && useRefQueue) topicInvBNIndex.remove(tref);
topicBNIndex.remove(t.getBaseName());
}
}
public synchronized DatabaseAssociation newAssociation(DatabaseTopic type,DatabaseTopicMap tm) throws TopicMapException {
DatabaseAssociation a=new DatabaseAssociation(type,tm);
a.create();
WeakReference<DatabaseAssociation> ref=new WeakReference<DatabaseAssociation>(a,associationRefQueue);
associationIDIndex.put(a.getID(),ref);
if(useRefQueue) associationInvIDIndex.put(ref,a.getID());
return a;
}
public synchronized DatabaseAssociation createAssociation(String id,DatabaseTopicMap tm){
DatabaseAssociation a=getAssociation(id,tm);
if(a!=null) return a;
a=new DatabaseAssociation(id,tm);
WeakReference<DatabaseAssociation> ref=new WeakReference<DatabaseAssociation>(a,associationRefQueue);
associationIDIndex.put(id,ref);
if(useRefQueue) associationInvIDIndex.put(ref,id);
return a;
}
public synchronized DatabaseAssociation getAssociation(String id,DatabaseTopicMap tm){
WeakReference<DatabaseAssociation> ref=associationIDIndex.get(id);
if(ref!=null) {
return ref.get();
}
else return null;
}
/**
* Removes entries that refer to the given WeakReferenc from topic indexes.
* This is used after a topic has been gargbage collected and it is not needed
* anymore in the indexes.
*/
private synchronized void removeTopicKey(Reference<? extends DatabaseTopic> ref){
// System.out.println("Removing topic from index");
String id=topicInvIDIndex.get(ref); // will produce null pointer exception if !useRefQueue, but that shouldn't happen
if(id!=null) topicIDIndex.remove(id);
topicInvIDIndex.remove(ref);
String bn=topicInvBNIndex.get(ref);
if(bn!=null) topicBNIndex.remove(bn);
topicInvBNIndex.remove(ref);
Collection<Locator> sis=topicInvSIIndex.get(ref);
if(sis!=null){
for(Locator l : sis){
topicSIIndex.remove(l);
}
}
topicInvSIIndex.remove(ref);
}
private synchronized void removeAssociationKey(Reference<? extends DatabaseAssociation> ref){
// System.out.println("Removing association from index");
String id=associationInvIDIndex.get(ref);
if(id!=null) associationIDIndex.remove(id);
associationInvIDIndex.remove(ref);
}
public void printDebugInfo(){
System.out.println("Index sizes "+topicIDIndex.size()+", "+topicInvIDIndex.size()+", "+associationIDIndex.size()+", "+associationInvIDIndex.size()+", "+topicBNIndex.size()+", "+topicInvBNIndex.size()+", "+topicSIIndex.size()+", "+topicInvSIIndex.size());
topicCache.printDebugInfo();
}
public void run(){
while(running && Thread.currentThread()==thread){
try{
Reference<? extends DatabaseTopic> ref=topicRefQueue.poll();
if(ref!=null) removeTopicKey(ref);
Reference<? extends DatabaseAssociation> ref2=associationRefQueue.poll();
if(ref2!=null) removeAssociationKey(ref2);
if(ref==null && ref2==null){
Thread.sleep(1000);
}
// System.out.println("Index sizes "+topicIDIndex.size()+", "+topicBNIndex.size()+", "+topicSIIndex.size()+", "+associationIDIndex.size());
}catch(InterruptedException ie){}
}
}
}
| 24,800 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
DatabaseTopicMapType.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/database2/DatabaseTopicMapType.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* DatabaseTopicMapType.java
*
* Created on 21. marraskuuta 2005, 13:48
*/
package org.wandora.topicmap.database2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.SQLException;
import javax.swing.Icon;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import org.wandora.application.Wandora;
import org.wandora.application.gui.DatabaseConfigurationPanel;
import org.wandora.application.gui.UIBox;
import org.wandora.application.tools.layers.MakeSIConsistentTool;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapConfigurationPanel;
import org.wandora.topicmap.TopicMapLogger;
import org.wandora.topicmap.TopicMapType;
import org.wandora.topicmap.packageio.PackageInput;
import org.wandora.topicmap.packageio.PackageOutput;
import org.wandora.utils.Options;
import org.wandora.utils.Tuples.T2;
/**
*
* @author olli
*/
public class DatabaseTopicMapType implements TopicMapType {
/** Creates a new instance of DatabaseTopicMapType */
public DatabaseTopicMapType() {
}
@Override
public String getTypeName(){
return "Database";
}
@Override
public TopicMap createTopicMap(Object params){
DatabaseConfigurationPanel.StoredConnection sc = (DatabaseConfigurationPanel.StoredConnection)params;
if(sc != null) {
T2<String,String> conInfo = DatabaseConfigurationPanel.getConnectionDriverAndString(sc);
if(conInfo != null) {
try {
return new DatabaseTopicMap(
conInfo.e1,
conInfo.e2,
sc.user,
sc.pass,
sc.script,
params
);
}
catch(java.sql.SQLException sqle) {
sqle.printStackTrace();
}
}
}
return null;
}
@Override
public TopicMap modifyTopicMap(TopicMap tm, Object params) {
TopicMap ret = createTopicMap(params);
ret.addTopicMapListeners(tm.getTopicMapListeners());
return ret;
}
@Override
public TopicMapConfigurationPanel getConfigurationPanel(Wandora admin, Options options) {
DatabaseConfiguration dc = new DatabaseConfiguration(admin, options);
return dc;
}
@Override
public TopicMapConfigurationPanel getModifyConfigurationPanel(Wandora wandora, Options options, TopicMap tm) {
DatabaseConfigurationPanel dcp = new DatabaseConfigurationPanel(wandora);
DatabaseTopicMap dtm = (DatabaseTopicMap)tm;
Object params = dtm.getConnectionParams();
if(params == null) {
params = DatabaseConfigurationPanel.StoredConnection.generic(
"Unknown connection",
DatabaseConfigurationPanel.GENERIC_TYPE,
dtm.getDBDriver(),
dtm.getDBConnectionString(),
dtm.getDBUser(),
dtm.getDBPassword()
);
}
return dcp.getEditConfigurationPanel(params);
}
@Override
public String toString() {
return getTypeName();
}
@Override
public void packageTopicMap(TopicMap tm, PackageOutput out, String path, TopicMapLogger logger) throws IOException {
DatabaseTopicMap dtm = (DatabaseTopicMap) tm;
Options options = new Options();
Object params = dtm.getConnectionParams();
if(params != null) {
DatabaseConfigurationPanel.StoredConnection p=(DatabaseConfigurationPanel.StoredConnection)params;
p.writeOptions(options,"params.");
}
else {
options.put("driver",dtm.getDBDriver());
options.put("connectionstring",dtm.getDBConnectionString());
options.put("user",dtm.getDBUser());
options.put("password",dtm.getDBPassword());
}
out.nextEntry(path, "dboptions.xml");
options.save(new java.io.OutputStreamWriter(out.getOutputStream()));
}
@Override
public TopicMap unpackageTopicMap(TopicMap topicmap, PackageInput in, String path, TopicMapLogger logger,Wandora wandora) throws IOException {
in.gotoEntry(path, "dboptions.xml");
Options options = new Options();
options.parseOptions(new BufferedReader(new InputStreamReader(in.getInputStream())));
if(options.get("params.name") != null) {
DatabaseConfigurationPanel.StoredConnection p = new DatabaseConfigurationPanel.StoredConnection();
p.readOptions(options,"params.");
T2<String,String> conInfo = DatabaseConfigurationPanel.getConnectionDriverAndString(p);
try {
return new DatabaseTopicMap(
conInfo.e1,
conInfo.e2,
p.user,
p.pass,
p.script,
p
);
}
catch(SQLException sqle) {
logger.log(sqle);
return null;
}
}
else {
try {
DatabaseTopicMap dtm=new DatabaseTopicMap(
options.get("driver"),
options.get("connectionstring"),
options.get("user"),
options.get("password")
);
return dtm;
}
catch(SQLException sqle) {
logger.log(sqle);
return null;
}
}
}
@Override
public TopicMap unpackageTopicMap(PackageInput in, String path, TopicMapLogger logger,Wandora wandora) throws IOException {
in.gotoEntry(path, "dboptions.xml");
Options options = new Options();
options.parseOptions(new BufferedReader(new InputStreamReader(in.getInputStream())));
if(options.get("params.name") != null) {
DatabaseConfigurationPanel.StoredConnection p = new DatabaseConfigurationPanel.StoredConnection();
p.readOptions(options,"params.");
T2<String,String> conInfo = DatabaseConfigurationPanel.getConnectionDriverAndString(p);
try {
return new DatabaseTopicMap(
conInfo.e1,
conInfo.e2,
p.user,
p.pass,
p.script,
p
);
}
catch(SQLException sqle) {
logger.log(sqle);
return null;
}
}
else {
try {
DatabaseTopicMap dtm=new DatabaseTopicMap(
options.get("driver"),
options.get("connectionstring"),
options.get("user"),
options.get("password")
);
return dtm;
}
catch(SQLException sqle){
logger.log(sqle);
return null;
}
}
}
@Override
public JMenuItem[] getTopicMapMenu(TopicMap tm,Wandora admin) {
JMenu menu=UIBox.makeMenu(
new Object[] {
"Make SI consistent...", new MakeSIConsistentTool(),
},
admin
);
JMenuItem[] items = new JMenuItem[menu.getItemCount()];
for(int i=0; i<items.length; i++) {
items[i]=menu.getItem(i);
items[i].setIcon(null);
}
return items;
}
@Override
public Icon getTypeIcon() {
//return UIBox.getIcon("gui/icons/layerinfo/layer_type_database.png");
return UIBox.getIcon(0xf1c0);
}
}
| 8,848 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AbstractDatabaseTopicMap.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/database2/AbstractDatabaseTopicMap.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
*/
package org.wandora.topicmap.database2;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author akivela
*/
public abstract class AbstractDatabaseTopicMap extends TopicMap {
private int queryCounter=1;
// connection info about current database
private String dbDriver;
private String dbConnectionString;
private String dbUser;
private String dbPassword;
private Object connectionParams;
protected boolean unconnected=false;
/**
* <p>
* The database flavor. Some operations need to be handled differently
* with different database vendors. This field is used to store what
* kind of database is being used. Currently it may have following values
* </p>
* <pre>
* "mysql" - MySQL database
* "generic" - Any other database presumed to be sufficiently standard compliant
* </pre>
* <p>
* It is set automatically based on the connection string used.
* </p>
*/
protected String databaseFlavour;
/**
* Note that this is different than topic map read only property. This property
* tells the state of the connection: is the connection a read only connection
* and does the user have privileges to modify the database. These can only
* be changed by connecting to the database using different settings.
*/
protected boolean isDBReadOnly = false;
/**
* The default stored connection
*/
protected Connection connection=null;
public AbstractDatabaseTopicMap(String dbDriver,String dbConnectionString, String dbUser, String dbPassword,String initScript,Object connectionParams) throws SQLException {
this.dbDriver=dbDriver;
this.dbConnectionString=dbConnectionString;
this.dbUser=dbUser;
this.dbPassword=dbPassword;
this.connectionParams=connectionParams;
if(dbConnectionString.startsWith("jdbc:mysql")) databaseFlavour="mysql";
else databaseFlavour="generic";
try {
getConnection();
if(initScript!=null && initScript.trim().length()>0 && !unconnected){
Statement stmt=getConnection().createStatement();
stmt.execute(initScript);
isDBReadOnly=testReadOnly(); // readOnly status may change because of init script
}
}
catch(SQLException sqle){
sqle.printStackTrace();
unconnected=true;
}
}
/**
* Gets the used jdbc database driver class.
*/
public String getDBDriver() {
return dbDriver;
}
/**
* Gets the used jdbc database connection string.
*/
public String getDBConnectionString() {
return dbConnectionString;
}
/**
* Gets the used database user name.
*/
public String getDBUser() {
return dbUser;
}
/**
* Gets the used database password.
*/
public String getDBPassword() {
return dbPassword;
}
/** A connection parameters object may be stored in the database topic map.
* It is not used by the database topic map, only stored by it. Currently
* this is used to store higher level connection information than the basic
* driver, connection string, user name, password. This makes it possible
* to modify the stored connection in Wandora. The connection parameters
* object is set at the constructor.
*/
public Object getConnectionParams() {
return connectionParams;
}
public String getDatabaseFlavour() {
return databaseFlavour;
}
// -------------------------------------------------------------------------
// ----------------------------------------------------------- READ ONLY ---
// -------------------------------------------------------------------------
/**
* Does the topic map only allow reading or both reading and writing.
* Note that this is different than topic map read only property. This property
* tells the state of the connection: is the connection a read only connection
* and does the user have privileges to modify the database. These can only
* be changed by connecting to the database using different settings.
*/
@Override
public boolean isReadOnly() {
return isDBReadOnly && isReadOnly;
}
/**
* Tests if the connection allows modifying the topic map. The test is done
* using an update sql statement that does not change anything in the database
* but should raise an exception if modifying is not allowed. Note that this
* only tests modifying the topic table and most database implementations
* allow specifying different privileges for each tables.
*/
protected boolean testReadOnly() {
if(connection==null) return true;
try{
Connection con=connection;
Statement stmt=con.createStatement();
stmt.executeUpdate("UPDATE TOPIC set TOPICID='READONLYTEST' where TOPICID='READONLYTEST';");
stmt.close();
return false;
}
catch(SQLException sqle){
// sqle.printStackTrace();
return true;
}
}
// -------------------------------------------------------------------------
// ---------------------------------------------------------- CONNECTION ---
// -------------------------------------------------------------------------
/**
* Checks if the database connection is active.
*/
@Override
public boolean isConnected(){
return !unconnected;
}
/**
* Gets the connection used with database queries. If the old stored connection
* has been closed for any reason, tries to create a new connection.
*/
protected Connection getConnection() {
synchronized(queryLock) {
if(unconnected) {
return null;
}
if(connection==null) {
connection=createConnection(false);
isDBReadOnly=testReadOnly();
}
if(connection==null) {
unconnected=true;
return null;}
try {
if(connection.isClosed()) {
System.out.println("SQL connection closed. Opening new connection!");
connection=createConnection(false);
isDBReadOnly=testReadOnly();
}
}
catch (SQLException sqle) {
System.out.println("SQL exception occurred while acquiring connection:");
sqle.printStackTrace();
System.out.println("Trying to open new connection!");
connection=createConnection(true);
isDBReadOnly=testReadOnly();
}
return connection;
}
}
/**
* Creates a new database connection using the connection parameters given
* to the constructor.
*/
protected Connection createConnection(boolean autocommit) {
try {
Class.forName(dbDriver);
Connection con = DriverManager.getConnection(dbConnectionString,dbUser,dbPassword);
if(autocommit) {
con.setAutoCommit(true);
}
else {
con.setAutoCommit(false);
}
// System.out.println("Database connection created");
return con;
}
catch(Exception e){
System.out.println("Database connection failed with");
System.out.println("Driver: " + dbDriver);
System.out.println("Connection string: " + dbConnectionString);
System.out.println("User: " + dbUser);
System.out.println("Password: " + dbPassword);
e.printStackTrace();
return null;
}
}
/**
* Closes the topic map. This closes the database connection.
* Topic map cannot be used or reopened
* after it has been closed.
*/
@Override
public void close() {
log("at close of database topicmap******");
if(connection!=null){
try {
log("Close database connection ******");
connection.close();
}
catch(SQLException sqle) {
sqle.printStackTrace();
}
}
}
// -------------------------------------------------------------------------
// ------------------------------------------------------- EXECUTE QUERY ---
// -------------------------------------------------------------------------
private final Object queryLock = new Object();
private QueryQueue updateQueue = new QueryQueue();
public boolean executeUpdate(String query) throws TopicMapException{
try {
return updateQueue.queue(query);
}
catch(SQLException sqle) {
throw new TopicMapSQLException(sqle);
}
}
/*
private boolean executeUpdate(String query, Connection con) throws TopicMapException {
synchronized(queryLock) {
queryCounter++;
Statement stmt = null;
try {
stmt = con.createStatement();
logQuery(query);
stmt.executeUpdate(query);
}
catch(SQLException sqle) {
sqle.printStackTrace();
throw new TopicMapException(sqle);
}
finally {
if(stmt != null) {
try {
stmt.close();
}
catch(SQLException sqle) {
throw new TopicMapException(sqle);
}
}
}
}
return true;
}
*/
/**
* Executes a database query and returns the results as a collection. Each
* element in the collection is a Map and represents a row of the result.
* The Map maps column names to the objects returned by query.
*/
public Collection<Map<String,Object>> executeQuery(String query) throws TopicMapException {
return executeQuery(query, getConnection());
}
private Collection<Map<String,Object>> executeQuery(String query, Connection con) throws TopicMapException {
try {
updateQueue.commit();
}
catch(SQLException sqle) {
throw new TopicMapSQLException(sqle);
}
synchronized(queryLock) {
Statement stmt = null;
ResultSet rs = null;
try {
queryCounter++;
logQuery(query);
stmt=con.createStatement();
rs=stmt.executeQuery(query);
ResultSetMetaData metaData=rs.getMetaData();
int columns=metaData.getColumnCount();
String[] columnNames=new String[columns];
for(int i=0;i<columns;i++) {
columnNames[i]=metaData.getColumnName(i+1);
}
List<Map<String,Object>> rows=new ArrayList<>();
while(rs.next()) {
Map<String,Object> row = new LinkedHashMap<>();
for(int i=0;i<columns;i++) {
// Column names are transformed to uppercase.
row.put(columnNames[i].toUpperCase(), rs.getObject(i+1));
//System.out.println(" "+columnNames[i]+"="+rs.getObject(i+1));
}
//System.out.println("---");
rows.add(row);
}
rs.close();
stmt.close();
return rows;
}
catch(SQLException sqle) {
try {
if(rs != null) rs.close();
} catch(Exception e) { e.printStackTrace(); }
try {
if(stmt != null) stmt.close();
} catch(Exception e) { e.printStackTrace(); }
sqle.printStackTrace();
throw new TopicMapSQLException(sqle);
}
}
}
protected int executeCountQuery(String query) {
try {
updateQueue.commit();
}
catch(TopicMapException | SQLException e) {
e.printStackTrace();
}
int count = 0;
synchronized(queryLock) {
if(!unconnected) {
Statement stmt = null;
ResultSet rs = null;
try {
queryCounter++;
logQuery(query);
Connection con=getConnection();
stmt=con.createStatement();
rs=stmt.executeQuery(query);
rs.next();
count=rs.getInt(1);
rs.close();
stmt.close();
return count;
}
catch(SQLException sqle) {
sqle.printStackTrace();
}
finally {
if(rs != null) {
try {
rs.close();
} catch(Exception e) { e.printStackTrace(); }
}
if(stmt != null) {
try {
stmt.close();
} catch(Exception e) { e.printStackTrace(); }
}
}
}
}
return count;
}
private void logQuery(String query) {
if(query != null) {
System.out.println(query.substring(0, query.length() > 512 ? 512 : query.length()));
}
}
public Iterator<Map<String,Object>> getRowIterator(final String query, final String orderby) {
if(unconnected) {
return new Iterator<>() {
@Override
public boolean hasNext() {
return false;
}
@Override
public Map<String,Object> next() {
throw new NoSuchElementException();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
else {
return new Iterator<>() {
boolean hasNext = false;
int offset = 0;
int limit = 1000;
List<Map<String,Object>> rows = null;
int rowIndex = 0;
private void prepare() {
try {
String newQuery = query +" order by "+orderby+ " limit "+limit+" offset "+offset;
rows = new ArrayList<>(executeQuery(newQuery));
offset += limit;
rowIndex = 0;
}
catch(Exception e) {
e.printStackTrace();
hasNext = false;
}
}
@Override
public boolean hasNext() {
if(rows == null || rowIndex >= rows.size()) {
prepare();
}
if(rows != null && rowIndex < rows.size()) {
return true;
}
return false;
}
@Override
public Map<String,Object> next() {
if(!hasNext()) {
throw new NoSuchElementException();
}
Map<String,Object> row = rows.get(rowIndex++);
return row;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}
// -------------------------------------------------------------------------
public void commit() throws SQLException, TopicMapException {
updateQueue.commit();
}
// -------------------------------------------------------------------------
/**
* Turns a collection of strings into sql syntax representing a collection of strings
* that can be used with 'in' clauses. The returned string contains each string
* in the collection escaped inside single quotes, each separated by commas
* and all contain inside parenthesis. For example: ('string1','string2','string3').
*/
protected String collectionToSQL(Collection<String> col){
StringBuilder sb=new StringBuilder("(");
for(String s : col){
if(sb.length()>1) sb.append(",");
sb.append("'").append(escapeSQL(s)).append("'");
}
sb.append(")");
return sb.toString();
}
/**
* Escapes a string so that it can be used in an sql query.
*/
protected String escapeSQL(String s) {
if(s != null) {
s=s.replace("'","''");
if(databaseFlavour.equals("mysql")) {
s=s.replace("\\","\\\\");
}
}
return s;
}
// -------------------------------------------------------------------------
class QueryQueue {
private final List<String> queryQueue = Collections.synchronizedList(new ArrayList<String>());
private int autoCommitQueueSize = 50;
private int maxTries = 10;
public boolean queue(String query) throws SQLException, TopicMapException {
boolean autoCommit = false;
synchronized(queryQueue) {
queryQueue.add(query);
autoCommit = (queryQueue.size() > autoCommitQueueSize);
}
if(autoCommit) {
commit();
}
return true;
}
public void commit() throws SQLException, TopicMapException {
synchronized(queryQueue) {
if(!queryQueue.isEmpty()) {
Connection connection = getConnection();
int tries = 0;
while(!queryQueue.isEmpty() && ++tries < maxTries) {
try {
for(String query : queryQueue) {
synchronized(queryLock) {
queryCounter++;
Statement stmt = connection.createStatement();
logQuery(query);
stmt.executeUpdate(query);
stmt.close();
}
}
connection.commit();
queryQueue.clear();
}
catch(SQLException sqle) {
sqle.printStackTrace();
connection.rollback();
try {
Thread.sleep(100);
}
catch (InterruptedException ex) {
// OK. Wakeup.
}
}
}
if(tries >= maxTries) {
throw new TopicMapException(new SQLException());
}
}
}
}
}
}
| 21,424 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
DatabaseConfiguration.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/database2/DatabaseConfiguration.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* DatabaseConfiguration.java
*
*/
package org.wandora.topicmap.database2;
import java.util.ArrayList;
import java.util.Collection;
import org.wandora.application.Wandora;
import org.wandora.application.gui.DatabaseConfigurationPanel;
import org.wandora.topicmap.TopicMapConfigurationPanel;
import org.wandora.utils.Options;
/**
*
* @author olli
*/
public class DatabaseConfiguration extends TopicMapConfigurationPanel {
private static final long serialVersionUID = 1L;
private DatabaseConfigurationPanel confPanel;
private Options options;
/** Creates new form DatabaseConfiguration */
public DatabaseConfiguration(Wandora wandora, Options options) {
initComponents();
this.options=options;
confPanel=new DatabaseConfigurationPanel(wandora);
initialize(options);
this.add(confPanel);
}
public static Collection<DatabaseConfigurationPanel.StoredConnection> parseConnections(Options options){
Collection<DatabaseConfigurationPanel.StoredConnection> connections=new ArrayList<>();
String prefix="options.dbconnections.connection";
int counter=0;
while(true){
String type=options.get(prefix+"["+counter+"].type");
if(type==null) break;
String name=options.get(prefix+"["+counter+"].name");
String user=options.get(prefix+"["+counter+"].user");
String pass=options.get(prefix+"["+counter+"].pass");
if(type.equals(DatabaseConfigurationPanel.GENERIC_TYPE)){
String driver=options.get(prefix+"["+counter+"].driver");
String conString=options.get(prefix+"["+counter+"].constring");
String script=options.get(prefix+"["+counter+"].script");
connections.add(DatabaseConfigurationPanel.StoredConnection.generic(name,type,driver,conString,user,pass,script));
}
else{
String server=options.get(prefix+"["+counter+"].server");
String database=options.get(prefix+"["+counter+"].database");
connections.add(DatabaseConfigurationPanel.StoredConnection.known(name,type,server,database,user,pass));
}
counter++;
}
return connections;
}
public void initialize(Options options){
Collection<DatabaseConfigurationPanel.StoredConnection> connections=parseConnections(options);
confPanel.setConnections(connections);
}
public void writeOptions(Options options){
writeOptions(options,confPanel);
}
public static void writeOptions(Options options,DatabaseConfigurationPanel confPanel){
int counter=0;
String prefix="options.dbconnections.connection";
while(true){
String type=options.get(prefix+"["+counter+"].type");
if(type==null) break;
options.put(prefix+"["+counter+"].type",null);
options.put(prefix+"["+counter+"].name",null);
options.put(prefix+"["+counter+"].user",null);
options.put(prefix+"["+counter+"].pass",null);
options.put(prefix+"["+counter+"].driver",null);
options.put(prefix+"["+counter+"].constring",null);
options.put(prefix+"["+counter+"].server",null);
options.put(prefix+"["+counter+"].database",null);
counter++;
}
Collection<DatabaseConfigurationPanel.StoredConnection> connections=confPanel.getAllConnections();
counter=0;
for(DatabaseConfigurationPanel.StoredConnection sc : connections){
options.put(prefix+"["+counter+"].type",sc.type);
options.put(prefix+"["+counter+"].name",sc.name);
options.put(prefix+"["+counter+"].user",sc.user);
options.put(prefix+"["+counter+"].pass",sc.pass);
if(sc.type.equals(DatabaseConfigurationPanel.GENERIC_TYPE)){
options.put(prefix+"["+counter+"].driver",sc.driver);
options.put(prefix+"["+counter+"].constring",sc.conString);
options.put(prefix+"["+counter+"].script",sc.script);
}
else{
options.put(prefix+"["+counter+"].server",sc.server);
options.put(prefix+"["+counter+"].database",sc.database);
}
counter++;
}
}
@Override
public Object getParameters(){
writeOptions(options);
DatabaseConfigurationPanel.StoredConnection sc=confPanel.getSelectedConnection();
if(sc==null) return null;
return sc;
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents() {
setLayout(new java.awt.BorderLayout());
}
// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
}
| 6,074 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
BasicDiffOutput.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/diff/BasicDiffOutput.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.wandora.topicmap.diff;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
import org.wandora.topicmap.diff.TopicMapDiff.DiffEntry;
/**
*
* @author olli
*/
public class BasicDiffOutput implements DiffOutput {
protected DiffEntryFormatter formatter;
protected Writer writer;
public BasicDiffOutput(DiffEntryFormatter formatter,Writer writer){
this.formatter=formatter;
this.writer=writer;
}
protected void doOutput(DiffEntry d) throws IOException,TopicMapException{
this.formatter.formatDiffEntry(d, writer);
}
public void startCompare(){
try{
this.formatter.header(writer);
}
catch(IOException ioe){
ioe.printStackTrace();
}
catch(TopicMapException tme){
tme.printStackTrace();
}
}
public void endCompare(){
try{
this.formatter.footer(writer);
}
catch(IOException ioe){
ioe.printStackTrace();
}
catch(TopicMapException tme){
tme.printStackTrace();
}
}
public boolean outputDiffEntry(DiffEntry d) {
try{
doOutput(d);
}
catch(IOException ioe){
ioe.printStackTrace();
return false;
}
catch(TopicMapException tme){
tme.printStackTrace();
return false;
}
return true;
}
public boolean noDifferences(Topic t){
return true;
}
public boolean noDifferences(Association a){
return true;
}
public void outputDiff(ArrayList<DiffEntry> diff) {
for(DiffEntry d : diff){
outputDiffEntry(d);
}
}
}
| 2,689 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
HTMLDiffEntryFormatter.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/diff/HTMLDiffEntryFormatter.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.wandora.topicmap.diff;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
import org.wandora.topicmap.diff.TopicMapDiff.AssociationAdded;
import org.wandora.topicmap.diff.TopicMapDiff.AssociationDeleted;
import org.wandora.topicmap.diff.TopicMapDiff.BNChanged;
import org.wandora.topicmap.diff.TopicMapDiff.DiffEntry;
import org.wandora.topicmap.diff.TopicMapDiff.SIAdded;
import org.wandora.topicmap.diff.TopicMapDiff.SIDeleted;
import org.wandora.topicmap.diff.TopicMapDiff.SLChanged;
import org.wandora.topicmap.diff.TopicMapDiff.TopicAdded;
import org.wandora.topicmap.diff.TopicMapDiff.TopicChanged;
import org.wandora.topicmap.diff.TopicMapDiff.TopicDeleted;
import org.wandora.topicmap.diff.TopicMapDiff.TopicDiffEntry;
import org.wandora.topicmap.diff.TopicMapDiff.TypeAdded;
import org.wandora.topicmap.diff.TopicMapDiff.TypeDeleted;
import org.wandora.topicmap.diff.TopicMapDiff.VariantChanged;
/**
*
* @author olli
*/
public class HTMLDiffEntryFormatter implements DiffEntryFormatter {
private boolean nochanges;
public HTMLDiffEntryFormatter(){
nochanges=true;
}
protected void formatTopicDiffEntry(ArrayList<TopicDiffEntry> diff,Writer writer) throws IOException,TopicMapException {
for(TopicDiffEntry d : diff){
if(d instanceof SIAdded){
writer.write("Added subject identifier "+((SIAdded)d).si+"<br />\n");
}
else if(d instanceof SIDeleted){
writer.write("Deleted subject identifier "+((SIDeleted)d).si+"<br />\n");
}
else if(d instanceof SLChanged){
Locator l=((SLChanged)d).sl;
Locator ol=((SLChanged)d).oldsl;
if(l!=null) {
if(ol==null) writer.write("Added subject locator "+l+"<br />\n");
else writer.write("Changed subject locator from "+ol+" to "+l+"<br />\n");
}
else writer.write("Deleted subject locator "+ol+"<br />\n");
}
else if(d instanceof BNChanged){
String bn=((BNChanged)d).bn;
String oldbn=((BNChanged)d).oldbn;
if(bn!=null) {
if(oldbn==null) writer.write("Added base name \""+bn+"\"<br />\n");
else writer.write("Changed base name from \""+oldbn+"\" to \""+bn+"\"<br />\n");
}
else writer.write("Deleted base name \""+oldbn+"\"<br />\n");
}
else if(d instanceof TypeAdded){
Topic t=((TypeAdded)d).t;
Object t2=((TypeAdded)d).t2;
writer.write("Added type "+formatTopic(t,t2)+"<br />\n");
}
else if(d instanceof TypeDeleted){
Topic t=((TypeDeleted)d).t;
Object t2=((TypeDeleted)d).t2;
writer.write("Deleted type "+formatTopic(t,t2)+"<br />\n");
}
else if(d instanceof VariantChanged){
VariantChanged vc=(VariantChanged)d;
String v=vc.name;
String oldv=vc.oldname;
StringBuffer scopeString=new StringBuffer("{");
if(vc.scope!=null){
for(Topic t : vc.scope){
if(scopeString.length()>1) scopeString.append(", ");
scopeString.append(formatTopic(t,null));
}
}
else{
for(Object t : vc.scope2){
if(scopeString.length()>1) scopeString.append(", ");
scopeString.append(formatTopic(null,t));
}
}
scopeString.append("}");
if(v!=null) {
if(oldv==null) writer.write("Added variant "+scopeString+" \""+v+"\"<br />\n");
else writer.write("Changed variant "+scopeString+" from \""+oldv+"\" to \""+v+"\"<br />\n");
}
else writer.write("Deleted variant "+scopeString+" \""+oldv+"\"<br />\n");
}
}
}
protected String formatTopic(Topic t,Object identifier) throws TopicMapException {
if(t!=null){
String bn=t.getBaseName();
if(bn!=null) return "\""+bn+"\"";
else {
Locator si = t.getOneSubjectIdentifier();
if(si != null) return si.toString();
else return "***null***";
}
}
else {
if(identifier instanceof Locator) return identifier.toString();
else return "\""+identifier.toString()+"\"";
}
}
protected void formatAssociation(Association a,Writer writer) throws IOException,TopicMapException {
Topic type=a.getType();
writer.write("Type: "+formatTopic(type,null)+"<br />\n");
for(Topic role : a.getRoles()){
writer.write(formatTopic(role,null)+": "+formatTopic(a.getPlayer(role),null)+"<br />\n");
}
}
protected void formatAssociation(Topic[] a,Writer writer) throws IOException,TopicMapException {
Topic type=a[0];
writer.write("Type: "+formatTopic(type,null)+"<br />\n");
for(int i=1;i+1<a.length;i+=2){
Topic role=a[i];
Topic player=a[i+1];
writer.write(formatTopic(role,null)+": "+formatTopic(player,null)+"<br />\n");
}
}
protected void formatAssociation(Object[] a,Writer writer) throws IOException,TopicMapException {
Object type=a[0];
writer.write("Type: "+formatTopic(null,type)+"<br />\n");
for(int i=1;i+1<a.length;i+=2){
Object role=a[i];
Object player=a[i+1];
writer.write(formatTopic(null,role)+": "+formatTopic(null,player)+"<br />\n");
}
}
@Override
public void header(Writer writer) throws IOException, TopicMapException{
}
@Override
public void footer(Writer writer) throws IOException, TopicMapException{
if(nochanges){
writer.write("<h2>No differences</h2>");
}
}
@Override
public void formatDiffEntry(DiffEntry entry,Writer writer) throws IOException,TopicMapException {
nochanges=false;
if(entry instanceof TopicChanged){
Topic t=((TopicChanged)entry).topic;
Object t2=((TopicChanged)entry).topic2;
ArrayList<TopicDiffEntry> diff=((TopicChanged)entry).diff;
writer.write("<h2>Changed topic "+formatTopic(t,t2)+"</h2>\n");
formatTopicDiffEntry(diff,writer);
}
else if(entry instanceof TopicDeleted){
Topic t=((TopicDeleted)entry).topic;
Object t2=((TopicDeleted)entry).topic2;
writer.write("<h2>Deleted topic "+formatTopic(t,t2)+"</h2>\n");
}
else if(entry instanceof TopicAdded){
ArrayList<TopicDiffEntry> diff=((TopicAdded)entry).diff;
String bn=null;
Locator si=null;
for(TopicDiffEntry e : diff){
if(e instanceof BNChanged){
bn=((BNChanged)e).bn;
break;
}
else if(si==null && e instanceof SIAdded){
si=((SIAdded)e).si;
}
}
if(bn!=null) writer.write("<h2>Added topic \""+bn+"\"</h2>\n");
else writer.write("<h2>Added topic "+si+"</h2>\n");
formatTopicDiffEntry(diff,writer);
}
else if(entry instanceof AssociationAdded){
writer.write("<h2>Added association</h2>\n");
if(((AssociationAdded)entry).a!=null)
formatAssociation(((AssociationAdded)entry).a,writer);
else
formatAssociation(((AssociationAdded)entry).a2,writer);
}
else if(entry instanceof AssociationDeleted){
writer.write("<h2>Deleted association</h2>\n");
if(((AssociationDeleted)entry).a!=null)
formatAssociation(((AssociationDeleted)entry).a,writer);
else
formatAssociation(((AssociationDeleted)entry).a2,writer);
}
}
}
| 9,433 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TopicMapDiff.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/diff/TopicMapDiff.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.wandora.topicmap.diff;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicInUseException;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.topicmap.TopicMapHashCode;
import org.wandora.topicmap.TopicMapType;
import org.wandora.topicmap.TopicMapTypeManager;
import org.wandora.topicmap.layered.LayerStack;
import org.wandora.topicmap.memory.TopicMapImpl;
import org.wandora.topicmap.packageio.PackageInput;
import org.wandora.topicmap.packageio.ZipPackageInput;
/**
*
* @author olli
*/
public class TopicMapDiff {
public TopicMapDiff(){
}
public ArrayList<TopicDiffEntry> compareTopics(Topic t1,Topic t2) throws TopicMapException {
ArrayList<TopicDiffEntry> ret=new ArrayList<TopicDiffEntry>();
TopicMap tm1=t1.getTopicMap();
TopicMap tm2=t2.getTopicMap();
String bn1=t1.getBaseName();
String bn2=t2.getBaseName();
if(bn1==null && bn2!=null) ret.add(new BNChanged(bn2,bn1));
else if(bn1!=null && bn2==null) ret.add(new BNChanged(bn2,bn1));
else if(bn1==null && bn2==null) {}
else if(! bn1.equals(bn2)) ret.add(new BNChanged(bn2,bn1));
Locator sl1=t1.getSubjectLocator();
Locator sl2=t2.getSubjectLocator();
if(sl1==null && sl2!=null) ret.add(new SLChanged(sl2,sl1));
else if(sl1!=null && sl2==null) ret.add(new SLChanged(sl2,sl1));
else if(sl1==null && sl2==null) {}
else if(! sl1.equals(sl2)) ret.add(new SLChanged(sl2,sl1));
Collection<Locator> sis1=t1.getSubjectIdentifiers();
Collection<Locator> sis2=t2.getSubjectIdentifiers();
ArrayList<Locator> ls=new ArrayList<Locator>(sis2);
ls.removeAll(sis1);
for(Locator l : ls){
ret.add(new SIAdded(l));
}
ls=new ArrayList<Locator>(sis1);
ls.removeAll(sis2);
for(Locator l : ls){
ret.add(new SIDeleted(l));
}
for(Topic type1 : t1.getTypes()){
Topic m2=getSingleMerging(tm2, type1);
if(m2==null) ret.add(new TypeDeleted(type1));
else{
Topic m1=getSingleMerging(tm1,m2);
if(m1==null || !t2.isOfType(m2)) ret.add(new TypeDeleted(type1));
}
}
for(Topic type2 : t2.getTypes()){
Topic m1=getSingleMerging(tm1, type2);
if(m1==null) ret.add(new TypeAdded(type2));
else{
Topic m2=getSingleMerging(tm2,m1);
if(m2==null || !t1.isOfType(m1)) ret.add(new TypeAdded(type2));
}
}
Set<Set<Topic>> scopes1=t1.getVariantScopes();
for(Set<Topic> s1 : scopes1){
String v1=t1.getVariant(s1);
Set<Topic> s2=getScope(s1,tm2);
if(s2==null) ret.add(new VariantChanged(s1,null,v1));
else{
String v2=t2.getVariant(s2);
if(v2==null || !v2.equals(v1)) ret.add(new VariantChanged(s2,v2,v1));
}
}
Set<Set<Topic>> scopes2=t2.getVariantScopes();
for(Set<Topic> s2 : scopes2){
String v2=t2.getVariant(s2);
Set<Topic> s1=getScope(s2,tm1);
if(s1==null) ret.add(new VariantChanged(s2,v2,null));
else{
String v1=t1.getVariant(s1);
if(v1==null) ret.add(new VariantChanged(s2,v2,null));
// !v1.equals(v2) should be covered by previous loop
}
}
return ret;
}
public ArrayList<TopicDiffEntry> newTopic(Topic t) throws TopicMapException {
ArrayList<TopicDiffEntry> ret=new ArrayList<TopicDiffEntry>();
for(Locator l : t.getSubjectIdentifiers()){
ret.add(new SIAdded(l));
}
Locator sl=t.getSubjectLocator();
if(sl!=null) ret.add(new SLChanged(sl,null));
String bn=t.getBaseName();
if(bn!=null) ret.add(new BNChanged(bn,null));
for(Topic type : t.getTypes()){
ret.add(new TypeAdded(type));
}
Set<Set<Topic>> scopes=t.getVariantScopes();
for(Set<Topic> s : scopes){
String variant=t.getVariant(s);
ret.add(new VariantChanged(s,variant,null));
}
return ret;
}
public ArrayList<TopicDiffEntry> deletedTopic(Topic t) throws TopicMapException {
ArrayList<TopicDiffEntry> ret=new ArrayList<TopicDiffEntry>();
for(Locator l : t.getSubjectIdentifiers()){
ret.add(new SIDeleted(l));
}
Locator sl=t.getSubjectLocator();
if(sl!=null) ret.add(new SLChanged(null,sl));
String bn=t.getBaseName();
if(bn!=null) ret.add(new BNChanged(null,bn));
for(Topic type : t.getTypes()){
ret.add(new TypeDeleted(type));
}
Set<Set<Topic>> scopes=t.getVariantScopes();
for(Set<Topic> s : scopes){
String v=t.getVariant(s);
ret.add(new VariantChanged(s,null,v));
}
return ret;
}
public Set<Topic> getScope(Set<Topic> scope,TopicMap tm) throws TopicMapException {
HashSet<Topic> ret=new HashSet<Topic>();
for(Topic t : scope){
Collection<Topic> merging=tm.getMergingTopics(t);
if(merging.size()!=1) return null;
Topic m1=merging.iterator().next();
Collection<Topic> merging2=t.getTopicMap().getMergingTopics(m1);
if(merging2.size()!=1) return null;
ret.add(m1);
}
return ret;
}
public boolean makeDiff(TopicMap tm1,TopicMap tm2,DiffOutput output) throws TopicMapException {
output.startCompare();
boolean cont=true;
Iterator<Topic> topics1=tm1.getTopics();
while(topics1.hasNext() && cont){
Topic t1=topics1.next();
Topic m2=getSingleMerging(tm2,t1);
if(m2!=null){
Topic m1=getSingleMerging(tm1,m2);
if(m1!=null){
ArrayList<TopicDiffEntry> tDiff=compareTopics(t1, m2);
if(tDiff.size()>0) cont=output.outputDiffEntry(new TopicChanged(t1,tDiff));
else output.noDifferences(t1);
}
else cont=output.outputDiffEntry(new TopicDeleted(t1,deletedTopic(t1)));
}
else cont=output.outputDiffEntry(new TopicDeleted(t1,deletedTopic(t1)));
}
if(!cont) return cont;
Iterator<Topic> topics2=tm2.getTopics();
while(topics2.hasNext() && cont){
Topic t2=topics2.next();
Topic m1=getSingleMerging(tm1,t2);
if(m1!=null){
Topic m2=getSingleMerging(tm2,m1);
if(m2==null) cont=output.outputDiffEntry(new TopicAdded(newTopic(t2)));
else output.noDifferences(t2);
}
else cont=output.outputDiffEntry(new TopicAdded(newTopic(t2)));
}
if(!cont) return cont;
Iterator<Association> associations1=tm1.getAssociations();
while(associations1.hasNext() && cont){
Association a1=associations1.next();
if(!findAssociation(tm2,a1)) cont=output.outputDiffEntry(new AssociationDeleted(a1));
else output.noDifferences(a1);
}
if(!cont) return cont;
Iterator<Association> associations2=tm2.getAssociations();
while(associations2.hasNext() && cont){
Association a2=associations2.next();
if(!findAssociation(tm1,a2)) cont=output.outputDiffEntry(new AssociationAdded(a2));
else output.noDifferences(a2);
}
output.endCompare();
return cont;
}
public boolean findAssociation(TopicMap tm2,Association a1) throws TopicMapException {
TopicMap tm1=a1.getType().getTopicMap();
Topic type2=getSingleMerging(tm2,a1.getType());
if(type2==null || getSingleMerging(tm1,type2)==null) return false;
HashMap<Topic,Topic> players2=new HashMap<Topic,Topic>();
for(Topic role1 : a1.getRoles()){
Topic role2=getSingleMerging(tm2,role1);
Topic player2=getSingleMerging(tm2,a1.getPlayer(role1));
if(role2==null || getSingleMerging(tm1,role2)==null ||
player2==null || getSingleMerging(tm1,player2)==null ){
return false;
}
players2.put(role2,player2);
}
ArrayList<Association> as2=null;
for(Map.Entry<Topic,Topic> e : players2.entrySet()){
if(as2==null){
as2=new ArrayList<Association>(e.getValue().getAssociations(type2, e.getKey()));
ArrayList<Association> next=new ArrayList<Association>();
for(Association test : as2){
if(test.getRoles().size()==a1.getRoles().size()) next.add(test);
}
as2=next;
}
else{
ArrayList<Association> next=new ArrayList<Association>();
for(Association test : as2){
Topic testPlayer=test.getPlayer(e.getKey());
if(testPlayer!=null && testPlayer.mergesWithTopic(e.getValue()))
next.add(test);
}
as2=next;
}
if(as2.size()==0) break;
}
if(as2!=null && as2.size()==1) return true;
return false;
}
public Topic getSingleMerging(TopicMap tm,Topic t) throws TopicMapException {
Topic ret=null;
for(Locator l : t.getSubjectIdentifiers()){
Topic found=tm.getTopic(l);
if(found!=null){
if(ret!=null) {
if(!ret.mergesWithTopic(found)) return null;
}
else ret=found;
}
}
Locator sl=t.getSubjectLocator();
if(sl!=null){
Topic found=tm.getTopicBySubjectLocator(sl);
if(found!=null){
if(ret!=null) {
if(!ret.mergesWithTopic(found)) return null;
}
else ret=found;
}
}
String bn=t.getBaseName();
if(bn!=null){
Topic found=tm.getTopicWithBaseName(bn);
if(found!=null){
if(ret!=null) {
if(!ret.mergesWithTopic(found)) return null;
}
else ret=found;
}
}
return ret;
}
public Topic getTopic(Object identifier,TopicMap tm) throws TopicMapException {
if(identifier instanceof Locator) return tm.getTopic((Locator)identifier);
else return tm.getTopicWithBaseName(identifier.toString());
}
public Association getAssociation(Object[] a,TopicMap tm) throws TopicMapException {
Topic t=getTopic(a[0],tm);
if(t==null) return null;
ArrayList<Association> as2=null;
for(int i=1;i+1<a.length;i+=2){
Topic role=getTopic(a[i],tm);
Topic player=getTopic(a[i+1],tm);
if(role==null || player==null) return null;
if(as2==null){
as2=new ArrayList<Association>(player.getAssociations(t, role));
}
else{
ArrayList<Association> next=new ArrayList<Association>();
for(Association test : as2){
Topic testPlayer=test.getPlayer(role);
if(testPlayer!=null && testPlayer.mergesWithTopic(player))
next.add(test);
}
as2=next;
}
if(as2.size()==0) return null;
}
if(as2.size()==1) {
Association a2=as2.get(0);
if(a2.getRoles().size()==(a.length-1)/2) return a2;
}
return null;
}
public Object getTopicIdentifier(ArrayList<TopicDiffEntry> diff){
Locator si=null;
for(TopicDiffEntry d : diff){
if(d instanceof SIAdded){
si=((SIAdded)d).si;
}
else if(d instanceof BNChanged){
return ((BNChanged)d).bn;
}
}
return si;
}
public boolean applyTopicDiff(ArrayList<TopicDiffEntry> diff,Topic t,TopicMap tm,int phase,PatchExceptionHandler eHandler) throws TopicMapException {
Diff: for(TopicDiffEntry d : diff){
if(d instanceof SIAdded){
if(phase==0 || phase==3){
SIAdded d2=(SIAdded)d;
if(t.getSubjectIdentifiers().contains(d2.si)){
if(!eHandler.handleException(new PatchException(PatchException.MINOR,"Topic already contains added subject identifier "+d2.si,t)))
return false;
}
else if(tm.getTopic(d2.si)!=null) {
if(!eHandler.handleException(new PatchException(PatchException.MODERATE,"Adding subject identifier "+d2.si+" to a topic but topic map already contains a topic with that idetnifier.",t)))
return false;
}
t.addSubjectIdentifier(d2.si);
}
}
else if(d instanceof SIDeleted){
if(phase==0 || phase==3){
SIDeleted d2=(SIDeleted)d;
if(t.getSubjectIdentifiers().contains(d2.si)){
if(!eHandler.handleException(new PatchException(PatchException.MINOR,"Topic does not contain removed subject identifier "+d2.si,t)))
return false;
}
t.removeSubjectIdentifier(d2.si);
}
}
else if(d instanceof SLChanged){
if(phase==0 || phase==4){
SLChanged d2=(SLChanged)d;
Locator l=t.getSubjectLocator();
boolean nochange=false;
if( (l==null && d2.oldsl!=null) || (l!=null && d2.oldsl==null) ||
(l!=null && d2.oldsl!=null && !l.equals(d2.oldsl)) ) {
if( (l!=null && d2.sl!=null && l.equals(d2.sl)) || (l==null && d2.sl==null)) {
if(!eHandler.handleException(new PatchException(PatchException.MINOR,"Changing subject locator to "+d2.sl+". Old subject locator is "+l+" expected "+d2.oldsl,t)))
return false;
nochange=true;
}
else if(!eHandler.handleException(new PatchException(PatchException.MODERATE,"Changing subject locator to "+d2.sl+". Old subject locator is "+l+" expected "+d2.oldsl,t)))
return false;
}
if(!nochange && d2.sl!=null && tm.getTopicBySubjectLocator(d2.sl)!=null)
if(!eHandler.handleException(new PatchException(PatchException.MODERATE,"Adding subject locator "+d2.sl+" to a topic but topic map already contains a topic with that locator.",t)))
return false;
t.setSubjectLocator(d2.sl);
}
}
else if(d instanceof BNChanged){
if(phase==0 || phase==3){
BNChanged d2=(BNChanged)d;
String bn=t.getBaseName();
boolean nochange=false;
if( (bn==null && d2.oldbn!=null) || (bn!=null && d2.oldbn==null) ||
(bn!=null && d2.oldbn!=null && !bn.equals(d2.oldbn)) ) {
if( (bn!=null && d2.bn!=null && bn.equals(d2.bn)) || (bn==null && d2.bn==null)) {
if(!eHandler.handleException(new PatchException(PatchException.MINOR,"Changing base name to "+d2.bn+". Old base name is "+bn+" expected "+d2.oldbn,t)))
return false;
nochange=true;
}
else if(!eHandler.handleException(new PatchException(PatchException.MODERATE,"Changing base name to "+d2.bn+". Old base name is "+bn+" expected "+d2.oldbn,t)))
return false;
}
if(!nochange && d2.bn!=null && tm.getTopicWithBaseName(d2.bn)!=null)
if(!eHandler.handleException(new PatchException(PatchException.MODERATE,"Adding base name "+d2.bn+" to a topic but topic map already contains a topic with that base name.",t)))
return false;
t.setBaseName(d2.bn);
}
}
else if(d instanceof VariantChanged){
if(phase==0 || phase==1 || phase==4){
VariantChanged d2=(VariantChanged)d;
if(phase==1 && d2.name!=null) continue;
else if(phase==4 && d2.name==null) continue;
if(d2.scope==null){
d2.scope=new HashSet<Topic>();
for(Object o : d2.scope2){
Topic s=getTopic(o,tm);
if(s==null){
if(!eHandler.handleException(new PatchException(PatchException.SEVERE,"Changing variant to "+d2.name+". Could not resolve scope topic "+o,t)))
return false;
continue Diff;
}
d2.scope.add(s);
}
}
String v=t.getVariant(d2.scope);
if( (v==null && d2.oldname!=null) || (v!=null && d2.oldname==null) ||
(v!=null && d2.oldname!=null && !v.equals(d2.oldname)) ) {
if( (v!=null && d2.name!=null && v.equals(d2.name)) || (v==null && d2.name==null)){
if(!eHandler.handleException(new PatchException(PatchException.MINOR,"Changing variant to "+d2.name+". Old variant is "+v+" expected "+d2.oldname,t)))
return false;
}
else if(!eHandler.handleException(new PatchException(PatchException.MODERATE,"Changing variant to "+d2.name+". Old variant is "+v+" expected "+d2.oldname,t)))
return false;
}
if(d2.name==null) t.removeVariant(d2.scope);
else t.setVariant(d2.scope, d2.name);
}
}
else if(d instanceof TypeAdded){
if(phase==0 || phase==4){
TypeAdded d2=(TypeAdded)d;
if(d2.t==null) d2.t=getTopic(d2.t2,tm);
if(d2.t==null){
if(!eHandler.handleException(new PatchException(PatchException.MODERATE,"Could not resolve added type topic "+d2.t2,t)))
return false;
}
else {
if(t.isOfType(d2.t))
if(!eHandler.handleException(new PatchException(PatchException.MINOR,"Topic is already of the added type "+d2.t2,t)))
return false;
t.addType(d2.t);
}
}
}
else if(d instanceof TypeDeleted){
if(phase==0 || phase==1){
TypeDeleted d2=(TypeDeleted)d;
if(d2.t==null) d2.t=getTopic(d2.t2,tm);
if(d2.t==null){
if(!eHandler.handleException(new PatchException(PatchException.MODERATE,"Could not resolve removed type topic "+d2.t2,t)))
return false;
}
else {
if(!t.isOfType(d2.t))
if(!eHandler.handleException(new PatchException(PatchException.MINOR,"Topic is not of the removed type "+d2.t2,t)))
return false;
t.removeType(d2.t);
}
}
}
}
return true;
}
public ArrayList<PatchException> applyDiff(ArrayList<DiffEntry> diff,TopicMap tm) throws TopicMapException {
final ArrayList<PatchException> ret=new ArrayList<PatchException>();
applyDiff(diff,tm,new PatchExceptionHandler(){
public boolean handleException(PatchException e){
ret.add(e);
return true;
}
});
return ret;
}
public void applyDiff(ArrayList<DiffEntry> diff,TopicMap tm,PatchExceptionHandler eHandler) throws TopicMapException {
/* Phases:
* 1 remove associations and variants and types in topics so we can then safely remove topics
* 2 remove topics so we can then safely apply other changes
* 3 create new topics, change old topics, but do only base names and subject identifiers
* 4 all needed topics are in now, do everything else
*/
for(int phase=1;phase<=4;phase++){
Diff: for(DiffEntry d : diff){
if(d instanceof TopicChanged){
if(phase==1 || phase==3 || phase==4){
TopicChanged d2=(TopicChanged)d;
if(d2.topic==null) d2.topic=getTopic(d2.topic2,tm);
if(d2.topic==null){
if(eHandler.handleException(new PatchException(PatchException.SEVERE,"Could not resolve changed topic "+d2.topic2)))
return;
}
else if(!applyTopicDiff(d2.diff,d2.topic,tm,phase,eHandler)) return;
}
}
else if(d instanceof TopicAdded){
TopicAdded d2=(TopicAdded)d;
if(phase==3){
Topic t=tm.createTopic();
if(!applyTopicDiff(d2.diff,t,tm,phase,eHandler)) return;
}
else if(phase==4){
Object o=getTopicIdentifier(d2.diff);
Topic t=getTopic(o,tm);
if(t==null) {
// this is critical since the topic should be there as it has been added earlier
// in other words, something strange is going on if this happens
if(eHandler.handleException(new PatchException(PatchException.CRITICAL,"Could not resolve added topic "+o)))
return;
}
else if(!applyTopicDiff(d2.diff,t,tm,phase,eHandler)) return;
}
}
else if(d instanceof TopicDeleted){
if(phase==1 || phase==2){
TopicDeleted d2=(TopicDeleted)d;
if(d2.topic==null) d2.topic=getTopic(d2.topic2,tm);
if(d2.topic==null) {
if(phase==1)
if(eHandler.handleException(new PatchException(PatchException.MINOR,"Could not find deleted topic "+d2.topic2)))
return;
}
else{
if(phase==1) {
if(!applyTopicDiff(d2.diff,d2.topic,tm,phase,eHandler)) return;
}
else {
try{
d2.topic.remove();
}catch(TopicInUseException tiue){
if(eHandler.handleException(new PatchException(PatchException.SEVERE,"Could not delete topic "+d2.topic2+". Topic is in use as a type or variant scope.")))
return;
}
}
}
}
}
else if(d instanceof AssociationAdded){
if(phase==4){
AssociationAdded d2=(AssociationAdded)d;
if(d2.a==null){
d2.a=new Topic[d2.a2.length];
for(int i=0;i<d2.a2.length;i++){
d2.a[i]=getTopic(d2.a2[i],tm);
if(d2.a[i]==null){
String type="player";
if(i==0) type="type";
else if((i%2)==1) type="role";
if(eHandler.handleException(new PatchException(PatchException.SEVERE,"Could not resolve association "+type+" topic "+d2.a2[i])))
return;
continue Diff;
}
}
}
if(getAssociation(d2.a2,tm)!=null){
if(eHandler.handleException(new PatchException(PatchException.MINOR,"Added association already exists.")))
return;
}
else{
Association a=tm.createAssociation(d2.a[0]);
for(int i=1;i+1<d2.a.length;i+=2){
a.addPlayer(d2.a[i+1], d2.a[i]);
}
}
}
}
else if(d instanceof AssociationDeleted){
if(phase==1){
AssociationDeleted d2=(AssociationDeleted)d;
if(d2.a==null) d2.a=getAssociation(d2.a2,tm);
if(d2.a==null){
if(eHandler.handleException(new PatchException(PatchException.MINOR,"Could not find deleted association.")))
return;
}
else d2.a.remove();
}
}
}
}
}
public Object getTopicIdentifier(Topic t) throws TopicMapException {
String bn=t.getBaseName();
if(bn!=null) return bn;
else return t.getOneSubjectIdentifier();
}
public ArrayList<TopicDiffEntry> makeInverseTopicDiff(ArrayList<TopicDiffEntry> diff) throws TopicMapException {
ArrayList<TopicDiffEntry> inverse=new ArrayList<TopicDiffEntry>();
for(TopicDiffEntry d : diff){
if(d instanceof SIAdded){
SIAdded d2=(SIAdded)d;
inverse.add(new SIDeleted(d2.si));
}
else if(d instanceof SIDeleted){
SIDeleted d2=(SIDeleted)d;
inverse.add(new SIAdded(d2.si));
}
else if(d instanceof SLChanged){
SLChanged d2=(SLChanged)d;
inverse.add(new SLChanged(d2.oldsl,d2.sl));
}
else if(d instanceof BNChanged){
BNChanged d2=(BNChanged)d;
inverse.add(new BNChanged(d2.oldbn,d2.bn));
}
else if(d instanceof VariantChanged){
VariantChanged d2=(VariantChanged)d;
Set<Object> scope=d2.scope2;
if(scope==null){
scope=new HashSet<Object>();
for(Topic t : d2.scope){
scope.add(getTopicIdentifier(t));
}
}
inverse.add(new VariantChanged(scope,d2.oldname,d2.name,true));
}
else if(d instanceof TypeAdded){
TypeAdded d2=(TypeAdded)d;
if(d2.t2!=null) inverse.add(new TypeDeleted(d2.t2));
else inverse.add(new TypeDeleted(getTopicIdentifier(d2.t)));
}
else if(d instanceof TypeDeleted){
TypeDeleted d2=(TypeDeleted)d;
if(d2.t2!=null) inverse.add(new TypeAdded(d2.t2));
else inverse.add(new TypeAdded(getTopicIdentifier(d2.t)));
}
}
return inverse;
}
public ArrayList<DiffEntry> makeInverse(ArrayList<DiffEntry> diff) throws TopicMapException {
ArrayList<DiffEntry> inverse=new ArrayList<DiffEntry>();
for(DiffEntry d : diff){
if(d instanceof TopicChanged){
TopicChanged d2=(TopicChanged)d;
if(d2.topic2!=null) inverse.add(new TopicChanged(d2.topic2,makeInverseTopicDiff(d2.diff)));
else inverse.add(new TopicChanged(getTopicIdentifier(d2.topic),makeInverseTopicDiff(d2.diff)));
}
else if(d instanceof TopicAdded){
TopicAdded d2=(TopicAdded)d;
inverse.add(new TopicDeleted(getTopicIdentifier(d2.diff),makeInverseTopicDiff(d2.diff)));
}
else if(d instanceof TopicDeleted){
TopicDeleted d2=(TopicDeleted)d;
inverse.add(new TopicAdded(makeInverseTopicDiff(d2.diff)));
}
else if(d instanceof AssociationAdded){
AssociationAdded d2=(AssociationAdded)d;
if(d2.a2!=null) inverse.add(new AssociationDeleted(d2.a2));
else inverse.add(new AssociationDeleted(d2.a));
}
else if(d instanceof AssociationDeleted){
AssociationDeleted d2=(AssociationDeleted)d;
if(d2.a2!=null) inverse.add(new AssociationAdded(d2.a2));
else inverse.add(new AssociationAdded(d2.a));
}
}
return inverse;
}
public ArrayList<PatchException> tryTopicDiff(ArrayList<TopicDiffEntry> diff,Topic t,TopicMap tm,int phase,HashSet<Object> addedTopics,HashSet<Object> deletedTopics) throws TopicMapException {
ArrayList<PatchException> ret=new ArrayList<PatchException>();
for(TopicDiffEntry d : diff){
if(d instanceof SIAdded){
if(phase==0 || phase==3){
SIAdded d2=(SIAdded)d;
Object o=tryGetTopic(d2.si, tm, addedTopics, deletedTopics);
if(o!=null){
ret.add(new PatchException(PatchException.SEVERE,
"Adding subject identifier "+d2.si+" would cause a topic merge.",t));
}
if(t.getSubjectIdentifiers().contains(d2.si)){
ret.add(new PatchException(PatchException.MINOR,
"Topic already contains subject identifier "+d2.si,t));
}
addedTopics.add(d2.si);
}
}
else if(d instanceof SIDeleted){
if(phase==0 || phase==3){
SIDeleted d2=(SIDeleted)d;
if(!t.getSubjectIdentifiers().contains(d2.si)){
ret.add(new PatchException(PatchException.MINOR,
"Topic does not contains deleted subject identifier "+d2.si,t));
}
deletedTopics.add(d2.si);
}
}
else if(d instanceof SLChanged){
if(phase==0 || phase==4){
SLChanged d2=(SLChanged)d;
Topic o=tm.getTopicBySubjectLocator(d2.sl);
if(o!=null){
ret.add(new PatchException(PatchException.SEVERE,
"Setting subject locator "+d2.sl+" would cause a topic merge.",t));
}
if( (d2.oldsl==null && t.getSubjectLocator()!=null) ||
(d2.oldsl!=null && (t.getSubjectLocator()==null || !d2.oldsl.equals(t.getSubjectLocator())) ) ) {
ret.add(new PatchException(PatchException.MODERATE,
"Old subject locator is "+t.getSubjectLocator()+", expected "+d2.oldsl,t));
}
}
}
else if(d instanceof BNChanged){
if(phase==0 || phase==3){
BNChanged d2=(BNChanged)d;
Topic o=tm.getTopicWithBaseName(d2.bn);
if(o!=null){
ret.add(new PatchException(PatchException.SEVERE,
"Setting base name "+d2.bn+" would cause a topic merge.",t));
}
if( (d2.oldbn==null && t.getBaseName()!=null) ||
(d2.oldbn!=null && (t.getBaseName()==null || !d2.oldbn.equals(t.getBaseName())) ) ) {
ret.add(new PatchException(PatchException.MODERATE,
"Old base name is "+t.getBaseName()+", expected "+d2.oldbn,t));
}
if(d2.bn!=null) addedTopics.add(d2.bn);
if(d2.oldbn!=null) deletedTopics.add(d2.oldbn);
}
}
else if(d instanceof VariantChanged){
if(phase==0 || phase==1 || phase==4){
VariantChanged d2=(VariantChanged)d;
if(phase==1 && d2.name!=null) continue;
else if(phase==4 && d2.name==null) continue;
HashSet<Topic> scope=new HashSet<Topic>();
for(Object o : d2.scope2){
Object u=tryGetTopic(o,tm,addedTopics,deletedTopics);
if(u==null){
ret.add(new PatchException(PatchException.MODERATE,
"Could not resolve variant scope.",t));
}
if(u!=null && scope!=null && u instanceof Topic) {
scope.add((Topic)u);
}
else scope=null;
}
if(scope!=null){
String v=t.getVariant(scope);
if( (d2.oldname==null && v!=null) ||
(d2.oldname!=null && (v==null || !d2.oldname.equals(v)) ) ) {
ret.add(new PatchException(PatchException.MODERATE,
"Old variant name is "+v+", expected "+d2.oldname,t));
}
}
}
}
else if(d instanceof TypeAdded){
if(phase==0 || phase==4){
TypeAdded d2=(TypeAdded)d;
Object o=tryGetTopic(d2.t2,tm,addedTopics,deletedTopics);
if(o==null){
ret.add(new PatchException(PatchException.MODERATE,
"Could not resolve added type "+d2.t2,t));
}
else if(o instanceof Topic && t.isOfType((Topic)o)){
ret.add(new PatchException(PatchException.MINOR,
"Topic is already of the added type "+d2.t2,t));
}
}
}
else if(d instanceof TypeDeleted){
if(phase==0 || phase==1){
TypeDeleted d2=(TypeDeleted)d;
Object o=tryGetTopic(d2.t2,tm,addedTopics,deletedTopics);
if(o==null){
ret.add(new PatchException(PatchException.MODERATE,
"Could not resolve removed type "+d2.t2,t));
}
else if(o instanceof Topic && !t.isOfType((Topic)o)){
ret.add(new PatchException(PatchException.MINOR,
"Topic is not of the removed type "+d2.t2,t));
}
}
}
}
return ret;
}
public Object tryGetTopic(Object identifier,TopicMap tm,HashSet<Object> added,HashSet<Object> deleted) throws TopicMapException {
if(deleted.contains(identifier)){
if(added.contains(identifier)) return Boolean.TRUE;
else return null;
}
if(added.contains(identifier)) return Boolean.TRUE;
Topic t=getTopic(identifier,tm);
return t;
}
public ArrayList<PatchException> tryPatch(ArrayList<DiffEntry> diff,TopicMap tm) throws TopicMapException {
ArrayList<PatchException> ret=new ArrayList<PatchException>();
/* Phases:
* 1 remove associations and variants and types in topics so we can then safely remove topics
* 2 remove topics so we can then safely apply other changes
* 3 create new topics, change old topics, but do only base names and subject identifiers
* 4 all needed topics are in now, do everything else
*/
HashSet<Object> addedTopics=new HashSet<Object>();
HashSet<Object> deletedTopics=new HashSet<Object>();
for(int phase=1;phase<=4;phase++){
for(DiffEntry d : diff){
if(d instanceof TopicChanged){
if(phase==1 || phase==3 || phase==4){
TopicChanged d2=(TopicChanged)d;
Object t=tryGetTopic(d2.topic2,tm,addedTopics,deletedTopics);
if(t==null){
ret.add(new PatchException(PatchException.SEVERE,
"Could not resolve changed topic "+d2.topic2));
}
if(t instanceof Topic)
ret.addAll(tryTopicDiff(d2.diff,(Topic)t,tm,phase,addedTopics,deletedTopics));
}
}
else if(d instanceof TopicAdded){
TopicAdded d2=(TopicAdded)d;
if(phase==3){
ret.addAll(tryTopicDiff(d2.diff,null,tm,phase,addedTopics,deletedTopics));
}
else if(phase==4){
Object o=getTopicIdentifier(d2.diff);
Object t=tryGetTopic(o,tm,addedTopics,deletedTopics);
if(t==null){
ret.add(new PatchException(PatchException.CRITICAL,
"Could not resolve added topic"));
}
if(t instanceof Topic)
ret.addAll(tryTopicDiff(d2.diff,(Topic)t,tm,phase,addedTopics,deletedTopics));
}
}
else if(d instanceof TopicDeleted){
if(phase==1 || phase==2){
TopicDeleted d2=(TopicDeleted)d;
Object t=tryGetTopic(d2.topic2,tm,addedTopics,deletedTopics);
if(t==null){
ret.add(new PatchException(PatchException.MINOR,
"Could not resolve deleted topic "+d2.topic2));
}
if(t instanceof Topic) {
deletedTopics.addAll(((Topic)t).getSubjectIdentifiers());
if(((Topic)t).getBaseName()!=null) deletedTopics.add(((Topic)t).getBaseName());
tryTopicDiff(d2.diff,(Topic)t,tm,phase,addedTopics,deletedTopics);
// tryTopicDiff checks if all changes in d2.diff are in the deleted topic
// need to also check if topic contains something not in d2.diff
}
}
}
else if(d instanceof AssociationAdded){
if(phase==4){
AssociationAdded d2=(AssociationAdded)d;
for(int i=0;i<d2.a2.length;i++){
Object t=tryGetTopic(d2.a2[i],tm,addedTopics,deletedTopics);
if(t==null){
if(i==0)
ret.add(new PatchException(PatchException.SEVERE,
"Could not resolve association type "+d2.a2[i]));
else if((i%2)==1)
ret.add(new PatchException(PatchException.SEVERE,
"Could not resolve association role "+d2.a2[i]));
else
ret.add(new PatchException(PatchException.SEVERE,
"Could not resolve association player "+d2.a2[i]));
}
}
}
}
else if(d instanceof AssociationDeleted){
if(phase==1){
AssociationDeleted d2=(AssociationDeleted)d;
Association a=getAssociation(d2.a2,tm);
if(a==null){
ret.add(new PatchException(PatchException.MINOR,
"Could not resolve deleted association"));
}
}
}
}
}
return ret;
}
public static interface PatchExceptionHandler {
public boolean handleException(PatchException e);
}
public static class PatchException {
/** Minor inconsistency with patch. For example changes that seem to
* have been already made. */
public static final int MINOR=1;
/** Moderate inconsistency with patch.
* Changes are still patched but some old values may be overwritten that
* were not there when the patch was made. This may indicate conflicting
* edits in the topic map. Unexpected merging of topics will also cause
* a warning of this level. */
public static final int MODERATE=2;
/** Severe inconsistency with patch. Unable to make changes described in
* the patch because the topic map is incompatible with the patch. */
public static final int SEVERE=3;
/** Critical failure with patch. */
public static final int CRITICAL=4;
public int level;
public String message;
public Object context;
public PatchException(int level,String message){
this(level,message,null);
}
public PatchException(int level,String message,Object context){
this.level=level;
this.message=message;
this.context=context;
}
}
public abstract static class DiffEntry {
}
public static class TopicChanged extends DiffEntry{
public Topic topic;
public Object topic2;
public ArrayList<TopicDiffEntry> diff;
public TopicChanged(){}
public TopicChanged(Topic topic,ArrayList<TopicDiffEntry> diff){
this.topic=topic;
this.diff=diff;
}
public TopicChanged(Object topic2,ArrayList<TopicDiffEntry> diff){
this.topic2=topic2;
this.diff=diff;
}
}
public static class TopicDeleted extends DiffEntry{
public Topic topic;
public Object topic2;
public ArrayList<TopicDiffEntry> diff;
public TopicDeleted(){}
public TopicDeleted(Topic topic,ArrayList<TopicDiffEntry> diff){
this.topic=topic;
this.diff=diff;
}
public TopicDeleted(Object topic2,ArrayList<TopicDiffEntry> diff){
this.topic2=topic2;
this.diff=diff;
}
}
public static class TopicAdded extends DiffEntry{
public ArrayList<TopicDiffEntry> diff;
public TopicAdded(){}
public TopicAdded(ArrayList<TopicDiffEntry> diff){this.diff=diff;}
}
public abstract static class TopicDiffEntry {
}
public static class SIAdded extends TopicDiffEntry {
public Locator si;
public SIAdded(){}
public SIAdded(Locator si){this.si=si;}
}
public static class SIDeleted extends TopicDiffEntry {
public Locator si;
public SIDeleted(){}
public SIDeleted(Locator si){this.si=si;}
}
public static class TypeAdded extends TopicDiffEntry {
public Topic t;
public Object t2;
public TypeAdded(){}
public TypeAdded(Topic t){this.t=t;}
public TypeAdded(Object t2){this.t2=t2;}
}
public static class TypeDeleted extends TopicDiffEntry {
public Topic t;
public Object t2;
public TypeDeleted(){}
public TypeDeleted(Topic t){this.t=t;}
public TypeDeleted(Object t2){this.t2=t2;}
}
public static class SLChanged extends TopicDiffEntry {
public Locator sl;
public Locator oldsl;
public SLChanged(){}
public SLChanged(Locator sl,Locator oldsl){
this.sl=sl;
this.oldsl=oldsl;
}
}
public static class BNChanged extends TopicDiffEntry {
public String bn;
public String oldbn;
public BNChanged(){}
public BNChanged(String bn,String oldbn){
this.bn=bn;
this.oldbn=oldbn;
}
}
public static class VariantChanged extends TopicDiffEntry {
public Set<Topic> scope;
public Set<Object> scope2;
public String name;
public String oldname;
public VariantChanged(){}
public VariantChanged(Set<Topic> scope,String name,String oldname){
this.scope=scope;
this.name=name;
this.oldname=oldname;
}
public VariantChanged(Set<Object> scope2,String name,String oldname,boolean dummy){
// dummy only to get different method signature
this.scope2=scope2;
this.name=name;
this.oldname=oldname;
}
}
public static class AssociationDeleted extends DiffEntry {
public Association a;
public Object[] a2;
public AssociationDeleted(){}
public AssociationDeleted(Association a){this.a=a;}
public AssociationDeleted(Object[] a2){
this.a2=a2;
}
}
public static class AssociationAdded extends DiffEntry {
public Topic[] a;
public Object[] a2;
public AssociationAdded(){}
public AssociationAdded(Association association) throws TopicMapException {
a=new Topic[association.getRoles().size()*2+1];
a[0]=association.getType();
int i=1;
for(Topic r : association.getRoles()){
a[i++]=r;
a[i++]=association.getPlayer(r);
}
}
public AssociationAdded(Topic[] a){this.a=a;}
public AssociationAdded(Object[] a2){
this.a2=a2;
}
}
//////// Command line tool //////////////
public static TopicMap openFile(String f) throws IOException, TopicMapException {
String extension="";
int ind=f.lastIndexOf(".");
if(ind>-1) extension=f.substring(ind+1);
if(extension.equalsIgnoreCase("wpr")){
PackageInput in=new ZipPackageInput(f);
TopicMapType type=TopicMapTypeManager.getType(LayerStack.class);
TopicMap tm=type.unpackageTopicMap(in,"",null,null);
in.close();
return tm;
}
else if(extension.equalsIgnoreCase("ltm")){
TopicMap tm=new TopicMapImpl();
tm.importLTM(f);
return tm;
}
else{ // xtm
TopicMap tm=new TopicMapImpl();
tm.importXTM(f);
return tm;
}
}
public static void printUsage(){
System.out.println("java org.wandora.topicmap.diff.DiffTool <command> <options>");
System.out.println("Commands:");
System.out.println(" c Compare two topic maps.");
System.out.println(" p Patch a topic map.");
System.out.println(" P Perform an inverse patch.");
System.out.println(" i Inverse a patch file.");
System.out.println(" h Calculate a hash code for a topic map.");
System.out.println("Options:");
System.out.println(" <filename> Input file. For comparison enter two topic maps.");
System.out.println(" For patching enter a topic map and a patch file in that order.");
System.out.println(" For hash code enter a single topic map.");
System.out.println(" -o Output in the specified file.");
System.out.println(" -e Character encoding for patch files, default is UTF-8.");
}
public static void main(String[] args) throws Exception {
if(args.length<1){
printUsage();
return;
}
char cmd=args[0].charAt(0);
String encoding="UTF-8";
String file1=null;
String file2=null;
String outfile=null;
for(int i=1;i<args.length;i++){
if(args[i].equals("-o")){
if(i+1<args.length) {
outfile=args[i+1];
i++;
}
else {
printUsage();
return;
}
}
else if(file1==null) file1=args[i];
else if(file2==null) file2=args[i];
else {
printUsage();
return;
}
}
if(cmd=='c'){
if(file1==null || file2==null){
printUsage();
return;
}
TopicMap tm1=openFile(file1);
TopicMap tm2=openFile(file2);
TopicMapDiff tmDiff=new TopicMapDiff();
Writer out=null;
if(outfile!=null) out=new OutputStreamWriter(new FileOutputStream(outfile),encoding);
else out=new OutputStreamWriter(System.out);
tmDiff.makeDiff(tm1, tm2, new BasicDiffOutput(new PatchDiffEntryFormatter(),out));
out.close();
}
else if(cmd=='p' || cmd=='P'){
if(file1==null || file2==null){
printUsage();
return;
}
TopicMap tm1=openFile(file1);
PatchDiffParser parser=new PatchDiffParser(new InputStreamReader(new FileInputStream(file2),encoding));
ArrayList<DiffEntry> diff=parser.parse();
TopicMapDiff tmDiff=new TopicMapDiff();
if(cmd=='P') diff=tmDiff.makeInverse(diff);
tmDiff.applyDiff(diff, tm1);
OutputStream out=null;
if(outfile!=null) out=new FileOutputStream(outfile);
else out=System.out;
tm1.exportXTM(out);
out.close();
}
else if(cmd=='i'){
if(file1==null || file2!=null){
printUsage();
return;
}
PatchDiffParser parser=new PatchDiffParser(new InputStreamReader(new FileInputStream(file1),encoding));
ArrayList<DiffEntry> diff=parser.parse();
TopicMapDiff tmDiff=new TopicMapDiff();
diff=tmDiff.makeInverse(diff);
Writer out=null;
if(outfile!=null) out=new OutputStreamWriter(new FileOutputStream(outfile),encoding);
else out=new OutputStreamWriter(System.out);
BasicDiffOutput diffOut=new BasicDiffOutput(new PatchDiffEntryFormatter(),out);
diffOut.outputDiff(diff);
out.close();
}
else if(cmd=='h'){
if(file1==null || file2!=null){
printUsage();
return;
}
TopicMap tm1=openFile(file1);
long hash=TopicMapHashCode.getTopicMapHashCode(tm1);
System.out.println(Long.toHexString(hash));
}
}
}
| 54,324 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ListDiffOutput.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/diff/ListDiffOutput.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.wandora.topicmap.diff;
import java.util.ArrayList;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
/**
*
* @author olli
*/
public class ListDiffOutput implements DiffOutput {
private ArrayList<TopicMapDiff.DiffEntry> diff;
public ListDiffOutput(){
diff=new ArrayList<TopicMapDiff.DiffEntry>();
}
public void startCompare(){}
public void endCompare(){}
public boolean outputDiffEntry(TopicMapDiff.DiffEntry d){
diff.add(d);
return true;
}
public boolean noDifferences(Topic t){
return true;
}
public boolean noDifferences(Association a){
return true;
}
public ArrayList<TopicMapDiff.DiffEntry> getList(){
return diff;
}
}
| 1,564 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
PatchDiffParser.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/diff/PatchDiffParser.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.wandora.topicmap.diff;
import java.io.IOException;
import java.io.PushbackReader;
import java.io.Reader;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.diff.TopicMapDiff.AssociationAdded;
import org.wandora.topicmap.diff.TopicMapDiff.AssociationDeleted;
import org.wandora.topicmap.diff.TopicMapDiff.BNChanged;
import org.wandora.topicmap.diff.TopicMapDiff.DiffEntry;
import org.wandora.topicmap.diff.TopicMapDiff.SIAdded;
import org.wandora.topicmap.diff.TopicMapDiff.SIDeleted;
import org.wandora.topicmap.diff.TopicMapDiff.SLChanged;
import org.wandora.topicmap.diff.TopicMapDiff.TopicAdded;
import org.wandora.topicmap.diff.TopicMapDiff.TopicChanged;
import org.wandora.topicmap.diff.TopicMapDiff.TopicDeleted;
import org.wandora.topicmap.diff.TopicMapDiff.TopicDiffEntry;
import org.wandora.topicmap.diff.TopicMapDiff.TypeAdded;
import org.wandora.topicmap.diff.TopicMapDiff.TypeDeleted;
import org.wandora.topicmap.diff.TopicMapDiff.VariantChanged;
/**
*
* @author olli
*/
public class PatchDiffParser {
protected int line;
protected PushbackReader reader;
public PatchDiffParser(PushbackReader reader){
this.reader=reader;
this.line=1;
}
public PatchDiffParser(Reader reader){
this(new PushbackReader(reader));
}
public ArrayList<DiffEntry> parse() throws IOException,ParseException {
ArrayList<DiffEntry> ret=new ArrayList<DiffEntry>();
DiffEntry d=null;
while( (d=parseEntry())!=null ){
ret.add(d);
}
return ret;
}
protected DiffEntry parseEntry() throws IOException,ParseException {
int mode=reader.read();
int type=reader.read();
if(mode==-1) return null;
else if(type==-1) throw new ParseException("Unexpected EOF, expecting diff entry type",line);
DiffEntry ret=null;
if(type=='T'){
readChar('[');
Object topic=null;
if(mode!='+') topic=readTopicIdentifier();
readEOL();
ArrayList<TopicDiffEntry> tDiff=readTopicDiff();
if(mode=='+') ret=new TopicAdded(tDiff);
else if(mode=='-') ret=new TopicDeleted(topic,tDiff);
else if(mode=='*') ret=new TopicChanged(topic,tDiff);
else throw new ParseException("Unknown mode for topic diff entry "+(char)mode,line);
}
else if(type=='A'){
readChar('[');
Object[] a=readAssociation();
if(mode=='+') ret=new AssociationAdded(a);
else if(mode=='-') ret=new AssociationDeleted(a);
else throw new ParseException("Unknown mode for association diff entry "+(char)mode,line);
}
else throw new ParseException("Unknown diff entry type "+(char)type,line);
readEOL();
return ret;
}
protected ArrayList<TopicDiffEntry> readTopicDiff() throws IOException,ParseException {
ArrayList<TopicDiffEntry> ret=new ArrayList<TopicDiffEntry>();
while(true){
int mode=reader.read();
if(mode==-1) throw new ParseException("Unexpected EOF, reading topic diff entry",line);
else if(mode==']') break;
else{
int type=reader.read();
if(type==-1) throw new ParseException("Unexpected EOF, reading type for topic diff entry",line);
else if(type=='I'){
String s=readQuotedString();
Locator l=new Locator(s);
if(mode=='-') ret.add(new SIDeleted(l));
else if(mode=='+') ret.add(new SIAdded(l));
else throw new ParseException("Invalid mode \""+(char)mode+"\" for subject identifier topic diff entry",line);
readEOL();
}
else if(type=='L'){
String s=readQuotedString();
Locator l=new Locator(s);
if(mode=='-') ret.add(new SLChanged(null,l));
else if(mode=='+') ret.add(new SLChanged(l,null));
else if(mode=='*') {
readChar('/');
String s2=readQuotedString();
Locator l2=new Locator(s2);
ret.add(new SLChanged(l,l2));
}
else throw new ParseException("Invalid mode \""+(char)mode+"\" for subject locator topic diff entry",line);
readEOL();
}
else if(type=='B'){
String s=readQuotedString();
if(mode=='-') ret.add(new BNChanged(null,s));
else if(mode=='+') ret.add(new BNChanged(s,null));
else if(mode=='*') {
readChar('/');
String s2=readQuotedString();
ret.add(new BNChanged(s,s2));
}
else throw new ParseException("Invalid mode \""+(char)mode+"\" for base name topic diff entry",line);
readEOL();
}
else if(type=='V'){
readChar('{');
Set<Object> scope=readScope();
String s=readQuotedString();
if(mode=='-') ret.add(new VariantChanged(scope,null,s,false));
else if(mode=='+') ret.add(new VariantChanged(scope,s,null,false));
else if(mode=='*') {
readChar('/');
String s2=readQuotedString();
ret.add(new VariantChanged(scope,s,s2,false));
}
else throw new ParseException("Invalid mode \""+(char)mode+"\" for variant topic diff entry",line);
readEOL();
}
else if(type=='T'){
Object topic=readTopicIdentifier();
if(mode=='-') ret.add(new TypeDeleted(topic));
else if(mode=='+') ret.add(new TypeAdded(topic));
else throw new ParseException("Invalid mode \""+(char)mode+"\" for type topic diff entry",line);
readEOL();
}
else throw new ParseException("Unknown topic diff type "+(char)type,line);
}
}
return ret;
}
protected HashSet<Object> readScope() throws IOException,ParseException {
HashSet<Object> ret=new HashSet<Object>();
while(true){
Object o=readTopicIdentifier();
ret.add(o);
int c=reader.read();
if(c=='}') break;
else if(c!=' ') throw new ParseException("Unexpected char \""+(char)c+"\" while reading scope, expecting space",line);
}
return ret;
}
protected Object[] readAssociation() throws IOException,ParseException {
Object atype=readTopicIdentifier();
readEOL();
ArrayList<Object> playersAndRoles=new ArrayList<Object>();
while(true){
int peek=reader.read();
if(peek==']') break;
else reader.unread(peek);
Object r=readTopicIdentifier();
readChar(':');
Object p=readTopicIdentifier();
playersAndRoles.add(r);
playersAndRoles.add(p);
readEOL();
}
Object[] ret=new Object[playersAndRoles.size()+1];
ret[0]=atype;
for(int i=0;i<playersAndRoles.size();i++){
ret[i+1]=playersAndRoles.get(i);
}
return ret;
}
protected Object readTopicIdentifier() throws IOException,ParseException {
int type=reader.read();
if(type==-1) throw new ParseException("Unexpected EOF, reading topic identifier",line);
else if(type=='B'){
String s=readQuotedString();
return s;
}
else if(type=='I'){
String s=readQuotedString();
return new Locator(s);
}
else throw new ParseException("Unknown topic idetnifier type "+(char)type,line);
}
protected String readQuotedString() throws IOException,ParseException {
int r=reader.read();
if(r!='"') throw new ParseException("Expecting \"",line);
StringBuffer read=new StringBuffer();
boolean escape=false;
while(true){
r=reader.read();
if(r==-1) throw new ParseException("Unexpected EOF, reading quoted string",line);
else if(r=='\\' && !escape) {
escape=true;
continue;
}
else if(r=='"' && !escape) break;
else read.append((char)r);
}
return read.toString();
}
protected void readChar(char c) throws IOException,ParseException {
int r=reader.read();
if(r!=c) throw new ParseException("Expecting "+c,line);
}
protected void readEOL() throws IOException,ParseException {
int c=reader.read();
if(c==0x0d) c=reader.read();
if(c!=0x0a) throw new ParseException("Expecting end of line",line);
line++;
}
}
| 10,212 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
DiffOutput.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/diff/DiffOutput.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.wandora.topicmap.diff;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
/**
*
* @author olli
*/
public interface DiffOutput {
public void startCompare();
public void endCompare();
public boolean outputDiffEntry(TopicMapDiff.DiffEntry d);
public boolean noDifferences(Topic t);
public boolean noDifferences(Association a);
}
| 1,185 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
DiffEntryFormatter.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/diff/DiffEntryFormatter.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.wandora.topicmap.diff;
import java.io.IOException;
import java.io.Writer;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author olli
*/
public interface DiffEntryFormatter {
public void header(Writer writer) throws IOException, TopicMapException;
public void footer(Writer writer) throws IOException, TopicMapException;
public void formatDiffEntry(TopicMapDiff.DiffEntry entry,Writer writer) throws IOException,TopicMapException ;
}
| 1,270 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
PlainTextDiffEntryFormatter.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/topicmap/diff/PlainTextDiffEntryFormatter.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.wandora.topicmap.diff;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
import org.wandora.topicmap.diff.TopicMapDiff.AssociationAdded;
import org.wandora.topicmap.diff.TopicMapDiff.AssociationDeleted;
import org.wandora.topicmap.diff.TopicMapDiff.BNChanged;
import org.wandora.topicmap.diff.TopicMapDiff.DiffEntry;
import org.wandora.topicmap.diff.TopicMapDiff.SIAdded;
import org.wandora.topicmap.diff.TopicMapDiff.SIDeleted;
import org.wandora.topicmap.diff.TopicMapDiff.SLChanged;
import org.wandora.topicmap.diff.TopicMapDiff.TopicAdded;
import org.wandora.topicmap.diff.TopicMapDiff.TopicChanged;
import org.wandora.topicmap.diff.TopicMapDiff.TopicDeleted;
import org.wandora.topicmap.diff.TopicMapDiff.TopicDiffEntry;
import org.wandora.topicmap.diff.TopicMapDiff.TypeAdded;
import org.wandora.topicmap.diff.TopicMapDiff.TypeDeleted;
import org.wandora.topicmap.diff.TopicMapDiff.VariantChanged;
/**
*
* @author olli
*/
public class PlainTextDiffEntryFormatter implements DiffEntryFormatter {
private boolean nochanges;
public PlainTextDiffEntryFormatter() {
nochanges=true;
}
protected void formatTopicDiffEntry(ArrayList<TopicDiffEntry> diff,Writer writer) throws IOException,TopicMapException {
for(TopicDiffEntry d : diff) {
if(d instanceof SIAdded) {
writer.write("Added subject identifier "+((SIAdded)d).si+"\n");
}
else if(d instanceof SIDeleted) {
writer.write("Deleted subject identifier "+((SIDeleted)d).si+"\n");
}
else if(d instanceof SLChanged) {
Locator l=((SLChanged)d).sl;
Locator ol=((SLChanged)d).oldsl;
if(l!=null) {
if(ol==null) writer.write("Added subject locator "+l+"\n");
else writer.write("Changed subject locator from "+ol+" to "+l+"\n");
}
else writer.write("Deleted subject locator "+ol+"\n");
}
else if(d instanceof BNChanged) {
String bn=((BNChanged)d).bn;
String oldbn=((BNChanged)d).oldbn;
if(bn!=null) {
if(oldbn==null) writer.write("Added base name \""+bn+"\"\n");
else writer.write("Changed base name from \""+oldbn+"\" to \""+bn+"\"\n");
}
else writer.write("Deleted base name \""+oldbn+"\"\n");
}
else if(d instanceof TypeAdded) {
Topic t=((TypeAdded)d).t;
Object t2=((TypeAdded)d).t2;
writer.write("Added type "+formatTopic(t,t2)+"\n");
}
else if(d instanceof TypeDeleted) {
Topic t=((TypeDeleted)d).t;
Object t2=((TypeDeleted)d).t2;
writer.write("Deleted type "+formatTopic(t,t2)+"\n");
}
else if(d instanceof VariantChanged){
VariantChanged vc=(VariantChanged)d;
String v=vc.name;
String oldv=vc.oldname;
StringBuffer scopeString=new StringBuffer("{");
if(vc.scope!=null) {
for(Topic t : vc.scope) {
if(scopeString.length()>1) scopeString.append(", ");
scopeString.append(formatTopic(t,null));
}
}
else {
for(Object t : vc.scope2) {
if(scopeString.length()>1) scopeString.append(", ");
scopeString.append(formatTopic(null,t));
}
}
scopeString.append("}");
if(v!=null) {
if(oldv==null) writer.write("Added variant "+scopeString+" \""+v+"\"\n");
else writer.write("Changed variant "+scopeString+" from \""+oldv+"\" to \""+v+"\"\n");
}
else writer.write("Deleted variant "+scopeString+" \""+oldv+"\"\n");
}
}
}
protected String formatTopic(Topic t, Object identifier) throws TopicMapException {
if(t!=null) {
String bn=t.getBaseName();
if(bn!=null) return "\""+bn+"\"";
else {
Locator si = t.getOneSubjectIdentifier();
if(si != null) return si.toString();
else return "***null***";
}
}
else {
if(identifier instanceof Locator) return identifier.toString();
else return "\""+identifier.toString()+"\"";
}
}
protected void formatAssociation(Association a, Writer writer) throws IOException,TopicMapException {
Topic type=a.getType();
writer.write("Type: "+formatTopic(type,null)+"\n");
for(Topic role : a.getRoles()){
writer.write(formatTopic(role,null)+": "+formatTopic(a.getPlayer(role),null)+"\n");
}
}
protected void formatAssociation(Topic[] a, Writer writer) throws IOException,TopicMapException {
Topic type=a[0];
writer.write("Type: "+formatTopic(type,null)+"\n");
for(int i=1;i+1<a.length;i+=2) {
Topic role=a[i];
Topic player=a[i+1];
writer.write(formatTopic(role,null)+": "+formatTopic(player,null)+"\n");
}
}
protected void formatAssociation(Object[] a, Writer writer) throws IOException,TopicMapException {
Object type=a[0];
writer.write("Type: "+formatTopic(null,type)+"\n");
for(int i=1;i+1<a.length;i+=2) {
Object role=a[i];
Object player=a[i+1];
writer.write(formatTopic(null,role)+": "+formatTopic(null,player)+"\n");
}
}
@Override
public void header(Writer writer) throws IOException, TopicMapException{
}
@Override
public void footer(Writer writer) throws IOException, TopicMapException{
if(nochanges){
writer.write("No differences");
}
}
@Override
public void formatDiffEntry(DiffEntry entry,Writer writer) throws IOException,TopicMapException {
nochanges=false;
if(entry instanceof TopicChanged) {
Topic t=((TopicChanged)entry).topic;
Object t2=((TopicChanged)entry).topic2;
ArrayList<TopicDiffEntry> diff=((TopicChanged)entry).diff;
writer.write("\nChanged topic "+formatTopic(t,t2)+"\n");
formatTopicDiffEntry(diff,writer);
}
else if(entry instanceof TopicDeleted) {
Topic t=((TopicDeleted)entry).topic;
Object t2=((TopicDeleted)entry).topic2;
writer.write("\nDeleted topic "+formatTopic(t,t2)+"\n");
}
else if(entry instanceof TopicAdded) {
ArrayList<TopicDiffEntry> diff=((TopicAdded)entry).diff;
String bn=null;
Locator si=null;
for(TopicDiffEntry e : diff) {
if(e instanceof BNChanged) {
bn=((BNChanged)e).bn;
break;
}
else if(si==null && e instanceof SIAdded) {
si=((SIAdded)e).si;
}
}
if(bn!=null) writer.write("\nAdded topic \""+bn+"\"\n");
else writer.write("\nAdded topic "+si+"\n");
formatTopicDiffEntry(diff,writer);
}
else if(entry instanceof AssociationAdded) {
writer.write("\nAdded association\n");
if(((AssociationAdded)entry).a!=null)
formatAssociation(((AssociationAdded)entry).a,writer);
else
formatAssociation(((AssociationAdded)entry).a2,writer);
}
else if(entry instanceof AssociationDeleted) {
writer.write("\nDeleted association\n");
if(((AssociationDeleted)entry).a!=null)
formatAssociation(((AssociationDeleted)entry).a,writer);
else
formatAssociation(((AssociationDeleted)entry).a2,writer);
}
}
}
| 9,292 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.