file_id
stringlengths 5
10
| content
stringlengths 110
36.3k
| repo
stringlengths 7
108
| path
stringlengths 8
198
| token_length
int64 37
8.19k
| original_comment
stringlengths 11
5.72k
| comment_type
stringclasses 2
values | detected_lang
stringclasses 1
value | prompt
stringlengths 62
36.3k
|
---|---|---|---|---|---|---|---|---|
163241_4 | package cn.ieclipse.smartim.console;
import cn.ieclipse.smartim.IMHistoryManager;
import cn.ieclipse.smartim.IMWindowFactory;
import cn.ieclipse.smartim.SmartClient;
import cn.ieclipse.smartim.actions.*;
import cn.ieclipse.smartim.common.*;
import cn.ieclipse.smartim.idea.EditorUtils;
import cn.ieclipse.smartim.model.IContact;
import cn.ieclipse.smartim.model.impl.AbstractContact;
import cn.ieclipse.smartim.settings.SmartIMSettings;
import cn.ieclipse.smartim.settings.StyleConfPanel;
import cn.ieclipse.smartim.views.IMPanel;
import cn.ieclipse.common.BareBonesBrowserLaunch;
import cn.ieclipse.util.EncodeUtils;
import cn.ieclipse.util.EncryptUtils;
import cn.ieclipse.util.StringUtils;
import com.intellij.ide.BrowserUtil;
import com.intellij.ide.browsers.BrowserLauncher;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.ActionToolbar;
import com.intellij.openapi.actionSystem.DefaultActionGroup;
import com.intellij.openapi.ui.SimpleToolWindowPanel;
import com.intellij.ui.BrowserHyperlinkListener;
import com.intellij.ui.JBSplitter;
import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.text.JTextComponent;
import javax.swing.text.ViewFactory;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.StyleSheet;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.File;
import java.net.URL;
import java.util.List;
/**
* Created by Jamling on 2017/7/1.
*/
public abstract class IMChatConsole extends SimpleToolWindowPanel {
public static final String ENTER_KEY = "\n";
protected IContact contact;
protected String uin;
protected IMPanel imPanel;
public IMChatConsole(IContact target, IMPanel imPanel) {
super(false, false);
this.contact = target;
this.uin = target.getUin();
this.imPanel = imPanel;
initUI();
if (getClient() != null) {
new Thread(this::loadHistories).start();
}
}
public SmartClient getClient() {
return imPanel.getClient();
}
public abstract void loadHistory(String raw);
public abstract void post(final String msg);
public File getHistoryDir() {
if (getClient() != null) {
return getClient().getWorkDir(IMHistoryManager.HISTORY_NAME);
}
File dir = IMWindowFactory.getDefault().getWorkDir().getAbsoluteFile();
return new File(dir, IMHistoryManager.HISTORY_NAME);
}
public String getHistoryFile() {
return EncryptUtils.encryptMd5(contact.getName());
}
public String getUin() {
return uin;
}
public String trimMsg(String msg) {
if (msg.endsWith(ENTER_KEY)) {
return msg;
}
return msg + ENTER_KEY;
}
public void loadHistories() {
List<String> ms = IMHistoryManager.getInstance().load(getHistoryDir(), getHistoryFile());
for (String raw : ms) {
if (!IMUtils.isEmpty(raw)) {
try {
loadHistory(raw);
} catch (Exception e) {
error("历史消息记录:" + raw);
}
}
}
}
public void clearHistories() {
IMHistoryManager.getInstance().clear(getHistoryDir(), getHistoryFile());
historyWidget.setText("");
}
public void clearUnread() {
if (contact != null && contact instanceof AbstractContact) {
((AbstractContact)contact).clearUnRead();
imPanel.notifyUpdateContacts(0, true);
}
}
public boolean hideMyInput() {
return false;
}
public boolean checkClient(SmartClient client) {
if (client == null || client.isClose()) {
error("连接已关闭");
return false;
}
if (!client.isLogin()) {
error("请先登录");
return false;
}
return true;
}
public void send(final String input) {
SmartClient client = getClient();
if (!checkClient(client)) {
return;
}
String name = client.getAccount().getName();
String msg = formatInput(name, input);
if (!hideMyInput()) {
insertDocument(msg);
IMHistoryManager.getInstance().save(getHistoryDir(), getHistoryFile(), msg);
}
new Thread(() -> post(input)).start();
}
public void sendWithoutPost(final String msg, boolean raw) {
if (!hideMyInput()) {
String name = getClient().getAccount().getName();
insertDocument(raw ? msg : formatInput(name, msg));
IMHistoryManager.getInstance().save(getHistoryDir(), getHistoryFile(), msg);
}
}
public void sendFile(final String file) {
new Thread(() -> {
uploadLock = true;
try {
sendFileInternal(file);
} catch (Exception e) {
LOG.error("发送文件失败 : " + e);
LOG.sendNotification("发送文件失败", String.format("文件:%s(%s)", file, e.getMessage()));
error(String.format("发送文件失败:%s(%s)", file, e.getMessage()));
} finally {
uploadLock = false;
}
}).start();
}
protected void sendFileInternal(final String file) throws Exception {
}
protected String encodeInput(String input) {
return EncodeUtils.encodeXml(input);
}
// 组装成我输入的历史记录,并显示在聊天窗口中
protected String formatInput(String name, String msg) {
return IMUtils.formatHtmlMyMsg(System.currentTimeMillis(), name, msg);
}
public void error(Throwable e) {
error(e == null ? "null" : e.toString());
}
public void error(final String msg) {
insertDocument(String.format("<div class=\"error\">%s</div>", msg));
}
private void createUIComponents() {
}
public void write(final String msg) {
insertDocument(msg);
}
protected JBSplitter splitter;
protected ChatHistoryPane top;
protected ChatInputPane bottom;
protected JEditorPane historyWidget;
protected JTextComponent inputWidget;
protected JButton btnSend;
public void initUI() {
top = new ChatHistoryPane();
bottom = new ChatInputPane();
historyWidget = top.getEditorPane();
inputWidget = bottom.getTextPane();
btnSend = bottom.getBtnSend();
btnSend.setVisible(SmartIMSettings.getInstance().getState().SHOW_SEND);
btnSend.addActionListener(new SendAction());
inputWidget.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Send");
inputWidget.getActionMap().put("Send", btnSend.getAction());
splitter = new JBSplitter(true);
splitter.setSplitterProportionKey("chat.splitter.key");
splitter.setFirstComponent(top.getPanel());
splitter.setSecondComponent(bottom.getPanel());
setContent(splitter);
splitter.setPreferredSize(new Dimension(-1, 200));
splitter.setProportion(0.85f);
inputWidget.addKeyListener(new KeyAdapter() {
@Override public void keyPressed(KeyEvent e) {
super.keyPressed(e);
if (SmartIMSettings.getInstance().getState().KEY_SEND.equals(SwingUtils.key2string(e))) {
String input = inputWidget.getText();
if (!input.isEmpty()) {
inputWidget.setText("");
send(input);
}
e.consume();
}
}
});
initToolBar();
initHistoryWidget();
}
protected void initToolBar() {
DefaultActionGroup group = new DefaultActionGroup();
ActionToolbar toolbar = ActionManager.getInstance().createActionToolbar("SmartQQ", group, false);
// toolbar.getComponent().addFocusListener(createFocusListener());
toolbar.setTargetComponent(this);
setToolbar(toolbar.getComponent());
initToolBar(group);
}
protected void initToolBar(DefaultActionGroup group) {
group.add(new SendImageAction(this));
group.add(new SendFileAction(this));
// group.add(new SendProjectFileAction(this));
group.add(new SendProjectFileAction2(this));
group.add(new ScrollLockAction(this));
group.add(new ClearHistoryAction(this));
}
public class SendAction extends AbstractAction {
@Override public void actionPerformed(ActionEvent e) {
String input = inputWidget.getText();
if (!input.isEmpty()) {
inputWidget.setText("");
send(input);
}
}
}
protected boolean scrollLock = false;
protected boolean uploadLock = false;
public boolean enableUpload() {
return !uploadLock;
}
public void setScrollLock(boolean scrollLock) {
this.scrollLock = scrollLock;
}
public boolean isScrollLock() {
return scrollLock;
}
protected void initHistoryWidget() {
HTMLEditorKit kit = new HTMLEditorKit() {
@Override public ViewFactory getViewFactory() {
return new WrapHTMLFactory();
}
};
final StyleSheet styleSheet = kit.getStyleSheet();
styleSheet.addRule("body {text-align: left; overflow-x: hidden;}");
styleSheet.addRule(".my {font-size: 1 em; font-style: italic; float: left;}");
styleSheet.addRule("div.error {color: red;}");
styleSheet.addRule("img {max-width: 100%; display: block;}");
styleSheet.addRule(".sender {display: inline; float: left;}");
styleSheet.addRule(".content {display: inline-block; white-space: pre-wrap; padding-left: 4px;}");
styleSheet.addRule(".br {height: 1px; line-height: 1px; min-height: 1px;}");
RestUtils.loadStyleAsync(styleSheet);
File f = StyleConfPanel.getCssFile();
try {
if (f.exists()) {
URL url = f.toURI().toURL();
styleSheet.importStyleSheet(url);
} else {
LOG.error("$idea.config.path not exists, smartim will use default css");
}
} catch (Exception e) {
LOG.error("加载SmartIM消息CSS失败", e);
}
HTMLDocument doc = (HTMLDocument)kit.createDefaultDocument();
String initText = String
.format("<html><head></head><body><div class=\"welcome\">%s</div></body></html>", imPanel.getWelcome());
historyWidget.setContentType("text/html");
historyWidget.setEditorKit(kit);
historyWidget.setDocument(doc);
historyWidget.setText(initText);
historyWidget.setEditable(false);
historyWidget.setBackground(null);
historyWidget.addHyperlinkListener(e -> {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
String desc = e.getDescription();
if (!StringUtils.isEmpty(desc)) {
hyperlinkActivated(desc);
}
}
});
}
protected boolean hyperlinkActivated(String desc) {
if (desc.startsWith("user://")) {
String user = desc.substring(7);
try {
inputWidget.getDocument().insertString(inputWidget.getCaretPosition(), "@" + user + " ", null);
} catch (Exception e) {
}
} else if (desc.startsWith("code://")) {
String code = desc.substring(7);
int pos = code.lastIndexOf(':');
String file = code.substring(0, pos);
int line = Integer.parseInt(code.substring(pos + 1).trim());
if (line > 0) {
line--;
}
// TODO open file in editor and located to line
EditorUtils.openFile(file, line);
} else {
BrowserUtil.browse(desc);
}
return false;
}
protected void insertDocument(final String msg) {
SwingUtilities.invokeLater(() -> {
try {
HTMLEditorKit kit = (HTMLEditorKit)historyWidget.getEditorKit();
HTMLDocument doc = (HTMLDocument)historyWidget.getDocument();
// historyWidget.getDocument().insertString(len - offset,
// trimMsg(msg), null);
// Element root = doc.getDefaultRootElement();
// Element body = root.getElement(1);
// doc.insertBeforeEnd(body, msg);
int pos = historyWidget.getCaretPosition();
kit.insertHTML(doc, doc.getLength(), msg, 0, 0, null);
historyWidget.setCaretPosition(scrollLock ? pos : doc.getLength());
} catch (Exception e) {
LOG.error("app chat message fail", e);
}
});
}
}
| Jamling/SmartIM4IntelliJ | src/cn/ieclipse/smartim/console/IMChatConsole.java | 3,675 | // Element body = root.getElement(1); | line_comment | nl | package cn.ieclipse.smartim.console;
import cn.ieclipse.smartim.IMHistoryManager;
import cn.ieclipse.smartim.IMWindowFactory;
import cn.ieclipse.smartim.SmartClient;
import cn.ieclipse.smartim.actions.*;
import cn.ieclipse.smartim.common.*;
import cn.ieclipse.smartim.idea.EditorUtils;
import cn.ieclipse.smartim.model.IContact;
import cn.ieclipse.smartim.model.impl.AbstractContact;
import cn.ieclipse.smartim.settings.SmartIMSettings;
import cn.ieclipse.smartim.settings.StyleConfPanel;
import cn.ieclipse.smartim.views.IMPanel;
import cn.ieclipse.common.BareBonesBrowserLaunch;
import cn.ieclipse.util.EncodeUtils;
import cn.ieclipse.util.EncryptUtils;
import cn.ieclipse.util.StringUtils;
import com.intellij.ide.BrowserUtil;
import com.intellij.ide.browsers.BrowserLauncher;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.ActionToolbar;
import com.intellij.openapi.actionSystem.DefaultActionGroup;
import com.intellij.openapi.ui.SimpleToolWindowPanel;
import com.intellij.ui.BrowserHyperlinkListener;
import com.intellij.ui.JBSplitter;
import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.text.JTextComponent;
import javax.swing.text.ViewFactory;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.StyleSheet;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.File;
import java.net.URL;
import java.util.List;
/**
* Created by Jamling on 2017/7/1.
*/
public abstract class IMChatConsole extends SimpleToolWindowPanel {
public static final String ENTER_KEY = "\n";
protected IContact contact;
protected String uin;
protected IMPanel imPanel;
public IMChatConsole(IContact target, IMPanel imPanel) {
super(false, false);
this.contact = target;
this.uin = target.getUin();
this.imPanel = imPanel;
initUI();
if (getClient() != null) {
new Thread(this::loadHistories).start();
}
}
public SmartClient getClient() {
return imPanel.getClient();
}
public abstract void loadHistory(String raw);
public abstract void post(final String msg);
public File getHistoryDir() {
if (getClient() != null) {
return getClient().getWorkDir(IMHistoryManager.HISTORY_NAME);
}
File dir = IMWindowFactory.getDefault().getWorkDir().getAbsoluteFile();
return new File(dir, IMHistoryManager.HISTORY_NAME);
}
public String getHistoryFile() {
return EncryptUtils.encryptMd5(contact.getName());
}
public String getUin() {
return uin;
}
public String trimMsg(String msg) {
if (msg.endsWith(ENTER_KEY)) {
return msg;
}
return msg + ENTER_KEY;
}
public void loadHistories() {
List<String> ms = IMHistoryManager.getInstance().load(getHistoryDir(), getHistoryFile());
for (String raw : ms) {
if (!IMUtils.isEmpty(raw)) {
try {
loadHistory(raw);
} catch (Exception e) {
error("历史消息记录:" + raw);
}
}
}
}
public void clearHistories() {
IMHistoryManager.getInstance().clear(getHistoryDir(), getHistoryFile());
historyWidget.setText("");
}
public void clearUnread() {
if (contact != null && contact instanceof AbstractContact) {
((AbstractContact)contact).clearUnRead();
imPanel.notifyUpdateContacts(0, true);
}
}
public boolean hideMyInput() {
return false;
}
public boolean checkClient(SmartClient client) {
if (client == null || client.isClose()) {
error("连接已关闭");
return false;
}
if (!client.isLogin()) {
error("请先登录");
return false;
}
return true;
}
public void send(final String input) {
SmartClient client = getClient();
if (!checkClient(client)) {
return;
}
String name = client.getAccount().getName();
String msg = formatInput(name, input);
if (!hideMyInput()) {
insertDocument(msg);
IMHistoryManager.getInstance().save(getHistoryDir(), getHistoryFile(), msg);
}
new Thread(() -> post(input)).start();
}
public void sendWithoutPost(final String msg, boolean raw) {
if (!hideMyInput()) {
String name = getClient().getAccount().getName();
insertDocument(raw ? msg : formatInput(name, msg));
IMHistoryManager.getInstance().save(getHistoryDir(), getHistoryFile(), msg);
}
}
public void sendFile(final String file) {
new Thread(() -> {
uploadLock = true;
try {
sendFileInternal(file);
} catch (Exception e) {
LOG.error("发送文件失败 : " + e);
LOG.sendNotification("发送文件失败", String.format("文件:%s(%s)", file, e.getMessage()));
error(String.format("发送文件失败:%s(%s)", file, e.getMessage()));
} finally {
uploadLock = false;
}
}).start();
}
protected void sendFileInternal(final String file) throws Exception {
}
protected String encodeInput(String input) {
return EncodeUtils.encodeXml(input);
}
// 组装成我输入的历史记录,并显示在聊天窗口中
protected String formatInput(String name, String msg) {
return IMUtils.formatHtmlMyMsg(System.currentTimeMillis(), name, msg);
}
public void error(Throwable e) {
error(e == null ? "null" : e.toString());
}
public void error(final String msg) {
insertDocument(String.format("<div class=\"error\">%s</div>", msg));
}
private void createUIComponents() {
}
public void write(final String msg) {
insertDocument(msg);
}
protected JBSplitter splitter;
protected ChatHistoryPane top;
protected ChatInputPane bottom;
protected JEditorPane historyWidget;
protected JTextComponent inputWidget;
protected JButton btnSend;
public void initUI() {
top = new ChatHistoryPane();
bottom = new ChatInputPane();
historyWidget = top.getEditorPane();
inputWidget = bottom.getTextPane();
btnSend = bottom.getBtnSend();
btnSend.setVisible(SmartIMSettings.getInstance().getState().SHOW_SEND);
btnSend.addActionListener(new SendAction());
inputWidget.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Send");
inputWidget.getActionMap().put("Send", btnSend.getAction());
splitter = new JBSplitter(true);
splitter.setSplitterProportionKey("chat.splitter.key");
splitter.setFirstComponent(top.getPanel());
splitter.setSecondComponent(bottom.getPanel());
setContent(splitter);
splitter.setPreferredSize(new Dimension(-1, 200));
splitter.setProportion(0.85f);
inputWidget.addKeyListener(new KeyAdapter() {
@Override public void keyPressed(KeyEvent e) {
super.keyPressed(e);
if (SmartIMSettings.getInstance().getState().KEY_SEND.equals(SwingUtils.key2string(e))) {
String input = inputWidget.getText();
if (!input.isEmpty()) {
inputWidget.setText("");
send(input);
}
e.consume();
}
}
});
initToolBar();
initHistoryWidget();
}
protected void initToolBar() {
DefaultActionGroup group = new DefaultActionGroup();
ActionToolbar toolbar = ActionManager.getInstance().createActionToolbar("SmartQQ", group, false);
// toolbar.getComponent().addFocusListener(createFocusListener());
toolbar.setTargetComponent(this);
setToolbar(toolbar.getComponent());
initToolBar(group);
}
protected void initToolBar(DefaultActionGroup group) {
group.add(new SendImageAction(this));
group.add(new SendFileAction(this));
// group.add(new SendProjectFileAction(this));
group.add(new SendProjectFileAction2(this));
group.add(new ScrollLockAction(this));
group.add(new ClearHistoryAction(this));
}
public class SendAction extends AbstractAction {
@Override public void actionPerformed(ActionEvent e) {
String input = inputWidget.getText();
if (!input.isEmpty()) {
inputWidget.setText("");
send(input);
}
}
}
protected boolean scrollLock = false;
protected boolean uploadLock = false;
public boolean enableUpload() {
return !uploadLock;
}
public void setScrollLock(boolean scrollLock) {
this.scrollLock = scrollLock;
}
public boolean isScrollLock() {
return scrollLock;
}
protected void initHistoryWidget() {
HTMLEditorKit kit = new HTMLEditorKit() {
@Override public ViewFactory getViewFactory() {
return new WrapHTMLFactory();
}
};
final StyleSheet styleSheet = kit.getStyleSheet();
styleSheet.addRule("body {text-align: left; overflow-x: hidden;}");
styleSheet.addRule(".my {font-size: 1 em; font-style: italic; float: left;}");
styleSheet.addRule("div.error {color: red;}");
styleSheet.addRule("img {max-width: 100%; display: block;}");
styleSheet.addRule(".sender {display: inline; float: left;}");
styleSheet.addRule(".content {display: inline-block; white-space: pre-wrap; padding-left: 4px;}");
styleSheet.addRule(".br {height: 1px; line-height: 1px; min-height: 1px;}");
RestUtils.loadStyleAsync(styleSheet);
File f = StyleConfPanel.getCssFile();
try {
if (f.exists()) {
URL url = f.toURI().toURL();
styleSheet.importStyleSheet(url);
} else {
LOG.error("$idea.config.path not exists, smartim will use default css");
}
} catch (Exception e) {
LOG.error("加载SmartIM消息CSS失败", e);
}
HTMLDocument doc = (HTMLDocument)kit.createDefaultDocument();
String initText = String
.format("<html><head></head><body><div class=\"welcome\">%s</div></body></html>", imPanel.getWelcome());
historyWidget.setContentType("text/html");
historyWidget.setEditorKit(kit);
historyWidget.setDocument(doc);
historyWidget.setText(initText);
historyWidget.setEditable(false);
historyWidget.setBackground(null);
historyWidget.addHyperlinkListener(e -> {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
String desc = e.getDescription();
if (!StringUtils.isEmpty(desc)) {
hyperlinkActivated(desc);
}
}
});
}
protected boolean hyperlinkActivated(String desc) {
if (desc.startsWith("user://")) {
String user = desc.substring(7);
try {
inputWidget.getDocument().insertString(inputWidget.getCaretPosition(), "@" + user + " ", null);
} catch (Exception e) {
}
} else if (desc.startsWith("code://")) {
String code = desc.substring(7);
int pos = code.lastIndexOf(':');
String file = code.substring(0, pos);
int line = Integer.parseInt(code.substring(pos + 1).trim());
if (line > 0) {
line--;
}
// TODO open file in editor and located to line
EditorUtils.openFile(file, line);
} else {
BrowserUtil.browse(desc);
}
return false;
}
protected void insertDocument(final String msg) {
SwingUtilities.invokeLater(() -> {
try {
HTMLEditorKit kit = (HTMLEditorKit)historyWidget.getEditorKit();
HTMLDocument doc = (HTMLDocument)historyWidget.getDocument();
// historyWidget.getDocument().insertString(len - offset,
// trimMsg(msg), null);
// Element root = doc.getDefaultRootElement();
// Element body<SUF>
// doc.insertBeforeEnd(body, msg);
int pos = historyWidget.getCaretPosition();
kit.insertHTML(doc, doc.getLength(), msg, 0, 0, null);
historyWidget.setCaretPosition(scrollLock ? pos : doc.getLength());
} catch (Exception e) {
LOG.error("app chat message fail", e);
}
});
}
}
|
131519_33 | /*
* This software Copyright by the RPTools.net development team, and
* licensed under the Affero GPL Version 3 or, at your option, any later
* version.
*
* MapTool Source Code 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.
*
* You should have received a copy of the GNU Affero General Public
* License * along with this source Code. If not, please visit
* <http://www.gnu.org/licenses/> and specifically the Affero license
* text at <http://www.gnu.org/licenses/agpl.html>.
*/
package net.rptools.maptool.client.walker.astar;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Rectangle;
import java.awt.geom.Area;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import net.rptools.maptool.client.MapTool;
import net.rptools.maptool.client.walker.AbstractZoneWalker;
import net.rptools.maptool.model.CellPoint;
import net.rptools.maptool.model.Label;
import net.rptools.maptool.model.Token;
import net.rptools.maptool.model.TokenFootprint;
import net.rptools.maptool.model.Zone;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.locationtech.jts.algorithm.ConvexHull;
import org.locationtech.jts.awt.ShapeReader;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.LineString;
import org.locationtech.jts.geom.prep.PreparedGeometry;
import org.locationtech.jts.geom.prep.PreparedGeometryFactory;
import org.locationtech.jts.operation.valid.IsValidOp;
public abstract class AbstractAStarWalker extends AbstractZoneWalker {
private record TerrainModifier(Token.TerrainModifierOperation operation, double value) {}
private static boolean isInteger(double d) {
return (int) d == d;
}
private static final Logger log = LogManager.getLogger(AbstractAStarWalker.class);
private final GeometryFactory geometryFactory = new GeometryFactory();
// private List<GUID> debugLabels;
protected int crossX = 0;
protected int crossY = 0;
private boolean debugCosts = false; // Manually set this to view H, G & F costs as rendered labels
private Area vbl = new Area();
private Area fowExposedArea = new Area();
private double cell_cost = zone.getUnitsPerCell();
private double distance = -1;
private ShapeReader shapeReader = new ShapeReader(geometryFactory);
private PreparedGeometry vblGeometry = null;
private PreparedGeometry fowExposedAreaGeometry = null;
// private long avgRetrieveTime;
// private long avgTestTime;
// private long retrievalCount;
// private long testCount;
private TokenFootprint footprint = new TokenFootprint();
private Map<CellPoint, Map<CellPoint, Boolean>> vblBlockedMovesByGoal = new ConcurrentHashMap<>();
private Map<CellPoint, Map<CellPoint, Boolean>> fowBlockedMovesByGoal = new ConcurrentHashMap<>();
private final Map<CellPoint, List<TerrainModifier>> terrainCells = new HashMap<>();
public AbstractAStarWalker(Zone zone) {
super(zone);
// Get tokens on map that may affect movement
for (Token token : zone.getTokensWithTerrainModifiers()) {
// log.info("Token: " + token.getName() + ", " + token.getTerrainModifier());
Set<CellPoint> cells = token.getOccupiedCells(zone.getGrid());
for (CellPoint cell : cells) {
terrainCells
.computeIfAbsent(cell, ignored -> new ArrayList<>())
.add(
new TerrainModifier(
token.getTerrainModifierOperation(), token.getTerrainModifier()));
}
}
}
/**
* Returns the list of neighbor cells that are valid for being movement-checked. This is an array
* of (x,y) offsets (see the constants in this class) named as compass points.
*
* <p>It should be possible to query the current (x,y) CellPoint passed in to determine which
* directions are feasible to move into. But it would require information about visibility (which
* token is moving, does it have sight, and so on). Currently that information is not available
* here, but perhaps an option Token parameter could be specified to the constructor? Or maybe as
* the tree was scanned, since I believe all Grids share a common ZoneWalker.
*
* @param x the x of the CellPoint
* @param y the y of the CellPoint
* @return the array of (x,y) for the neighbor cells
*/
protected abstract int[][] getNeighborMap(int x, int y);
protected abstract double hScore(AStarCellPoint p1, CellPoint p2);
protected abstract double getDiagonalMultiplier(int[] neighborArray);
public double getDistance() {
if (distance < 0) {
return 0;
} else {
return distance;
}
}
public Map<CellPoint, Set<CellPoint>> getBlockedMoves() {
final Map<CellPoint, Set<CellPoint>> result = new HashMap<>();
for (var entry : vblBlockedMovesByGoal.entrySet()) {
result.put(
entry.getKey(),
entry.getValue().entrySet().stream()
.filter(Map.Entry::getValue)
.map(Map.Entry::getKey)
.collect(Collectors.toSet()));
}
for (var entry : fowBlockedMovesByGoal.entrySet()) {
result.put(
entry.getKey(),
entry.getValue().entrySet().stream()
.filter(Map.Entry::getValue)
.map(Map.Entry::getKey)
.collect(Collectors.toSet()));
}
return result;
}
@Override
public void setFootprint(TokenFootprint footprint) {
this.footprint = footprint;
}
@Override
protected List<CellPoint> calculatePath(CellPoint start, CellPoint goal) {
crossX = start.x - goal.x;
crossY = start.y - goal.y;
Queue<AStarCellPoint> openList =
new PriorityQueue<>(Comparator.comparingDouble(AStarCellPoint::fCost));
Map<AStarCellPoint, AStarCellPoint> openSet = new HashMap<>(); // For faster lookups
Set<AStarCellPoint> closedSet = new HashSet<>();
// Current fail safe... bail out after 10 seconds of searching just in case, shouldn't hang UI
// as this is off the AWT thread
long timeOut = System.currentTimeMillis();
double estimatedTimeoutNeeded = 10000;
// if (start.equals(end))
// log.info("NO WORK!");
var startNode = new AStarCellPoint(start, !isInteger(start.distanceTraveledWithoutTerrain));
openList.add(startNode);
openSet.put(startNode, startNode);
AStarCellPoint currentNode = null;
// Get current VBL for map...
// Using JTS because AWT Area can only intersect with Area and we want to use simple lines here.
// Render VBL to Geometry class once and store.
// Note: zoneRenderer will be null if map is not visible to players.
Area newVbl = new Area();
Area newFowExposedArea = new Area();
final var zoneRenderer = MapTool.getFrame().getCurrentZoneRenderer();
if (zoneRenderer != null) {
final var zoneView = zoneRenderer.getZoneView();
var mbl = zoneView.getTopology(Zone.TopologyType.MBL);
if (tokenMbl != null) {
mbl = new Area(mbl);
mbl.subtract(tokenMbl);
}
if (MapTool.getServerPolicy().getVblBlocksMove()) {
var wallVbl = zoneView.getTopology(Zone.TopologyType.WALL_VBL);
var hillVbl = zoneView.getTopology(Zone.TopologyType.HILL_VBL);
var pitVbl = zoneView.getTopology(Zone.TopologyType.PIT_VBL);
// A token's topology should not be used to block itself!
if (tokenWallVbl != null) {
wallVbl = new Area(wallVbl);
wallVbl.subtract(tokenWallVbl);
}
if (tokenHillVbl != null) {
hillVbl = new Area(hillVbl);
hillVbl.subtract(tokenHillVbl);
}
if (tokenPitVbl != null) {
pitVbl = new Area(pitVbl);
pitVbl.subtract(tokenPitVbl);
}
newVbl.add(wallVbl);
newVbl.add(hillVbl);
newVbl.add(pitVbl);
// Finally, add the Move Blocking Layer!
newVbl.add(mbl);
} else {
newVbl = mbl;
}
newFowExposedArea =
zoneRenderer.getZone().hasFog()
? zoneRenderer.getZone().getExposedArea(zoneRenderer.getPlayerView())
: null;
}
boolean blockedMovesHasChanged = false;
if (!newVbl.equals(vbl)) {
blockedMovesHasChanged = true;
vbl = newVbl;
// VBL has changed. Let's update the JTS geometry to match.
if (vbl.isEmpty()) {
this.vblGeometry = null;
} else {
try {
var vblGeometry =
shapeReader.read(new ReverseShapePathIterator(vbl.getPathIterator(null)));
// polygons
if (!vblGeometry.isValid()) {
log.info(
"vblGeometry is invalid! May cause issues. Check for self-intersecting polygons.");
log.debug("Invalid vblGeometry: " + new IsValidOp(vblGeometry).getValidationError());
}
vblGeometry = vblGeometry.buffer(1); // .buffer always creates valid geometry.
this.vblGeometry = PreparedGeometryFactory.prepare(vblGeometry);
} catch (Exception e) {
log.info("vblGeometry oh oh: ", e);
}
}
// log.info("vblGeometry bounds: " + vblGeometry.toString());
}
if (!Objects.equals(newFowExposedArea, fowExposedArea)) {
blockedMovesHasChanged = true;
fowExposedArea = newFowExposedArea;
// FoW has changed. Let's update the JTS geometry to match.
if (fowExposedArea == null || fowExposedArea.isEmpty()) {
this.fowExposedAreaGeometry = null;
} else {
try {
var fowExposedAreaGeometry =
shapeReader.read(new ReverseShapePathIterator(fowExposedArea.getPathIterator(null)));
// polygons
if (!fowExposedAreaGeometry.isValid()) {
log.info(
"FoW Geometry is invalid! May cause issues. Check for self-intersecting polygons.");
log.debug(
"Invalid FoW Geometry: "
+ new IsValidOp(fowExposedAreaGeometry).getValidationError());
}
fowExposedAreaGeometry =
fowExposedAreaGeometry.buffer(1); // .buffer always creates valid geometry.
this.fowExposedAreaGeometry = PreparedGeometryFactory.prepare(fowExposedAreaGeometry);
} catch (Exception e) {
log.info("FoW Geometry oh oh: ", e);
}
}
}
if (blockedMovesHasChanged) {
// The move cache may no longer accurately reflect the VBL limitations.
this.vblBlockedMovesByGoal.clear();
}
// Erase previous debug labels, this actually erases ALL labels! Use only when debugging!
EventQueue.invokeLater(
() -> {
if (!zone.getLabels().isEmpty() && debugCosts) {
for (Label label : zone.getLabels()) {
zone.removeLabel(label.getId());
}
}
});
// Timeout quicker for GM cause reasons
if (MapTool.getPlayer().isGM()) {
estimatedTimeoutNeeded = estimatedTimeoutNeeded / 2;
}
// log.info("A* Path timeout estimate: " + estimatedTimeoutNeeded);
Rectangle pathfindingBounds = this.getPathfindingBounds(start, goal);
while (!openList.isEmpty()) {
if (System.currentTimeMillis() > timeOut + estimatedTimeoutNeeded) {
log.info("Timing out after " + estimatedTimeoutNeeded);
break;
}
currentNode = openList.remove();
openSet.remove(currentNode);
if (currentNode.position.equals(goal)) {
break;
}
for (AStarCellPoint currentNeighbor :
getNeighbors(currentNode, closedSet, pathfindingBounds)) {
currentNeighbor.h = hScore(currentNeighbor, goal);
showDebugInfo(currentNeighbor);
if (openSet.containsKey(currentNeighbor)) {
// check if it is cheaper to get here the way that we just came, versus the previous path
AStarCellPoint oldNode = openSet.get(currentNeighbor);
if (currentNeighbor.g < oldNode.g) {
// We're about to modify the node cost, so we have to reinsert the node.
openList.remove(oldNode);
oldNode.replaceG(currentNeighbor);
oldNode.parent = currentNode;
openList.add(oldNode);
}
continue;
}
openList.add(currentNeighbor);
openSet.put(currentNeighbor, currentNeighbor);
}
closedSet.add(currentNode);
currentNode = null;
/*
We now calculate paths off the main UI thread but only one at a time.
If the token moves, we cancel the thread and restart so we're only calculating the most
recent path request. Clearing the list effectively finishes this thread gracefully.
*/
if (Thread.interrupted()) {
// log.info("Thread interrupted!");
openList.clear();
}
}
List<CellPoint> returnedCellPointList = new LinkedList<>();
while (currentNode != null) {
returnedCellPointList.add(currentNode.position);
currentNode = currentNode.parent;
}
// We don't need to "calculate" distance after the fact as it's already stored as the G cost...
if (!returnedCellPointList.isEmpty()) {
distance = returnedCellPointList.get(0).getDistanceTraveled(zone);
} else { // if path finding was interrupted because of timeout
distance = 0;
goal.setAStarCanceled(true);
returnedCellPointList.add(goal);
returnedCellPointList.add(start);
}
Collections.reverse(returnedCellPointList);
timeOut = (System.currentTimeMillis() - timeOut);
if (timeOut > 500) {
log.debug("Time to calculate A* path warning: " + timeOut + "ms");
}
// if (retrievalCount > 0)
// log.info("avgRetrieveTime: " + Math.floor(avgRetrieveTime / retrievalCount)/1000 + " micro");
// if (testCount > 0)
// log.info("avgTestTime: " + Math.floor(avgTestTime / testCount)/1000 + " micro");
return returnedCellPointList;
}
/**
* Find a suitable bounding box in which A* can look for paths.
*
* <p>The bounding box will surround all of the following:
*
* <ul>
* <li>All MBL/VBL
* <li>All terrain modifiers
* <li>The start and goal cells
* </ul>
*
* Additionally, some padding is provided around all this so that a token can navigate around the
* outside if necessary.
*
* @param start
* @param goal
* @return A bounding box suitable for constraining the A* search space.
*/
protected Rectangle getPathfindingBounds(CellPoint start, CellPoint goal) {
// Bounding box must contain all VBL/MBL ...
Rectangle pathfindingBounds = vbl.getBounds();
// ... and the footprints of all terrain tokens ...
for (var cellPoint : terrainCells.keySet()) {
pathfindingBounds = pathfindingBounds.union(zone.getGrid().getBounds(cellPoint));
}
// ... and the original token position ...
pathfindingBounds = pathfindingBounds.union(zone.getGrid().getBounds(start));
// ... and the target token position ...
pathfindingBounds = pathfindingBounds.union(zone.getGrid().getBounds(goal));
// ... and have ample room for the token to go anywhere around the outside if necessary.
var tokenBounds = footprint.getBounds(zone.getGrid());
pathfindingBounds.grow(2 * tokenBounds.width, 2 * tokenBounds.height);
return pathfindingBounds;
}
protected List<AStarCellPoint> getNeighbors(
AStarCellPoint node, Set<AStarCellPoint> closedSet, Rectangle pathfindingBounds) {
List<AStarCellPoint> neighbors = new ArrayList<>();
int[][] neighborMap = getNeighborMap(node.position.x, node.position.y);
// Find all the neighbors.
for (int[] neighborArray : neighborMap) {
double terrainMultiplier = 0;
double terrainAdder = 0;
boolean terrainIsFree = false;
boolean blockNode = false;
// Get diagonal cost multiplier, if any...
double diagonalMultiplier = getDiagonalMultiplier(neighborArray);
boolean invertEvenOddDiagonals = !isInteger(diagonalMultiplier);
AStarCellPoint neighbor =
new AStarCellPoint(
node.position.x + neighborArray[0],
node.position.y + neighborArray[1],
node.isOddStepOfOneTwoOneMovement ^ invertEvenOddDiagonals);
if (closedSet.contains(neighbor)) {
continue;
}
if (!zone.getGrid().getBounds(node.position).intersects(pathfindingBounds)) {
// This position is too far out to possibly be part of the optimal path.
closedSet.add(neighbor);
continue;
}
// Add the cell we're coming from
neighbor.parent = node;
// Don't count VBL or Terrain Modifiers
if (restrictMovement) {
if (tokenFootprintIntersectsVBL(neighbor.position)) {
// The token would overlap VBL if moved to this position, so it is not a valid position.
closedSet.add(neighbor);
blockNode = true;
continue;
}
Set<CellPoint> occupiedCells = footprint.getOccupiedCells(node.position);
for (CellPoint cellPoint : occupiedCells) {
// Check whether moving the occupied cell to its new location would be prohibited by VBL.
var cellNeighbor =
new CellPoint(cellPoint.x + neighborArray[0], cellPoint.y + neighborArray[1]);
if (vblBlocksMovement(cellPoint, cellNeighbor)) {
blockNode = true;
break;
}
if (fowBlocksMovement(cellPoint, cellNeighbor)) {
blockNode = true;
break;
}
}
if (blockNode) {
continue;
}
// Check for terrain modifiers
for (TerrainModifier terrainModifier :
terrainCells.getOrDefault(neighbor.position, Collections.emptyList())) {
if (!terrainModifiersIgnored.contains(terrainModifier.operation)) {
switch (terrainModifier.operation) {
case MULTIPLY:
terrainMultiplier += terrainModifier.value;
break;
case ADD:
terrainAdder += terrainModifier.value;
break;
case BLOCK:
// Terrain blocking applies equally regardless of even/odd diagonals.
closedSet.add(new AStarCellPoint(neighbor.position, false));
closedSet.add(new AStarCellPoint(neighbor.position, true));
blockNode = true;
continue;
case FREE:
terrainIsFree = true;
break;
case NONE:
break;
}
}
}
}
terrainAdder = terrainAdder / cell_cost;
if (blockNode) {
continue;
}
// If the total terrainMultiplier equals out to zero, or there were no multipliers,
// set to 1 so we do math right...
if (terrainMultiplier == 0) {
terrainMultiplier = 1;
}
terrainMultiplier = Math.abs(terrainMultiplier); // net negative multipliers screw with the AI
if (terrainIsFree) {
neighbor.g = node.g;
neighbor.position.distanceTraveled = node.position.distanceTraveled;
} else {
neighbor.position.distanceTraveledWithoutTerrain =
node.position.distanceTraveledWithoutTerrain + diagonalMultiplier;
if (neighbor.isOddStepOfOneTwoOneMovement()) {
neighbor.g = node.g + terrainAdder + terrainMultiplier;
neighbor.position.distanceTraveled =
node.position.distanceTraveled + terrainAdder + terrainMultiplier;
} else {
neighbor.g = node.g + terrainAdder + terrainMultiplier * Math.ceil(diagonalMultiplier);
neighbor.position.distanceTraveled =
node.position.distanceTraveled
+ terrainAdder
+ terrainMultiplier * Math.ceil(diagonalMultiplier);
}
}
neighbors.add(neighbor);
}
return neighbors;
}
private boolean tokenFootprintIntersectsVBL(CellPoint position) {
if (vblGeometry == null) {
return false;
}
var points =
footprint.getOccupiedCells(position).stream()
.map(
cellPoint -> {
var bounds = zone.getGrid().getBounds(cellPoint);
return new Coordinate(bounds.getCenterX(), bounds.getCenterY());
})
.toArray(Coordinate[]::new);
Geometry footprintGeometry = new ConvexHull(points, geometryFactory).getConvexHull();
return vblGeometry.intersects(footprintGeometry);
}
private boolean vblBlocksMovement(CellPoint start, CellPoint goal) {
if (vblGeometry == null) {
return false;
}
// Stopwatch stopwatch = Stopwatch.createStarted();
Map<CellPoint, Boolean> blockedMoves =
vblBlockedMovesByGoal.computeIfAbsent(goal, pos -> new HashMap<>());
Boolean test = blockedMoves.get(start);
// if it's null then the test for that direction hasn't been set yet otherwise just return the
// previous result
if (test != null) {
// log.info("Time to retrieve: " + stopwatch.elapsed(TimeUnit.NANOSECONDS));
// avgRetrieveTime += stopwatch.elapsed(TimeUnit.NANOSECONDS);
// retrievalCount++;
return test;
}
Rectangle startBounds = zone.getGrid().getBounds(start);
Rectangle goalBounds = zone.getGrid().getBounds(goal);
if (goalBounds.isEmpty() || startBounds.isEmpty()) {
return false;
}
// If the goal center point is in vbl, allow to maintain path through vbl (should be GM only?)
/*
if (vbl.contains(goal.toPoint())) {
// Allow GM to move through VBL
return !MapTool.getPlayer().isGM();
}
*/
// NEW WAY - use polygon test
double x1 = startBounds.getCenterX();
double y1 = startBounds.getCenterY();
double x2 = goalBounds.getCenterX();
double y2 = goalBounds.getCenterY();
LineString centerRay =
geometryFactory.createLineString(
new Coordinate[] {new Coordinate(x1, y1), new Coordinate(x2, y2)});
boolean blocksMovement;
try {
blocksMovement = vblGeometry.intersects(centerRay);
} catch (Exception e) {
log.info("clipped.intersects oh oh: ", e);
return true;
}
// avgTestTime += stopwatch.elapsed(TimeUnit.NANOSECONDS);
// testCount++;
blockedMoves.put(start, blocksMovement);
return blocksMovement;
}
private boolean fowBlocksMovement(CellPoint start, CellPoint goal) {
if (MapTool.getPlayer().isEffectiveGM()) {
return false;
}
if (fowExposedAreaGeometry == null) {
return false;
}
// Stopwatch stopwatch = Stopwatch.createStarted();
Map<CellPoint, Boolean> blockedMoves =
fowBlockedMovesByGoal.computeIfAbsent(goal, pos -> new HashMap<>());
Boolean test = blockedMoves.get(start);
// if it's null then the test for that direction hasn't been set yet otherwise just return the
// previous result
if (test != null) {
// log.info("Time to retrieve: " + stopwatch.elapsed(TimeUnit.NANOSECONDS));
// avgRetrieveTime += stopwatch.elapsed(TimeUnit.NANOSECONDS);
// retrievalCount++;
return test;
}
Rectangle startBounds = zone.getGrid().getBounds(start);
Rectangle goalBounds = zone.getGrid().getBounds(goal);
if (goalBounds.isEmpty() || startBounds.isEmpty()) {
return false;
}
// Check whether a center-to-center line touches hard FoW.
double x1 = startBounds.getCenterX();
double y1 = startBounds.getCenterY();
double x2 = goalBounds.getCenterX();
double y2 = goalBounds.getCenterY();
LineString centerRay =
geometryFactory.createLineString(
new Coordinate[] {new Coordinate(x1, y1), new Coordinate(x2, y2)});
boolean blocksMovement;
try {
blocksMovement = !fowExposedAreaGeometry.covers(centerRay);
} catch (Exception e) {
log.info("clipped.intersects oh oh: ", e);
return true;
}
// avgTestTime += stopwatch.elapsed(TimeUnit.NANOSECONDS);
// testCount++;
blockedMoves.put(start, blocksMovement);
return blocksMovement;
}
protected void showDebugInfo(AStarCellPoint node) {
if (!log.isDebugEnabled() && !debugCosts) {
return;
}
final int basis = zone.getGrid().getSize() / 10;
final int xOffset = basis * (node.isOddStepOfOneTwoOneMovement ? 7 : 3);
// if (debugLabels == null) { debugLabels = new ArrayList<>(); }
Rectangle cellBounds = zone.getGrid().getBounds(node.position);
DecimalFormat f = new DecimalFormat("##.00");
Label gScore = new Label();
Label hScore = new Label();
Label fScore = new Label();
Label parent = new Label();
gScore.setLabel(f.format(node.g));
gScore.setX(cellBounds.x + xOffset);
gScore.setY(cellBounds.y + 1 * basis);
hScore.setLabel(f.format(node.h));
hScore.setX(cellBounds.x + xOffset);
hScore.setY(cellBounds.y + 3 * basis);
fScore.setLabel(f.format(node.fCost()));
fScore.setX(cellBounds.x + xOffset);
fScore.setY(cellBounds.y + 5 * basis);
fScore.setForegroundColor(Color.RED);
if (node.parent != null) {
parent.setLabel(
String.format(
"(%d, %d | %s)",
node.parent.position.x,
node.parent.position.y,
node.parent.isOddStepOfOneTwoOneMovement() ? "O" : "E"));
} else {
parent.setLabel("(none)");
}
parent.setX(cellBounds.x + xOffset);
parent.setY(cellBounds.y + 7 * basis);
parent.setForegroundColor(Color.BLUE);
EventQueue.invokeLater(
() -> {
zone.putLabel(gScore);
zone.putLabel(hScore);
zone.putLabel(fScore);
zone.putLabel(parent);
});
// Track labels to delete later
// debugLabels.add(gScore.getId());
// debugLabels.add(hScore.getId());
// debugLabels.add(fScore.getId());
}
}
| JamzTheMan/MapTool | src/main/java/net/rptools/maptool/client/walker/astar/AbstractAStarWalker.java | 8,038 | // if (retrievalCount > 0) | line_comment | nl | /*
* This software Copyright by the RPTools.net development team, and
* licensed under the Affero GPL Version 3 or, at your option, any later
* version.
*
* MapTool Source Code 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.
*
* You should have received a copy of the GNU Affero General Public
* License * along with this source Code. If not, please visit
* <http://www.gnu.org/licenses/> and specifically the Affero license
* text at <http://www.gnu.org/licenses/agpl.html>.
*/
package net.rptools.maptool.client.walker.astar;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Rectangle;
import java.awt.geom.Area;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import net.rptools.maptool.client.MapTool;
import net.rptools.maptool.client.walker.AbstractZoneWalker;
import net.rptools.maptool.model.CellPoint;
import net.rptools.maptool.model.Label;
import net.rptools.maptool.model.Token;
import net.rptools.maptool.model.TokenFootprint;
import net.rptools.maptool.model.Zone;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.locationtech.jts.algorithm.ConvexHull;
import org.locationtech.jts.awt.ShapeReader;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.LineString;
import org.locationtech.jts.geom.prep.PreparedGeometry;
import org.locationtech.jts.geom.prep.PreparedGeometryFactory;
import org.locationtech.jts.operation.valid.IsValidOp;
public abstract class AbstractAStarWalker extends AbstractZoneWalker {
private record TerrainModifier(Token.TerrainModifierOperation operation, double value) {}
private static boolean isInteger(double d) {
return (int) d == d;
}
private static final Logger log = LogManager.getLogger(AbstractAStarWalker.class);
private final GeometryFactory geometryFactory = new GeometryFactory();
// private List<GUID> debugLabels;
protected int crossX = 0;
protected int crossY = 0;
private boolean debugCosts = false; // Manually set this to view H, G & F costs as rendered labels
private Area vbl = new Area();
private Area fowExposedArea = new Area();
private double cell_cost = zone.getUnitsPerCell();
private double distance = -1;
private ShapeReader shapeReader = new ShapeReader(geometryFactory);
private PreparedGeometry vblGeometry = null;
private PreparedGeometry fowExposedAreaGeometry = null;
// private long avgRetrieveTime;
// private long avgTestTime;
// private long retrievalCount;
// private long testCount;
private TokenFootprint footprint = new TokenFootprint();
private Map<CellPoint, Map<CellPoint, Boolean>> vblBlockedMovesByGoal = new ConcurrentHashMap<>();
private Map<CellPoint, Map<CellPoint, Boolean>> fowBlockedMovesByGoal = new ConcurrentHashMap<>();
private final Map<CellPoint, List<TerrainModifier>> terrainCells = new HashMap<>();
public AbstractAStarWalker(Zone zone) {
super(zone);
// Get tokens on map that may affect movement
for (Token token : zone.getTokensWithTerrainModifiers()) {
// log.info("Token: " + token.getName() + ", " + token.getTerrainModifier());
Set<CellPoint> cells = token.getOccupiedCells(zone.getGrid());
for (CellPoint cell : cells) {
terrainCells
.computeIfAbsent(cell, ignored -> new ArrayList<>())
.add(
new TerrainModifier(
token.getTerrainModifierOperation(), token.getTerrainModifier()));
}
}
}
/**
* Returns the list of neighbor cells that are valid for being movement-checked. This is an array
* of (x,y) offsets (see the constants in this class) named as compass points.
*
* <p>It should be possible to query the current (x,y) CellPoint passed in to determine which
* directions are feasible to move into. But it would require information about visibility (which
* token is moving, does it have sight, and so on). Currently that information is not available
* here, but perhaps an option Token parameter could be specified to the constructor? Or maybe as
* the tree was scanned, since I believe all Grids share a common ZoneWalker.
*
* @param x the x of the CellPoint
* @param y the y of the CellPoint
* @return the array of (x,y) for the neighbor cells
*/
protected abstract int[][] getNeighborMap(int x, int y);
protected abstract double hScore(AStarCellPoint p1, CellPoint p2);
protected abstract double getDiagonalMultiplier(int[] neighborArray);
public double getDistance() {
if (distance < 0) {
return 0;
} else {
return distance;
}
}
public Map<CellPoint, Set<CellPoint>> getBlockedMoves() {
final Map<CellPoint, Set<CellPoint>> result = new HashMap<>();
for (var entry : vblBlockedMovesByGoal.entrySet()) {
result.put(
entry.getKey(),
entry.getValue().entrySet().stream()
.filter(Map.Entry::getValue)
.map(Map.Entry::getKey)
.collect(Collectors.toSet()));
}
for (var entry : fowBlockedMovesByGoal.entrySet()) {
result.put(
entry.getKey(),
entry.getValue().entrySet().stream()
.filter(Map.Entry::getValue)
.map(Map.Entry::getKey)
.collect(Collectors.toSet()));
}
return result;
}
@Override
public void setFootprint(TokenFootprint footprint) {
this.footprint = footprint;
}
@Override
protected List<CellPoint> calculatePath(CellPoint start, CellPoint goal) {
crossX = start.x - goal.x;
crossY = start.y - goal.y;
Queue<AStarCellPoint> openList =
new PriorityQueue<>(Comparator.comparingDouble(AStarCellPoint::fCost));
Map<AStarCellPoint, AStarCellPoint> openSet = new HashMap<>(); // For faster lookups
Set<AStarCellPoint> closedSet = new HashSet<>();
// Current fail safe... bail out after 10 seconds of searching just in case, shouldn't hang UI
// as this is off the AWT thread
long timeOut = System.currentTimeMillis();
double estimatedTimeoutNeeded = 10000;
// if (start.equals(end))
// log.info("NO WORK!");
var startNode = new AStarCellPoint(start, !isInteger(start.distanceTraveledWithoutTerrain));
openList.add(startNode);
openSet.put(startNode, startNode);
AStarCellPoint currentNode = null;
// Get current VBL for map...
// Using JTS because AWT Area can only intersect with Area and we want to use simple lines here.
// Render VBL to Geometry class once and store.
// Note: zoneRenderer will be null if map is not visible to players.
Area newVbl = new Area();
Area newFowExposedArea = new Area();
final var zoneRenderer = MapTool.getFrame().getCurrentZoneRenderer();
if (zoneRenderer != null) {
final var zoneView = zoneRenderer.getZoneView();
var mbl = zoneView.getTopology(Zone.TopologyType.MBL);
if (tokenMbl != null) {
mbl = new Area(mbl);
mbl.subtract(tokenMbl);
}
if (MapTool.getServerPolicy().getVblBlocksMove()) {
var wallVbl = zoneView.getTopology(Zone.TopologyType.WALL_VBL);
var hillVbl = zoneView.getTopology(Zone.TopologyType.HILL_VBL);
var pitVbl = zoneView.getTopology(Zone.TopologyType.PIT_VBL);
// A token's topology should not be used to block itself!
if (tokenWallVbl != null) {
wallVbl = new Area(wallVbl);
wallVbl.subtract(tokenWallVbl);
}
if (tokenHillVbl != null) {
hillVbl = new Area(hillVbl);
hillVbl.subtract(tokenHillVbl);
}
if (tokenPitVbl != null) {
pitVbl = new Area(pitVbl);
pitVbl.subtract(tokenPitVbl);
}
newVbl.add(wallVbl);
newVbl.add(hillVbl);
newVbl.add(pitVbl);
// Finally, add the Move Blocking Layer!
newVbl.add(mbl);
} else {
newVbl = mbl;
}
newFowExposedArea =
zoneRenderer.getZone().hasFog()
? zoneRenderer.getZone().getExposedArea(zoneRenderer.getPlayerView())
: null;
}
boolean blockedMovesHasChanged = false;
if (!newVbl.equals(vbl)) {
blockedMovesHasChanged = true;
vbl = newVbl;
// VBL has changed. Let's update the JTS geometry to match.
if (vbl.isEmpty()) {
this.vblGeometry = null;
} else {
try {
var vblGeometry =
shapeReader.read(new ReverseShapePathIterator(vbl.getPathIterator(null)));
// polygons
if (!vblGeometry.isValid()) {
log.info(
"vblGeometry is invalid! May cause issues. Check for self-intersecting polygons.");
log.debug("Invalid vblGeometry: " + new IsValidOp(vblGeometry).getValidationError());
}
vblGeometry = vblGeometry.buffer(1); // .buffer always creates valid geometry.
this.vblGeometry = PreparedGeometryFactory.prepare(vblGeometry);
} catch (Exception e) {
log.info("vblGeometry oh oh: ", e);
}
}
// log.info("vblGeometry bounds: " + vblGeometry.toString());
}
if (!Objects.equals(newFowExposedArea, fowExposedArea)) {
blockedMovesHasChanged = true;
fowExposedArea = newFowExposedArea;
// FoW has changed. Let's update the JTS geometry to match.
if (fowExposedArea == null || fowExposedArea.isEmpty()) {
this.fowExposedAreaGeometry = null;
} else {
try {
var fowExposedAreaGeometry =
shapeReader.read(new ReverseShapePathIterator(fowExposedArea.getPathIterator(null)));
// polygons
if (!fowExposedAreaGeometry.isValid()) {
log.info(
"FoW Geometry is invalid! May cause issues. Check for self-intersecting polygons.");
log.debug(
"Invalid FoW Geometry: "
+ new IsValidOp(fowExposedAreaGeometry).getValidationError());
}
fowExposedAreaGeometry =
fowExposedAreaGeometry.buffer(1); // .buffer always creates valid geometry.
this.fowExposedAreaGeometry = PreparedGeometryFactory.prepare(fowExposedAreaGeometry);
} catch (Exception e) {
log.info("FoW Geometry oh oh: ", e);
}
}
}
if (blockedMovesHasChanged) {
// The move cache may no longer accurately reflect the VBL limitations.
this.vblBlockedMovesByGoal.clear();
}
// Erase previous debug labels, this actually erases ALL labels! Use only when debugging!
EventQueue.invokeLater(
() -> {
if (!zone.getLabels().isEmpty() && debugCosts) {
for (Label label : zone.getLabels()) {
zone.removeLabel(label.getId());
}
}
});
// Timeout quicker for GM cause reasons
if (MapTool.getPlayer().isGM()) {
estimatedTimeoutNeeded = estimatedTimeoutNeeded / 2;
}
// log.info("A* Path timeout estimate: " + estimatedTimeoutNeeded);
Rectangle pathfindingBounds = this.getPathfindingBounds(start, goal);
while (!openList.isEmpty()) {
if (System.currentTimeMillis() > timeOut + estimatedTimeoutNeeded) {
log.info("Timing out after " + estimatedTimeoutNeeded);
break;
}
currentNode = openList.remove();
openSet.remove(currentNode);
if (currentNode.position.equals(goal)) {
break;
}
for (AStarCellPoint currentNeighbor :
getNeighbors(currentNode, closedSet, pathfindingBounds)) {
currentNeighbor.h = hScore(currentNeighbor, goal);
showDebugInfo(currentNeighbor);
if (openSet.containsKey(currentNeighbor)) {
// check if it is cheaper to get here the way that we just came, versus the previous path
AStarCellPoint oldNode = openSet.get(currentNeighbor);
if (currentNeighbor.g < oldNode.g) {
// We're about to modify the node cost, so we have to reinsert the node.
openList.remove(oldNode);
oldNode.replaceG(currentNeighbor);
oldNode.parent = currentNode;
openList.add(oldNode);
}
continue;
}
openList.add(currentNeighbor);
openSet.put(currentNeighbor, currentNeighbor);
}
closedSet.add(currentNode);
currentNode = null;
/*
We now calculate paths off the main UI thread but only one at a time.
If the token moves, we cancel the thread and restart so we're only calculating the most
recent path request. Clearing the list effectively finishes this thread gracefully.
*/
if (Thread.interrupted()) {
// log.info("Thread interrupted!");
openList.clear();
}
}
List<CellPoint> returnedCellPointList = new LinkedList<>();
while (currentNode != null) {
returnedCellPointList.add(currentNode.position);
currentNode = currentNode.parent;
}
// We don't need to "calculate" distance after the fact as it's already stored as the G cost...
if (!returnedCellPointList.isEmpty()) {
distance = returnedCellPointList.get(0).getDistanceTraveled(zone);
} else { // if path finding was interrupted because of timeout
distance = 0;
goal.setAStarCanceled(true);
returnedCellPointList.add(goal);
returnedCellPointList.add(start);
}
Collections.reverse(returnedCellPointList);
timeOut = (System.currentTimeMillis() - timeOut);
if (timeOut > 500) {
log.debug("Time to calculate A* path warning: " + timeOut + "ms");
}
// if (retrievalCount<SUF>
// log.info("avgRetrieveTime: " + Math.floor(avgRetrieveTime / retrievalCount)/1000 + " micro");
// if (testCount > 0)
// log.info("avgTestTime: " + Math.floor(avgTestTime / testCount)/1000 + " micro");
return returnedCellPointList;
}
/**
* Find a suitable bounding box in which A* can look for paths.
*
* <p>The bounding box will surround all of the following:
*
* <ul>
* <li>All MBL/VBL
* <li>All terrain modifiers
* <li>The start and goal cells
* </ul>
*
* Additionally, some padding is provided around all this so that a token can navigate around the
* outside if necessary.
*
* @param start
* @param goal
* @return A bounding box suitable for constraining the A* search space.
*/
protected Rectangle getPathfindingBounds(CellPoint start, CellPoint goal) {
// Bounding box must contain all VBL/MBL ...
Rectangle pathfindingBounds = vbl.getBounds();
// ... and the footprints of all terrain tokens ...
for (var cellPoint : terrainCells.keySet()) {
pathfindingBounds = pathfindingBounds.union(zone.getGrid().getBounds(cellPoint));
}
// ... and the original token position ...
pathfindingBounds = pathfindingBounds.union(zone.getGrid().getBounds(start));
// ... and the target token position ...
pathfindingBounds = pathfindingBounds.union(zone.getGrid().getBounds(goal));
// ... and have ample room for the token to go anywhere around the outside if necessary.
var tokenBounds = footprint.getBounds(zone.getGrid());
pathfindingBounds.grow(2 * tokenBounds.width, 2 * tokenBounds.height);
return pathfindingBounds;
}
protected List<AStarCellPoint> getNeighbors(
AStarCellPoint node, Set<AStarCellPoint> closedSet, Rectangle pathfindingBounds) {
List<AStarCellPoint> neighbors = new ArrayList<>();
int[][] neighborMap = getNeighborMap(node.position.x, node.position.y);
// Find all the neighbors.
for (int[] neighborArray : neighborMap) {
double terrainMultiplier = 0;
double terrainAdder = 0;
boolean terrainIsFree = false;
boolean blockNode = false;
// Get diagonal cost multiplier, if any...
double diagonalMultiplier = getDiagonalMultiplier(neighborArray);
boolean invertEvenOddDiagonals = !isInteger(diagonalMultiplier);
AStarCellPoint neighbor =
new AStarCellPoint(
node.position.x + neighborArray[0],
node.position.y + neighborArray[1],
node.isOddStepOfOneTwoOneMovement ^ invertEvenOddDiagonals);
if (closedSet.contains(neighbor)) {
continue;
}
if (!zone.getGrid().getBounds(node.position).intersects(pathfindingBounds)) {
// This position is too far out to possibly be part of the optimal path.
closedSet.add(neighbor);
continue;
}
// Add the cell we're coming from
neighbor.parent = node;
// Don't count VBL or Terrain Modifiers
if (restrictMovement) {
if (tokenFootprintIntersectsVBL(neighbor.position)) {
// The token would overlap VBL if moved to this position, so it is not a valid position.
closedSet.add(neighbor);
blockNode = true;
continue;
}
Set<CellPoint> occupiedCells = footprint.getOccupiedCells(node.position);
for (CellPoint cellPoint : occupiedCells) {
// Check whether moving the occupied cell to its new location would be prohibited by VBL.
var cellNeighbor =
new CellPoint(cellPoint.x + neighborArray[0], cellPoint.y + neighborArray[1]);
if (vblBlocksMovement(cellPoint, cellNeighbor)) {
blockNode = true;
break;
}
if (fowBlocksMovement(cellPoint, cellNeighbor)) {
blockNode = true;
break;
}
}
if (blockNode) {
continue;
}
// Check for terrain modifiers
for (TerrainModifier terrainModifier :
terrainCells.getOrDefault(neighbor.position, Collections.emptyList())) {
if (!terrainModifiersIgnored.contains(terrainModifier.operation)) {
switch (terrainModifier.operation) {
case MULTIPLY:
terrainMultiplier += terrainModifier.value;
break;
case ADD:
terrainAdder += terrainModifier.value;
break;
case BLOCK:
// Terrain blocking applies equally regardless of even/odd diagonals.
closedSet.add(new AStarCellPoint(neighbor.position, false));
closedSet.add(new AStarCellPoint(neighbor.position, true));
blockNode = true;
continue;
case FREE:
terrainIsFree = true;
break;
case NONE:
break;
}
}
}
}
terrainAdder = terrainAdder / cell_cost;
if (blockNode) {
continue;
}
// If the total terrainMultiplier equals out to zero, or there were no multipliers,
// set to 1 so we do math right...
if (terrainMultiplier == 0) {
terrainMultiplier = 1;
}
terrainMultiplier = Math.abs(terrainMultiplier); // net negative multipliers screw with the AI
if (terrainIsFree) {
neighbor.g = node.g;
neighbor.position.distanceTraveled = node.position.distanceTraveled;
} else {
neighbor.position.distanceTraveledWithoutTerrain =
node.position.distanceTraveledWithoutTerrain + diagonalMultiplier;
if (neighbor.isOddStepOfOneTwoOneMovement()) {
neighbor.g = node.g + terrainAdder + terrainMultiplier;
neighbor.position.distanceTraveled =
node.position.distanceTraveled + terrainAdder + terrainMultiplier;
} else {
neighbor.g = node.g + terrainAdder + terrainMultiplier * Math.ceil(diagonalMultiplier);
neighbor.position.distanceTraveled =
node.position.distanceTraveled
+ terrainAdder
+ terrainMultiplier * Math.ceil(diagonalMultiplier);
}
}
neighbors.add(neighbor);
}
return neighbors;
}
private boolean tokenFootprintIntersectsVBL(CellPoint position) {
if (vblGeometry == null) {
return false;
}
var points =
footprint.getOccupiedCells(position).stream()
.map(
cellPoint -> {
var bounds = zone.getGrid().getBounds(cellPoint);
return new Coordinate(bounds.getCenterX(), bounds.getCenterY());
})
.toArray(Coordinate[]::new);
Geometry footprintGeometry = new ConvexHull(points, geometryFactory).getConvexHull();
return vblGeometry.intersects(footprintGeometry);
}
private boolean vblBlocksMovement(CellPoint start, CellPoint goal) {
if (vblGeometry == null) {
return false;
}
// Stopwatch stopwatch = Stopwatch.createStarted();
Map<CellPoint, Boolean> blockedMoves =
vblBlockedMovesByGoal.computeIfAbsent(goal, pos -> new HashMap<>());
Boolean test = blockedMoves.get(start);
// if it's null then the test for that direction hasn't been set yet otherwise just return the
// previous result
if (test != null) {
// log.info("Time to retrieve: " + stopwatch.elapsed(TimeUnit.NANOSECONDS));
// avgRetrieveTime += stopwatch.elapsed(TimeUnit.NANOSECONDS);
// retrievalCount++;
return test;
}
Rectangle startBounds = zone.getGrid().getBounds(start);
Rectangle goalBounds = zone.getGrid().getBounds(goal);
if (goalBounds.isEmpty() || startBounds.isEmpty()) {
return false;
}
// If the goal center point is in vbl, allow to maintain path through vbl (should be GM only?)
/*
if (vbl.contains(goal.toPoint())) {
// Allow GM to move through VBL
return !MapTool.getPlayer().isGM();
}
*/
// NEW WAY - use polygon test
double x1 = startBounds.getCenterX();
double y1 = startBounds.getCenterY();
double x2 = goalBounds.getCenterX();
double y2 = goalBounds.getCenterY();
LineString centerRay =
geometryFactory.createLineString(
new Coordinate[] {new Coordinate(x1, y1), new Coordinate(x2, y2)});
boolean blocksMovement;
try {
blocksMovement = vblGeometry.intersects(centerRay);
} catch (Exception e) {
log.info("clipped.intersects oh oh: ", e);
return true;
}
// avgTestTime += stopwatch.elapsed(TimeUnit.NANOSECONDS);
// testCount++;
blockedMoves.put(start, blocksMovement);
return blocksMovement;
}
private boolean fowBlocksMovement(CellPoint start, CellPoint goal) {
if (MapTool.getPlayer().isEffectiveGM()) {
return false;
}
if (fowExposedAreaGeometry == null) {
return false;
}
// Stopwatch stopwatch = Stopwatch.createStarted();
Map<CellPoint, Boolean> blockedMoves =
fowBlockedMovesByGoal.computeIfAbsent(goal, pos -> new HashMap<>());
Boolean test = blockedMoves.get(start);
// if it's null then the test for that direction hasn't been set yet otherwise just return the
// previous result
if (test != null) {
// log.info("Time to retrieve: " + stopwatch.elapsed(TimeUnit.NANOSECONDS));
// avgRetrieveTime += stopwatch.elapsed(TimeUnit.NANOSECONDS);
// retrievalCount++;
return test;
}
Rectangle startBounds = zone.getGrid().getBounds(start);
Rectangle goalBounds = zone.getGrid().getBounds(goal);
if (goalBounds.isEmpty() || startBounds.isEmpty()) {
return false;
}
// Check whether a center-to-center line touches hard FoW.
double x1 = startBounds.getCenterX();
double y1 = startBounds.getCenterY();
double x2 = goalBounds.getCenterX();
double y2 = goalBounds.getCenterY();
LineString centerRay =
geometryFactory.createLineString(
new Coordinate[] {new Coordinate(x1, y1), new Coordinate(x2, y2)});
boolean blocksMovement;
try {
blocksMovement = !fowExposedAreaGeometry.covers(centerRay);
} catch (Exception e) {
log.info("clipped.intersects oh oh: ", e);
return true;
}
// avgTestTime += stopwatch.elapsed(TimeUnit.NANOSECONDS);
// testCount++;
blockedMoves.put(start, blocksMovement);
return blocksMovement;
}
protected void showDebugInfo(AStarCellPoint node) {
if (!log.isDebugEnabled() && !debugCosts) {
return;
}
final int basis = zone.getGrid().getSize() / 10;
final int xOffset = basis * (node.isOddStepOfOneTwoOneMovement ? 7 : 3);
// if (debugLabels == null) { debugLabels = new ArrayList<>(); }
Rectangle cellBounds = zone.getGrid().getBounds(node.position);
DecimalFormat f = new DecimalFormat("##.00");
Label gScore = new Label();
Label hScore = new Label();
Label fScore = new Label();
Label parent = new Label();
gScore.setLabel(f.format(node.g));
gScore.setX(cellBounds.x + xOffset);
gScore.setY(cellBounds.y + 1 * basis);
hScore.setLabel(f.format(node.h));
hScore.setX(cellBounds.x + xOffset);
hScore.setY(cellBounds.y + 3 * basis);
fScore.setLabel(f.format(node.fCost()));
fScore.setX(cellBounds.x + xOffset);
fScore.setY(cellBounds.y + 5 * basis);
fScore.setForegroundColor(Color.RED);
if (node.parent != null) {
parent.setLabel(
String.format(
"(%d, %d | %s)",
node.parent.position.x,
node.parent.position.y,
node.parent.isOddStepOfOneTwoOneMovement() ? "O" : "E"));
} else {
parent.setLabel("(none)");
}
parent.setX(cellBounds.x + xOffset);
parent.setY(cellBounds.y + 7 * basis);
parent.setForegroundColor(Color.BLUE);
EventQueue.invokeLater(
() -> {
zone.putLabel(gScore);
zone.putLabel(hScore);
zone.putLabel(fScore);
zone.putLabel(parent);
});
// Track labels to delete later
// debugLabels.add(gScore.getId());
// debugLabels.add(hScore.getId());
// debugLabels.add(fScore.getId());
}
}
|
32372_6 | import SortingAlgorithms.SortingAlgorithm;
public class ThreadManager {
private Thread sortingThread;
// private SortingAlgorithm sortingAlgorithm;
public void setSortingAlgorithm(SortingAlgorithm sa) {
// sortingAlgorithm = sa;
}
// TODO: if thread is started, start should be grayed out and reset should be clickable. Also when thread is done. Can we listen for thread finish event?
public void startSorting(SortingAlgorithm sortingAlgorithm) {
if (sortingThread == null && sortingAlgorithm != null) {
sortingThread = new Thread(sortingAlgorithm::run);
sortingThread.start();
} else {
resumeSorting();
}
}
public void resumeSorting() {
try {
sortingThread.notify();
} catch (Exception ignored) {
System.out.println("Could not resume thread");
}
}
// TODO: kan start of moet ik resume hierna doen? & hoe houdt ie state bij van de array???
// tuurlijk als ik continue gaat gwn die thread verder, duhh, nee dat is niet, die
// sortingAlgorithm is dan tot een bepaald punt gesorteerd en daar gaat ie gwn op verder!
// Met een nieuwe thread.
public void pauseSorting() {
try {
sortingThread.suspend();
// sortingThread.wait(); // TODO: test better than suspend.
} catch (Exception ignored) {
System.out.println("Could not suspend thread");
}
}
public void stopSorting() {
if (sortingThread != null) {
// sortingThread.stop();
sortingThread.interrupt(); // TODO: test interrupt better than stop?
this.sortingThread = null;
}
}
}
| JanBelterman/visualsort | src/ThreadManager.java | 454 | // Met een nieuwe thread. | line_comment | nl | import SortingAlgorithms.SortingAlgorithm;
public class ThreadManager {
private Thread sortingThread;
// private SortingAlgorithm sortingAlgorithm;
public void setSortingAlgorithm(SortingAlgorithm sa) {
// sortingAlgorithm = sa;
}
// TODO: if thread is started, start should be grayed out and reset should be clickable. Also when thread is done. Can we listen for thread finish event?
public void startSorting(SortingAlgorithm sortingAlgorithm) {
if (sortingThread == null && sortingAlgorithm != null) {
sortingThread = new Thread(sortingAlgorithm::run);
sortingThread.start();
} else {
resumeSorting();
}
}
public void resumeSorting() {
try {
sortingThread.notify();
} catch (Exception ignored) {
System.out.println("Could not resume thread");
}
}
// TODO: kan start of moet ik resume hierna doen? & hoe houdt ie state bij van de array???
// tuurlijk als ik continue gaat gwn die thread verder, duhh, nee dat is niet, die
// sortingAlgorithm is dan tot een bepaald punt gesorteerd en daar gaat ie gwn op verder!
// Met een<SUF>
public void pauseSorting() {
try {
sortingThread.suspend();
// sortingThread.wait(); // TODO: test better than suspend.
} catch (Exception ignored) {
System.out.println("Could not suspend thread");
}
}
public void stopSorting() {
if (sortingThread != null) {
// sortingThread.stop();
sortingThread.interrupt(); // TODO: test interrupt better than stop?
this.sortingThread = null;
}
}
}
|
169612_1 | import java.io.File;
import java.io.IOException;
public class Duplicator {
public static void main(String[] arg) {
}
public static String path = "//Users//jan//SUT.txt";
public int duplicateCounter(int number) {
return number * 2;
}
public void createFile() {
try {
File output = new File(path);
boolean isFileCreated = output.createNewFile();
if (isFileCreated) {
System.out.println("File successfully created!");
} else {
System.out.println("File already exist!");
}
} catch (IOException e) {
System.out.println("Exception Occurred:");
e.printStackTrace();
}
}
public void deleteFile() {
try {
File output = new File(path);
if (output.delete()) {
System.out.println(output.getName() + " is deleted!");
} else {
System.out.println("Delete failed");
}
} catch (Exception e) {
System.out.println("Exception occurred");
e.printStackTrace();
}
/**
* TEST DIRECTORY en TEST CLASS
*
* 1. Maak een test directory aan.
* 2. Maak van deze directory een Test Resource Folder wordt
*
* 3. Maak een test class aan.
*
*/
/**
*
* 1. Maak een SUT aan in je test class.
*
* 2. Maak een test method aan waarbij je de onderstaande
* functie duplicateCounter() test
*
* 3. Run de test en bekijk het resultaat
*
* 4. Maak de functie duplicateCounter() af zodat de test wel werkt.
*
*/
public int duplicateCounter ( int number){
return number * 2;
}
}
}
| JanHenst/RedGreenRefactor | src/Duplicator.java | 501 | /**
*
* 1. Maak een SUT aan in je test class.
*
* 2. Maak een test method aan waarbij je de onderstaande
* functie duplicateCounter() test
*
* 3. Run de test en bekijk het resultaat
*
* 4. Maak de functie duplicateCounter() af zodat de test wel werkt.
*
*/ | block_comment | nl | import java.io.File;
import java.io.IOException;
public class Duplicator {
public static void main(String[] arg) {
}
public static String path = "//Users//jan//SUT.txt";
public int duplicateCounter(int number) {
return number * 2;
}
public void createFile() {
try {
File output = new File(path);
boolean isFileCreated = output.createNewFile();
if (isFileCreated) {
System.out.println("File successfully created!");
} else {
System.out.println("File already exist!");
}
} catch (IOException e) {
System.out.println("Exception Occurred:");
e.printStackTrace();
}
}
public void deleteFile() {
try {
File output = new File(path);
if (output.delete()) {
System.out.println(output.getName() + " is deleted!");
} else {
System.out.println("Delete failed");
}
} catch (Exception e) {
System.out.println("Exception occurred");
e.printStackTrace();
}
/**
* TEST DIRECTORY en TEST CLASS
*
* 1. Maak een test directory aan.
* 2. Maak van deze directory een Test Resource Folder wordt
*
* 3. Maak een test class aan.
*
*/
/**
*
* 1. Maak een<SUF>*/
public int duplicateCounter ( int number){
return number * 2;
}
}
}
|
203327_6 | package be.ucll.workloadplanner;
import static android.content.ContentValues.TAG;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.fragment.NavHostFragment;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
// Hoofdscherm waarin de verschillende fragmenten geladen worden
public class MainActivity extends AppCompatActivity {
private NavController navController;
private FirebaseAuth firebaseAuth;
private FirebaseFirestore db;
private String userRole;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuth = FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance();
setSupportActionBar(findViewById(R.id.toolbar));
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container_view);
navController = navHostFragment.getNavController();
logCurrentUserId();
}
// Controle ingelogde user om te checken of de login gewerkt heeft
private void logCurrentUserId() {
FirebaseUser user = getCurrentUser();
if (user != null) {
String phoneNumber = user.getPhoneNumber();
if (phoneNumber != null) {
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("users").whereEqualTo("userId", phoneNumber)
.get()
.addOnSuccessListener(queryDocumentSnapshots -> {
if (!queryDocumentSnapshots.isEmpty()) {
DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0);
String userId = documentSnapshot.getString("userId");
Log.d("MainActivity", "User ID: " + userId);
getUserRole(userId); // Call to get user role after user ID retrieval
} else {
Log.d("MainActivity", "User document does not exist");
}
})
.addOnFailureListener(e -> {
Log.e("MainActivity", "Error getting user document", e);
});
} else {
Log.d("MainActivity", "No phone number associated with the current user");
}
} else {
Log.d("MainActivity", "No user is currently authenticated");
}
}
// Huidige gebruiker ophalen
private FirebaseUser getCurrentUser() {
return firebaseAuth.getCurrentUser();
}
// Voor het weergeven van het menu rechtsboven
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
// Hide or show menu items based on user role
MenuItem homeItem = menu.findItem(R.id.action_home);
MenuItem addTicketItem = menu.findItem(R.id.action_addTicket);
MenuItem logoutItem = menu.findItem(R.id.action_logout);
if (userRole != null && userRole.equals("Project Manager")) {
homeItem.setVisible(true);
addTicketItem.setVisible(true);
logoutItem.setVisible(true);
} else if (userRole != null && userRole.equals("Member")) {
homeItem.setVisible(true);
addTicketItem.setVisible(false);
logoutItem.setVisible(true);
} else {
addTicketItem.setVisible(false);
logoutItem.setVisible(false);
}
return true;
}
// Instellen van de opties van het menu
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_home) {
navController.navigate(R.id.action_any_fragment_to_tickets);
return true;
}
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container_view);
if (navHostFragment != null) {
Fragment currentFragment = navHostFragment.getChildFragmentManager().getPrimaryNavigationFragment();
// Now you have the current fragment
Log.d("MainActivity", "Current fragment: " + currentFragment.getClass().getSimpleName());
if (currentFragment instanceof TicketsFragment || currentFragment instanceof AddTicketFragment || currentFragment instanceof UpdateTicketFragment) {
if (item.getItemId() == R.id.action_addTicket) {
Log.d("MainActivity", "Adding ticket...");
navController.navigate(R.id.action_any_fragment_to_addTicket);
return true;
}
}
}
if (item.getItemId() == R.id.action_logout) {
firebaseAuth.signOut();
Log.d("MainActivity", "User logged out. Is user still logged in: " + (firebaseAuth.getCurrentUser() != null));
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(loginIntent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
// De rol van de gebruiker opzoeken, member of project manager
private void getUserRole(String userId) {
FirebaseFirestore.getInstance()
.collection("users")
.whereEqualTo("userId", userId)
.get()
.addOnSuccessListener(queryDocumentSnapshots -> {
if (!queryDocumentSnapshots.isEmpty()) {
DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0);
String role = documentSnapshot.getString("role");
if (role != null) {
Log.d(TAG, "User id found: " + userId);
Log.d(TAG, "User role found: " + role);
userRole = role; // Update user role variable
invalidateOptionsMenu(); // Refresh menu to reflect changes
} else {
Log.d(TAG, "Role field not found in user document");
}
} else {
Log.d(TAG, "User document not found for userId: " + userId);
}
})
.addOnFailureListener(e -> {
Log.e(TAG, "Error fetching user document", e);
});
}
} | JanVHanssen/WorkloadPlanner | app/src/main/java/be/ucll/workloadplanner/MainActivity.java | 1,848 | // Instellen van de opties van het menu | line_comment | nl | package be.ucll.workloadplanner;
import static android.content.ContentValues.TAG;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.fragment.NavHostFragment;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
// Hoofdscherm waarin de verschillende fragmenten geladen worden
public class MainActivity extends AppCompatActivity {
private NavController navController;
private FirebaseAuth firebaseAuth;
private FirebaseFirestore db;
private String userRole;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuth = FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance();
setSupportActionBar(findViewById(R.id.toolbar));
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container_view);
navController = navHostFragment.getNavController();
logCurrentUserId();
}
// Controle ingelogde user om te checken of de login gewerkt heeft
private void logCurrentUserId() {
FirebaseUser user = getCurrentUser();
if (user != null) {
String phoneNumber = user.getPhoneNumber();
if (phoneNumber != null) {
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("users").whereEqualTo("userId", phoneNumber)
.get()
.addOnSuccessListener(queryDocumentSnapshots -> {
if (!queryDocumentSnapshots.isEmpty()) {
DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0);
String userId = documentSnapshot.getString("userId");
Log.d("MainActivity", "User ID: " + userId);
getUserRole(userId); // Call to get user role after user ID retrieval
} else {
Log.d("MainActivity", "User document does not exist");
}
})
.addOnFailureListener(e -> {
Log.e("MainActivity", "Error getting user document", e);
});
} else {
Log.d("MainActivity", "No phone number associated with the current user");
}
} else {
Log.d("MainActivity", "No user is currently authenticated");
}
}
// Huidige gebruiker ophalen
private FirebaseUser getCurrentUser() {
return firebaseAuth.getCurrentUser();
}
// Voor het weergeven van het menu rechtsboven
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
// Hide or show menu items based on user role
MenuItem homeItem = menu.findItem(R.id.action_home);
MenuItem addTicketItem = menu.findItem(R.id.action_addTicket);
MenuItem logoutItem = menu.findItem(R.id.action_logout);
if (userRole != null && userRole.equals("Project Manager")) {
homeItem.setVisible(true);
addTicketItem.setVisible(true);
logoutItem.setVisible(true);
} else if (userRole != null && userRole.equals("Member")) {
homeItem.setVisible(true);
addTicketItem.setVisible(false);
logoutItem.setVisible(true);
} else {
addTicketItem.setVisible(false);
logoutItem.setVisible(false);
}
return true;
}
// Instellen van<SUF>
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_home) {
navController.navigate(R.id.action_any_fragment_to_tickets);
return true;
}
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container_view);
if (navHostFragment != null) {
Fragment currentFragment = navHostFragment.getChildFragmentManager().getPrimaryNavigationFragment();
// Now you have the current fragment
Log.d("MainActivity", "Current fragment: " + currentFragment.getClass().getSimpleName());
if (currentFragment instanceof TicketsFragment || currentFragment instanceof AddTicketFragment || currentFragment instanceof UpdateTicketFragment) {
if (item.getItemId() == R.id.action_addTicket) {
Log.d("MainActivity", "Adding ticket...");
navController.navigate(R.id.action_any_fragment_to_addTicket);
return true;
}
}
}
if (item.getItemId() == R.id.action_logout) {
firebaseAuth.signOut();
Log.d("MainActivity", "User logged out. Is user still logged in: " + (firebaseAuth.getCurrentUser() != null));
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(loginIntent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
// De rol van de gebruiker opzoeken, member of project manager
private void getUserRole(String userId) {
FirebaseFirestore.getInstance()
.collection("users")
.whereEqualTo("userId", userId)
.get()
.addOnSuccessListener(queryDocumentSnapshots -> {
if (!queryDocumentSnapshots.isEmpty()) {
DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0);
String role = documentSnapshot.getString("role");
if (role != null) {
Log.d(TAG, "User id found: " + userId);
Log.d(TAG, "User role found: " + role);
userRole = role; // Update user role variable
invalidateOptionsMenu(); // Refresh menu to reflect changes
} else {
Log.d(TAG, "Role field not found in user document");
}
} else {
Log.d(TAG, "User document not found for userId: " + userId);
}
})
.addOnFailureListener(e -> {
Log.e(TAG, "Error fetching user document", e);
});
}
} |
21048_9 | package be.intecbrussel.sellers;
// stelt een ijsjeszaak voor die een ongelimiteerd aantal ijsjes heeft die ze
//zelf produceren
import be.intecbrussel.eatables.*;
// Je kan er ijsjes bestellen en je kan er de winst van opvragen.
public class IceCreamSalon implements IceCreamSeller {
//attributes
PriceList priceList;
double totalProfit;
//constructor
public IceCreamSalon(PriceList priceList, double totalProfit) {
this.priceList = priceList;
this.totalProfit = totalProfit;
}
//medthod om ijsejes te bestellen en winst opvragen
@Override
public Cone orderCone(Cone.Flavor[] flavors) {
double price = priceList.getBallPrice()*flavors.length;//de perice van ball isje ophallen vanuit de pricelist voor de berekening van de winst
Cone cone = new Cone(flavors);
totalProfit += price * 0.25;//verhoogt totale winstwaarde (total profit) aan de hand van de price list
return cone;
//daarrom een nieuw ijse maak op basis van smaak flavor(een nieuwe cone maken) en verhoogt totale winstwaarde(total profit) aan de hand van price list
}
@Override
public IceRocket orderIceRocket() {
double price = priceList.getRocketPrice();
totalProfit += price * 0.20;
return new IceRocket();
}
@Override
public Magnum orderMagnum(Magnum.MagnumType magnumType) {
double price = priceList.getMagnumStandardPrice(Magnum.MagnumType.BLACKCHOCOLATE); //Haal de prijs op uit de prijslijst
totalProfit += price * 0.01;//verhoogt totale winst waarde (total profit) aan de hand van de price list
return new Magnum(Magnum.MagnumType.BLACKCHOCOLATE); // Retourneer een nieuw Magnum object
}
@Override
public double getProfit() {//get profit bedoel om totale winst waarde van de ijsverkoper te geven
System.out.println("Total Profit : "+ totalProfit);
return totalProfit;
}
@Override
public String toString() {
return "IceCreamSalon{" +
"priceList=" + priceList +
", totalProfit=" + totalProfit +
'}';
}
}
| JananJavdan/IceCreamShop | IceCreamShop/src/be/intecbrussel/sellers/IceCreamSalon.java | 706 | //get profit bedoel om totale winst waarde van de ijsverkoper te geven
| line_comment | nl | package be.intecbrussel.sellers;
// stelt een ijsjeszaak voor die een ongelimiteerd aantal ijsjes heeft die ze
//zelf produceren
import be.intecbrussel.eatables.*;
// Je kan er ijsjes bestellen en je kan er de winst van opvragen.
public class IceCreamSalon implements IceCreamSeller {
//attributes
PriceList priceList;
double totalProfit;
//constructor
public IceCreamSalon(PriceList priceList, double totalProfit) {
this.priceList = priceList;
this.totalProfit = totalProfit;
}
//medthod om ijsejes te bestellen en winst opvragen
@Override
public Cone orderCone(Cone.Flavor[] flavors) {
double price = priceList.getBallPrice()*flavors.length;//de perice van ball isje ophallen vanuit de pricelist voor de berekening van de winst
Cone cone = new Cone(flavors);
totalProfit += price * 0.25;//verhoogt totale winstwaarde (total profit) aan de hand van de price list
return cone;
//daarrom een nieuw ijse maak op basis van smaak flavor(een nieuwe cone maken) en verhoogt totale winstwaarde(total profit) aan de hand van price list
}
@Override
public IceRocket orderIceRocket() {
double price = priceList.getRocketPrice();
totalProfit += price * 0.20;
return new IceRocket();
}
@Override
public Magnum orderMagnum(Magnum.MagnumType magnumType) {
double price = priceList.getMagnumStandardPrice(Magnum.MagnumType.BLACKCHOCOLATE); //Haal de prijs op uit de prijslijst
totalProfit += price * 0.01;//verhoogt totale winst waarde (total profit) aan de hand van de price list
return new Magnum(Magnum.MagnumType.BLACKCHOCOLATE); // Retourneer een nieuw Magnum object
}
@Override
public double getProfit() {//get profit<SUF>
System.out.println("Total Profit : "+ totalProfit);
return totalProfit;
}
@Override
public String toString() {
return "IceCreamSalon{" +
"priceList=" + priceList +
", totalProfit=" + totalProfit +
'}';
}
}
|
129324_1 | package Map;
import java.util.HashMap;
import java.util.Map;
public class HashMapExample {
public static void main(String[] args) {
// Een Map maken en elementen toevoegen
//string is de key integer is value //interface "map" als een referance (polymorphisem) hasp implementeerd map
Map<String, Integer> map = new HashMap<>();
map.put("Alice", 25); //"put" om element toe te voegen (list = add) (set= offer)
map.put("Bob", 30);
map.put("Charlie", 35);
// Een element opzoeken en de waarde afdrukken
int ageOfAlice = map.get("Alice");
System.out.println("Leeftijd van Alice:"+ageOfAlice);
// Controleren of een sleutel aanwezig is in de Map
boolean containBob = map.containsKey("Bob");
System.out.println("Bevat bob?"+containBob);
// De grootte van de Map opvragen
int size = map.size();
System.out.println("Grootte van de Map:" +size);
//Alle sleutels van de Map afdrukken
for (String key : map.keySet()){ //methode kayset belangrijk is
System.out.println("Sleutel: "+key);
}
//alle waarde van de map afdrukken
for (int value : map.values()){ //methode values belangrijk is
System.out.println("Waarde: "+value);
}
//De Map leegmaken
map.clear();
boolean isEmpty = map.isEmpty();
System.out.println(" Is de map leeg? "+isEmpty);
}
//Veelgebruikte Map-methoden
//● put(key, value): Voegt een sleutel-waardepaar toe aan de Map.
//● get(key): Haalt de waarde op die is geassocieerd met de opgegeven sleutel.
//● containsKey(key): Controleert of de opgegeven sleutel aanwezig is in de Map.
//● remove(key): Verwijdert het sleutel-waardepaar met de opgegeven sleutel.
}
| JananJavdan/Java-Fundamentals | Chapter13_Collections/src/Map/HashMapExample.java | 606 | //string is de key integer is value //interface "map" als een referance (polymorphisem) hasp implementeerd map
| line_comment | nl | package Map;
import java.util.HashMap;
import java.util.Map;
public class HashMapExample {
public static void main(String[] args) {
// Een Map maken en elementen toevoegen
//string is<SUF>
Map<String, Integer> map = new HashMap<>();
map.put("Alice", 25); //"put" om element toe te voegen (list = add) (set= offer)
map.put("Bob", 30);
map.put("Charlie", 35);
// Een element opzoeken en de waarde afdrukken
int ageOfAlice = map.get("Alice");
System.out.println("Leeftijd van Alice:"+ageOfAlice);
// Controleren of een sleutel aanwezig is in de Map
boolean containBob = map.containsKey("Bob");
System.out.println("Bevat bob?"+containBob);
// De grootte van de Map opvragen
int size = map.size();
System.out.println("Grootte van de Map:" +size);
//Alle sleutels van de Map afdrukken
for (String key : map.keySet()){ //methode kayset belangrijk is
System.out.println("Sleutel: "+key);
}
//alle waarde van de map afdrukken
for (int value : map.values()){ //methode values belangrijk is
System.out.println("Waarde: "+value);
}
//De Map leegmaken
map.clear();
boolean isEmpty = map.isEmpty();
System.out.println(" Is de map leeg? "+isEmpty);
}
//Veelgebruikte Map-methoden
//● put(key, value): Voegt een sleutel-waardepaar toe aan de Map.
//● get(key): Haalt de waarde op die is geassocieerd met de opgegeven sleutel.
//● containsKey(key): Controleert of de opgegeven sleutel aanwezig is in de Map.
//● remove(key): Verwijdert het sleutel-waardepaar met de opgegeven sleutel.
}
|
31830_18 |
import java.util.Scanner;
public class Rekenmachine {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Voer een wiskundige expressie in of typ 'exit' om te stoppen: ");
String expressie = scanner.nextLine();//Gebruikersinvoer lezen
if (expressie.equalsIgnoreCase("exit")) {//Controle op stoppen
System.out.println("Programma beëindigd.");// Als dit waar is, wordt de boodschap "Programma beëindigd." afgedrukt.
break;//wordt de lus beëindigd met het gebruik van break.
}
//Dit gedeelte van de code voert een poging uit om de ingevoerde wiskundige expressie te evalueren en geeft vervolgens het resultaat weer.
// Als er tijdens het evalueren een fout optreedt, wordt een 'catch'-blok gebruikt om de fout af te handelen en een bericht naar de gebruiker te sturen.
try {
double resultaat = evaluate(expressie);
System.out.println("Resultaat: " + resultaat);
} catch (Exception e) {
System.out.println("Foutieve invoer, probeer opnieuw.");
}
}
scanner.close();
}
//Deze code definieert een methode genaamd evaluate die verantwoordelijk is voor het evalueren van een wiskundige expressie die wordt doorgegeven als een stringparameter expressie.
//numerieke resultaat als een double-waarde terug te geven.
private static double evaluate(String expressie) {
return new Object() {//Dit creëert een anoniem object in Java, een instantie van een anonieme inner class, die binnen de evaluate-methode wordt aangemaakt
int positie = -1, karakter;// variabelen positie en karakter gedefinieerd. (positie wordt geïnitialiseerd op -1 en karakter wordt nog niet geïnitialiseerd.)
void volgendeKarakter() {//Dit is een methode binnen het anonieme object die verantwoordelijk is voor het verplaatsen naar het volgende karakter in de invoerexpressie.
karakter = (++positie < expressie.length()) ? expressie.charAt(positie) : -1;
}//deze logica verhoogt eerst de positie met 1 en controleert vervolgens of deze nieuwe positie binnen de lengte van de expressie valt
void overslaanLeegtes() {//dit is een methode die geen waarde retourneert ,(void)
while (Character.isWhitespace(karakter)) {//de methode controleert of het karakter een spatie, tab, newline of een andere vorm van witruimte is.
volgendeKarakter();// Deze methode is verantwoordelijk voor het bijwerken van het karakter naar het volgende karakter in de reeks, dat geen witruimte is
}
//Deze methode is bedoeld om spaties en andere witruimtes in de invoer over te slaan terwijl de parser door de expressie gaat.
}
double parseUitdrukking() {//parse gebruik voor het analizeren en evalueren van de wiskunde
volgendeKarakter();
double resultaat = parseToevoegingEnAftrek();//Dit is een methode binnen de parser die verantwoordelijk is voor het analyseren en evalueren van de gehele wiskundige expressie.
if (positie < expressie.length()) {
throw new RuntimeException("Ongeldige expressie.");
}
return resultaat;//Als er geen ongeldige expressie is aangetroffen, wordt het berekende resultaat van de expressie geretourneerd als een double
}
double parseToevoegingEnAftrek() {//Deze methode is verantwoordelijk voor het verwerken van optelling en aftrek in een wiskundige expressie
double resultaat = parseVermenigvuldigingEnDelen();//hier wordt voor om de vermenigvuldiging en deling in de expressie te verwerken en het resulterende getal te verkrijgen.
while (true) {//Dit geeft een oneindige lus aan waarin de methode blijft werken om de optelling en aftrek uit te voeren, totdat de hele expressie is geëvalueerd.
overslaanLeegtes();// Deze methode wordt gebruikt om eventuele witruimtes over te slaan en naar het volgende relevante karakter in de expressie te gaan.
if (karakter == '+') {
volgendeKarakter();
resultaat += parseVermenigvuldigingEnDelen();
} else if (karakter == '-') {
volgendeKarakter();
resultaat -= parseVermenigvuldigingEnDelen();
} else {
return resultaat;
}
}
// Deze sectie controleert het huidige karakter in de expressie. Als het een '+' is, wordt de methode parseVermenigvuldigingEnDelen() opnieuw aangeroepen om de
// volgende waarde te verkrijgen, en deze waarde wordt toegevoegd aan het totaal. Als het een '-' is, wordt de methode opnieuw aangeroepen en de verkregen waarde
// wordt afgetrokken van het totaal. Als het geen '+' of '-' is, betekent dit dat we klaar zijn met optellen en aftrekken, en het huidige resultaat wordt geretourneerd
// als het eindresultaat van de optelling en aftrek in dit deel van de expressie.
}
double parseVermenigvuldigingEnDelen() {
double resultaat = parseModulo();
while (true) {
overslaanLeegtes();
if (karakter == '*') {
volgendeKarakter();
resultaat *= parseModulo();
} else if (karakter == '/') {
volgendeKarakter();
resultaat /= parseModulo();
} else {
return resultaat;
}
}
}
double parseModulo() {
double resultaat = parseWaarde();
while (true) {
overslaanLeegtes();
if (karakter == '%') {
volgendeKarakter();
resultaat %= parseWaarde();
} else {
return resultaat;
}
}
}
//deze methode vertegenwoordigt voor het verwerken van waarden binnen een wiskundige expressie om haakjes in de expressie te verwerken en de waarde binnen deze haakjes te evalueren.
double parseWaarde() {//een methode die double waarde retourneert
overslaanLeegtes();//Dit is een methode die wordt aangeroepen om eventuele witruimtes over te slaan en naar het volgende relevante karakter in de expressie te gaan.
if (karakter == '(') {//Deze voorwaarde controleert of het huidige karakter gelijk is aan '(' (een openingshaakje). Als dat het geval is, betekent dit dat er een wiskundige expressie tussen haakjes is.
volgendeKarakter();// Als er een openingshaakje is , deze methode aangeroepen om naar het volgende karakter te gaan na het openingshaakje.
double resultaat = parseToevoegingEnAftrek();// Dit is een methodeaanroep die verantwoordelijk is voor het parseren en evalueren van de wiskundige expressie binnen de haakjes.
if (karakter != ')') {//controleert of het huidige karakter niet gelijk is aan ')' (een sluitingshaakje).
throw new RuntimeException("Ontbrekende haakjes.");// Als dat het geval is, wordt er een uitzondering (exception) gegenereerd omdat de sluitingshaakjes ontbreken.
}
volgendeKarakter();//Als er een sluitingshaakje is, wordt de methode aangeroepen om naar het karakter na het sluitingshaakje te gaan.
return resultaat;//Het resulterende getal binnen de haakjes wordt geretourneerd als het eindresultaat van de evaluatie van deze wiskundige expressie.
}
//deze deel wordt gebruikt om numerieke waarden te verwerken die kunnen voorkomen in de expressie, zoals getallen of kommagetallen.
if (Character.isDigit(karakter) || karakter == '.') {//controleert of het huidige karakter een cijfer is (0-9) of een punt (.) dat wordt gebruikt in decimale getallen Als het karakter een cijfer is of een punt, betekent dit dat we mogelijk een numerieke waarde aan het verwerken zijn.
StringBuilder nummer = new StringBuilder();//Hier wordt een StringBuilder aangemaakt om een numerieke waarde op te bouwen tijdens het verwerken van de opeenvolgende cijfers en punt in de expressie.
while (Character.isDigit(karakter) || karakter == '.') {//Deze while-lus wordt uitgevoerd zolang het huidige karakter een cijfer is of een punt.
nummer.append((char) karakter);//Het voegt elk karakter toe aan de StringBuilder nummer
volgendeKarakter();//en gaat vervolgens naar het volgende karakter totdat er geen cijfers of punt meer zijn.
}
return Double.parseDouble(nummer.toString());// Nadat alle opeenvolgende cijfers of punten zijn verwerkt, wordt de waarde in de StringBuilder geconverteerd naar een double-waarde met behulp van Double.parseDouble().( retorneert double waarde)
}
throw new RuntimeException("Ongeldige expressie.");// Als het karakter geen cijfer is en geen punt, wordt een uitzondering gegenereerd omdat de expressie ongeldig is.
}
}.parseUitdrukking();
}
}
//korte uitleggen over "parse":
// pars ebetekent dat het analyseren van een reeks tekens (zoals een string)om de structuur of betekenis ervan te begrijpen en om te zetten naar een ander formaat of gegevenstype.
//in de rekening machine applicatie "parsen" verwijzen naar het analyseren van een wiskundige expressie in een string,waarbij elk wiskundig teken
//en andere relevante elementen worden herkend en omgezet naar een intern formaat dat kan worden gebruikt om de berekening uit te voeren.
//De parser van een rekenmachine kan bijvoorbeeld de invoerstring "10 - 5 + 6 + 8" analyseren en begrijpen dat het gaat om een reeks getallen gescheiden door wiskundige operatoren.
//De parse zal elk getal en elk teken herkennen en de nodige stappen nemen om de berekening correct uit te voeren.
| JananJavdan/Rekenmachine | src/main/java/Rekenmachine.java | 2,948 | //Deze methode is verantwoordelijk voor het verwerken van optelling en aftrek in een wiskundige expressie | line_comment | nl |
import java.util.Scanner;
public class Rekenmachine {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Voer een wiskundige expressie in of typ 'exit' om te stoppen: ");
String expressie = scanner.nextLine();//Gebruikersinvoer lezen
if (expressie.equalsIgnoreCase("exit")) {//Controle op stoppen
System.out.println("Programma beëindigd.");// Als dit waar is, wordt de boodschap "Programma beëindigd." afgedrukt.
break;//wordt de lus beëindigd met het gebruik van break.
}
//Dit gedeelte van de code voert een poging uit om de ingevoerde wiskundige expressie te evalueren en geeft vervolgens het resultaat weer.
// Als er tijdens het evalueren een fout optreedt, wordt een 'catch'-blok gebruikt om de fout af te handelen en een bericht naar de gebruiker te sturen.
try {
double resultaat = evaluate(expressie);
System.out.println("Resultaat: " + resultaat);
} catch (Exception e) {
System.out.println("Foutieve invoer, probeer opnieuw.");
}
}
scanner.close();
}
//Deze code definieert een methode genaamd evaluate die verantwoordelijk is voor het evalueren van een wiskundige expressie die wordt doorgegeven als een stringparameter expressie.
//numerieke resultaat als een double-waarde terug te geven.
private static double evaluate(String expressie) {
return new Object() {//Dit creëert een anoniem object in Java, een instantie van een anonieme inner class, die binnen de evaluate-methode wordt aangemaakt
int positie = -1, karakter;// variabelen positie en karakter gedefinieerd. (positie wordt geïnitialiseerd op -1 en karakter wordt nog niet geïnitialiseerd.)
void volgendeKarakter() {//Dit is een methode binnen het anonieme object die verantwoordelijk is voor het verplaatsen naar het volgende karakter in de invoerexpressie.
karakter = (++positie < expressie.length()) ? expressie.charAt(positie) : -1;
}//deze logica verhoogt eerst de positie met 1 en controleert vervolgens of deze nieuwe positie binnen de lengte van de expressie valt
void overslaanLeegtes() {//dit is een methode die geen waarde retourneert ,(void)
while (Character.isWhitespace(karakter)) {//de methode controleert of het karakter een spatie, tab, newline of een andere vorm van witruimte is.
volgendeKarakter();// Deze methode is verantwoordelijk voor het bijwerken van het karakter naar het volgende karakter in de reeks, dat geen witruimte is
}
//Deze methode is bedoeld om spaties en andere witruimtes in de invoer over te slaan terwijl de parser door de expressie gaat.
}
double parseUitdrukking() {//parse gebruik voor het analizeren en evalueren van de wiskunde
volgendeKarakter();
double resultaat = parseToevoegingEnAftrek();//Dit is een methode binnen de parser die verantwoordelijk is voor het analyseren en evalueren van de gehele wiskundige expressie.
if (positie < expressie.length()) {
throw new RuntimeException("Ongeldige expressie.");
}
return resultaat;//Als er geen ongeldige expressie is aangetroffen, wordt het berekende resultaat van de expressie geretourneerd als een double
}
double parseToevoegingEnAftrek() {//Deze methode<SUF>
double resultaat = parseVermenigvuldigingEnDelen();//hier wordt voor om de vermenigvuldiging en deling in de expressie te verwerken en het resulterende getal te verkrijgen.
while (true) {//Dit geeft een oneindige lus aan waarin de methode blijft werken om de optelling en aftrek uit te voeren, totdat de hele expressie is geëvalueerd.
overslaanLeegtes();// Deze methode wordt gebruikt om eventuele witruimtes over te slaan en naar het volgende relevante karakter in de expressie te gaan.
if (karakter == '+') {
volgendeKarakter();
resultaat += parseVermenigvuldigingEnDelen();
} else if (karakter == '-') {
volgendeKarakter();
resultaat -= parseVermenigvuldigingEnDelen();
} else {
return resultaat;
}
}
// Deze sectie controleert het huidige karakter in de expressie. Als het een '+' is, wordt de methode parseVermenigvuldigingEnDelen() opnieuw aangeroepen om de
// volgende waarde te verkrijgen, en deze waarde wordt toegevoegd aan het totaal. Als het een '-' is, wordt de methode opnieuw aangeroepen en de verkregen waarde
// wordt afgetrokken van het totaal. Als het geen '+' of '-' is, betekent dit dat we klaar zijn met optellen en aftrekken, en het huidige resultaat wordt geretourneerd
// als het eindresultaat van de optelling en aftrek in dit deel van de expressie.
}
double parseVermenigvuldigingEnDelen() {
double resultaat = parseModulo();
while (true) {
overslaanLeegtes();
if (karakter == '*') {
volgendeKarakter();
resultaat *= parseModulo();
} else if (karakter == '/') {
volgendeKarakter();
resultaat /= parseModulo();
} else {
return resultaat;
}
}
}
double parseModulo() {
double resultaat = parseWaarde();
while (true) {
overslaanLeegtes();
if (karakter == '%') {
volgendeKarakter();
resultaat %= parseWaarde();
} else {
return resultaat;
}
}
}
//deze methode vertegenwoordigt voor het verwerken van waarden binnen een wiskundige expressie om haakjes in de expressie te verwerken en de waarde binnen deze haakjes te evalueren.
double parseWaarde() {//een methode die double waarde retourneert
overslaanLeegtes();//Dit is een methode die wordt aangeroepen om eventuele witruimtes over te slaan en naar het volgende relevante karakter in de expressie te gaan.
if (karakter == '(') {//Deze voorwaarde controleert of het huidige karakter gelijk is aan '(' (een openingshaakje). Als dat het geval is, betekent dit dat er een wiskundige expressie tussen haakjes is.
volgendeKarakter();// Als er een openingshaakje is , deze methode aangeroepen om naar het volgende karakter te gaan na het openingshaakje.
double resultaat = parseToevoegingEnAftrek();// Dit is een methodeaanroep die verantwoordelijk is voor het parseren en evalueren van de wiskundige expressie binnen de haakjes.
if (karakter != ')') {//controleert of het huidige karakter niet gelijk is aan ')' (een sluitingshaakje).
throw new RuntimeException("Ontbrekende haakjes.");// Als dat het geval is, wordt er een uitzondering (exception) gegenereerd omdat de sluitingshaakjes ontbreken.
}
volgendeKarakter();//Als er een sluitingshaakje is, wordt de methode aangeroepen om naar het karakter na het sluitingshaakje te gaan.
return resultaat;//Het resulterende getal binnen de haakjes wordt geretourneerd als het eindresultaat van de evaluatie van deze wiskundige expressie.
}
//deze deel wordt gebruikt om numerieke waarden te verwerken die kunnen voorkomen in de expressie, zoals getallen of kommagetallen.
if (Character.isDigit(karakter) || karakter == '.') {//controleert of het huidige karakter een cijfer is (0-9) of een punt (.) dat wordt gebruikt in decimale getallen Als het karakter een cijfer is of een punt, betekent dit dat we mogelijk een numerieke waarde aan het verwerken zijn.
StringBuilder nummer = new StringBuilder();//Hier wordt een StringBuilder aangemaakt om een numerieke waarde op te bouwen tijdens het verwerken van de opeenvolgende cijfers en punt in de expressie.
while (Character.isDigit(karakter) || karakter == '.') {//Deze while-lus wordt uitgevoerd zolang het huidige karakter een cijfer is of een punt.
nummer.append((char) karakter);//Het voegt elk karakter toe aan de StringBuilder nummer
volgendeKarakter();//en gaat vervolgens naar het volgende karakter totdat er geen cijfers of punt meer zijn.
}
return Double.parseDouble(nummer.toString());// Nadat alle opeenvolgende cijfers of punten zijn verwerkt, wordt de waarde in de StringBuilder geconverteerd naar een double-waarde met behulp van Double.parseDouble().( retorneert double waarde)
}
throw new RuntimeException("Ongeldige expressie.");// Als het karakter geen cijfer is en geen punt, wordt een uitzondering gegenereerd omdat de expressie ongeldig is.
}
}.parseUitdrukking();
}
}
//korte uitleggen over "parse":
// pars ebetekent dat het analyseren van een reeks tekens (zoals een string)om de structuur of betekenis ervan te begrijpen en om te zetten naar een ander formaat of gegevenstype.
//in de rekening machine applicatie "parsen" verwijzen naar het analyseren van een wiskundige expressie in een string,waarbij elk wiskundig teken
//en andere relevante elementen worden herkend en omgezet naar een intern formaat dat kan worden gebruikt om de berekening uit te voeren.
//De parser van een rekenmachine kan bijvoorbeeld de invoerstring "10 - 5 + 6 + 8" analyseren en begrijpen dat het gaat om een reeks getallen gescheiden door wiskundige operatoren.
//De parse zal elk getal en elk teken herkennen en de nodige stappen nemen om de berekening correct uit te voeren.
|
152641_17 | package intecbrussel.be.Vaccination;
import java.util.*;
import java.util.stream.Collectors;
public class AnimalShelter {
private List<Animal> animals;
private int animalId;
public AnimalShelter() {
this.animals = new ArrayList<>();
this.animalId = 1;
}
public List<Animal> getAnimals() {
return animals;
}
public void setAnimals(List<Animal> animals) {
this.animals = animals;
}
public int getAnimalId() {
return animalId;
}
public void setAnimalId(int animalId) {
this.animalId = animalId;
}
//1
public void printAnimals(){
for (Animal animal : animals){
System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());
}
}
// sorteert de dieren volgens hun natuurlijke volgorde, dit is volgens hun animalNumber.
//2
public void sortAnimals(){
animals.sort(Comparator.comparing(Animal::getAnimalNumber));
}
//sorteert de dieren op naam
//3
public void sortAnimalsByName(){
animals.sort(Comparator.comparing(Animal::getName));
}
// sorteert de dieren op leeftijd
//4
public void sortAnimalsByAge(){
animals.sort(Comparator.comparing(Animal::getAge));
}
//print alle dieren af die niet gevaccineert zijn voor een opgegeven ziekte
//5
public void printAnimalsNotVaccinated(Disease disease){
List<Animal> notVaccinated = animals.stream().filter(animal -> animal.getIsVaccinated().getOrDefault(disease, false)).collect(Collectors.toList());
for (Animal animal : notVaccinated){
System.out.println(animal.getName()+" is not vaccinated "+disease.name());
}
}
//zoek dier op dierennummer
//6
public Animal findAnimal(int animalNumber) {
for (Animal animal : animals){
if (animal.getAnimalNumber() == animalNumber){
return animal;
}
}
return null;
// return animals.stream().filter(animal -> animal.getAnimalNumber()==animalNumber).findFirst();
}
//zoek dier op dierennaam
//7
public Optional<Animal> findAnimal(String name){
return animals.stream().filter(animal -> animal.getName().equalsIgnoreCase(name)).findFirst();
}
// behandel opgegeven dier
//8
public void treatAnimal(int animalNumber){
for (Animal animal : animals){
if (animal.getAnimalNumber()==animalNumber){
System.out.println("treat animal by number: "+animal.getAnimalNumber()+animal.getIsVaccinated());
}
}
//System.out.println("animal with number "+animalNumber+"not found");
/* animals.stream()
.sorted(Comparator.comparingInt(Animal::getAnimalNumber))
.forEach(animal -> System.out.println(
"Animal number: "+animal.getAnimalNumber()+
"| name: "+animal.getName()+
"| age: "+animal.getAge()+
"| is clean? "+animal.getIsVaccinated()
));///////////////////////////////////////////////////////////////////////////////////////////////////////
/*Optional<Animal> optionalAnimal = findAnimal(animalNumber);
if (optionalAnimal.isPresent()){
Animal animal = optionalAnimal.get();
animal.treatAnimal();
System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());
}else {
System.out.println("animal met number "+animalNumber+"not found");
}*/
}
//behandel opgegeven dier
//9
public void treatAnimal(String name){
for (Animal animal : animals){
if (animal.getName()==name){
System.out.println("treat animal by name: "+animal.getName()+animal.getIsVaccinated());
}
}
/*animals.stream()
.sorted(Comparator.comparing(Animal::getName))
.forEach(animal -> System.out.println(
"name: "+animal.getName()+
"| animal number: "+animal.getAnimalNumber()+
"| age: "+animal.getAge()+
"| is clean? "+animal.getIsVaccinated()
));/////////////////////////////////////////////////////////////////////////////////////////////////////
/* Optional<Animal> optionalAnimal = findAnimal(name);
if (optionalAnimal.isPresent()){
Animal animal = optionalAnimal.get();
animal.treatAnimal();
System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());
}else {
System.out.println("animal met name "+name+ "not found");
}*/
}
//behandel alle dieren
//10
public void treatAllAnimals(){
for (Animal animal : animals){
animal.treatAnimal();
System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());
}
}
//geef het oudste dier terug
//11
public Animal findOldestAnimal() throws NoSuchElementException {
if (animals.isEmpty()) {
throw new NoSuchElementException("No animal found in this list");
}
Animal oldestAnimal = animals.get(0);
for (Animal animal : animals){
if (animal.getAge() > oldestAnimal.getAge()){
oldestAnimal = animal;
//System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());
}
}
return oldestAnimal;
}
// geef het aantal dieren terug
//12
public int countAnimals(){
if (animals != null){
return animals.size();
}else {
return 0;
}
}
//voeg een dier toe aan de lijst van animals
//13
public void addAnimal(Animal animal) throws IllegalArgumentException{
if (animal != null){
animal.setAnimalNumber(animalId);//toewijzen de nummer animal
animals.add(animal);//add de animal to de list
animalId++;//verhoog de animal id
}else {
throw new IllegalArgumentException("Can not add null animal to de list");
}
}
}
| JananJavdan/Vaccination | Vaccination/src/main/java/intecbrussel/be/Vaccination/AnimalShelter.java | 2,073 | //toewijzen de nummer animal
| line_comment | nl | package intecbrussel.be.Vaccination;
import java.util.*;
import java.util.stream.Collectors;
public class AnimalShelter {
private List<Animal> animals;
private int animalId;
public AnimalShelter() {
this.animals = new ArrayList<>();
this.animalId = 1;
}
public List<Animal> getAnimals() {
return animals;
}
public void setAnimals(List<Animal> animals) {
this.animals = animals;
}
public int getAnimalId() {
return animalId;
}
public void setAnimalId(int animalId) {
this.animalId = animalId;
}
//1
public void printAnimals(){
for (Animal animal : animals){
System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());
}
}
// sorteert de dieren volgens hun natuurlijke volgorde, dit is volgens hun animalNumber.
//2
public void sortAnimals(){
animals.sort(Comparator.comparing(Animal::getAnimalNumber));
}
//sorteert de dieren op naam
//3
public void sortAnimalsByName(){
animals.sort(Comparator.comparing(Animal::getName));
}
// sorteert de dieren op leeftijd
//4
public void sortAnimalsByAge(){
animals.sort(Comparator.comparing(Animal::getAge));
}
//print alle dieren af die niet gevaccineert zijn voor een opgegeven ziekte
//5
public void printAnimalsNotVaccinated(Disease disease){
List<Animal> notVaccinated = animals.stream().filter(animal -> animal.getIsVaccinated().getOrDefault(disease, false)).collect(Collectors.toList());
for (Animal animal : notVaccinated){
System.out.println(animal.getName()+" is not vaccinated "+disease.name());
}
}
//zoek dier op dierennummer
//6
public Animal findAnimal(int animalNumber) {
for (Animal animal : animals){
if (animal.getAnimalNumber() == animalNumber){
return animal;
}
}
return null;
// return animals.stream().filter(animal -> animal.getAnimalNumber()==animalNumber).findFirst();
}
//zoek dier op dierennaam
//7
public Optional<Animal> findAnimal(String name){
return animals.stream().filter(animal -> animal.getName().equalsIgnoreCase(name)).findFirst();
}
// behandel opgegeven dier
//8
public void treatAnimal(int animalNumber){
for (Animal animal : animals){
if (animal.getAnimalNumber()==animalNumber){
System.out.println("treat animal by number: "+animal.getAnimalNumber()+animal.getIsVaccinated());
}
}
//System.out.println("animal with number "+animalNumber+"not found");
/* animals.stream()
.sorted(Comparator.comparingInt(Animal::getAnimalNumber))
.forEach(animal -> System.out.println(
"Animal number: "+animal.getAnimalNumber()+
"| name: "+animal.getName()+
"| age: "+animal.getAge()+
"| is clean? "+animal.getIsVaccinated()
));///////////////////////////////////////////////////////////////////////////////////////////////////////
/*Optional<Animal> optionalAnimal = findAnimal(animalNumber);
if (optionalAnimal.isPresent()){
Animal animal = optionalAnimal.get();
animal.treatAnimal();
System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());
}else {
System.out.println("animal met number "+animalNumber+"not found");
}*/
}
//behandel opgegeven dier
//9
public void treatAnimal(String name){
for (Animal animal : animals){
if (animal.getName()==name){
System.out.println("treat animal by name: "+animal.getName()+animal.getIsVaccinated());
}
}
/*animals.stream()
.sorted(Comparator.comparing(Animal::getName))
.forEach(animal -> System.out.println(
"name: "+animal.getName()+
"| animal number: "+animal.getAnimalNumber()+
"| age: "+animal.getAge()+
"| is clean? "+animal.getIsVaccinated()
));/////////////////////////////////////////////////////////////////////////////////////////////////////
/* Optional<Animal> optionalAnimal = findAnimal(name);
if (optionalAnimal.isPresent()){
Animal animal = optionalAnimal.get();
animal.treatAnimal();
System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());
}else {
System.out.println("animal met name "+name+ "not found");
}*/
}
//behandel alle dieren
//10
public void treatAllAnimals(){
for (Animal animal : animals){
animal.treatAnimal();
System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());
}
}
//geef het oudste dier terug
//11
public Animal findOldestAnimal() throws NoSuchElementException {
if (animals.isEmpty()) {
throw new NoSuchElementException("No animal found in this list");
}
Animal oldestAnimal = animals.get(0);
for (Animal animal : animals){
if (animal.getAge() > oldestAnimal.getAge()){
oldestAnimal = animal;
//System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());
}
}
return oldestAnimal;
}
// geef het aantal dieren terug
//12
public int countAnimals(){
if (animals != null){
return animals.size();
}else {
return 0;
}
}
//voeg een dier toe aan de lijst van animals
//13
public void addAnimal(Animal animal) throws IllegalArgumentException{
if (animal != null){
animal.setAnimalNumber(animalId);//toewijzen de<SUF>
animals.add(animal);//add de animal to de list
animalId++;//verhoog de animal id
}else {
throw new IllegalArgumentException("Can not add null animal to de list");
}
}
}
|
202134_1 |
package ss.week6.voteMachine.gui;
import java.awt.Container;
import java.awt.FlowLayout;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import java.util.Set;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import ss.week6.voteMachine.VoteList;
/**
* P2 prac wk3.
* UitslagJFrame: GUI voor een Uitslag.
* @author Arend Rensink en Theo Ruys
* @version 2005.02.15
*/
public class ResultJFrame extends JFrame {
// Grafische componenten
private JTextArea resultField;
private JLabel messageLabel;
/** Construeert een UitslagJFrame die een gegeven uitslag observeert. */
public ResultJFrame(VoteGUIView view) {
// Initialisatie grafische componenten
super("Result");
Container cc = getContentPane();
cc.setLayout(new FlowLayout());
messageLabel = new JLabel("Votes:");
cc.add(messageLabel);
resultField = new JTextArea("", 10, 20);
resultField.setEditable(false);
cc.add(resultField);
setSize(250, 255);
}
/** Zet de uitslag op het tekstveld, met 1 regel per partij. */
public void update(Map<String,Integer> votes) {
resultField.setText("");
for(Map.Entry<String,Integer> entry: votes.entrySet()){
resultField.append(entry.getKey() + ": " + entry.getValue() + "\n");
}
}
}
| Janwillemtv/ProgrammingProject | softwaresystems/src/ss/week6/voteMachine/gui/ResultJFrame.java | 461 | /** Construeert een UitslagJFrame die een gegeven uitslag observeert. */ | block_comment | nl |
package ss.week6.voteMachine.gui;
import java.awt.Container;
import java.awt.FlowLayout;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import java.util.Set;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import ss.week6.voteMachine.VoteList;
/**
* P2 prac wk3.
* UitslagJFrame: GUI voor een Uitslag.
* @author Arend Rensink en Theo Ruys
* @version 2005.02.15
*/
public class ResultJFrame extends JFrame {
// Grafische componenten
private JTextArea resultField;
private JLabel messageLabel;
/** Construeert een UitslagJFrame<SUF>*/
public ResultJFrame(VoteGUIView view) {
// Initialisatie grafische componenten
super("Result");
Container cc = getContentPane();
cc.setLayout(new FlowLayout());
messageLabel = new JLabel("Votes:");
cc.add(messageLabel);
resultField = new JTextArea("", 10, 20);
resultField.setEditable(false);
cc.add(resultField);
setSize(250, 255);
}
/** Zet de uitslag op het tekstveld, met 1 regel per partij. */
public void update(Map<String,Integer> votes) {
resultField.setText("");
for(Map.Entry<String,Integer> entry: votes.entrySet()){
resultField.append(entry.getKey() + ": " + entry.getValue() + "\n");
}
}
}
|
73684_2 | /**
* Appcelerator Titanium Mobile
* Copyright (c) 2009-2010 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
package org.appcelerator.titanium.view;
import java.util.Comparator;
import java.util.TreeSet;
import org.appcelerator.kroll.common.Log;
import org.appcelerator.kroll.common.TiConfig;
import org.appcelerator.titanium.TiC;
import org.appcelerator.titanium.TiDimension;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.OnHierarchyChangeListener;
public class TiCompositeLayout extends ViewGroup
implements OnHierarchyChangeListener
{
public enum LayoutArrangement {DEFAULT, VERTICAL, HORIZONTAL}
protected static final String TAG = "TiCompositeLayout";
protected static final boolean DBG = TiConfig.LOGD && false;
public static final int NOT_SET = Integer.MIN_VALUE;
private TreeSet<View> viewSorter;
private boolean needsSort;
protected LayoutArrangement arrangement;
// Used by horizonal arrangement calculations
private int horizontalLayoutTopBuffer = 0;
private int horizontalLayoutCurrentLeft = 0;
private int horizontalLayoutLineHeight = 0;
private boolean disableHorizontalWrap = false;
public TiCompositeLayout(Context context)
{
this(context, LayoutArrangement.DEFAULT);
}
public TiCompositeLayout(Context context, LayoutArrangement arrangement)
{
super(context);
this.arrangement = arrangement;
this.viewSorter = new TreeSet<View>(new Comparator<View>(){
public int compare(View o1, View o2)
{
TiCompositeLayout.LayoutParams p1 =
(TiCompositeLayout.LayoutParams) o1.getLayoutParams();
TiCompositeLayout.LayoutParams p2 =
(TiCompositeLayout.LayoutParams) o2.getLayoutParams();
int result = 0;
if (p1.optionZIndex != NOT_SET && p2.optionZIndex != NOT_SET) {
if (p1.optionZIndex < p2.optionZIndex) {
result = -1;
} else if (p1.optionZIndex > p2.optionZIndex) {
result = 1;
}
} else if (p1.optionZIndex != NOT_SET) {
if (p1.optionZIndex < 0) {
result = -1;
} if (p1.optionZIndex > 0) {
result = 1;
}
} else if (p2.optionZIndex != NOT_SET) {
if (p2.optionZIndex < 0) {
result = 1;
} if (p2.optionZIndex > 0) {
result = -1;
}
}
if (result == 0) {
if (p1.index < p2.index) {
result = -1;
} else if (p1.index > p2.index) {
result = 1;
} else {
throw new IllegalStateException("Ambiguous Z-Order");
}
}
return result;
}});
needsSort = true;
setOnHierarchyChangeListener(this);
}
public TiCompositeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TiCompositeLayout(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
private String viewToString(View view) {
return view.getClass().getSimpleName() + "@" + Integer.toHexString(view.hashCode());
}
public void resort()
{
needsSort = true;
requestLayout();
invalidate();
}
public void onChildViewAdded(View parent, View child) {
needsSort = true;
if (DBG && parent != null && child != null) {
Log.d(TAG, "Attaching: " + viewToString(child) + " to " + viewToString(parent));
}
}
public void onChildViewRemoved(View parent, View child) {
needsSort = true;
if (DBG) {
Log.d(TAG, "Removing: " + viewToString(child) + " from " + viewToString(parent));
}
}
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof TiCompositeLayout.LayoutParams;
}
@Override
protected LayoutParams generateDefaultLayoutParams()
{
// Default is fill view
LayoutParams params = new LayoutParams();
params.optionLeft = null;
params.optionRight = null;
params.optionTop = null;
params.optionBottom = null;
params.optionZIndex = NOT_SET;
params.autoHeight = true;
params.autoWidth = true;
return params;
}
protected int getViewWidthPadding(View child, int parentWidth)
{
LayoutParams p = (LayoutParams) child.getLayoutParams();
int padding = 0;
if (p.optionLeft != null) {
if (p.optionLeft.isUnitPercent()) {
padding += (int) ((p.optionLeft.getValue() / 100.0) * parentWidth);
} else {
padding += p.optionLeft.getAsPixels(this);
}
}
if (p.optionRight != null) {
if (p.optionRight.isUnitPercent()) {
padding += (int) ((p.optionRight.getValue() / 100.0) * parentWidth);
} else {
padding += p.optionRight.getAsPixels(this);
}
}
return padding;
}
protected int getViewHeightPadding(View child, int parentHeight)
{
LayoutParams p = (LayoutParams) child.getLayoutParams();
int padding = 0;
if (p.optionTop != null) {
if (p.optionTop.isUnitPercent()) {
padding += (int) ((p.optionTop.getValue() / 100.0) * parentHeight);
} else {
padding += p.optionTop.getAsPixels(this);
}
}
if (p.optionBottom != null) {
if (p.optionBottom.isUnitPercent()) {
padding += (int) ((p.optionBottom.getValue() / 100.0) * parentHeight);
} else {
padding += p.optionBottom.getAsPixels(this);
}
}
return padding;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
int childCount = getChildCount();
int wFromSpec = MeasureSpec.getSize(widthMeasureSpec);
int hFromSpec = MeasureSpec.getSize(heightMeasureSpec);
int wSuggested = getSuggestedMinimumWidth();
int hSuggested = getSuggestedMinimumHeight();
int w = Math.max(wFromSpec, wSuggested);
int wMode = MeasureSpec.getMode(widthMeasureSpec);
int h = Math.max(hFromSpec, hSuggested);
int hMode = MeasureSpec.getMode(heightMeasureSpec);
int maxWidth = 0;
int maxHeight = 0;
for(int i = 0; i < childCount; i++) {
View child = getChildAt(i);
if (child.getVisibility() != View.GONE) {
constrainChild(child, w, wMode, h, hMode);
}
int childWidth = child.getMeasuredWidth();
int childHeight = child.getMeasuredHeight();
if (child.getVisibility() != View.GONE) {
childWidth += getViewWidthPadding(child, w);
childHeight += getViewHeightPadding(child, h);
}
if (isHorizontalArrangement()) {
maxWidth += childWidth;
} else {
maxWidth = Math.max(maxWidth, childWidth);
}
if (isVerticalArrangement()) {
maxHeight += childHeight;
} else {
maxHeight = Math.max(maxHeight, childHeight);
}
}
// account for padding
maxWidth += getPaddingLeft() + getPaddingRight();
maxHeight += getPaddingTop() + getPaddingBottom();
// Account for border
//int padding = Math.round(borderHelper.calculatePadding());
//maxWidth += padding;
//maxHeight += padding;
// check minimums
maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());
maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
int measuredWidth = getMeasuredWidth(maxWidth, widthMeasureSpec);
int measuredHeight = getMeasuredHeight(maxHeight,heightMeasureSpec);
setMeasuredDimension(measuredWidth, measuredHeight);
}
protected void constrainChild(View child, int width, int wMode, int height, int hMode)
{
LayoutParams p = (LayoutParams) child.getLayoutParams();
int childDimension = LayoutParams.WRAP_CONTENT;
if (p.optionWidth != null) {
if (p.optionWidth.isUnitPercent() && width > 0) {
childDimension = (int) ((p.optionWidth.getValue() / 100.0) * width);
} else {
childDimension = p.optionWidth.getAsPixels(this);
}
} else {
if (p.autoWidth && p.autoFillsWidth && !isHorizontalArrangement()) {
childDimension = LayoutParams.FILL_PARENT;
}
}
int widthPadding = getViewWidthPadding(child, width);
int widthSpec = ViewGroup.getChildMeasureSpec(MeasureSpec.makeMeasureSpec(width, wMode), widthPadding,
childDimension);
childDimension = LayoutParams.WRAP_CONTENT;
if (p.optionHeight != null) {
if (p.optionHeight.isUnitPercent() && height > 0) {
childDimension = (int) ((p.optionHeight.getValue() / 100.0) * height);
} else {
childDimension = p.optionHeight.getAsPixels(this);
}
} else {
if (p.autoHeight && p.autoFillsHeight && !isVerticalArrangement()) {
childDimension = LayoutParams.FILL_PARENT;
}
}
int heightPadding = getViewHeightPadding(child, height);
int heightSpec = ViewGroup.getChildMeasureSpec(MeasureSpec.makeMeasureSpec(height, hMode), heightPadding,
childDimension);
child.measure(widthSpec, heightSpec);
// Useful for debugging.
// int childWidth = child.getMeasuredWidth();
// int childHeight = child.getMeasuredHeight();
}
protected int getMeasuredWidth(int maxWidth, int widthSpec)
{
return resolveSize(maxWidth, widthSpec);
}
protected int getMeasuredHeight(int maxHeight, int heightSpec)
{
return resolveSize(maxHeight, heightSpec);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b)
{
int count = getChildCount();
int left = 0;
int top = 0;
int right = r - l;
int bottom = b - t;
if (needsSort) {
viewSorter.clear();
if (count > 1) { // No need to sort one item.
for(int i = 0; i < count; i++) {
View child = getChildAt(i);
TiCompositeLayout.LayoutParams params =
(TiCompositeLayout.LayoutParams) child.getLayoutParams();
params.index = i;
viewSorter.add(child);
}
detachAllViewsFromParent();
int i = 0;
for (View child : viewSorter) {
attachViewToParent(child, i++, child.getLayoutParams());
}
}
needsSort = false;
}
// viewSorter is not needed after this. It's a source of
// memory leaks if it retains the views it's holding.
viewSorter.clear();
int[] horizontal = new int[2];
int[] vertical = new int[2];
int currentHeight = 0; // Used by vertical arrangement calcs
for (int i = 0; i < count; i++) {
View child = getChildAt(i);
TiCompositeLayout.LayoutParams params =
(TiCompositeLayout.LayoutParams) child.getLayoutParams();
if (child.getVisibility() != View.GONE) {
// Dimension is required from Measure. Positioning is determined here.
int childMeasuredWidth = child.getMeasuredWidth();
int childMeasuredHeight = child.getMeasuredHeight();
if (isHorizontalArrangement()) {
if (i == 0) {
horizontalLayoutCurrentLeft = left;
horizontalLayoutLineHeight = 0;
horizontalLayoutTopBuffer = 0;
}
computeHorizontalLayoutPosition(params, childMeasuredWidth, childMeasuredHeight, right, top, bottom, horizontal, vertical);
} else {
computePosition(this, params.optionLeft, params.optionCenterX, params.optionRight, childMeasuredWidth, left, right, horizontal);
if (isVerticalArrangement()) {
computeVerticalLayoutPosition(currentHeight, params.optionTop, params.optionBottom, childMeasuredHeight, top, bottom, vertical);
} else {
computePosition(this, params.optionTop, params.optionCenterY, params.optionBottom, childMeasuredHeight, top, bottom, vertical);
}
}
if (DBG) {
Log.d(TAG, child.getClass().getName() + " {" + horizontal[0] + "," + vertical[0] + "," + horizontal[1] + "," + vertical[1] + "}");
}
int newWidth = horizontal[1] - horizontal[0];
int newHeight = vertical[1] - vertical[0];
if (newWidth != childMeasuredWidth
|| newHeight != childMeasuredHeight) {
int newWidthSpec = MeasureSpec.makeMeasureSpec(newWidth, MeasureSpec.EXACTLY);
int newHeightSpec = MeasureSpec.makeMeasureSpec(newHeight, MeasureSpec.EXACTLY);
child.measure(newWidthSpec, newHeightSpec);
}
child.layout(horizontal[0], vertical[0], horizontal[1], vertical[1]);
currentHeight += newHeight;
if (params.optionTop != null) {
currentHeight += params.optionTop.getAsPixels(this);
}
}
}
}
// 0 is left/top, 1 is right/bottom
public static void computePosition(View parent, TiDimension option0, TiDimension optionCenter, TiDimension option1,
int measuredSize, int layoutPosition0, int layoutPosition1, int[] pos)
{
int dist = layoutPosition1 - layoutPosition0;
if (optionCenter != null) {
int halfSize= measuredSize/2;
pos[0] = layoutPosition0 + optionCenter.getAsPixels(parent) - halfSize;
pos[1] = pos[0] + measuredSize;
} else if (option0 == null && option1 == null) {
// Center
int offset = (dist-measuredSize)/2;
pos[0] = layoutPosition0 + offset;
pos[1] = pos[0] + measuredSize;
} else if (option0 == null) {
// peg right/bottom
int option1Pixels = option1.getAsPixels(parent);
pos[0] = dist - option1Pixels - measuredSize;
pos[1] = dist - option1Pixels;
} else if (option1 == null) {
// peg left/top
int option0Pixels = option0.getAsPixels(parent);
pos[0] = layoutPosition0 + option0Pixels;
pos[1] = layoutPosition0 + option0Pixels + measuredSize;
} else {
// pegged both. override and force.
pos[0] = layoutPosition0 + option0.getAsPixels(parent);
pos[1] = layoutPosition1 - option1.getAsPixels(parent);
}
}
private void computeVerticalLayoutPosition(int currentHeight,
TiDimension optionTop, TiDimension optionBottom, int measuredHeight, int layoutTop, int layoutBottom, int[] pos)
{
int top = layoutTop + currentHeight;
if (optionTop != null) {
top += optionTop.getAsPixels(this);
}
int bottom = top + measuredHeight;
pos[0] = top;
pos[1] = bottom;
}
private void computeHorizontalLayoutPosition(TiCompositeLayout.LayoutParams params, int measuredWidth, int measuredHeight, int layoutRight, int layoutTop, int layoutBottom, int[] hpos, int[] vpos)
{
TiDimension optionLeft = params.optionLeft;
int left = horizontalLayoutCurrentLeft;
if (optionLeft != null) {
left += optionLeft.getAsPixels(this);
}
int right = left + measuredWidth;
if (right > layoutRight && !disableHorizontalWrap) {
// Too long for the current "line" that it's on. Need to move it down.
left = 0;
right = measuredWidth;
horizontalLayoutTopBuffer = horizontalLayoutTopBuffer + horizontalLayoutLineHeight;
horizontalLayoutLineHeight = 0;
}
hpos[0] = left;
hpos[1] = right;
horizontalLayoutCurrentLeft = right;
// Get vertical position into vpos
computePosition(this, params.optionTop, params.optionCenterY, params.optionBottom, measuredHeight, layoutTop, layoutBottom, vpos);
horizontalLayoutLineHeight = Math.max(horizontalLayoutLineHeight, vpos[1] - vpos[0]);
// account for moving the item "down" to later line(s) if there has been wrapping.
vpos[0] = vpos[0] + horizontalLayoutTopBuffer;
vpos[1] = vpos[1] + horizontalLayoutTopBuffer;
}
protected int getWidthMeasureSpec(View child) {
return MeasureSpec.EXACTLY;
}
protected int getHeightMeasureSpec(View child) {
return MeasureSpec.EXACTLY;
}
public static class LayoutParams extends ViewGroup.LayoutParams {
protected int index;
public int optionZIndex = NOT_SET;
public TiDimension optionLeft = null;
public TiDimension optionTop = null;
public TiDimension optionCenterX = null;
public TiDimension optionCenterY = null;
public TiDimension optionRight = null;
public TiDimension optionBottom = null;
public TiDimension optionWidth = null;
public TiDimension optionHeight = null;
public Ti2DMatrix optionTransform = null;
public boolean autoHeight = true;
public boolean autoWidth = true;
public boolean autoFillsWidth = false;
public boolean autoFillsHeight = false;
public LayoutParams() {
super(WRAP_CONTENT, WRAP_CONTENT);
index = Integer.MIN_VALUE;
}
}
protected boolean isVerticalArrangement()
{
return (arrangement == LayoutArrangement.VERTICAL);
}
protected boolean isHorizontalArrangement()
{
return (arrangement == LayoutArrangement.HORIZONTAL);
}
protected boolean isDefaultArrangement()
{
return (arrangement == LayoutArrangement.DEFAULT);
}
public void setLayoutArrangement(String arrangementProperty)
{
if (arrangementProperty != null && arrangementProperty.equals(TiC.LAYOUT_HORIZONTAL)) {
arrangement = LayoutArrangement.HORIZONTAL;
} else if (arrangementProperty != null && arrangementProperty.equals(TiC.LAYOUT_VERTICAL)) {
arrangement = LayoutArrangement.VERTICAL;
} else {
arrangement = LayoutArrangement.DEFAULT;
}
}
public void setDisableHorizontalWrap(boolean disable)
{
disableHorizontalWrap = disable;
}
}
| Jasig/titanium_mobile | android/titanium/src/java/org/appcelerator/titanium/view/TiCompositeLayout.java | 5,424 | // Default is fill view | line_comment | nl | /**
* Appcelerator Titanium Mobile
* Copyright (c) 2009-2010 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
package org.appcelerator.titanium.view;
import java.util.Comparator;
import java.util.TreeSet;
import org.appcelerator.kroll.common.Log;
import org.appcelerator.kroll.common.TiConfig;
import org.appcelerator.titanium.TiC;
import org.appcelerator.titanium.TiDimension;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.OnHierarchyChangeListener;
public class TiCompositeLayout extends ViewGroup
implements OnHierarchyChangeListener
{
public enum LayoutArrangement {DEFAULT, VERTICAL, HORIZONTAL}
protected static final String TAG = "TiCompositeLayout";
protected static final boolean DBG = TiConfig.LOGD && false;
public static final int NOT_SET = Integer.MIN_VALUE;
private TreeSet<View> viewSorter;
private boolean needsSort;
protected LayoutArrangement arrangement;
// Used by horizonal arrangement calculations
private int horizontalLayoutTopBuffer = 0;
private int horizontalLayoutCurrentLeft = 0;
private int horizontalLayoutLineHeight = 0;
private boolean disableHorizontalWrap = false;
public TiCompositeLayout(Context context)
{
this(context, LayoutArrangement.DEFAULT);
}
public TiCompositeLayout(Context context, LayoutArrangement arrangement)
{
super(context);
this.arrangement = arrangement;
this.viewSorter = new TreeSet<View>(new Comparator<View>(){
public int compare(View o1, View o2)
{
TiCompositeLayout.LayoutParams p1 =
(TiCompositeLayout.LayoutParams) o1.getLayoutParams();
TiCompositeLayout.LayoutParams p2 =
(TiCompositeLayout.LayoutParams) o2.getLayoutParams();
int result = 0;
if (p1.optionZIndex != NOT_SET && p2.optionZIndex != NOT_SET) {
if (p1.optionZIndex < p2.optionZIndex) {
result = -1;
} else if (p1.optionZIndex > p2.optionZIndex) {
result = 1;
}
} else if (p1.optionZIndex != NOT_SET) {
if (p1.optionZIndex < 0) {
result = -1;
} if (p1.optionZIndex > 0) {
result = 1;
}
} else if (p2.optionZIndex != NOT_SET) {
if (p2.optionZIndex < 0) {
result = 1;
} if (p2.optionZIndex > 0) {
result = -1;
}
}
if (result == 0) {
if (p1.index < p2.index) {
result = -1;
} else if (p1.index > p2.index) {
result = 1;
} else {
throw new IllegalStateException("Ambiguous Z-Order");
}
}
return result;
}});
needsSort = true;
setOnHierarchyChangeListener(this);
}
public TiCompositeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TiCompositeLayout(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
private String viewToString(View view) {
return view.getClass().getSimpleName() + "@" + Integer.toHexString(view.hashCode());
}
public void resort()
{
needsSort = true;
requestLayout();
invalidate();
}
public void onChildViewAdded(View parent, View child) {
needsSort = true;
if (DBG && parent != null && child != null) {
Log.d(TAG, "Attaching: " + viewToString(child) + " to " + viewToString(parent));
}
}
public void onChildViewRemoved(View parent, View child) {
needsSort = true;
if (DBG) {
Log.d(TAG, "Removing: " + viewToString(child) + " from " + viewToString(parent));
}
}
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof TiCompositeLayout.LayoutParams;
}
@Override
protected LayoutParams generateDefaultLayoutParams()
{
// Default is<SUF>
LayoutParams params = new LayoutParams();
params.optionLeft = null;
params.optionRight = null;
params.optionTop = null;
params.optionBottom = null;
params.optionZIndex = NOT_SET;
params.autoHeight = true;
params.autoWidth = true;
return params;
}
protected int getViewWidthPadding(View child, int parentWidth)
{
LayoutParams p = (LayoutParams) child.getLayoutParams();
int padding = 0;
if (p.optionLeft != null) {
if (p.optionLeft.isUnitPercent()) {
padding += (int) ((p.optionLeft.getValue() / 100.0) * parentWidth);
} else {
padding += p.optionLeft.getAsPixels(this);
}
}
if (p.optionRight != null) {
if (p.optionRight.isUnitPercent()) {
padding += (int) ((p.optionRight.getValue() / 100.0) * parentWidth);
} else {
padding += p.optionRight.getAsPixels(this);
}
}
return padding;
}
protected int getViewHeightPadding(View child, int parentHeight)
{
LayoutParams p = (LayoutParams) child.getLayoutParams();
int padding = 0;
if (p.optionTop != null) {
if (p.optionTop.isUnitPercent()) {
padding += (int) ((p.optionTop.getValue() / 100.0) * parentHeight);
} else {
padding += p.optionTop.getAsPixels(this);
}
}
if (p.optionBottom != null) {
if (p.optionBottom.isUnitPercent()) {
padding += (int) ((p.optionBottom.getValue() / 100.0) * parentHeight);
} else {
padding += p.optionBottom.getAsPixels(this);
}
}
return padding;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
int childCount = getChildCount();
int wFromSpec = MeasureSpec.getSize(widthMeasureSpec);
int hFromSpec = MeasureSpec.getSize(heightMeasureSpec);
int wSuggested = getSuggestedMinimumWidth();
int hSuggested = getSuggestedMinimumHeight();
int w = Math.max(wFromSpec, wSuggested);
int wMode = MeasureSpec.getMode(widthMeasureSpec);
int h = Math.max(hFromSpec, hSuggested);
int hMode = MeasureSpec.getMode(heightMeasureSpec);
int maxWidth = 0;
int maxHeight = 0;
for(int i = 0; i < childCount; i++) {
View child = getChildAt(i);
if (child.getVisibility() != View.GONE) {
constrainChild(child, w, wMode, h, hMode);
}
int childWidth = child.getMeasuredWidth();
int childHeight = child.getMeasuredHeight();
if (child.getVisibility() != View.GONE) {
childWidth += getViewWidthPadding(child, w);
childHeight += getViewHeightPadding(child, h);
}
if (isHorizontalArrangement()) {
maxWidth += childWidth;
} else {
maxWidth = Math.max(maxWidth, childWidth);
}
if (isVerticalArrangement()) {
maxHeight += childHeight;
} else {
maxHeight = Math.max(maxHeight, childHeight);
}
}
// account for padding
maxWidth += getPaddingLeft() + getPaddingRight();
maxHeight += getPaddingTop() + getPaddingBottom();
// Account for border
//int padding = Math.round(borderHelper.calculatePadding());
//maxWidth += padding;
//maxHeight += padding;
// check minimums
maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());
maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
int measuredWidth = getMeasuredWidth(maxWidth, widthMeasureSpec);
int measuredHeight = getMeasuredHeight(maxHeight,heightMeasureSpec);
setMeasuredDimension(measuredWidth, measuredHeight);
}
protected void constrainChild(View child, int width, int wMode, int height, int hMode)
{
LayoutParams p = (LayoutParams) child.getLayoutParams();
int childDimension = LayoutParams.WRAP_CONTENT;
if (p.optionWidth != null) {
if (p.optionWidth.isUnitPercent() && width > 0) {
childDimension = (int) ((p.optionWidth.getValue() / 100.0) * width);
} else {
childDimension = p.optionWidth.getAsPixels(this);
}
} else {
if (p.autoWidth && p.autoFillsWidth && !isHorizontalArrangement()) {
childDimension = LayoutParams.FILL_PARENT;
}
}
int widthPadding = getViewWidthPadding(child, width);
int widthSpec = ViewGroup.getChildMeasureSpec(MeasureSpec.makeMeasureSpec(width, wMode), widthPadding,
childDimension);
childDimension = LayoutParams.WRAP_CONTENT;
if (p.optionHeight != null) {
if (p.optionHeight.isUnitPercent() && height > 0) {
childDimension = (int) ((p.optionHeight.getValue() / 100.0) * height);
} else {
childDimension = p.optionHeight.getAsPixels(this);
}
} else {
if (p.autoHeight && p.autoFillsHeight && !isVerticalArrangement()) {
childDimension = LayoutParams.FILL_PARENT;
}
}
int heightPadding = getViewHeightPadding(child, height);
int heightSpec = ViewGroup.getChildMeasureSpec(MeasureSpec.makeMeasureSpec(height, hMode), heightPadding,
childDimension);
child.measure(widthSpec, heightSpec);
// Useful for debugging.
// int childWidth = child.getMeasuredWidth();
// int childHeight = child.getMeasuredHeight();
}
protected int getMeasuredWidth(int maxWidth, int widthSpec)
{
return resolveSize(maxWidth, widthSpec);
}
protected int getMeasuredHeight(int maxHeight, int heightSpec)
{
return resolveSize(maxHeight, heightSpec);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b)
{
int count = getChildCount();
int left = 0;
int top = 0;
int right = r - l;
int bottom = b - t;
if (needsSort) {
viewSorter.clear();
if (count > 1) { // No need to sort one item.
for(int i = 0; i < count; i++) {
View child = getChildAt(i);
TiCompositeLayout.LayoutParams params =
(TiCompositeLayout.LayoutParams) child.getLayoutParams();
params.index = i;
viewSorter.add(child);
}
detachAllViewsFromParent();
int i = 0;
for (View child : viewSorter) {
attachViewToParent(child, i++, child.getLayoutParams());
}
}
needsSort = false;
}
// viewSorter is not needed after this. It's a source of
// memory leaks if it retains the views it's holding.
viewSorter.clear();
int[] horizontal = new int[2];
int[] vertical = new int[2];
int currentHeight = 0; // Used by vertical arrangement calcs
for (int i = 0; i < count; i++) {
View child = getChildAt(i);
TiCompositeLayout.LayoutParams params =
(TiCompositeLayout.LayoutParams) child.getLayoutParams();
if (child.getVisibility() != View.GONE) {
// Dimension is required from Measure. Positioning is determined here.
int childMeasuredWidth = child.getMeasuredWidth();
int childMeasuredHeight = child.getMeasuredHeight();
if (isHorizontalArrangement()) {
if (i == 0) {
horizontalLayoutCurrentLeft = left;
horizontalLayoutLineHeight = 0;
horizontalLayoutTopBuffer = 0;
}
computeHorizontalLayoutPosition(params, childMeasuredWidth, childMeasuredHeight, right, top, bottom, horizontal, vertical);
} else {
computePosition(this, params.optionLeft, params.optionCenterX, params.optionRight, childMeasuredWidth, left, right, horizontal);
if (isVerticalArrangement()) {
computeVerticalLayoutPosition(currentHeight, params.optionTop, params.optionBottom, childMeasuredHeight, top, bottom, vertical);
} else {
computePosition(this, params.optionTop, params.optionCenterY, params.optionBottom, childMeasuredHeight, top, bottom, vertical);
}
}
if (DBG) {
Log.d(TAG, child.getClass().getName() + " {" + horizontal[0] + "," + vertical[0] + "," + horizontal[1] + "," + vertical[1] + "}");
}
int newWidth = horizontal[1] - horizontal[0];
int newHeight = vertical[1] - vertical[0];
if (newWidth != childMeasuredWidth
|| newHeight != childMeasuredHeight) {
int newWidthSpec = MeasureSpec.makeMeasureSpec(newWidth, MeasureSpec.EXACTLY);
int newHeightSpec = MeasureSpec.makeMeasureSpec(newHeight, MeasureSpec.EXACTLY);
child.measure(newWidthSpec, newHeightSpec);
}
child.layout(horizontal[0], vertical[0], horizontal[1], vertical[1]);
currentHeight += newHeight;
if (params.optionTop != null) {
currentHeight += params.optionTop.getAsPixels(this);
}
}
}
}
// 0 is left/top, 1 is right/bottom
public static void computePosition(View parent, TiDimension option0, TiDimension optionCenter, TiDimension option1,
int measuredSize, int layoutPosition0, int layoutPosition1, int[] pos)
{
int dist = layoutPosition1 - layoutPosition0;
if (optionCenter != null) {
int halfSize= measuredSize/2;
pos[0] = layoutPosition0 + optionCenter.getAsPixels(parent) - halfSize;
pos[1] = pos[0] + measuredSize;
} else if (option0 == null && option1 == null) {
// Center
int offset = (dist-measuredSize)/2;
pos[0] = layoutPosition0 + offset;
pos[1] = pos[0] + measuredSize;
} else if (option0 == null) {
// peg right/bottom
int option1Pixels = option1.getAsPixels(parent);
pos[0] = dist - option1Pixels - measuredSize;
pos[1] = dist - option1Pixels;
} else if (option1 == null) {
// peg left/top
int option0Pixels = option0.getAsPixels(parent);
pos[0] = layoutPosition0 + option0Pixels;
pos[1] = layoutPosition0 + option0Pixels + measuredSize;
} else {
// pegged both. override and force.
pos[0] = layoutPosition0 + option0.getAsPixels(parent);
pos[1] = layoutPosition1 - option1.getAsPixels(parent);
}
}
private void computeVerticalLayoutPosition(int currentHeight,
TiDimension optionTop, TiDimension optionBottom, int measuredHeight, int layoutTop, int layoutBottom, int[] pos)
{
int top = layoutTop + currentHeight;
if (optionTop != null) {
top += optionTop.getAsPixels(this);
}
int bottom = top + measuredHeight;
pos[0] = top;
pos[1] = bottom;
}
private void computeHorizontalLayoutPosition(TiCompositeLayout.LayoutParams params, int measuredWidth, int measuredHeight, int layoutRight, int layoutTop, int layoutBottom, int[] hpos, int[] vpos)
{
TiDimension optionLeft = params.optionLeft;
int left = horizontalLayoutCurrentLeft;
if (optionLeft != null) {
left += optionLeft.getAsPixels(this);
}
int right = left + measuredWidth;
if (right > layoutRight && !disableHorizontalWrap) {
// Too long for the current "line" that it's on. Need to move it down.
left = 0;
right = measuredWidth;
horizontalLayoutTopBuffer = horizontalLayoutTopBuffer + horizontalLayoutLineHeight;
horizontalLayoutLineHeight = 0;
}
hpos[0] = left;
hpos[1] = right;
horizontalLayoutCurrentLeft = right;
// Get vertical position into vpos
computePosition(this, params.optionTop, params.optionCenterY, params.optionBottom, measuredHeight, layoutTop, layoutBottom, vpos);
horizontalLayoutLineHeight = Math.max(horizontalLayoutLineHeight, vpos[1] - vpos[0]);
// account for moving the item "down" to later line(s) if there has been wrapping.
vpos[0] = vpos[0] + horizontalLayoutTopBuffer;
vpos[1] = vpos[1] + horizontalLayoutTopBuffer;
}
protected int getWidthMeasureSpec(View child) {
return MeasureSpec.EXACTLY;
}
protected int getHeightMeasureSpec(View child) {
return MeasureSpec.EXACTLY;
}
public static class LayoutParams extends ViewGroup.LayoutParams {
protected int index;
public int optionZIndex = NOT_SET;
public TiDimension optionLeft = null;
public TiDimension optionTop = null;
public TiDimension optionCenterX = null;
public TiDimension optionCenterY = null;
public TiDimension optionRight = null;
public TiDimension optionBottom = null;
public TiDimension optionWidth = null;
public TiDimension optionHeight = null;
public Ti2DMatrix optionTransform = null;
public boolean autoHeight = true;
public boolean autoWidth = true;
public boolean autoFillsWidth = false;
public boolean autoFillsHeight = false;
public LayoutParams() {
super(WRAP_CONTENT, WRAP_CONTENT);
index = Integer.MIN_VALUE;
}
}
protected boolean isVerticalArrangement()
{
return (arrangement == LayoutArrangement.VERTICAL);
}
protected boolean isHorizontalArrangement()
{
return (arrangement == LayoutArrangement.HORIZONTAL);
}
protected boolean isDefaultArrangement()
{
return (arrangement == LayoutArrangement.DEFAULT);
}
public void setLayoutArrangement(String arrangementProperty)
{
if (arrangementProperty != null && arrangementProperty.equals(TiC.LAYOUT_HORIZONTAL)) {
arrangement = LayoutArrangement.HORIZONTAL;
} else if (arrangementProperty != null && arrangementProperty.equals(TiC.LAYOUT_VERTICAL)) {
arrangement = LayoutArrangement.VERTICAL;
} else {
arrangement = LayoutArrangement.DEFAULT;
}
}
public void setDisableHorizontalWrap(boolean disable)
{
disableHorizontalWrap = disable;
}
}
|
169862_0 | package duplicates;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class PersonServiceTest {
/**
* De PersonService zou alleen de unieke personen moeten toevoegen en duplicaten negeren.
*/
//Wat wil je afvangen? Wil je dat er niet twee dezelfde objecten zijn met dezelfde info? Oftwel geen Person en Person met zelfde info. Of wil je dat er niet twee keer Person met locatie x in de lijst staan.
// Opgelost door person.toString te gebruiken. Hierdoor vergelijk je niet meer de locatie maar de inhoud
@Test
void testPersonService(){
PersonService personService = new PersonService();
personService.addPerson(new Person("John Doe", 30, 1.75, 70));
personService.addPerson(new Person("Jane Smith", 28, 1.65, 60));
personService.addPerson(new Person("Alice Johnson", 35, 1.70, 65));
personService.addPerson(new Person("Bob Williams", 40, 1.80, 75));
personService.addPerson(new Person("Charlie Brown", 45, 1.85, 80));
personService.addPerson(new Person("David Davis", 50, 1.90, 85));
personService.addPerson(new Person("Eve Evans", 55, 1.60, 55));
personService.addPerson(new Person("Frank Foster", 60, 1.95, 90));
personService.addPerson(new Person("Grace Green", 65, 1.55, 50));
personService.addPerson(new Person("Harry Hall", 70, 2.00, 95));
personService.addPerson(new Person("Ivy Irving", 75, 1.50, 45));
personService.addPerson(new Person("Jack Jackson", 80, 2.05, 100));
personService.addPerson(new Person("Kathy King", 85, 1.45, 40));
personService.addPerson(new Person("Larry Lewis", 90, 2.10, 105));
personService.addPerson(new Person("Molly Moore", 95, 1.40, 35));
personService.addPerson(new Person("John Doe", 30, 1.75, 70));
personService.addPerson(new Person("Jane Smith", 28, 1.65, 60));
personService.addPerson(new Person("Alice Johnson", 35, 1.70, 65));
personService.addPerson(new Person("Bob Williams", 40, 1.80, 75));
personService.addPerson(new Person("Charlie Brown", 45, 1.85, 80));
assertEquals(15, personService.size());
}
} | Jasmijn-Ginger/BadCode | BadCode/src/test/java/duplicates/PersonServiceTest.java | 720 | /**
* De PersonService zou alleen de unieke personen moeten toevoegen en duplicaten negeren.
*/ | block_comment | nl | package duplicates;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class PersonServiceTest {
/**
* De PersonService zou<SUF>*/
//Wat wil je afvangen? Wil je dat er niet twee dezelfde objecten zijn met dezelfde info? Oftwel geen Person en Person met zelfde info. Of wil je dat er niet twee keer Person met locatie x in de lijst staan.
// Opgelost door person.toString te gebruiken. Hierdoor vergelijk je niet meer de locatie maar de inhoud
@Test
void testPersonService(){
PersonService personService = new PersonService();
personService.addPerson(new Person("John Doe", 30, 1.75, 70));
personService.addPerson(new Person("Jane Smith", 28, 1.65, 60));
personService.addPerson(new Person("Alice Johnson", 35, 1.70, 65));
personService.addPerson(new Person("Bob Williams", 40, 1.80, 75));
personService.addPerson(new Person("Charlie Brown", 45, 1.85, 80));
personService.addPerson(new Person("David Davis", 50, 1.90, 85));
personService.addPerson(new Person("Eve Evans", 55, 1.60, 55));
personService.addPerson(new Person("Frank Foster", 60, 1.95, 90));
personService.addPerson(new Person("Grace Green", 65, 1.55, 50));
personService.addPerson(new Person("Harry Hall", 70, 2.00, 95));
personService.addPerson(new Person("Ivy Irving", 75, 1.50, 45));
personService.addPerson(new Person("Jack Jackson", 80, 2.05, 100));
personService.addPerson(new Person("Kathy King", 85, 1.45, 40));
personService.addPerson(new Person("Larry Lewis", 90, 2.10, 105));
personService.addPerson(new Person("Molly Moore", 95, 1.40, 35));
personService.addPerson(new Person("John Doe", 30, 1.75, 70));
personService.addPerson(new Person("Jane Smith", 28, 1.65, 60));
personService.addPerson(new Person("Alice Johnson", 35, 1.70, 65));
personService.addPerson(new Person("Bob Williams", 40, 1.80, 75));
personService.addPerson(new Person("Charlie Brown", 45, 1.85, 80));
assertEquals(15, personService.size());
}
} |
75209_6 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package treinsimulator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
/**
*
* @author Bernard
*/
public class TreinSimulator {
private static ArrayList<Station> stationLijst;
private static ArrayList<Lijn> lijnenLijst;
private static HashMap<Integer, ArrayList<Reiziger>> reizigersLijst;
// DAO mijnDAO; -----------> niet nodig, want zijn statische methodes..
// to do : readlists updaten
public static void main(String[] args) {
//Set up:
DAO.initialiseer();
stationLijst = DAO.getStationLijst();
lijnenLijst = DAO.getLijnenLijst();
reizigersLijst = DAO.getReizigersLijst();
int STOPTIJD = 2459;
Klok.setTijd(400);
//Klok:
System.out.println("-----------SIMULATIE START ----------");
while (Klok.getTijd() <= STOPTIJD) {
Set<Trein> alleTreinen = new HashSet<>();
System.out.println("----------- TREINEN KOMEN TOE ----------");
for (Lijn lijn : lijnenLijst) {
for (Trein trein : lijn.getTreinen().values()) {
alleTreinen.add(trein); // Tijdelijk treinen opslaan in een set, om niet twee keer
// iedere lijn te moeten afgaan om daar alle treinen uit te halen
trein.aankomst(Klok.getTijd());
}
}
System.out.println("----------- PASSAGIERS WORDEN OVERLOPEN ----------");
if (reizigersLijst.get(Klok.getTijd()) != null) {
for (Reiziger reiziger : reizigersLijst.get(Klok.getTijd())) {
if (!reiziger.gestrand) { //gestrande reizigers niet meer overlopen
reiziger.activeer(Klok.getTijd());
}
}
}
System.out.println("----------- TREINEN VERTREKKEN ----------");
for (Trein trein : alleTreinen) {
trein.vertrek(Klok.getTijd());
}
System.out.println("Tijd: " + Klok.getTijd());
Klok.ticktock();
}
//Data-stuff:
Statistiek st = new Statistiek(lijnenLijst, reizigersLijst);
}
}
| JasperDeRoeck/TreinSimulator | TreinSimulator/src/treinsimulator/TreinSimulator.java | 787 | //gestrande reizigers niet meer overlopen
| line_comment | nl | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package treinsimulator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
/**
*
* @author Bernard
*/
public class TreinSimulator {
private static ArrayList<Station> stationLijst;
private static ArrayList<Lijn> lijnenLijst;
private static HashMap<Integer, ArrayList<Reiziger>> reizigersLijst;
// DAO mijnDAO; -----------> niet nodig, want zijn statische methodes..
// to do : readlists updaten
public static void main(String[] args) {
//Set up:
DAO.initialiseer();
stationLijst = DAO.getStationLijst();
lijnenLijst = DAO.getLijnenLijst();
reizigersLijst = DAO.getReizigersLijst();
int STOPTIJD = 2459;
Klok.setTijd(400);
//Klok:
System.out.println("-----------SIMULATIE START ----------");
while (Klok.getTijd() <= STOPTIJD) {
Set<Trein> alleTreinen = new HashSet<>();
System.out.println("----------- TREINEN KOMEN TOE ----------");
for (Lijn lijn : lijnenLijst) {
for (Trein trein : lijn.getTreinen().values()) {
alleTreinen.add(trein); // Tijdelijk treinen opslaan in een set, om niet twee keer
// iedere lijn te moeten afgaan om daar alle treinen uit te halen
trein.aankomst(Klok.getTijd());
}
}
System.out.println("----------- PASSAGIERS WORDEN OVERLOPEN ----------");
if (reizigersLijst.get(Klok.getTijd()) != null) {
for (Reiziger reiziger : reizigersLijst.get(Klok.getTijd())) {
if (!reiziger.gestrand) { //gestrande reizigers<SUF>
reiziger.activeer(Klok.getTijd());
}
}
}
System.out.println("----------- TREINEN VERTREKKEN ----------");
for (Trein trein : alleTreinen) {
trein.vertrek(Klok.getTijd());
}
System.out.println("Tijd: " + Klok.getTijd());
Klok.ticktock();
}
//Data-stuff:
Statistiek st = new Statistiek(lijnenLijst, reizigersLijst);
}
}
|
42843_22 | public class DancingState extends State {
/////////
//singleton stuff
////////
private static DancingState instance;
private DancingState(){};
public static DancingState getInstance() {
if (instance == null)
instance = new DancingState();
return instance;
}
///////
//actual implementation
///////
@Override
public void takeAction(PersonState ps) {
setGoalPosition(ps);
moveToGoalPosition(ps);
//spend 20 percent of energy per hour, aka be able to stay dancing for 5 hours
//however stop dancing at 30 percent energy so effectively dance for 5*.7 = 3.5 hours
ps.addToEnergy(-1* (20f/100f * Day.timeIncrementInHours));
//once on the dancefloor and dancing you are always at the goalposition
//as youre not targeting a spot thats further away than you can walk in a timestep
boolean notWalking = ps.getPosition().equals(ps.getGoalPosition());
if (notWalking) {
ps.takeSip();
}
}
@Override
public void moveNextState(PersonState ps) {
if (!ps.isWantingToBeAtClub()){
ps.setState(OutsideState.getInstance());
return;
}
if (ps.getEnergy()<0.30){
ps.setState(TalkingState.getInstance());
} else {
float likelinessToGoGrabADrink = 0;//out of 100
//if has no alcohol and has money, then create a chance to go get a drink
if (!ps.hasAlcohol() && ps.getSpendableMoney() > 0) {
//if has no alcohol average of 85 percent chance per hour to go get drinks, least 70, high 100
likelinessToGoGrabADrink += 70;
likelinessToGoGrabADrink += Main.random.nextInt(30);
//kansrekening werkt niet zo 2* 0.5 kans is niet hetzelfde als 1* 1 kans, gemiddeld wel though
//we doen hier dus x* (1/x) * y kans, als die x heel groot is, dan is het allemaal ongeveer hetzelfde,
//dus hoe kleiner te timestep hoe nauwkeuriger? dat is vast hoe het werkt
likelinessToGoGrabADrink *= Day.timeIncrementInHours; //multiply by the amount of hours in this step
}
//note if likeliness is 0, then chance is also 0, if likeliness is 100 then chance is also 100
if (likelinessToGoGrabADrink > Main.random.nextInt(100)) {
//set Nextstate to be drinking!!!
ps.setState(GoToBarState.getInstance());
} else {
//set Nextstate to be dancing !!!
ps.setState(this);
}
}
}
@Override
public void setGoalPosition(PersonState ps) {
//TODO: make dancing not depend on simuluation time
//float secondsPerTick = Day.timeIncrementInHours * 3600;
//float secondsPerDanceMove = 2f;
//float tickPerMove = secondsPerDanceMove / secondsPerTick;
if (isAtTargetBarObject(ps.getGoalPosition(), 0)){
if(ps.getGoalPosition().equals(ps.getPosition())){
//were dancing so move a little
Position targetPosition = ps.getPosition().clone();
//1.08 km/h == 30cm per second
float speed = (0.54f * 1000f)/0.03f * Day.timeIncrementInHours;
//select one cardinal direction to move in
if (Main.random.nextBoolean()) {
if (Main.random.nextBoolean()) {
targetPosition.addToX(speed);
} else { //or down
targetPosition.addToX(-1 * speed);
}
} else {
if (Main.random.nextBoolean()) {
targetPosition.addToY(speed);
} else {
targetPosition.addToY(-1 * speed);
}
}
//if not wanting to move outside of bar
if (isAtTargetBarObject(targetPosition, 0)) {
ps.setGoalPosition(targetPosition);
}
} //else just keep going to that goal
//if we dont have a goal on the dancefloor, set a new goal on the dancefloor
} else {
//not yet intending to go to dancefloor and not on dancefloor (to not keep changing the position at the dancefloor
float x = Main.clubs.get(0).getBarObjects()[1][0] + Main.random.nextInt(Main.clubs.get(0).getBarObjects()[1][2]);
float y = Main.clubs.get(0).getBarObjects()[1][1] + Main.random.nextInt(Main.clubs.get(0).getBarObjects()[1][3]);
ps.setGoalPosition(new Position(x, y));
}
}
@Override
public int[] getTargetBarObject() {
return Main.clubs.get(0).danceFloor;
}
} | JasperDell/Robots-everywhere | src/DancingState.java | 1,373 | //else just keep going to that goal | line_comment | nl | public class DancingState extends State {
/////////
//singleton stuff
////////
private static DancingState instance;
private DancingState(){};
public static DancingState getInstance() {
if (instance == null)
instance = new DancingState();
return instance;
}
///////
//actual implementation
///////
@Override
public void takeAction(PersonState ps) {
setGoalPosition(ps);
moveToGoalPosition(ps);
//spend 20 percent of energy per hour, aka be able to stay dancing for 5 hours
//however stop dancing at 30 percent energy so effectively dance for 5*.7 = 3.5 hours
ps.addToEnergy(-1* (20f/100f * Day.timeIncrementInHours));
//once on the dancefloor and dancing you are always at the goalposition
//as youre not targeting a spot thats further away than you can walk in a timestep
boolean notWalking = ps.getPosition().equals(ps.getGoalPosition());
if (notWalking) {
ps.takeSip();
}
}
@Override
public void moveNextState(PersonState ps) {
if (!ps.isWantingToBeAtClub()){
ps.setState(OutsideState.getInstance());
return;
}
if (ps.getEnergy()<0.30){
ps.setState(TalkingState.getInstance());
} else {
float likelinessToGoGrabADrink = 0;//out of 100
//if has no alcohol and has money, then create a chance to go get a drink
if (!ps.hasAlcohol() && ps.getSpendableMoney() > 0) {
//if has no alcohol average of 85 percent chance per hour to go get drinks, least 70, high 100
likelinessToGoGrabADrink += 70;
likelinessToGoGrabADrink += Main.random.nextInt(30);
//kansrekening werkt niet zo 2* 0.5 kans is niet hetzelfde als 1* 1 kans, gemiddeld wel though
//we doen hier dus x* (1/x) * y kans, als die x heel groot is, dan is het allemaal ongeveer hetzelfde,
//dus hoe kleiner te timestep hoe nauwkeuriger? dat is vast hoe het werkt
likelinessToGoGrabADrink *= Day.timeIncrementInHours; //multiply by the amount of hours in this step
}
//note if likeliness is 0, then chance is also 0, if likeliness is 100 then chance is also 100
if (likelinessToGoGrabADrink > Main.random.nextInt(100)) {
//set Nextstate to be drinking!!!
ps.setState(GoToBarState.getInstance());
} else {
//set Nextstate to be dancing !!!
ps.setState(this);
}
}
}
@Override
public void setGoalPosition(PersonState ps) {
//TODO: make dancing not depend on simuluation time
//float secondsPerTick = Day.timeIncrementInHours * 3600;
//float secondsPerDanceMove = 2f;
//float tickPerMove = secondsPerDanceMove / secondsPerTick;
if (isAtTargetBarObject(ps.getGoalPosition(), 0)){
if(ps.getGoalPosition().equals(ps.getPosition())){
//were dancing so move a little
Position targetPosition = ps.getPosition().clone();
//1.08 km/h == 30cm per second
float speed = (0.54f * 1000f)/0.03f * Day.timeIncrementInHours;
//select one cardinal direction to move in
if (Main.random.nextBoolean()) {
if (Main.random.nextBoolean()) {
targetPosition.addToX(speed);
} else { //or down
targetPosition.addToX(-1 * speed);
}
} else {
if (Main.random.nextBoolean()) {
targetPosition.addToY(speed);
} else {
targetPosition.addToY(-1 * speed);
}
}
//if not wanting to move outside of bar
if (isAtTargetBarObject(targetPosition, 0)) {
ps.setGoalPosition(targetPosition);
}
} //else just<SUF>
//if we dont have a goal on the dancefloor, set a new goal on the dancefloor
} else {
//not yet intending to go to dancefloor and not on dancefloor (to not keep changing the position at the dancefloor
float x = Main.clubs.get(0).getBarObjects()[1][0] + Main.random.nextInt(Main.clubs.get(0).getBarObjects()[1][2]);
float y = Main.clubs.get(0).getBarObjects()[1][1] + Main.random.nextInt(Main.clubs.get(0).getBarObjects()[1][3]);
ps.setGoalPosition(new Position(x, y));
}
}
@Override
public int[] getTargetBarObject() {
return Main.clubs.get(0).danceFloor;
}
} |
49980_4 | package domain;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.validator.constraints.Range;
@Getter @Setter
public class Price {
//private Integer percentIncrease;
//+ getter en setter
//drie @
//het moet ingevuld zijn - foutboodschap wordt overschreven (zonder sleutel)
//moet minstens 1 zijn - foutboodschap overschrijven (met sleutel)
//hoogtens 50 - foutboodschap wordt overschreven (zonder sleutel)
//foutboodschap NumberFormatException wordt overschreven
@NotNull
@Min(value = 1, message = "{price.percentIncrease.Min.message}")
@Max(50)
private Integer percentIncrease;
//private Integer percentDecrease;
//twee @
//het moet ingevuld zijn - foutboodschap wordt overschreven (zonder sleutel)
//het moet liggen tussen 1 en 25 - foutboodschap overschrijven (met sleutel)
//foutboodschap NumberFormatException wordt overschreven
@NotNull
@Range(min = 1, max = 25, message = "{price.percentDecrease.Range.message}")
private Integer percentDecrease;
}
| JasperLefever/EWDJOef | Spring_Boot_i18n_ProductStart/src/main/java/domain/Price.java | 393 | //moet minstens 1 zijn - foutboodschap overschrijven (met sleutel) | line_comment | nl | package domain;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.validator.constraints.Range;
@Getter @Setter
public class Price {
//private Integer percentIncrease;
//+ getter en setter
//drie @
//het moet ingevuld zijn - foutboodschap wordt overschreven (zonder sleutel)
//moet minstens<SUF>
//hoogtens 50 - foutboodschap wordt overschreven (zonder sleutel)
//foutboodschap NumberFormatException wordt overschreven
@NotNull
@Min(value = 1, message = "{price.percentIncrease.Min.message}")
@Max(50)
private Integer percentIncrease;
//private Integer percentDecrease;
//twee @
//het moet ingevuld zijn - foutboodschap wordt overschreven (zonder sleutel)
//het moet liggen tussen 1 en 25 - foutboodschap overschrijven (met sleutel)
//foutboodschap NumberFormatException wordt overschreven
@NotNull
@Range(min = 1, max = 25, message = "{price.percentDecrease.Range.message}")
private Integer percentDecrease;
}
|
57265_1 | package model.domain.Korting;
import model.domain.ArtikelContainer;
public class GroepsKorting extends Korting{
private String categorie;
private static final String omschrijving = "Groepskorting";
public GroepsKorting() {
}
public void setTotaalMetKortingKassier() {
//loopen door artikelen
double multiplier = convertKorting(kortingsAantal);
for(int i = 0;i<artikelContainers.size();i++){
ArtikelContainer ac = artikelContainers.get(i);
//als categorie gelijk pas de prijs aan
if(ac.getArtikelCategorie().equalsIgnoreCase(getCategorie())){
double prijs = ac.getPrijs();
//opgehaalde prijs veranderen (bv bij 70% korting, prijs * 0.3)
ac.setPrijs(prijs * multiplier);
artikelContainers.set(i, ac);
}
}
}
@Override
public String getOmschrijving() {
return omschrijving;
}
public void setDrempel() {
}
public void setKortingsAantal(String kortingsAantal){
this.kortingsAantal = Integer.parseInt(kortingsAantal);
}
public String getCategorie() {
return categorie;
}
//setter voor instellen op welke categorie er korting is
@Override
public void setCategorie(String categorie) {
this.categorie = categorie;
}
@Override
public void setDrempel(String drempel) {
}
}
| JasperVandenberghen/28_Swennen_Vandenberghen_Verheyden_KassaApp2019 | code/src/model/domain/Korting/GroepsKorting.java | 460 | //als categorie gelijk pas de prijs aan | line_comment | nl | package model.domain.Korting;
import model.domain.ArtikelContainer;
public class GroepsKorting extends Korting{
private String categorie;
private static final String omschrijving = "Groepskorting";
public GroepsKorting() {
}
public void setTotaalMetKortingKassier() {
//loopen door artikelen
double multiplier = convertKorting(kortingsAantal);
for(int i = 0;i<artikelContainers.size();i++){
ArtikelContainer ac = artikelContainers.get(i);
//als categorie<SUF>
if(ac.getArtikelCategorie().equalsIgnoreCase(getCategorie())){
double prijs = ac.getPrijs();
//opgehaalde prijs veranderen (bv bij 70% korting, prijs * 0.3)
ac.setPrijs(prijs * multiplier);
artikelContainers.set(i, ac);
}
}
}
@Override
public String getOmschrijving() {
return omschrijving;
}
public void setDrempel() {
}
public void setKortingsAantal(String kortingsAantal){
this.kortingsAantal = Integer.parseInt(kortingsAantal);
}
public String getCategorie() {
return categorie;
}
//setter voor instellen op welke categorie er korting is
@Override
public void setCategorie(String categorie) {
this.categorie = categorie;
}
@Override
public void setDrempel(String drempel) {
}
}
|
96246_11 | package be.hvwebsites.itembord;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import java.util.List;
import be.hvwebsites.itembord.adapters.LogboekItemListAdapter;
import be.hvwebsites.itembord.constants.SpecificData;
import be.hvwebsites.itembord.entities.Log;
import be.hvwebsites.itembord.entities.Opvolgingsitem;
import be.hvwebsites.itembord.entities.Rubriek;
import be.hvwebsites.itembord.helpers.ListItemTwoLinesHelper;
import be.hvwebsites.itembord.services.FileBaseService;
import be.hvwebsites.itembord.services.FileBaseServiceOld;
import be.hvwebsites.itembord.viewmodels.EntitiesViewModel;
import be.hvwebsites.libraryandroid4.helpers.IDNumber;
import be.hvwebsites.libraryandroid4.helpers.ListItemHelper;
import be.hvwebsites.libraryandroid4.returninfo.ReturnInfo;
import be.hvwebsites.libraryandroid4.statics.StaticData;
public class Logboek extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
private EntitiesViewModel viewModel;
private List<ListItemTwoLinesHelper> logboekList = new ArrayList<>();
// Filters
private IDNumber filterRubriekID = new IDNumber(StaticData.IDNUMBER_NOT_FOUND.getId());
private IDNumber filterOItemID = new IDNumber(StaticData.IDNUMBER_NOT_FOUND.getId());
// Device
private final String deviceModel = Build.MODEL;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logboek);
// Creer een filebase service, bepaalt file base directory obv device en Context
FileBaseService fileBaseService = new FileBaseService(deviceModel, this);
// Data ophalen
// Get a viewmodel from the viewmodelproviders
viewModel = new ViewModelProvider(this).get(EntitiesViewModel.class);
// Basis directory definitie
String baseDir = fileBaseService.getFileBaseDir();
// Initialize viewmodel mt basis directory (data wordt opgehaald in viewmodel)
List<ReturnInfo> viewModelRetInfo = viewModel.initializeViewModel(baseDir);
// Display return msg(s)
for (int i = 0; i < viewModelRetInfo.size(); i++) {
Toast.makeText(getApplicationContext(),
viewModelRetInfo.get(i).getReturnMessage(),
Toast.LENGTH_SHORT).show();
}
// Rubriekfilter Spinner en adapter definieren
Spinner rubriekFilterSpinner = (Spinner) findViewById(R.id.spinr_rubriek);
// rubriekfilterAdapter obv ListItemHelper
ArrayAdapter<ListItemHelper> rubriekFilterAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item);
rubriekFilterAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Rubriekfilter vullen met alle rubrieken
rubriekFilterAdapter.add(new ListItemHelper(SpecificData.NO_RUBRIEK_FILTER,
"",
StaticData.IDNUMBER_NOT_FOUND));
rubriekFilterAdapter.addAll(viewModel.getRubriekItemList());
rubriekFilterSpinner.setAdapter(rubriekFilterAdapter);
// Opvolgingsitemfilter Spinner en adapter definieren
Spinner oItemFilterSpinner = (Spinner) findViewById(R.id.spinr_oitem);
// OpvolgingsitemfilterAdapter obv ListItemHelper
ArrayAdapter<ListItemHelper> oItemFilterAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item);
oItemFilterAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Opvolgingsitemfilter invullen
oItemFilterAdapter.add(new ListItemHelper(SpecificData.NO_OPVOLGINGSITEM_FILTER,
"",
StaticData.IDNUMBER_NOT_FOUND));
oItemFilterSpinner.setAdapter(oItemFilterAdapter);
// Recyclerview definieren
RecyclerView recyclerView = findViewById(R.id.recyc_logboek);
final LogboekItemListAdapter logboekAdapter = new LogboekItemListAdapter(this);
recyclerView.setAdapter(logboekAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
// Recyclerview invullen met logboek items
logboekList.clear();
logboekList.addAll(buildLogboek(StaticData.IDNUMBER_NOT_FOUND, StaticData.IDNUMBER_NOT_FOUND));
logboekAdapter.setItemList(logboekList);
if (logboekList.size() == 0){
Toast.makeText(this,
SpecificData.NO_LOGBOEKITEMS_YET,
Toast.LENGTH_LONG).show();
}
// selection listener activeren, moet gebueren nadat de adapter gekoppeld is aan de spinner !!
rubriekFilterSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
ListItemHelper selHelper = (ListItemHelper) adapterView.getItemAtPosition(i);
filterRubriekID = selHelper.getItemID();
// Als er een rubriekID geselecteerd
if (filterRubriekID.getId() != StaticData.IDNUMBER_NOT_FOUND.getId()){
// Clearen van filter opvolgingsitem
filterOItemID = StaticData.IDNUMBER_NOT_FOUND;
// Spinner selectie zetten
//rubriekFilterSpinner.setSelection(i, false);
// Inhoud vd opvolgingsitem filter bepalen adhv gekozen rubriek
oItemFilterAdapter.clear();
oItemFilterAdapter.add(new ListItemHelper(SpecificData.NO_OPVOLGINGSITEM_FILTER,
"",
StaticData.IDNUMBER_NOT_FOUND));
oItemFilterAdapter.addAll(viewModel.getOpvolgingsItemItemListByRubriekID(filterRubriekID));
oItemFilterSpinner.setAdapter(oItemFilterAdapter);
}
// Inhoud vd logboek bepalen adhv gekozen filters
logboekList.clear();
logboekList.addAll(buildLogboek(filterRubriekID, filterOItemID));
logboekAdapter.setItemList(logboekList);
recyclerView.setAdapter(logboekAdapter);
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
oItemFilterSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
ListItemHelper selHelper = (ListItemHelper) adapterView.getItemAtPosition(i);
filterOItemID = selHelper.getItemID();
// Spinner selectie zetten
//oItemFilterSpinner.setSelection(i, false);
// Inhoud vd logboek bepalen adhv gekozen filters
logboekList.clear();
logboekList.addAll(buildLogboek(filterRubriekID, filterOItemID));
logboekAdapter.setItemList(logboekList);
recyclerView.setAdapter(logboekAdapter);
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
private List<ListItemTwoLinesHelper> buildLogboek(IDNumber rubriekID, IDNumber oItemID){
List<ListItemTwoLinesHelper> logboekList = new ArrayList<>();
String item1;
String item2;
Log log;
Rubriek rubriekLog;
Opvolgingsitem opvolgingsitemLog;
String rubriekLogName = "";
String oItemLogName = "";
int indexhelp;
// Bepaal voor elke logitem dat voldoet, lijn1 & 2
for (int i = 0; i < viewModel.getLogList().size(); i++) {
log = viewModel.getLogList().get(i);
if ((rubriekID.getId() == StaticData.IDNUMBER_NOT_FOUND.getId()
|| (log.getRubriekId().getId() == rubriekID.getId()))
&& (oItemID.getId() == StaticData.IDNUMBER_NOT_FOUND.getId()
|| (log.getItemId().getId() == oItemID.getId()))){
// Ophalen rubriek en opvolgingsitem
rubriekLog = viewModel.getRubriekById(log.getRubriekId());
opvolgingsitemLog = viewModel.getOpvolgingsitemById(log.getItemId());
// Bepaal lijn1
item1 = log.getLogDate().getFormatDate() + ": ";
// Als rubriek filter niet ingevuld is, moet rubriek name in lijn 1 gezet worden
if ((rubriekLog != null)
&& (rubriekID.getId() == StaticData.IDNUMBER_NOT_FOUND.getId())){
rubriekLogName = rubriekLog.getEntityName();
item1 = item1.concat(rubriekLogName).concat(": ");
}
// Opvolgingsitem kan null zijn !
if ((opvolgingsitemLog != null)
&& (oItemID.getId() == StaticData.IDNUMBER_NOT_FOUND.getId())){
oItemLogName = opvolgingsitemLog.getEntityName();
item1 = item1.concat(oItemLogName);
}
// Vul tweede lijn in
item2 = log.getLogDescTrunc(70);
// Creer logboekitem en steek in list
logboekList.add(new ListItemTwoLinesHelper(item1,
item2,
"",
log.getEntityId(),
rubriekLogName,
oItemLogName,
log.getLogDate().getIntDate()));
}
}
// Logboeklist sorteren op rubriek, oitem en datum
// Er wordt gesorteerd op de rubriekId en de opvolgingsitemId ipv op naam !!
ListItemTwoLinesHelper temp = new ListItemTwoLinesHelper();
String sortf11, sortf12 ,sortf21, sortf22;
int sortf31, sortf32;
int testint1, testint2;
for (int i = logboekList.size() ; i > 0 ; i--) {
for (int j = 1 ; j < i ; j++) {
sortf11 = logboekList.get(j-1).getSortField1();
sortf12 = logboekList.get(j).getSortField1();
sortf21 = logboekList.get(j-1).getSortField2();
sortf22 = logboekList.get(j).getSortField2();
sortf31 = logboekList.get(j-1).getSortField3();
sortf32 = logboekList.get(j).getSortField3();
testint1 = sortf11.compareToIgnoreCase(sortf12);
testint2 = sortf21.compareToIgnoreCase(sortf22);
if ((sortf11.compareToIgnoreCase(sortf12) > 0)
|| ((sortf11.compareToIgnoreCase(sortf12) == 0) && (sortf21.compareToIgnoreCase(sortf22) > 0))
|| ((sortf11.compareToIgnoreCase(sortf12) == 0) && (sortf21.compareToIgnoreCase(sortf22) == 0) && (sortf31 < sortf32))) {
// wisselen
temp.setLogItem(logboekList.get(j));
logboekList.get(j).setLogItem(logboekList.get(j-1));
logboekList.get(j-1).setLogItem(temp);
}
}
}
return logboekList;
}
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
} | JavaAppsJM/appItemBord | src/main/java/be/hvwebsites/itembord/Logboek.java | 3,585 | // selection listener activeren, moet gebueren nadat de adapter gekoppeld is aan de spinner !! | line_comment | nl | package be.hvwebsites.itembord;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import java.util.List;
import be.hvwebsites.itembord.adapters.LogboekItemListAdapter;
import be.hvwebsites.itembord.constants.SpecificData;
import be.hvwebsites.itembord.entities.Log;
import be.hvwebsites.itembord.entities.Opvolgingsitem;
import be.hvwebsites.itembord.entities.Rubriek;
import be.hvwebsites.itembord.helpers.ListItemTwoLinesHelper;
import be.hvwebsites.itembord.services.FileBaseService;
import be.hvwebsites.itembord.services.FileBaseServiceOld;
import be.hvwebsites.itembord.viewmodels.EntitiesViewModel;
import be.hvwebsites.libraryandroid4.helpers.IDNumber;
import be.hvwebsites.libraryandroid4.helpers.ListItemHelper;
import be.hvwebsites.libraryandroid4.returninfo.ReturnInfo;
import be.hvwebsites.libraryandroid4.statics.StaticData;
public class Logboek extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
private EntitiesViewModel viewModel;
private List<ListItemTwoLinesHelper> logboekList = new ArrayList<>();
// Filters
private IDNumber filterRubriekID = new IDNumber(StaticData.IDNUMBER_NOT_FOUND.getId());
private IDNumber filterOItemID = new IDNumber(StaticData.IDNUMBER_NOT_FOUND.getId());
// Device
private final String deviceModel = Build.MODEL;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logboek);
// Creer een filebase service, bepaalt file base directory obv device en Context
FileBaseService fileBaseService = new FileBaseService(deviceModel, this);
// Data ophalen
// Get a viewmodel from the viewmodelproviders
viewModel = new ViewModelProvider(this).get(EntitiesViewModel.class);
// Basis directory definitie
String baseDir = fileBaseService.getFileBaseDir();
// Initialize viewmodel mt basis directory (data wordt opgehaald in viewmodel)
List<ReturnInfo> viewModelRetInfo = viewModel.initializeViewModel(baseDir);
// Display return msg(s)
for (int i = 0; i < viewModelRetInfo.size(); i++) {
Toast.makeText(getApplicationContext(),
viewModelRetInfo.get(i).getReturnMessage(),
Toast.LENGTH_SHORT).show();
}
// Rubriekfilter Spinner en adapter definieren
Spinner rubriekFilterSpinner = (Spinner) findViewById(R.id.spinr_rubriek);
// rubriekfilterAdapter obv ListItemHelper
ArrayAdapter<ListItemHelper> rubriekFilterAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item);
rubriekFilterAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Rubriekfilter vullen met alle rubrieken
rubriekFilterAdapter.add(new ListItemHelper(SpecificData.NO_RUBRIEK_FILTER,
"",
StaticData.IDNUMBER_NOT_FOUND));
rubriekFilterAdapter.addAll(viewModel.getRubriekItemList());
rubriekFilterSpinner.setAdapter(rubriekFilterAdapter);
// Opvolgingsitemfilter Spinner en adapter definieren
Spinner oItemFilterSpinner = (Spinner) findViewById(R.id.spinr_oitem);
// OpvolgingsitemfilterAdapter obv ListItemHelper
ArrayAdapter<ListItemHelper> oItemFilterAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item);
oItemFilterAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Opvolgingsitemfilter invullen
oItemFilterAdapter.add(new ListItemHelper(SpecificData.NO_OPVOLGINGSITEM_FILTER,
"",
StaticData.IDNUMBER_NOT_FOUND));
oItemFilterSpinner.setAdapter(oItemFilterAdapter);
// Recyclerview definieren
RecyclerView recyclerView = findViewById(R.id.recyc_logboek);
final LogboekItemListAdapter logboekAdapter = new LogboekItemListAdapter(this);
recyclerView.setAdapter(logboekAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
// Recyclerview invullen met logboek items
logboekList.clear();
logboekList.addAll(buildLogboek(StaticData.IDNUMBER_NOT_FOUND, StaticData.IDNUMBER_NOT_FOUND));
logboekAdapter.setItemList(logboekList);
if (logboekList.size() == 0){
Toast.makeText(this,
SpecificData.NO_LOGBOEKITEMS_YET,
Toast.LENGTH_LONG).show();
}
// selection listener<SUF>
rubriekFilterSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
ListItemHelper selHelper = (ListItemHelper) adapterView.getItemAtPosition(i);
filterRubriekID = selHelper.getItemID();
// Als er een rubriekID geselecteerd
if (filterRubriekID.getId() != StaticData.IDNUMBER_NOT_FOUND.getId()){
// Clearen van filter opvolgingsitem
filterOItemID = StaticData.IDNUMBER_NOT_FOUND;
// Spinner selectie zetten
//rubriekFilterSpinner.setSelection(i, false);
// Inhoud vd opvolgingsitem filter bepalen adhv gekozen rubriek
oItemFilterAdapter.clear();
oItemFilterAdapter.add(new ListItemHelper(SpecificData.NO_OPVOLGINGSITEM_FILTER,
"",
StaticData.IDNUMBER_NOT_FOUND));
oItemFilterAdapter.addAll(viewModel.getOpvolgingsItemItemListByRubriekID(filterRubriekID));
oItemFilterSpinner.setAdapter(oItemFilterAdapter);
}
// Inhoud vd logboek bepalen adhv gekozen filters
logboekList.clear();
logboekList.addAll(buildLogboek(filterRubriekID, filterOItemID));
logboekAdapter.setItemList(logboekList);
recyclerView.setAdapter(logboekAdapter);
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
oItemFilterSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
ListItemHelper selHelper = (ListItemHelper) adapterView.getItemAtPosition(i);
filterOItemID = selHelper.getItemID();
// Spinner selectie zetten
//oItemFilterSpinner.setSelection(i, false);
// Inhoud vd logboek bepalen adhv gekozen filters
logboekList.clear();
logboekList.addAll(buildLogboek(filterRubriekID, filterOItemID));
logboekAdapter.setItemList(logboekList);
recyclerView.setAdapter(logboekAdapter);
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
private List<ListItemTwoLinesHelper> buildLogboek(IDNumber rubriekID, IDNumber oItemID){
List<ListItemTwoLinesHelper> logboekList = new ArrayList<>();
String item1;
String item2;
Log log;
Rubriek rubriekLog;
Opvolgingsitem opvolgingsitemLog;
String rubriekLogName = "";
String oItemLogName = "";
int indexhelp;
// Bepaal voor elke logitem dat voldoet, lijn1 & 2
for (int i = 0; i < viewModel.getLogList().size(); i++) {
log = viewModel.getLogList().get(i);
if ((rubriekID.getId() == StaticData.IDNUMBER_NOT_FOUND.getId()
|| (log.getRubriekId().getId() == rubriekID.getId()))
&& (oItemID.getId() == StaticData.IDNUMBER_NOT_FOUND.getId()
|| (log.getItemId().getId() == oItemID.getId()))){
// Ophalen rubriek en opvolgingsitem
rubriekLog = viewModel.getRubriekById(log.getRubriekId());
opvolgingsitemLog = viewModel.getOpvolgingsitemById(log.getItemId());
// Bepaal lijn1
item1 = log.getLogDate().getFormatDate() + ": ";
// Als rubriek filter niet ingevuld is, moet rubriek name in lijn 1 gezet worden
if ((rubriekLog != null)
&& (rubriekID.getId() == StaticData.IDNUMBER_NOT_FOUND.getId())){
rubriekLogName = rubriekLog.getEntityName();
item1 = item1.concat(rubriekLogName).concat(": ");
}
// Opvolgingsitem kan null zijn !
if ((opvolgingsitemLog != null)
&& (oItemID.getId() == StaticData.IDNUMBER_NOT_FOUND.getId())){
oItemLogName = opvolgingsitemLog.getEntityName();
item1 = item1.concat(oItemLogName);
}
// Vul tweede lijn in
item2 = log.getLogDescTrunc(70);
// Creer logboekitem en steek in list
logboekList.add(new ListItemTwoLinesHelper(item1,
item2,
"",
log.getEntityId(),
rubriekLogName,
oItemLogName,
log.getLogDate().getIntDate()));
}
}
// Logboeklist sorteren op rubriek, oitem en datum
// Er wordt gesorteerd op de rubriekId en de opvolgingsitemId ipv op naam !!
ListItemTwoLinesHelper temp = new ListItemTwoLinesHelper();
String sortf11, sortf12 ,sortf21, sortf22;
int sortf31, sortf32;
int testint1, testint2;
for (int i = logboekList.size() ; i > 0 ; i--) {
for (int j = 1 ; j < i ; j++) {
sortf11 = logboekList.get(j-1).getSortField1();
sortf12 = logboekList.get(j).getSortField1();
sortf21 = logboekList.get(j-1).getSortField2();
sortf22 = logboekList.get(j).getSortField2();
sortf31 = logboekList.get(j-1).getSortField3();
sortf32 = logboekList.get(j).getSortField3();
testint1 = sortf11.compareToIgnoreCase(sortf12);
testint2 = sortf21.compareToIgnoreCase(sortf22);
if ((sortf11.compareToIgnoreCase(sortf12) > 0)
|| ((sortf11.compareToIgnoreCase(sortf12) == 0) && (sortf21.compareToIgnoreCase(sortf22) > 0))
|| ((sortf11.compareToIgnoreCase(sortf12) == 0) && (sortf21.compareToIgnoreCase(sortf22) == 0) && (sortf31 < sortf32))) {
// wisselen
temp.setLogItem(logboekList.get(j));
logboekList.get(j).setLogItem(logboekList.get(j-1));
logboekList.get(j-1).setLogItem(temp);
}
}
}
return logboekList;
}
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
} |
10049_1 | import java.util.*;
public class Challenge40 {
public static void main (String[] args) {
Scanner myScanner = new Scanner(System.in);
ArrayList<RobotCommand> list = new ArrayList<>();
RobotCommand commandOne = commands(myScanner.nextLine().toLowerCase());
RobotCommand commandTwo = commands(myScanner.nextLine().toLowerCase());
RobotCommand commandThree = commands(myScanner.nextLine().toLowerCase());
list.add(commandOne);
list.add(commandTwo);
list.add(commandThree);
Robot robot = new Robot(list);
robot.run();
}
private static RobotCommand commands (String command) {
return switch(command) {
case "on" -> new OnCommand();
case "off" -> new OffCommand();
case "north" -> new NorthCommand();
case "south" -> new SouthCommand();
case "west" -> new WestCommand();
case "east" -> new EastCommand();
default -> null;
};
}
}
class Robot {
private int x;
private int y;
private boolean isPowered;
public void moveX(int step) {
if (isPowered) x += step;
}
public void moveY(int step) {
if (isPowered) y += step;
}
private final RobotCommand[] commands = new RobotCommand[3];
public Robot(List<RobotCommand> inputCommands) {
if (inputCommands.size() != 3) throw new IllegalArgumentException("Error: Need three commands.");
inputCommands.toArray(commands);
}
public void setPowered(boolean powered) {
isPowered = powered;
}
public void run() {
for (RobotCommand command : commands) {
command.run(this);
System.out.printf("[%d %d %b]\n", x, y, isPowered);
}
}
}
interface RobotCommand {
void run(Robot robot);
}
public class OnCommand implements RobotCommand {
public void run(Robot robot) {
robot.setPowered(true);
}
}
public class OffCommand implements RobotCommand {
public void run(Robot robot) {
robot.setPowered(false);
}
}
public class NorthCommand implements RobotCommand {
public void run(Robot robot) {
robot.moveY(1);
}
}
public class SouthCommand implements RobotCommand {
public void run(Robot robot) {
robot.moveY(-1);
}
}
public class WestCommand implements RobotCommand {
public void run(Robot robot) {
robot.moveX(1);
}
}
public class EastCommand implements RobotCommand {
public void run(Robot robot) {
robot.moveX(-1);
}
}
//het zou misschien een klein beetje beter zijn dan een abstract classe omdat je hier geen acces/non-acces modifiers mee geeft,
// en daar dus ook geen fouten in kan maken. | JavaGerben/Java55 | challenges/Challenge40.java | 806 | // en daar dus ook geen fouten in kan maken. | line_comment | nl | import java.util.*;
public class Challenge40 {
public static void main (String[] args) {
Scanner myScanner = new Scanner(System.in);
ArrayList<RobotCommand> list = new ArrayList<>();
RobotCommand commandOne = commands(myScanner.nextLine().toLowerCase());
RobotCommand commandTwo = commands(myScanner.nextLine().toLowerCase());
RobotCommand commandThree = commands(myScanner.nextLine().toLowerCase());
list.add(commandOne);
list.add(commandTwo);
list.add(commandThree);
Robot robot = new Robot(list);
robot.run();
}
private static RobotCommand commands (String command) {
return switch(command) {
case "on" -> new OnCommand();
case "off" -> new OffCommand();
case "north" -> new NorthCommand();
case "south" -> new SouthCommand();
case "west" -> new WestCommand();
case "east" -> new EastCommand();
default -> null;
};
}
}
class Robot {
private int x;
private int y;
private boolean isPowered;
public void moveX(int step) {
if (isPowered) x += step;
}
public void moveY(int step) {
if (isPowered) y += step;
}
private final RobotCommand[] commands = new RobotCommand[3];
public Robot(List<RobotCommand> inputCommands) {
if (inputCommands.size() != 3) throw new IllegalArgumentException("Error: Need three commands.");
inputCommands.toArray(commands);
}
public void setPowered(boolean powered) {
isPowered = powered;
}
public void run() {
for (RobotCommand command : commands) {
command.run(this);
System.out.printf("[%d %d %b]\n", x, y, isPowered);
}
}
}
interface RobotCommand {
void run(Robot robot);
}
public class OnCommand implements RobotCommand {
public void run(Robot robot) {
robot.setPowered(true);
}
}
public class OffCommand implements RobotCommand {
public void run(Robot robot) {
robot.setPowered(false);
}
}
public class NorthCommand implements RobotCommand {
public void run(Robot robot) {
robot.moveY(1);
}
}
public class SouthCommand implements RobotCommand {
public void run(Robot robot) {
robot.moveY(-1);
}
}
public class WestCommand implements RobotCommand {
public void run(Robot robot) {
robot.moveX(1);
}
}
public class EastCommand implements RobotCommand {
public void run(Robot robot) {
robot.moveX(-1);
}
}
//het zou misschien een klein beetje beter zijn dan een abstract classe omdat je hier geen acces/non-acces modifiers mee geeft,
// en daar<SUF> |
99699_6 | package uno;
import java.util.Iterator;
import java.util.Random;
/**
* Een eigen Lijst klasse voor Uno
*
* HERNOEM DEZE KLASSE NAAR Lijst
*
* @author Pieter Koopman
*/
public class LijstBegin <T>
{
/**
* de iteraror voor Lijst
*/
private class LijstIterator implements Iterator
{
/**
* De vorige knoop en de knoop die het laatst is gezien bij next();
*/
private Knoop <T> vorige, huidige;
/**
* De constructor van de LijstIterator
* Alle info van lijst is bekend omdat de LijstItertor lokaal is
* De aanname is dat er altijd hoogestens een iterator actief is
*/
public LijstIterator( )
{
huidige = vorige = null;
}
/**
* is er nog een volgend element in de lijst
* @return True als er nog een element is
*/
public boolean hasNext()
{
return false;
}
/**
* lever het volgende elemnt op
* huidige en vorige worden aangepast.
* huidige wordt de Knoop van het op geleverde element
* @return de inhoud van de Knoop
*/
public T next()
{
return null;
}
/**
* verwijder het laatst opgeleverde element (huidige)
* Mag alleen gebruikt worden na een next
* speciale aandacht nodig voor eerste en laatste element
*/
public void remove()
{
}
}
/**
* Lijst bevat referentie naar eerste en laatste knoop en de lengte.
* De random generator wordt gebruikt in voegErgensToe.
*/
private Knoop <T> kop = null, staart = null;
private int lengte = 0;
Random randomgen;
/**
* de constructor, maakt een lege lijst
*/
public LijstBegin ()
{
randomgen = new Random();
}
/**
* predicaat om te controleren of de lijst leeg is
* @return true als de lijst leeg is
*/
public boolean isLeeg ()
{
return true;
}
/**
* getter van het lengte attribuut
* @return de huidige lengte van de lijst
*/
public int getLengte ()
{
return 0;
}
/**
* Voeg een element vooraan in de lijst toe
* @param t het nieuw element
*/
public void voegVooraanToe (T t)
{
}
/**
* voeg een element achteraan in de lijst toe
* @param t het nieuwe element
*/
public void voegAchteraanToe (T t)
{
}
/**
* Voeg een element op een pseudo random plek toe
* @param t het nieuwe element
*/
public void voegErgensToe (T t)
{
}
/**
* pak het eerste element van de lijst en verwijder dat
* @return het eerste element
* @throws java.lang.Exception als de lijst leeg is
*/
public T pakEerste () throws Exception
{
throw new Exception ("eerste element van lege lijst!");
}
/**
* maak een string die de inhoud van de lijst beschrijft
* elementen worden gescheiden door spaties
* @return de opgebouwd string
*/
@Override
public String toString ()
{
StringBuilder output = new StringBuilder();
return output.toString();
}
/**
* maak een iterator voor deze lijst, deze begint voor aan de lijst
* @return de LijstIterator
*/
public Iterator iterator()
{
return new LijstIterator();
}
}
| Jaxan/AedsHomework | 03 Uno/LijstBegin.java | 1,047 | /**
* verwijder het laatst opgeleverde element (huidige)
* Mag alleen gebruikt worden na een next
* speciale aandacht nodig voor eerste en laatste element
*/ | block_comment | nl | package uno;
import java.util.Iterator;
import java.util.Random;
/**
* Een eigen Lijst klasse voor Uno
*
* HERNOEM DEZE KLASSE NAAR Lijst
*
* @author Pieter Koopman
*/
public class LijstBegin <T>
{
/**
* de iteraror voor Lijst
*/
private class LijstIterator implements Iterator
{
/**
* De vorige knoop en de knoop die het laatst is gezien bij next();
*/
private Knoop <T> vorige, huidige;
/**
* De constructor van de LijstIterator
* Alle info van lijst is bekend omdat de LijstItertor lokaal is
* De aanname is dat er altijd hoogestens een iterator actief is
*/
public LijstIterator( )
{
huidige = vorige = null;
}
/**
* is er nog een volgend element in de lijst
* @return True als er nog een element is
*/
public boolean hasNext()
{
return false;
}
/**
* lever het volgende elemnt op
* huidige en vorige worden aangepast.
* huidige wordt de Knoop van het op geleverde element
* @return de inhoud van de Knoop
*/
public T next()
{
return null;
}
/**
* verwijder het laatst<SUF>*/
public void remove()
{
}
}
/**
* Lijst bevat referentie naar eerste en laatste knoop en de lengte.
* De random generator wordt gebruikt in voegErgensToe.
*/
private Knoop <T> kop = null, staart = null;
private int lengte = 0;
Random randomgen;
/**
* de constructor, maakt een lege lijst
*/
public LijstBegin ()
{
randomgen = new Random();
}
/**
* predicaat om te controleren of de lijst leeg is
* @return true als de lijst leeg is
*/
public boolean isLeeg ()
{
return true;
}
/**
* getter van het lengte attribuut
* @return de huidige lengte van de lijst
*/
public int getLengte ()
{
return 0;
}
/**
* Voeg een element vooraan in de lijst toe
* @param t het nieuw element
*/
public void voegVooraanToe (T t)
{
}
/**
* voeg een element achteraan in de lijst toe
* @param t het nieuwe element
*/
public void voegAchteraanToe (T t)
{
}
/**
* Voeg een element op een pseudo random plek toe
* @param t het nieuwe element
*/
public void voegErgensToe (T t)
{
}
/**
* pak het eerste element van de lijst en verwijder dat
* @return het eerste element
* @throws java.lang.Exception als de lijst leeg is
*/
public T pakEerste () throws Exception
{
throw new Exception ("eerste element van lege lijst!");
}
/**
* maak een string die de inhoud van de lijst beschrijft
* elementen worden gescheiden door spaties
* @return de opgebouwd string
*/
@Override
public String toString ()
{
StringBuilder output = new StringBuilder();
return output.toString();
}
/**
* maak een iterator voor deze lijst, deze begint voor aan de lijst
* @return de LijstIterator
*/
public Iterator iterator()
{
return new LijstIterator();
}
}
|
130855_11 | package org.clas.modules;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.clas.view.DetectorShape2D;
import org.clas.viewer.FTCalibrationModule;
import org.clas.viewer.FTDetector;
import org.jlab.detector.calib.utils.CalibrationConstants;
import org.jlab.detector.calib.utils.ConstantsManager;
import org.jlab.groot.data.H1F;
import org.jlab.groot.group.DataGroup;
import org.jlab.io.base.DataBank;
import org.jlab.io.base.DataEvent;
import org.jlab.groot.math.F1D;
import org.jlab.groot.fitter.DataFitter;
import org.jlab.groot.data.GraphErrors;
import org.jlab.clas.pdg.PhysicsConstants;
import org.jlab.clas.physics.Particle;
import org.jlab.groot.data.H2F;
/**
*
* @author devita
*/
public class FTTimeCalibration extends FTCalibrationModule {
public FTTimeCalibration(FTDetector d, String name, ConstantsManager ccdb, Map<String,CalibrationConstants> gConstants) {
super(d, name, "offset:offset_error:delta:resolution",3, ccdb, gConstants);
this.getCalibrationTable().addConstraint(5, -0.1, 0.1);
this.setRange(30.,40.);
this.setRange(-10.,0.);
this.setCols(-2, 2);
}
@Override
public void resetEventListener() {
H1F htsum = new H1F("htsum", 275, -450.0, 100.0);
htsum.setTitleX("Time Offset (ns)");
htsum.setTitleY("Counts");
htsum.setTitle("Global Time Offset");
htsum.setFillColor(3);
H1F htsum_calib = new H1F("htsum_calib", 300, -6.0, 6.0);
htsum_calib.setTitleX("Time Offset (ns)");
htsum_calib.setTitleY("Counts");
htsum_calib.setTitle("Global Time Offset");
htsum_calib.setFillColor(44);
H1F htsum_cluster = new H1F("htsum_cluster" , 400, -2., 2.);
htsum_cluster.setTitleX("Time (ns)");
htsum_cluster.setTitleY("Counts");
htsum_cluster.setTitle("Cluster Time");
htsum_cluster.setFillColor(3);
htsum_cluster.setLineColor(1);
F1D fsum_cluster = new F1D("fsum_cluster", "[amp]*gaus(x,[mean],[sigma])", -1., 1.);
fsum_cluster.setParameter(0, 0.0);
fsum_cluster.setParameter(1, 0.0);
fsum_cluster.setParameter(2, 2.0);
fsum_cluster.setLineWidth(2);
fsum_cluster.setOptStat("1111");
H2F h2d_cluster = new H2F("h2d_cluster" , 100, 0., 12., 100, -2., 2.);
h2d_cluster.setTitleX("Energy (GeV)");
h2d_cluster.setTitleY("Time (ns)");
h2d_cluster.setTitle("Cluster Time");
GraphErrors gtoffsets = new GraphErrors("gtoffsets");
gtoffsets.setTitle("Timing Offsets"); // title
gtoffsets.setTitleX("Crystal ID"); // X axis title
gtoffsets.setTitleY("Offset (ns)"); // Y axis title
gtoffsets.setMarkerColor(5); // color from 0-9 for given palette
gtoffsets.setMarkerSize(2); // size in points on the screen
gtoffsets.addPoint(0., 0., 0., 0.);
gtoffsets.addPoint(1., 1., 0., 0.);
GraphErrors gtdeltas = new GraphErrors("gtdeltas");
gtdeltas.setTitle("#Delta Offset (ns)"); // title
gtdeltas.setTitleX("Crystal ID"); // X axis title
gtdeltas.setTitleY("#Delta Offset (ns)"); // Y axis title
gtdeltas.setMarkerColor(3); // color from 0-9 for given palette
gtdeltas.setMarkerSize(2); // size in points on the screen
gtdeltas.addPoint(0., 0., 0., 0.);
gtdeltas.addPoint(1., 1., 0., 0.);
H1F htoffsets = new H1F("htoffsets", 100, -2, 2);
htoffsets.setTitle("Hit Time");
htoffsets.setTitleX("#DeltaT (ns)");
htoffsets.setTitleY("Counts");
htoffsets.setFillColor(23);
htoffsets.setLineColor(3);
htoffsets.setOptStat("1111");
for (int key : this.getDetector().getDetectorComponents()) {
// initializa calibration constant table
this.getCalibrationTable().addEntry(1, 1, key);
this.getCalibrationTable().setDoubleValue(0.0, "offset", 1,1,key);
// initialize data group
H1F htime_wide = new H1F("htime_wide_" + key, 275, -400.0, 150.0);
htime_wide.setTitleX("Time (ns)");
htime_wide.setTitleY("Counts");
htime_wide.setTitle("Component " + key);
H1F htime = new H1F("htime_" + key, 500, this.getRange()[0], this.getRange()[1]);
htime.setTitleX("Time (ns)");
htime.setTitleY("Counts");
htime.setTitle("Component " + key);
H1F htime_calib = new H1F("htime_calib_" + key, 200, -4., 4.);
htime_calib.setTitleX("Time (ns)");
htime_calib.setTitleY("Counts");
htime_calib.setTitle("Component " + key);
htime_calib.setFillColor(44);
htime_calib.setLineColor(24);
F1D ftime = new F1D("ftime_" + key, "[amp]*gaus(x,[mean],[sigma])", -1., 1.);
ftime.setParameter(0, 0.0);
ftime.setParameter(1, 0.0);
ftime.setParameter(2, 2.0);
ftime.setLineColor(24);
ftime.setLineWidth(2);
ftime.setOptStat("1111");
F1D ftime_calib = new F1D("ftime_calib_" + key, "[amp]*gaus(x,[mean],[sigma])", -1., 1.);
ftime_calib.setParameter(0, 0.0);
ftime_calib.setParameter(1, 0.0);
ftime_calib.setParameter(2, 2.0);
ftime_calib.setLineColor(24);
ftime_calib.setLineWidth(2);
ftime_calib.setOptStat("1111");
// ftime.setLineColor(2);
// ftime.setLineStyle(1);
H1F htcluster = new H1F("htcluster_" + key, 200, -2., 2.);
htcluster.setTitleX("Time (ns)");
htcluster.setTitleY("Counts");
htcluster.setTitle("Cluster Time");
htcluster.setFillColor(3);
htcluster.setLineColor(1);
F1D fcluster = new F1D("fcluster_" + key, "[amp]*gaus(x,[mean],[sigma])", -1., 1.);
fcluster.setParameter(0, 0.0);
fcluster.setParameter(1, 0.0);
fcluster.setParameter(2, 2.0);
fcluster.setLineWidth(2);
fcluster.setOptStat("1111");
DataGroup dg = new DataGroup(4, 2);
dg.addDataSet(htsum, 0);
dg.addDataSet(htsum_calib, 1);
dg.addDataSet(htoffsets, 2);
dg.addDataSet(htsum_cluster, 3);
dg.addDataSet(fsum_cluster, 3);
// dg.addDataSet(htime_wide, 4);
dg.addDataSet(htime, 4);
dg.addDataSet(ftime, 4);
dg.addDataSet(htime_calib, 5);
dg.addDataSet(ftime_calib, 5);
// dg.addDataSet(gtoffsets, 6);
dg.addDataSet(htcluster, 6);
dg.addDataSet(fcluster, 6);
dg.addDataSet(h2d_cluster, 7);
this.getDataGroup().add(dg, 1, 1, key);
}
getCalibrationTable().fireTableDataChanged();
}
@Override
public List<CalibrationConstants> getCalibrationConstants() {
return Arrays.asList(getCalibrationTable());
}
@Override
public int getNEvents(DetectorShape2D dsd) {
int sector = dsd.getDescriptor().getSector();
int layer = dsd.getDescriptor().getLayer();
int key = dsd.getDescriptor().getComponent();
return (int) this.getDataGroup().getItem(sector,layer,key).getH1F("htime_" + key).getIntegral();
}
@Override
public void processEvent(DataEvent event) {
// loop over FTCAL reconstructed cluster
double startTime = -100000;
int triggerPID = 0;
// get start time
if(event.hasBank("REC::Event") && event.hasBank("REC::Particle")) {
DataBank recEvent = event.getBank("REC::Event");
DataBank recPart = event.getBank("REC::Particle");
startTime = recEvent.getFloat("startTime", 0);
if(recPart.getShort("status", 0)<-2000)
triggerPID = recPart.getInt("pid",0);
}
// loop over FTCAL reconstructed cluster
if (event.hasBank("FT::particles") && event.hasBank("FTCAL::clusters") && event.hasBank("FTCAL::hits") && event.hasBank("FTCAL::adc")) {
ArrayList<Particle> ftParticles = new ArrayList();
DataBank particlesFT = event.getBank("FT::particles");
DataBank clusterFTCAL = event.getBank("FTCAL::clusters");
DataBank hitFTCAL = event.getBank("FTCAL::hits");
DataBank adcFTCAL = event.getBank("FTCAL::adc");
// start from clusters
for (int loop = 0; loop < clusterFTCAL.rows(); loop++) {
int cluster = getDetector().getComponent(clusterFTCAL.getFloat("x", loop), clusterFTCAL.getFloat("y", loop));
int id = clusterFTCAL.getShort("id", loop);
int size = clusterFTCAL.getShort("size", loop);
int charge = particlesFT.getByte("charge", loop);
double x = clusterFTCAL.getFloat("x", loop);
double y = clusterFTCAL.getFloat("y", loop);
double z = this.getConstants().crystal_distance+this.getConstants().shower_depth-this.getConstants().z0;//clusterFTCAL.getFloat("z", loop);
double time = clusterFTCAL.getFloat("time", loop);
double energy = clusterFTCAL.getFloat("energy", loop);
double energyR = clusterFTCAL.getFloat("recEnergy", loop);
double path = Math.sqrt(x*x+y*y+z*z);
double theta = Math.toDegrees(Math.acos(z/path));
double tof = (path/PhysicsConstants.speedOfLight()); //ns
// find hits associated to clusters
if(energy>0.5 && energyR>0.3 && size > 3 && charge==0) {
double clusterTime = 0;
double seedTime = 0;
for(int k=0; k<hitFTCAL.rows(); k++) {
int clusterID = hitFTCAL.getShort("clusterID", k);
// select hits that belong to cluster
if(clusterID == id) {
int hitID = hitFTCAL.getShort("hitID", k);
double hitEnergy = hitFTCAL.getFloat("energy", k);
int component = adcFTCAL.getInt("component",hitID);
double hitTime = adcFTCAL.getFloat("time", hitID);
double hitCharge =((double) adcFTCAL.getInt("ADC", hitID))*(this.getConstants().LSB*this.getConstants().nsPerSample/50);
// double radius = Math.sqrt(Math.pow(this.getDetector().getIdX(component)-0.5,2.0)+Math.pow(this.getDetector().getIdY(component)-0.5,2.0))*this.getConstants().crystal_size;//meters
// double hitPath = Math.sqrt(Math.pow(this.getConstants().crystal_distance+this.getConstants().shower_depth,2)+Math.pow(radius,2));
// double hitTof = (hitPath/PhysicsConstants.speedOfLight()); //ns
double twalk = 0;
double offset = 0;
if(this.getGlobalCalibration().containsKey("TimeWalk")) {
double amp = this.getGlobalCalibration().get("TimeWalk").getDoubleValue("A", 1,1,component);
double lam = this.getGlobalCalibration().get("TimeWalk").getDoubleValue("L", 1,1,component);
twalk = amp*Math.exp(-hitCharge*lam);
}
if(this.getPreviousCalibrationTable().hasEntry(1,1,component)) {
offset = this.getPreviousCalibrationTable().getDoubleValue("offset", 1, 1, component);
}
hitTime = hitTime - (this.getConstants().crystal_length-this.getConstants().shower_depth)/this.getConstants().light_speed - twalk - offset;
clusterTime += hitTime*hitEnergy;
double timec = (adcFTCAL.getFloat("time", hitID) -(startTime + tof + (this.getConstants().crystal_length-this.getConstants().shower_depth)/this.getConstants().light_speed));
// System.out.println(component + " " + hitEnergy + " " + hitFTCAL.getFloat("time", k) + " " + hitTime);
this.getDataGroup().getItem(1,1,component).getH1F("htsum").fill(timec-twalk);
// this.getDataGroup().getItem(1,1,component).getH1F("htime_wide_"+component).fill(timec-twalk);
this.getDataGroup().getItem(1,1,component).getH1F("htime_"+component).fill(timec-twalk);
this.getDataGroup().getItem(1,1,component).getH1F("htsum_calib").fill(timec-twalk-offset);
this.getDataGroup().getItem(1,1,component).getH1F("htime_calib_"+component).fill(timec-twalk-offset);
// System.out.println(key + " " + (time-twalk-offset-(this.getConstants().crystal_length-this.getConstants().shower_depth)/this.getConstants().light_speed) + " " + adc + " " + charge + " " + time + " " + twalk + " " + offset);
// if(event.hasBank("FTCAL::hits")) {event.getBank("FTCAL::adc").show();event.getBank("FTCAL::hits").show();}
}
}
clusterTime /= energyR;
if(theta>2.5 && theta<4.5) {
this.getDataGroup().getItem(1,1,cluster).getH1F("htsum_cluster").fill(clusterTime-tof-startTime);
this.getDataGroup().getItem(1,1,cluster).getH2F("h2d_cluster").fill(energy,clusterTime-tof-startTime);
this.getDataGroup().getItem(1,1,cluster).getH1F("htcluster_"+cluster).fill(clusterTime-tof-startTime);
// System.out.println(time + " " + clusterTime);
}
}
}
}
}
@Override
public void analyze() {
// System.out.println("Analyzing");
H1F htime = this.getDataGroup().getItem(1,1,8).getH1F("htsum_cluster");
F1D ftime = this.getDataGroup().getItem(1,1,8).getF1D("fsum_cluster");
this.initTimeGaussFitPar(ftime,htime, 0.35, false);
DataFitter.fit(ftime,htime,"LQ");
for (int key : this.getDetector().getDetectorComponents()) {
// this.getDataGroup().getItem(1,1,key).getGraph("gtoffsets").reset();
this.getDataGroup().getItem(1,1,key).getH1F("htoffsets").reset();
}
for (int key : this.getDetector().getDetectorComponents()) {
htime = this.getDataGroup().getItem(1,1,key).getH1F("htime_" + key);
ftime = this.getDataGroup().getItem(1,1,key).getF1D("ftime_" + key);
this.initTimeGaussFitPar(ftime,htime, 0.5, false);
DataFitter.fit(ftime,htime,"LQ");
// this.getDataGroup().getItem(1,1,key).getGraph("gtoffsets").addPoint(key, ftime.getParameter(1), 0, ftime.parameter(1).error());
htime = this.getDataGroup().getItem(1,1,key).getH1F("htime_calib_" + key);
ftime = this.getDataGroup().getItem(1,1,key).getF1D("ftime_calib_" + key);
this.initTimeGaussFitPar(ftime,htime, 0.5, false);
DataFitter.fit(ftime,htime,"LQ");
double hoffset = ftime.getParameter(1);
if(Math.abs(hoffset)<2) this.getDataGroup().getItem(1,1,key).getH1F("htoffsets").fill(hoffset);
htime = this.getDataGroup().getItem(1,1,key).getH1F("htcluster_" + key);
ftime = this.getDataGroup().getItem(1,1,key).getF1D("fcluster_" + key);
this.initTimeGaussFitPar(ftime,htime, 0.4, false);
DataFitter.fit(ftime,htime,"LQ");
double finalOffset = this.getDataGroup().getItem(1, 1, key).getF1D("ftime_" + key).getParameter(1);
if(this.getDataGroup().getItem(1, 1, key).getF1D("fcluster_" + key).getParameter(0)>20) {
finalOffset = finalOffset
+ this.getDataGroup().getItem(1, 1, key).getF1D("fcluster_" + key).getParameter(1)
- this.getDataGroup().getItem(1, 1, key).getF1D("ftime_calib_" + key).getParameter(1);
}
getCalibrationTable().setDoubleValue(finalOffset, "offset", 1, 1, key);
getCalibrationTable().setDoubleValue(this.getDataGroup().getItem(1, 1, key).getF1D("ftime_" + key).parameter(1).error(), "offset_error", 1, 1, key);
getCalibrationTable().setDoubleValue(this.getDataGroup().getItem(1, 1, key).getF1D("ftime_calib_" + key).getParameter(1), "delta" , 1, 1, key);
getCalibrationTable().setDoubleValue(this.getDataGroup().getItem(1, 1, key).getF1D("ftime_calib_" + key).getParameter(2), "resolution" , 1, 1, key);
}
getCalibrationTable().fireTableDataChanged();
}
@Override
public void setCanvasBookData() {
int[] pads = {4,5,6};
this.getCanvasBook().setData(this.getDataGroup(), pads);
}
private void initTimeGaussFitPar(F1D ftime, H1F htime, double range, boolean limits) {
double hAmp = htime.getBinContent(htime.getMaximumBin());
double hMean = htime.getAxis().getBinCenter(htime.getMaximumBin());
double hRMS = 2; //ns
double rangeMin = (hMean - range);
double rangeMax = (hMean + range);
double pm = (hMean*10.0)/100.0;
ftime.setRange(rangeMin, rangeMax);
ftime.setParameter(0, hAmp);
ftime.setParLimits(0, hAmp*0.8, hAmp*1.2);
ftime.setParameter(1, hMean);
ftime.setParameter(2, 0.2);
if(limits) {
ftime.setParLimits(1, hMean-pm, hMean+(pm));
ftime.setParLimits(2, 0.05*hRMS, 0.8*hRMS);
}
}
@Override
public double getValue(DetectorShape2D dsd) {
// show summary
int sector = dsd.getDescriptor().getSector();
int layer = dsd.getDescriptor().getLayer();
int key = dsd.getDescriptor().getComponent();
if (this.getDetector().hasComponent(key)) {
return this.getDataGroup().getItem(1, 1, key).getF1D("ftime_calib_" + key).getParameter(1);
}
return 0;
}
@Override
public void drawDataGroup(int sector, int layer, int component) {
if(this.getDataGroup().hasItem(sector,layer,component)==true){
DataGroup dataGroup = this.getDataGroup().getItem(sector,layer,component);
this.getCanvas().clear();
this.getCanvas().divide(4,2);
this.getCanvas().setGridX(false);
this.getCanvas().setGridY(false);
this.getCanvas().cd(0);
this.getCanvas().draw(dataGroup.getH1F("htsum"));
this.getCanvas().cd(1);
this.getCanvas().draw(dataGroup.getH1F("htsum_calib"));
this.getCanvas().cd(2);
// this.getCanvas().draw(dataGroup.getGraph("gtoffsets"));
this.getCanvas().draw(dataGroup.getH1F("htoffsets"));
this.getCanvas().getPad(2).getAxisY().setLog(true);
this.getCanvas().cd(3);
this.getCanvas().draw(dataGroup.getH1F("htsum_cluster"));
// this.getCanvas().cd(4);
// this.getCanvas().draw(dataGroup.getH1F("htime_wide_" + component));
this.getCanvas().cd(4);
this.getCanvas().draw(dataGroup.getH1F("htime_" + component));
this.getCanvas().cd(5);
this.getCanvas().draw(dataGroup.getH1F("htime_calib_" + component));
this.getCanvas().cd(6);
// this.getCanvas().draw(dataGroup.getGraph("gtoffsets"));
this.getCanvas().draw(dataGroup.getH1F("htcluster_" + component));
this.getCanvas().cd(7);
this.getCanvas().getPad(7).getAxisZ().setLog(true);
this.getCanvas().draw(dataGroup.getH2F("h2d_cluster"));
}
}
@Override
public void timerUpdate() {
this.analyze();
}
}
| JeffersonLab/clas12calibration-ft | ftCalCalib/src/main/java/org/clas/modules/FTTimeCalibration.java | 6,720 | // dg.addDataSet(htime_wide, 4); | line_comment | nl | package org.clas.modules;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.clas.view.DetectorShape2D;
import org.clas.viewer.FTCalibrationModule;
import org.clas.viewer.FTDetector;
import org.jlab.detector.calib.utils.CalibrationConstants;
import org.jlab.detector.calib.utils.ConstantsManager;
import org.jlab.groot.data.H1F;
import org.jlab.groot.group.DataGroup;
import org.jlab.io.base.DataBank;
import org.jlab.io.base.DataEvent;
import org.jlab.groot.math.F1D;
import org.jlab.groot.fitter.DataFitter;
import org.jlab.groot.data.GraphErrors;
import org.jlab.clas.pdg.PhysicsConstants;
import org.jlab.clas.physics.Particle;
import org.jlab.groot.data.H2F;
/**
*
* @author devita
*/
public class FTTimeCalibration extends FTCalibrationModule {
public FTTimeCalibration(FTDetector d, String name, ConstantsManager ccdb, Map<String,CalibrationConstants> gConstants) {
super(d, name, "offset:offset_error:delta:resolution",3, ccdb, gConstants);
this.getCalibrationTable().addConstraint(5, -0.1, 0.1);
this.setRange(30.,40.);
this.setRange(-10.,0.);
this.setCols(-2, 2);
}
@Override
public void resetEventListener() {
H1F htsum = new H1F("htsum", 275, -450.0, 100.0);
htsum.setTitleX("Time Offset (ns)");
htsum.setTitleY("Counts");
htsum.setTitle("Global Time Offset");
htsum.setFillColor(3);
H1F htsum_calib = new H1F("htsum_calib", 300, -6.0, 6.0);
htsum_calib.setTitleX("Time Offset (ns)");
htsum_calib.setTitleY("Counts");
htsum_calib.setTitle("Global Time Offset");
htsum_calib.setFillColor(44);
H1F htsum_cluster = new H1F("htsum_cluster" , 400, -2., 2.);
htsum_cluster.setTitleX("Time (ns)");
htsum_cluster.setTitleY("Counts");
htsum_cluster.setTitle("Cluster Time");
htsum_cluster.setFillColor(3);
htsum_cluster.setLineColor(1);
F1D fsum_cluster = new F1D("fsum_cluster", "[amp]*gaus(x,[mean],[sigma])", -1., 1.);
fsum_cluster.setParameter(0, 0.0);
fsum_cluster.setParameter(1, 0.0);
fsum_cluster.setParameter(2, 2.0);
fsum_cluster.setLineWidth(2);
fsum_cluster.setOptStat("1111");
H2F h2d_cluster = new H2F("h2d_cluster" , 100, 0., 12., 100, -2., 2.);
h2d_cluster.setTitleX("Energy (GeV)");
h2d_cluster.setTitleY("Time (ns)");
h2d_cluster.setTitle("Cluster Time");
GraphErrors gtoffsets = new GraphErrors("gtoffsets");
gtoffsets.setTitle("Timing Offsets"); // title
gtoffsets.setTitleX("Crystal ID"); // X axis title
gtoffsets.setTitleY("Offset (ns)"); // Y axis title
gtoffsets.setMarkerColor(5); // color from 0-9 for given palette
gtoffsets.setMarkerSize(2); // size in points on the screen
gtoffsets.addPoint(0., 0., 0., 0.);
gtoffsets.addPoint(1., 1., 0., 0.);
GraphErrors gtdeltas = new GraphErrors("gtdeltas");
gtdeltas.setTitle("#Delta Offset (ns)"); // title
gtdeltas.setTitleX("Crystal ID"); // X axis title
gtdeltas.setTitleY("#Delta Offset (ns)"); // Y axis title
gtdeltas.setMarkerColor(3); // color from 0-9 for given palette
gtdeltas.setMarkerSize(2); // size in points on the screen
gtdeltas.addPoint(0., 0., 0., 0.);
gtdeltas.addPoint(1., 1., 0., 0.);
H1F htoffsets = new H1F("htoffsets", 100, -2, 2);
htoffsets.setTitle("Hit Time");
htoffsets.setTitleX("#DeltaT (ns)");
htoffsets.setTitleY("Counts");
htoffsets.setFillColor(23);
htoffsets.setLineColor(3);
htoffsets.setOptStat("1111");
for (int key : this.getDetector().getDetectorComponents()) {
// initializa calibration constant table
this.getCalibrationTable().addEntry(1, 1, key);
this.getCalibrationTable().setDoubleValue(0.0, "offset", 1,1,key);
// initialize data group
H1F htime_wide = new H1F("htime_wide_" + key, 275, -400.0, 150.0);
htime_wide.setTitleX("Time (ns)");
htime_wide.setTitleY("Counts");
htime_wide.setTitle("Component " + key);
H1F htime = new H1F("htime_" + key, 500, this.getRange()[0], this.getRange()[1]);
htime.setTitleX("Time (ns)");
htime.setTitleY("Counts");
htime.setTitle("Component " + key);
H1F htime_calib = new H1F("htime_calib_" + key, 200, -4., 4.);
htime_calib.setTitleX("Time (ns)");
htime_calib.setTitleY("Counts");
htime_calib.setTitle("Component " + key);
htime_calib.setFillColor(44);
htime_calib.setLineColor(24);
F1D ftime = new F1D("ftime_" + key, "[amp]*gaus(x,[mean],[sigma])", -1., 1.);
ftime.setParameter(0, 0.0);
ftime.setParameter(1, 0.0);
ftime.setParameter(2, 2.0);
ftime.setLineColor(24);
ftime.setLineWidth(2);
ftime.setOptStat("1111");
F1D ftime_calib = new F1D("ftime_calib_" + key, "[amp]*gaus(x,[mean],[sigma])", -1., 1.);
ftime_calib.setParameter(0, 0.0);
ftime_calib.setParameter(1, 0.0);
ftime_calib.setParameter(2, 2.0);
ftime_calib.setLineColor(24);
ftime_calib.setLineWidth(2);
ftime_calib.setOptStat("1111");
// ftime.setLineColor(2);
// ftime.setLineStyle(1);
H1F htcluster = new H1F("htcluster_" + key, 200, -2., 2.);
htcluster.setTitleX("Time (ns)");
htcluster.setTitleY("Counts");
htcluster.setTitle("Cluster Time");
htcluster.setFillColor(3);
htcluster.setLineColor(1);
F1D fcluster = new F1D("fcluster_" + key, "[amp]*gaus(x,[mean],[sigma])", -1., 1.);
fcluster.setParameter(0, 0.0);
fcluster.setParameter(1, 0.0);
fcluster.setParameter(2, 2.0);
fcluster.setLineWidth(2);
fcluster.setOptStat("1111");
DataGroup dg = new DataGroup(4, 2);
dg.addDataSet(htsum, 0);
dg.addDataSet(htsum_calib, 1);
dg.addDataSet(htoffsets, 2);
dg.addDataSet(htsum_cluster, 3);
dg.addDataSet(fsum_cluster, 3);
// dg.addDataSet(htime_wide, <SUF>
dg.addDataSet(htime, 4);
dg.addDataSet(ftime, 4);
dg.addDataSet(htime_calib, 5);
dg.addDataSet(ftime_calib, 5);
// dg.addDataSet(gtoffsets, 6);
dg.addDataSet(htcluster, 6);
dg.addDataSet(fcluster, 6);
dg.addDataSet(h2d_cluster, 7);
this.getDataGroup().add(dg, 1, 1, key);
}
getCalibrationTable().fireTableDataChanged();
}
@Override
public List<CalibrationConstants> getCalibrationConstants() {
return Arrays.asList(getCalibrationTable());
}
@Override
public int getNEvents(DetectorShape2D dsd) {
int sector = dsd.getDescriptor().getSector();
int layer = dsd.getDescriptor().getLayer();
int key = dsd.getDescriptor().getComponent();
return (int) this.getDataGroup().getItem(sector,layer,key).getH1F("htime_" + key).getIntegral();
}
@Override
public void processEvent(DataEvent event) {
// loop over FTCAL reconstructed cluster
double startTime = -100000;
int triggerPID = 0;
// get start time
if(event.hasBank("REC::Event") && event.hasBank("REC::Particle")) {
DataBank recEvent = event.getBank("REC::Event");
DataBank recPart = event.getBank("REC::Particle");
startTime = recEvent.getFloat("startTime", 0);
if(recPart.getShort("status", 0)<-2000)
triggerPID = recPart.getInt("pid",0);
}
// loop over FTCAL reconstructed cluster
if (event.hasBank("FT::particles") && event.hasBank("FTCAL::clusters") && event.hasBank("FTCAL::hits") && event.hasBank("FTCAL::adc")) {
ArrayList<Particle> ftParticles = new ArrayList();
DataBank particlesFT = event.getBank("FT::particles");
DataBank clusterFTCAL = event.getBank("FTCAL::clusters");
DataBank hitFTCAL = event.getBank("FTCAL::hits");
DataBank adcFTCAL = event.getBank("FTCAL::adc");
// start from clusters
for (int loop = 0; loop < clusterFTCAL.rows(); loop++) {
int cluster = getDetector().getComponent(clusterFTCAL.getFloat("x", loop), clusterFTCAL.getFloat("y", loop));
int id = clusterFTCAL.getShort("id", loop);
int size = clusterFTCAL.getShort("size", loop);
int charge = particlesFT.getByte("charge", loop);
double x = clusterFTCAL.getFloat("x", loop);
double y = clusterFTCAL.getFloat("y", loop);
double z = this.getConstants().crystal_distance+this.getConstants().shower_depth-this.getConstants().z0;//clusterFTCAL.getFloat("z", loop);
double time = clusterFTCAL.getFloat("time", loop);
double energy = clusterFTCAL.getFloat("energy", loop);
double energyR = clusterFTCAL.getFloat("recEnergy", loop);
double path = Math.sqrt(x*x+y*y+z*z);
double theta = Math.toDegrees(Math.acos(z/path));
double tof = (path/PhysicsConstants.speedOfLight()); //ns
// find hits associated to clusters
if(energy>0.5 && energyR>0.3 && size > 3 && charge==0) {
double clusterTime = 0;
double seedTime = 0;
for(int k=0; k<hitFTCAL.rows(); k++) {
int clusterID = hitFTCAL.getShort("clusterID", k);
// select hits that belong to cluster
if(clusterID == id) {
int hitID = hitFTCAL.getShort("hitID", k);
double hitEnergy = hitFTCAL.getFloat("energy", k);
int component = adcFTCAL.getInt("component",hitID);
double hitTime = adcFTCAL.getFloat("time", hitID);
double hitCharge =((double) adcFTCAL.getInt("ADC", hitID))*(this.getConstants().LSB*this.getConstants().nsPerSample/50);
// double radius = Math.sqrt(Math.pow(this.getDetector().getIdX(component)-0.5,2.0)+Math.pow(this.getDetector().getIdY(component)-0.5,2.0))*this.getConstants().crystal_size;//meters
// double hitPath = Math.sqrt(Math.pow(this.getConstants().crystal_distance+this.getConstants().shower_depth,2)+Math.pow(radius,2));
// double hitTof = (hitPath/PhysicsConstants.speedOfLight()); //ns
double twalk = 0;
double offset = 0;
if(this.getGlobalCalibration().containsKey("TimeWalk")) {
double amp = this.getGlobalCalibration().get("TimeWalk").getDoubleValue("A", 1,1,component);
double lam = this.getGlobalCalibration().get("TimeWalk").getDoubleValue("L", 1,1,component);
twalk = amp*Math.exp(-hitCharge*lam);
}
if(this.getPreviousCalibrationTable().hasEntry(1,1,component)) {
offset = this.getPreviousCalibrationTable().getDoubleValue("offset", 1, 1, component);
}
hitTime = hitTime - (this.getConstants().crystal_length-this.getConstants().shower_depth)/this.getConstants().light_speed - twalk - offset;
clusterTime += hitTime*hitEnergy;
double timec = (adcFTCAL.getFloat("time", hitID) -(startTime + tof + (this.getConstants().crystal_length-this.getConstants().shower_depth)/this.getConstants().light_speed));
// System.out.println(component + " " + hitEnergy + " " + hitFTCAL.getFloat("time", k) + " " + hitTime);
this.getDataGroup().getItem(1,1,component).getH1F("htsum").fill(timec-twalk);
// this.getDataGroup().getItem(1,1,component).getH1F("htime_wide_"+component).fill(timec-twalk);
this.getDataGroup().getItem(1,1,component).getH1F("htime_"+component).fill(timec-twalk);
this.getDataGroup().getItem(1,1,component).getH1F("htsum_calib").fill(timec-twalk-offset);
this.getDataGroup().getItem(1,1,component).getH1F("htime_calib_"+component).fill(timec-twalk-offset);
// System.out.println(key + " " + (time-twalk-offset-(this.getConstants().crystal_length-this.getConstants().shower_depth)/this.getConstants().light_speed) + " " + adc + " " + charge + " " + time + " " + twalk + " " + offset);
// if(event.hasBank("FTCAL::hits")) {event.getBank("FTCAL::adc").show();event.getBank("FTCAL::hits").show();}
}
}
clusterTime /= energyR;
if(theta>2.5 && theta<4.5) {
this.getDataGroup().getItem(1,1,cluster).getH1F("htsum_cluster").fill(clusterTime-tof-startTime);
this.getDataGroup().getItem(1,1,cluster).getH2F("h2d_cluster").fill(energy,clusterTime-tof-startTime);
this.getDataGroup().getItem(1,1,cluster).getH1F("htcluster_"+cluster).fill(clusterTime-tof-startTime);
// System.out.println(time + " " + clusterTime);
}
}
}
}
}
@Override
public void analyze() {
// System.out.println("Analyzing");
H1F htime = this.getDataGroup().getItem(1,1,8).getH1F("htsum_cluster");
F1D ftime = this.getDataGroup().getItem(1,1,8).getF1D("fsum_cluster");
this.initTimeGaussFitPar(ftime,htime, 0.35, false);
DataFitter.fit(ftime,htime,"LQ");
for (int key : this.getDetector().getDetectorComponents()) {
// this.getDataGroup().getItem(1,1,key).getGraph("gtoffsets").reset();
this.getDataGroup().getItem(1,1,key).getH1F("htoffsets").reset();
}
for (int key : this.getDetector().getDetectorComponents()) {
htime = this.getDataGroup().getItem(1,1,key).getH1F("htime_" + key);
ftime = this.getDataGroup().getItem(1,1,key).getF1D("ftime_" + key);
this.initTimeGaussFitPar(ftime,htime, 0.5, false);
DataFitter.fit(ftime,htime,"LQ");
// this.getDataGroup().getItem(1,1,key).getGraph("gtoffsets").addPoint(key, ftime.getParameter(1), 0, ftime.parameter(1).error());
htime = this.getDataGroup().getItem(1,1,key).getH1F("htime_calib_" + key);
ftime = this.getDataGroup().getItem(1,1,key).getF1D("ftime_calib_" + key);
this.initTimeGaussFitPar(ftime,htime, 0.5, false);
DataFitter.fit(ftime,htime,"LQ");
double hoffset = ftime.getParameter(1);
if(Math.abs(hoffset)<2) this.getDataGroup().getItem(1,1,key).getH1F("htoffsets").fill(hoffset);
htime = this.getDataGroup().getItem(1,1,key).getH1F("htcluster_" + key);
ftime = this.getDataGroup().getItem(1,1,key).getF1D("fcluster_" + key);
this.initTimeGaussFitPar(ftime,htime, 0.4, false);
DataFitter.fit(ftime,htime,"LQ");
double finalOffset = this.getDataGroup().getItem(1, 1, key).getF1D("ftime_" + key).getParameter(1);
if(this.getDataGroup().getItem(1, 1, key).getF1D("fcluster_" + key).getParameter(0)>20) {
finalOffset = finalOffset
+ this.getDataGroup().getItem(1, 1, key).getF1D("fcluster_" + key).getParameter(1)
- this.getDataGroup().getItem(1, 1, key).getF1D("ftime_calib_" + key).getParameter(1);
}
getCalibrationTable().setDoubleValue(finalOffset, "offset", 1, 1, key);
getCalibrationTable().setDoubleValue(this.getDataGroup().getItem(1, 1, key).getF1D("ftime_" + key).parameter(1).error(), "offset_error", 1, 1, key);
getCalibrationTable().setDoubleValue(this.getDataGroup().getItem(1, 1, key).getF1D("ftime_calib_" + key).getParameter(1), "delta" , 1, 1, key);
getCalibrationTable().setDoubleValue(this.getDataGroup().getItem(1, 1, key).getF1D("ftime_calib_" + key).getParameter(2), "resolution" , 1, 1, key);
}
getCalibrationTable().fireTableDataChanged();
}
@Override
public void setCanvasBookData() {
int[] pads = {4,5,6};
this.getCanvasBook().setData(this.getDataGroup(), pads);
}
private void initTimeGaussFitPar(F1D ftime, H1F htime, double range, boolean limits) {
double hAmp = htime.getBinContent(htime.getMaximumBin());
double hMean = htime.getAxis().getBinCenter(htime.getMaximumBin());
double hRMS = 2; //ns
double rangeMin = (hMean - range);
double rangeMax = (hMean + range);
double pm = (hMean*10.0)/100.0;
ftime.setRange(rangeMin, rangeMax);
ftime.setParameter(0, hAmp);
ftime.setParLimits(0, hAmp*0.8, hAmp*1.2);
ftime.setParameter(1, hMean);
ftime.setParameter(2, 0.2);
if(limits) {
ftime.setParLimits(1, hMean-pm, hMean+(pm));
ftime.setParLimits(2, 0.05*hRMS, 0.8*hRMS);
}
}
@Override
public double getValue(DetectorShape2D dsd) {
// show summary
int sector = dsd.getDescriptor().getSector();
int layer = dsd.getDescriptor().getLayer();
int key = dsd.getDescriptor().getComponent();
if (this.getDetector().hasComponent(key)) {
return this.getDataGroup().getItem(1, 1, key).getF1D("ftime_calib_" + key).getParameter(1);
}
return 0;
}
@Override
public void drawDataGroup(int sector, int layer, int component) {
if(this.getDataGroup().hasItem(sector,layer,component)==true){
DataGroup dataGroup = this.getDataGroup().getItem(sector,layer,component);
this.getCanvas().clear();
this.getCanvas().divide(4,2);
this.getCanvas().setGridX(false);
this.getCanvas().setGridY(false);
this.getCanvas().cd(0);
this.getCanvas().draw(dataGroup.getH1F("htsum"));
this.getCanvas().cd(1);
this.getCanvas().draw(dataGroup.getH1F("htsum_calib"));
this.getCanvas().cd(2);
// this.getCanvas().draw(dataGroup.getGraph("gtoffsets"));
this.getCanvas().draw(dataGroup.getH1F("htoffsets"));
this.getCanvas().getPad(2).getAxisY().setLog(true);
this.getCanvas().cd(3);
this.getCanvas().draw(dataGroup.getH1F("htsum_cluster"));
// this.getCanvas().cd(4);
// this.getCanvas().draw(dataGroup.getH1F("htime_wide_" + component));
this.getCanvas().cd(4);
this.getCanvas().draw(dataGroup.getH1F("htime_" + component));
this.getCanvas().cd(5);
this.getCanvas().draw(dataGroup.getH1F("htime_calib_" + component));
this.getCanvas().cd(6);
// this.getCanvas().draw(dataGroup.getGraph("gtoffsets"));
this.getCanvas().draw(dataGroup.getH1F("htcluster_" + component));
this.getCanvas().cd(7);
this.getCanvas().getPad(7).getAxisZ().setLog(true);
this.getCanvas().draw(dataGroup.getH2F("h2d_cluster"));
}
}
@Override
public void timerUpdate() {
this.analyze();
}
}
|
141487_6 | package hep.lcio.implementation.event;
import hep.lcio.event.MCParticle;
import hep.lcio.event.SimTrackerHit;
/**
* A default implementation of SimTrackerHit
* @author Tony Johnson
* @version $Id: ISimTrackerHit.java,v 1.11 2010-06-02 10:59:34 engels Exp $
*/
public class ISimTrackerHit extends ILCObject implements SimTrackerHit
{
protected Object particle;
protected double[] position = new double[3];
//protected float dEdx; // DEPRECATED. renamed to EDep
protected float EDep;
protected float time;
//protected int cellID; // DEPRECATED. renamed to cellID0
protected int cellID0;
protected int cellID1;
protected float[] momentum = new float[3] ;
protected float pathLength;
// DEPRECATED. renamed to setcellID0
public void setCellID(int cellID)
{
//checkAccess();
//this.cellID = cellID;
setCellID0( cellID );
}
// DEPRECATED. renamed to getcellID0
public int getCellID()
{
//return cellID;
return getCellID0();
}
public void setCellID0(int cellID)
{
checkAccess();
this.cellID0 = cellID;
}
public int getCellID0()
{
return cellID0;
}
public void setCellID1(int cellID)
{
checkAccess();
this.cellID1 = cellID;
}
public int getCellID1()
{
return cellID1;
}
public void setMCParticle(MCParticle mc)
{
checkAccess();
particle = mc;
}
public MCParticle getMCParticle()
{
return (MCParticle) particle;
}
public void setPosition(double[] pos)
{
checkAccess();
if (pos.length != 3)
throw new IllegalArgumentException();
position = pos;
}
public double[] getPosition()
{
return position;
}
public void setTime(float time)
{
checkAccess();
this.time = time;
}
public float getTime()
{
return time;
}
// DEPRECATED. renamed to getEDep()
public float getdEdx()
{
//return dEdx;
return getEDep();
}
// DEPRECATED. renamed to setEDep()
public void setdEdx(float dEdx)
{
//checkAccess();
//this.dEdx = dEdx;
setEDep( dEdx );
}
public float getEDep()
{
return EDep;
}
public void setEDep(float e)
{
checkAccess();
this.EDep = e;
}
public float[] getMomentum()
{
return momentum;
}
public void setMomentum(float[] fs)
{
checkAccess() ;
if (fs.length != 3) throw new IllegalArgumentException();
momentum = fs;
}
public float getPathLength()
{
return pathLength;
}
public void setPathLength(float length)
{
this.pathLength = length;
}
}
| JeffersonLab/hps-analysis | MiniDst/lcio/src/java/hep/lcio/implementation/event/ISimTrackerHit.java | 983 | // DEPRECATED. renamed to getEDep() | line_comment | nl | package hep.lcio.implementation.event;
import hep.lcio.event.MCParticle;
import hep.lcio.event.SimTrackerHit;
/**
* A default implementation of SimTrackerHit
* @author Tony Johnson
* @version $Id: ISimTrackerHit.java,v 1.11 2010-06-02 10:59:34 engels Exp $
*/
public class ISimTrackerHit extends ILCObject implements SimTrackerHit
{
protected Object particle;
protected double[] position = new double[3];
//protected float dEdx; // DEPRECATED. renamed to EDep
protected float EDep;
protected float time;
//protected int cellID; // DEPRECATED. renamed to cellID0
protected int cellID0;
protected int cellID1;
protected float[] momentum = new float[3] ;
protected float pathLength;
// DEPRECATED. renamed to setcellID0
public void setCellID(int cellID)
{
//checkAccess();
//this.cellID = cellID;
setCellID0( cellID );
}
// DEPRECATED. renamed to getcellID0
public int getCellID()
{
//return cellID;
return getCellID0();
}
public void setCellID0(int cellID)
{
checkAccess();
this.cellID0 = cellID;
}
public int getCellID0()
{
return cellID0;
}
public void setCellID1(int cellID)
{
checkAccess();
this.cellID1 = cellID;
}
public int getCellID1()
{
return cellID1;
}
public void setMCParticle(MCParticle mc)
{
checkAccess();
particle = mc;
}
public MCParticle getMCParticle()
{
return (MCParticle) particle;
}
public void setPosition(double[] pos)
{
checkAccess();
if (pos.length != 3)
throw new IllegalArgumentException();
position = pos;
}
public double[] getPosition()
{
return position;
}
public void setTime(float time)
{
checkAccess();
this.time = time;
}
public float getTime()
{
return time;
}
// DEPRECATED. renamed<SUF>
public float getdEdx()
{
//return dEdx;
return getEDep();
}
// DEPRECATED. renamed to setEDep()
public void setdEdx(float dEdx)
{
//checkAccess();
//this.dEdx = dEdx;
setEDep( dEdx );
}
public float getEDep()
{
return EDep;
}
public void setEDep(float e)
{
checkAccess();
this.EDep = e;
}
public float[] getMomentum()
{
return momentum;
}
public void setMomentum(float[] fs)
{
checkAccess() ;
if (fs.length != 3) throw new IllegalArgumentException();
momentum = fs;
}
public float getPathLength()
{
return pathLength;
}
public void setPathLength(float length)
{
this.pathLength = length;
}
}
|
11189_5 | /*
* Naam: Jelte Fennema
* Studentnummer: 10183159
* Opleiding: Informatica
*
* Functionaliteit: Het programma moet, achtereenvolgens, de volgende vier,
* onderling niet geralateerde, onderdelen uitvoeren:
* 1. Het programma vraagt de gebruiker om een totaal aantal seconden
* (een integer) in te voeren. Het programma print vervolgens dezelfde
* hoeveelheid tijd, maar nu gerepresenteerd in uren, minuten en seconden.
*
* 2. Het programma vraagt de gebruiker om een geheel getal (integer) tussen
* 0 en 128 in te voeren. Het programma print vervolgens het ASCII karakter dat
* door dit getal wordt gerepresenteerd.
*
* 3. Het programma vraagt de gebruiker om de straal van een bol (een double)
* in te voeren. Het programma print vervolgens de oppervlakte en het volume van
* deze bol.
*
* 4. Schrijf een hulpfunctie die de uitvoer bij onderdeel 3 afrondt op 3
* decimalen.
*/
import java.util.*;
public class Opgave2 {
/*
* Main method: Deze roept alle drie de functies aan en vraagt om de invoer voor
* voor die functies.
*/
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
System.out.println("Voer een geheel aantal seconden in:");
tijd(scanner.nextInt());
System.out.println("Geef een integer tussen 0 en 128:");
charConverter(scanner.nextInt());
System.out.println("Geef de straal van de bol:");
bol(scanner.nextDouble());
}
/*
* Bol method: Deze methode berekent de oppervlakte en de inhoud van een bol
* aan de hand van de straal. Ook worden deze waardes daarna afgerond op
* drie decimalen.
*/
static void bol (double straal){
if(straal >= 0){
double oppervlakte = 4*Math.PI*straal*straal;
double inhoud = 4/3*Math.PI*straal*straal*straal;
System.out.println("\nOppervlakte: " + oppervlakte + "\nInhoud: " +
inhoud);
System.out.println("\nAfgerond op drie decimalen is het dan:\n" +
"Oppervlakte: "+ roundNumber3(oppervlakte) +
"\nInhoud: " + roundNumber3(inhoud));
} else {
System.out.println("Ga eens positieve getallen invullen ofzo.\n");
}
}
/*
* RoundNumber3 method: Deze methode rond doubles af op 3 decimalen.
*/
static double roundNumber3(double roundable){
roundable=Math.round(roundable*1000)/1000.0;
return roundable;
}
/*
* CharConverter method: Deze methode converteerd een int tussen
* de 0 en 128 naar een char.
*/
static void charConverter (int convertable){
if (convertable > 0 && convertable < 128)
System.out.println("\nHet corresponderende ASCII karakter is: " +
(char) convertable + "\n");
else
System.out.println("Ga eens leren tellen, " + convertable +
" zit niet tussen de 0 en 128.\n");
}
/*
* Tijd method: Deze methode geeft aan hoeveel uur, minuten en secondes er
* zitten in een bepaald aantal secondes.
*/
static void tijd(int sec){
if(sec>=0){
int uren = sec/3600;
int minuten = (sec%3600)/60;
int secondes = (sec%3600)%60;
System.out.println("\nHet totaal aantal seconden komt overeen met:"
+ "\n" + uren + uurOfUren(uren) +
minuten + minuutOfMinuten(minuten) +
secondes + secondeOfSecondes(secondes) +
"\n");
} else {
System.out.println("Really, ben je dom? Er bestaat toch geen "
+ "negatieve tijd.\n");
}
}
/*
* Deze drie methodes kijken of er een meervoud van het woord uur, minuut of
* seconde gebruikt moet worden.
*/
static String uurOfUren(int k){
if (k>1) {
return " uren, ";
} else {
return " uur, ";
}
}
static String minuutOfMinuten(int k){
if (k>1) {
return " minuten en ";
} else {
return " minuut en ";
}
}
static String secondeOfSecondes(int k){
if (k>1) {
return " secondes.";
} else {
return " seconde.";
}
}
}
| JelteF/java | assignment2/Opgave2.java | 1,356 | /*
* Tijd method: Deze methode geeft aan hoeveel uur, minuten en secondes er
* zitten in een bepaald aantal secondes.
*/ | block_comment | nl | /*
* Naam: Jelte Fennema
* Studentnummer: 10183159
* Opleiding: Informatica
*
* Functionaliteit: Het programma moet, achtereenvolgens, de volgende vier,
* onderling niet geralateerde, onderdelen uitvoeren:
* 1. Het programma vraagt de gebruiker om een totaal aantal seconden
* (een integer) in te voeren. Het programma print vervolgens dezelfde
* hoeveelheid tijd, maar nu gerepresenteerd in uren, minuten en seconden.
*
* 2. Het programma vraagt de gebruiker om een geheel getal (integer) tussen
* 0 en 128 in te voeren. Het programma print vervolgens het ASCII karakter dat
* door dit getal wordt gerepresenteerd.
*
* 3. Het programma vraagt de gebruiker om de straal van een bol (een double)
* in te voeren. Het programma print vervolgens de oppervlakte en het volume van
* deze bol.
*
* 4. Schrijf een hulpfunctie die de uitvoer bij onderdeel 3 afrondt op 3
* decimalen.
*/
import java.util.*;
public class Opgave2 {
/*
* Main method: Deze roept alle drie de functies aan en vraagt om de invoer voor
* voor die functies.
*/
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
System.out.println("Voer een geheel aantal seconden in:");
tijd(scanner.nextInt());
System.out.println("Geef een integer tussen 0 en 128:");
charConverter(scanner.nextInt());
System.out.println("Geef de straal van de bol:");
bol(scanner.nextDouble());
}
/*
* Bol method: Deze methode berekent de oppervlakte en de inhoud van een bol
* aan de hand van de straal. Ook worden deze waardes daarna afgerond op
* drie decimalen.
*/
static void bol (double straal){
if(straal >= 0){
double oppervlakte = 4*Math.PI*straal*straal;
double inhoud = 4/3*Math.PI*straal*straal*straal;
System.out.println("\nOppervlakte: " + oppervlakte + "\nInhoud: " +
inhoud);
System.out.println("\nAfgerond op drie decimalen is het dan:\n" +
"Oppervlakte: "+ roundNumber3(oppervlakte) +
"\nInhoud: " + roundNumber3(inhoud));
} else {
System.out.println("Ga eens positieve getallen invullen ofzo.\n");
}
}
/*
* RoundNumber3 method: Deze methode rond doubles af op 3 decimalen.
*/
static double roundNumber3(double roundable){
roundable=Math.round(roundable*1000)/1000.0;
return roundable;
}
/*
* CharConverter method: Deze methode converteerd een int tussen
* de 0 en 128 naar een char.
*/
static void charConverter (int convertable){
if (convertable > 0 && convertable < 128)
System.out.println("\nHet corresponderende ASCII karakter is: " +
(char) convertable + "\n");
else
System.out.println("Ga eens leren tellen, " + convertable +
" zit niet tussen de 0 en 128.\n");
}
/*
* Tijd method: Deze<SUF>*/
static void tijd(int sec){
if(sec>=0){
int uren = sec/3600;
int minuten = (sec%3600)/60;
int secondes = (sec%3600)%60;
System.out.println("\nHet totaal aantal seconden komt overeen met:"
+ "\n" + uren + uurOfUren(uren) +
minuten + minuutOfMinuten(minuten) +
secondes + secondeOfSecondes(secondes) +
"\n");
} else {
System.out.println("Really, ben je dom? Er bestaat toch geen "
+ "negatieve tijd.\n");
}
}
/*
* Deze drie methodes kijken of er een meervoud van het woord uur, minuut of
* seconde gebruikt moet worden.
*/
static String uurOfUren(int k){
if (k>1) {
return " uren, ";
} else {
return " uur, ";
}
}
static String minuutOfMinuten(int k){
if (k>1) {
return " minuten en ";
} else {
return " minuut en ";
}
}
static String secondeOfSecondes(int k){
if (k>1) {
return " secondes.";
} else {
return " seconde.";
}
}
}
|
53963_22 | package com.jeno.fantasyleague;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;
import com.google.common.collect.Maps;
public class Lala {
// private static final String welcomeSlaapie = "" +
// "_____/\\\\\\\\\\\\\\\\\\\\\\___ __/\\\\\\_____________ _____/\\\\\\\\\\\\\\\\\\____ _____/\\\\\\\\\\\\\\\\\\____ __/\\\\\\\\\\\\\\\\\\\\\\\\\\___ __/\\\\\\\\\\\\\\\\\\\\\\_ __/\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\_ \n" +
// " ___/\\\\\\/////////\\\\\\_ _\\/\\\\\\_____________ ___/\\\\\\\\\\\\\\\\\\\\\\\\\\__ ___/\\\\\\\\\\\\\\\\\\\\\\\\\\__ _\\/\\\\\\/////////\\\\\\_ _\\/////\\\\\\///__ _\\/\\\\\\///////////__ \n" +
// " __\\//\\\\\\______\\///__ _\\/\\\\\\_____________ __/\\\\\\/////////\\\\\\_ __/\\\\\\/////////\\\\\\_ _\\/\\\\\\_______\\/\\\\\\_ _____\\/\\\\\\_____ _\\/\\\\\\_____________ \n" +
// " ___\\////\\\\\\_________ _\\/\\\\\\_____________ _\\/\\\\\\_______\\/\\\\\\_ _\\/\\\\\\_______\\/\\\\\\_ _\\/\\\\\\\\\\\\\\\\\\\\\\\\\\/__ _____\\/\\\\\\_____ _\\/\\\\\\\\\\\\\\\\\\\\\\_____ \n" +
// " ______\\////\\\\\\______ _\\/\\\\\\_____________ _\\/\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\_ _\\/\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\_ _\\/\\\\\\/////////____ _____\\/\\\\\\_____ _\\/\\\\\\///////______ \n" +
// " _________\\////\\\\\\___ _\\/\\\\\\_____________ _\\/\\\\\\/////////\\\\\\_ _\\/\\\\\\/////////\\\\\\_ _\\/\\\\\\_____________ _____\\/\\\\\\_____ _\\/\\\\\\_____________ \n" +
// " __/\\\\\\______\\//\\\\\\__ _\\/\\\\\\_____________ _\\/\\\\\\_______\\/\\\\\\_ _\\/\\\\\\_______\\/\\\\\\_ _\\/\\\\\\_____________ _____\\/\\\\\\_____ _\\/\\\\\\_____________ \n" +
// " _\\///\\\\\\\\\\\\\\\\\\\\\\/___ _\\/\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\_ _\\/\\\\\\_______\\/\\\\\\_ _\\/\\\\\\_______\\/\\\\\\_ _\\/\\\\\\_____________ __/\\\\\\\\\\\\\\\\\\\\\\_ _\\/\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\_ \n" +
// " ___\\///////////_____ _\\///////////////__ _\\///________\\///__ _\\///________\\///__ _\\///______________ _\\///////////__ _\\///////////////__\n" +
// "\n";
//
// public static void main(String[] args) {
// Map<String, Integer> scores = Maps.newHashMap();
//
// while(true) {
// int bound = 15;
// System.out.println();
// System.out.println();
// System.out.println("-------- Guess the number ---------------");
// System.out.println("De limiet is " + bound);
// Random r = new Random();
// int result = r.nextInt(15);
//
// String name = askForName();
// boolean passwordEntered = false;
// boolean newNameChosen = false;
// while(name != null && name.isEmpty() || nameIsInvalid(name, passwordEntered, newNameChosen)) {
// name = askForName();
// if ("ikzalzelfwelkiezen".equalsIgnoreCase(name)) {
// passwordEntered = true;
// } else if (passwordEntered) {
// newNameChosen = true;
// }
// }
//
// int turns = 0;
// boolean correct = false;
// while(!correct) {
// String guess = askForNumber(turns);
// turns++;
// correct = parseGuess(guess, result, bound);
// if (nameIsSlaapie(name, welcomeSlaapie)) {
// result = r.nextInt(15);
// }
// }
// System.out.println("Het duurde voor jou " + turns + " beurten.");
// TurnResult turnResult = calculateTurnResult(turns, bound);
// if (turnResult == null) {
// System.err.println("WHAT THA FUCK");
// } else {
// System.out.println("Analyse leert dat: " + turnResult.getFeedback());
// }
//
// if (!scores.containsKey(name)) {
// scores.put(name, turns);
// } else if (scores.get(name) > turns) {
// scores.put(name, turns);
// }
//
// System.out.println("Scoreboard: ");
// prettyPrintMap(scores);
// System.out.println();
// System.out.println();
// }
// }
//
// private static boolean nameIsInvalid(String name, boolean passwordEntered, boolean newNameChosen) {
// if (passwordEntered && newNameChosen) {
// return false;
// }
// if (passwordEntered && !newNameChosen) {
// return true;
// }
// boolean nameIsSlaapie = nameIsSlaapie(name, welcomeSlaapie);
// if (!nameIsSlaapie) {
// System.err.println("Error: foutieve naam! Tip: probeer eens");
// System.out.println(welcomeSlaapie);
// }
// return !nameIsSlaapie;
// }
//
// private static boolean nameIsSlaapie(String name, String welcomeSlaapie) {
// return "slaapie".equalsIgnoreCase(name) || welcomeSlaapie.equals(name);
// }
//
// public static String askForName() {
// Scanner myObj = new Scanner(System.in);
// System.out.println("Geef jouw naam in: ");
// return myObj.nextLine();
// }
//
// private static void prettyPrintMap(Map<String, Integer> map) {
// map.entrySet().stream()
// .sorted(Comparator.comparing(Map.Entry::getValue))
// .forEach(score -> {
// System.out.println(score.getKey() + " = " + score.getValue());
// });
// }
//
// private static TurnResult calculateTurnResult(int turns, int bound) {
// return Arrays.stream(TurnResult.values())
// .filter(turnResult -> {
// int lower = Math.round((((float) turnResult.getRange().getLower()) / 100) * bound);
// int upper = Math.round((((float) turnResult.getRange().getUpper()) / 100) * bound);
// return turns >= lower && turns <= upper;
// })
// .findFirst()
// .orElse(null);
// }
//
// private static boolean parseGuess(String guess, int result, int bound) {
// try {
// int guessInt = Integer.parseInt(guess);
// if (guessInt < 0 || guessInt > bound) {
// System.err.println("ELABA MAKKER, blijf tss de grenzen :)");
// return false;
// } else {
// if (guessInt > result) {
// System.out.println("Ge zit te hoog");
// return false;
// } else if (guessInt < result) {
// System.out.println("Ge zit te laag, te leeg e");
// return false;
// } else {
// System.out.println("Goed zo! Het was inderdaad " + result);
// return true;
// }
// }
// } catch (NumberFormatException e) {
// System.err.println("ELABA MAKKER, GE MOET WEL EEN NUMMER KIEZEN E VRIEND!");
// return false;
// }
// }
//
// public static String askForNumber(int turns) {
// Scanner myObj = new Scanner(System.in);
// System.out.println("Geef jouw gokje voor beurt " + turns + ": ");
// return myObj.nextLine();
// }
//
// public enum TurnResult {
// FEW_GUESSES(new Range(0, 15), "Super goed"),
// AVG_GUESSES(new Range(15, 35), "Hmmmm, cva... I guess"),
// A_LOT_OF_GUESSES(new Range(35, 100), "HAHAHAHAHAHAHA, gij suckt wel");
//
// private final Range range;
// private final String feedback;
//
// TurnResult(Range range, String feedback) {
// this.range = range;
// this.feedback = feedback;
// }
//
// public Range getRange() {
// return range;
// }
//
// public String getFeedback() {
// return feedback;
// }
// }
//
// public static class Range {
// private final int lower;
// private final int upper;
//
// public Range(int lower, int upper) {
// this.lower = lower;
// this.upper = upper;
// }
//
// public int getLower() {
// return lower;
// }
//
// public int getUpper() {
// return upper;
// }
// }
}
| JenoDK/fantasy-league-app | src/test/java/com/jeno/fantasyleague/Lala.java | 2,741 | // if ("ikzalzelfwelkiezen".equalsIgnoreCase(name)) { | line_comment | nl | package com.jeno.fantasyleague;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;
import com.google.common.collect.Maps;
public class Lala {
// private static final String welcomeSlaapie = "" +
// "_____/\\\\\\\\\\\\\\\\\\\\\\___ __/\\\\\\_____________ _____/\\\\\\\\\\\\\\\\\\____ _____/\\\\\\\\\\\\\\\\\\____ __/\\\\\\\\\\\\\\\\\\\\\\\\\\___ __/\\\\\\\\\\\\\\\\\\\\\\_ __/\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\_ \n" +
// " ___/\\\\\\/////////\\\\\\_ _\\/\\\\\\_____________ ___/\\\\\\\\\\\\\\\\\\\\\\\\\\__ ___/\\\\\\\\\\\\\\\\\\\\\\\\\\__ _\\/\\\\\\/////////\\\\\\_ _\\/////\\\\\\///__ _\\/\\\\\\///////////__ \n" +
// " __\\//\\\\\\______\\///__ _\\/\\\\\\_____________ __/\\\\\\/////////\\\\\\_ __/\\\\\\/////////\\\\\\_ _\\/\\\\\\_______\\/\\\\\\_ _____\\/\\\\\\_____ _\\/\\\\\\_____________ \n" +
// " ___\\////\\\\\\_________ _\\/\\\\\\_____________ _\\/\\\\\\_______\\/\\\\\\_ _\\/\\\\\\_______\\/\\\\\\_ _\\/\\\\\\\\\\\\\\\\\\\\\\\\\\/__ _____\\/\\\\\\_____ _\\/\\\\\\\\\\\\\\\\\\\\\\_____ \n" +
// " ______\\////\\\\\\______ _\\/\\\\\\_____________ _\\/\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\_ _\\/\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\_ _\\/\\\\\\/////////____ _____\\/\\\\\\_____ _\\/\\\\\\///////______ \n" +
// " _________\\////\\\\\\___ _\\/\\\\\\_____________ _\\/\\\\\\/////////\\\\\\_ _\\/\\\\\\/////////\\\\\\_ _\\/\\\\\\_____________ _____\\/\\\\\\_____ _\\/\\\\\\_____________ \n" +
// " __/\\\\\\______\\//\\\\\\__ _\\/\\\\\\_____________ _\\/\\\\\\_______\\/\\\\\\_ _\\/\\\\\\_______\\/\\\\\\_ _\\/\\\\\\_____________ _____\\/\\\\\\_____ _\\/\\\\\\_____________ \n" +
// " _\\///\\\\\\\\\\\\\\\\\\\\\\/___ _\\/\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\_ _\\/\\\\\\_______\\/\\\\\\_ _\\/\\\\\\_______\\/\\\\\\_ _\\/\\\\\\_____________ __/\\\\\\\\\\\\\\\\\\\\\\_ _\\/\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\_ \n" +
// " ___\\///////////_____ _\\///////////////__ _\\///________\\///__ _\\///________\\///__ _\\///______________ _\\///////////__ _\\///////////////__\n" +
// "\n";
//
// public static void main(String[] args) {
// Map<String, Integer> scores = Maps.newHashMap();
//
// while(true) {
// int bound = 15;
// System.out.println();
// System.out.println();
// System.out.println("-------- Guess the number ---------------");
// System.out.println("De limiet is " + bound);
// Random r = new Random();
// int result = r.nextInt(15);
//
// String name = askForName();
// boolean passwordEntered = false;
// boolean newNameChosen = false;
// while(name != null && name.isEmpty() || nameIsInvalid(name, passwordEntered, newNameChosen)) {
// name = askForName();
// if ("ikzalzelfwelkiezen".equalsIgnoreCase(name))<SUF>
// passwordEntered = true;
// } else if (passwordEntered) {
// newNameChosen = true;
// }
// }
//
// int turns = 0;
// boolean correct = false;
// while(!correct) {
// String guess = askForNumber(turns);
// turns++;
// correct = parseGuess(guess, result, bound);
// if (nameIsSlaapie(name, welcomeSlaapie)) {
// result = r.nextInt(15);
// }
// }
// System.out.println("Het duurde voor jou " + turns + " beurten.");
// TurnResult turnResult = calculateTurnResult(turns, bound);
// if (turnResult == null) {
// System.err.println("WHAT THA FUCK");
// } else {
// System.out.println("Analyse leert dat: " + turnResult.getFeedback());
// }
//
// if (!scores.containsKey(name)) {
// scores.put(name, turns);
// } else if (scores.get(name) > turns) {
// scores.put(name, turns);
// }
//
// System.out.println("Scoreboard: ");
// prettyPrintMap(scores);
// System.out.println();
// System.out.println();
// }
// }
//
// private static boolean nameIsInvalid(String name, boolean passwordEntered, boolean newNameChosen) {
// if (passwordEntered && newNameChosen) {
// return false;
// }
// if (passwordEntered && !newNameChosen) {
// return true;
// }
// boolean nameIsSlaapie = nameIsSlaapie(name, welcomeSlaapie);
// if (!nameIsSlaapie) {
// System.err.println("Error: foutieve naam! Tip: probeer eens");
// System.out.println(welcomeSlaapie);
// }
// return !nameIsSlaapie;
// }
//
// private static boolean nameIsSlaapie(String name, String welcomeSlaapie) {
// return "slaapie".equalsIgnoreCase(name) || welcomeSlaapie.equals(name);
// }
//
// public static String askForName() {
// Scanner myObj = new Scanner(System.in);
// System.out.println("Geef jouw naam in: ");
// return myObj.nextLine();
// }
//
// private static void prettyPrintMap(Map<String, Integer> map) {
// map.entrySet().stream()
// .sorted(Comparator.comparing(Map.Entry::getValue))
// .forEach(score -> {
// System.out.println(score.getKey() + " = " + score.getValue());
// });
// }
//
// private static TurnResult calculateTurnResult(int turns, int bound) {
// return Arrays.stream(TurnResult.values())
// .filter(turnResult -> {
// int lower = Math.round((((float) turnResult.getRange().getLower()) / 100) * bound);
// int upper = Math.round((((float) turnResult.getRange().getUpper()) / 100) * bound);
// return turns >= lower && turns <= upper;
// })
// .findFirst()
// .orElse(null);
// }
//
// private static boolean parseGuess(String guess, int result, int bound) {
// try {
// int guessInt = Integer.parseInt(guess);
// if (guessInt < 0 || guessInt > bound) {
// System.err.println("ELABA MAKKER, blijf tss de grenzen :)");
// return false;
// } else {
// if (guessInt > result) {
// System.out.println("Ge zit te hoog");
// return false;
// } else if (guessInt < result) {
// System.out.println("Ge zit te laag, te leeg e");
// return false;
// } else {
// System.out.println("Goed zo! Het was inderdaad " + result);
// return true;
// }
// }
// } catch (NumberFormatException e) {
// System.err.println("ELABA MAKKER, GE MOET WEL EEN NUMMER KIEZEN E VRIEND!");
// return false;
// }
// }
//
// public static String askForNumber(int turns) {
// Scanner myObj = new Scanner(System.in);
// System.out.println("Geef jouw gokje voor beurt " + turns + ": ");
// return myObj.nextLine();
// }
//
// public enum TurnResult {
// FEW_GUESSES(new Range(0, 15), "Super goed"),
// AVG_GUESSES(new Range(15, 35), "Hmmmm, cva... I guess"),
// A_LOT_OF_GUESSES(new Range(35, 100), "HAHAHAHAHAHAHA, gij suckt wel");
//
// private final Range range;
// private final String feedback;
//
// TurnResult(Range range, String feedback) {
// this.range = range;
// this.feedback = feedback;
// }
//
// public Range getRange() {
// return range;
// }
//
// public String getFeedback() {
// return feedback;
// }
// }
//
// public static class Range {
// private final int lower;
// private final int upper;
//
// public Range(int lower, int upper) {
// this.lower = lower;
// this.upper = upper;
// }
//
// public int getLower() {
// return lower;
// }
//
// public int getUpper() {
// return upper;
// }
// }
}
|
101939_8 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import models.*;
import DAO.*;
/**
*
* @author joycee
*/
public class runierun {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// aanmaken van connectie
UsersDAO userdao = new UsersDAO();
// Toevoegen van een user
//Users user1 = new Users("test", "testiie", "19940629", "Hitek", "Directeur", "/../img/lekker.jpg", "[email protected]", "passwoord", true);
//userdao.insertUser(user1);
// Updaten van een user
//Users user1 = userdao.findById(1);
//user1.setName("Mario");
//user1.setForename("Van Corselis");
//userdao.updateUser(user1);
// sluiten van connectie
userdao.close();
}
}
| JensGryspeert/Eindopdracht | webcafe/src/main/java/runierun.java | 302 | // sluiten van connectie | line_comment | nl | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import models.*;
import DAO.*;
/**
*
* @author joycee
*/
public class runierun {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// aanmaken van connectie
UsersDAO userdao = new UsersDAO();
// Toevoegen van een user
//Users user1 = new Users("test", "testiie", "19940629", "Hitek", "Directeur", "/../img/lekker.jpg", "[email protected]", "passwoord", true);
//userdao.insertUser(user1);
// Updaten van een user
//Users user1 = userdao.findById(1);
//user1.setName("Mario");
//user1.setForename("Van Corselis");
//userdao.updateUser(user1);
// sluiten van<SUF>
userdao.close();
}
}
|
33350_11 | package generator;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeProperty;
import iloc.eval.Machine;
import iloc.model.*;
import iloc.Simulator;
import checker.Result;
import checker.Type;
import grammar.TempNameBaseVisitor;
import grammar.TempNameParser.*;
public class Generator extends TempNameBaseVisitor<String> {
/** The representation of the boolean value <code>false</code>. */
public final static Num FALSE_VALUE = new Num(Simulator.FALSE);
/** The representation of the boolean value <code>true</code>. */
public final static Num TRUE_VALUE = new Num(Simulator.TRUE);
/** The base register. */
private Reg arp = new Reg("r_arp");
/** The outcome of the checker phase. */
private Result checkResult;
/** Association of statement nodes to labels. */
private ParseTreeProperty<Label> labels;
/** The program being built. */
private Program prog;
/** The memory manager of this generator */
private MemoryManager mM;
/**
* Generates ILOC code for a given parse tree, given a pre-computed checker
* result.
*/
public Program generate(ParseTree tree, Result checkResult) {
this.prog = new Program();
this.checkResult = checkResult;
this.labels = new ParseTreeProperty<>();
this.mM = new MemoryManager();
tree.accept(this);
return this.prog;
}
/**
* Helpfunction for TypedStore stores a string
*/
private void storeString(ParseTree from, ParseTree to, boolean closeScope, String fromid, String toid) {
// SETUP
int[] stringData = mM.getSizeAndOffset(from, fromid);
if (closeScope) {
mM.closeScope();
}
int parentoff = mM.getOffset(to, stringData[0], toid);
Reg helpreg = new Reg(mM.getConstReg());
// MOVE ALL CHARS
for (int i = 0; i < stringData[0]; i = i + Machine.DEFAULT_CHAR_SIZE) {
emit(OpCode.cloadAI, arp, new Num(i + stringData[1]), helpreg);
emit(OpCode.cstoreAI, helpreg, arp, new Num(i + parentoff));
}
}
/**
* Store the result of a child ctx as the result of the parent ctx (another
* ctx). IF an id is know it will store the value of the id as the result of
* the parent.
*
* Closes the scope if necesary
*
* @requires from != null
* @requires to != null
*/
private void typedStore(ParseTree from, ParseTree to, boolean closeScope, String id) {
if (id != null) {
// hoeft volgens mij niet
} else if (mM.hasMemory(from)) {
if (checkResult.getType(from).equals(Type.CHAR)) {
emit(OpCode.cloadAI, arp, offset(from), reg(to));
if (closeScope)
mM.closeScope();
emit(OpCode.cstoreAI, reg(to), arp, offset(to));
} else if (checkResult.getType(from).equals(Type.STRING)) {
this.storeString(from, to, closeScope, null, id);
} else {
emit(OpCode.loadAI, arp, offset(from), reg(to));
if (closeScope)
mM.closeScope();
emit(OpCode.storeAI, reg(to), arp, offset(to));
}
} else {
if (checkResult.getType(from).equals(Type.CHAR)) {
if (closeScope)
mM.closeScope();
emit(OpCode.cstoreAI, reg(from), arp, offset(to));
} else if (checkResult.getType(from).equals(Type.STRING)) {
System.out.println("this state should not happen");
} else {
mM.closeScope();
emit(OpCode.storeAI, reg(from), arp, offset(to));
}
}
}
/**
* Loads an id from memory for use by the given node
*
* @requires id != null
* @requires ctx != null
*/
private void typedLoad(ParseTree ctx, String id) {
Type type = checkResult.getType(ctx);
if (type.equals(Type.CHAR)) {
emit(OpCode.cloadAI, arp, offset(ctx, id), reg(ctx));
} else if (type.equals(Type.STRING)) {
// Strings cant be loaded into a single register
} else {
emit(OpCode.loadAI, arp, offset(ctx, id), reg(ctx));
}
}
/**
* Improved visit method. Visits the node and if the result of the node was
* stored to an id loads that value into the register of the node.
*
* @requires ctx != null
* @return
*/
private String visitH(ParseTree ctx) {
String id0 = visit(ctx);
if (id0 != null && mM.hasMemory(ctx)) {
typedLoad(ctx, id0);
}
return id0;
}
/**
* Generates the necesary iloc code to return the result of one node and
* load it as input into the other node. If an id is known it will use that
* instead of the node.
*
* @requires from != null
* @requires to != null
*/
private void returnResult(ParseTree from, ParseTree to, String fromid, String toid) {
Type type = checkResult.getType(from);
if (mM.hasReg(from) || fromid != null || mM.hasMemory(from)) {
if (type.equals(Type.CHAR)) {
emit(OpCode.cstoreAI, reg(from), arp, offset(to, toid));
} else if (type.equals(Type.STRING)) {
storeString(from, to, false, fromid, toid);
} else {
emit(OpCode.storeAI, reg(from), arp, offset(to, toid));
}
} else {
// No return needed
}
}
/**
* Constructs an operation from the parameters and adds it to the program
* under construction.
*/
private Op emit(Label label, OpCode opCode, Operand... args) {
Op result = new Op(label, opCode, args);
this.prog.addInstr(result);
return result;
}
/**
* Constructs an operation from the parameters and adds it to the program
* under construction.
*/
private Op emit(OpCode opCode, Operand... args) {
return emit((Label) null, opCode, args);
}
/**
* Looks up the label for a given parse tree node, creating it if none has
* been created before. The label is actually constructed from the entry
* node in the flow graph, as stored in the checker result.
*/
private Label label(ParserRuleContext node) {
Label result = this.labels.get(node);
if (result == null) {
ParserRuleContext entry = this.checkResult.getEntry(node);
result = createLabel(entry, "n");
this.labels.put(node, result);
}
return result;
}
/** Creates a label for a given parse tree node and prefix. */
private Label createLabel(ParserRuleContext node, String prefix) {
Token token = node.getStart();
int line = token.getLine();
int column = token.getCharPositionInLine();
String result = prefix + "_" + line + "_" + column;
return new Label(result);
}
/**
* If the id is not null it will look up the memory offset of this id, or
* create a new one if it doesnt exist.
*
* If the id is null it will look up the memory offset of the return value
* of the node, or create a new one if it doesnt exist.
*
* @requires node != null
* @ensures result>0
*/
private Num offset(ParseTree node, String id) {
int size = 0;
if (checkResult.getType(node).equals(Type.INT) || checkResult.getType(node).equals(Type.BOOL)) {
size = Machine.INT_SIZE;
} else if (checkResult.getType(node).equals(Type.CHAR)) {
size = Machine.DEFAULT_CHAR_SIZE;
}
Num offset = new Num(mM.getOffset(node, size, id));
return offset;
}
/**
* @see offset(node, null);
*/
private Num offset(ParseTree node) {
return offset(node, null);
}
/**
* Gives the reg that belongs to this node, reserves a new reg if the node
* does not have a reg.
*
* @requires node != null
* @ensure result != null
*/
private Reg reg(ParseTree node) {
Reg reg;
// IF the value is ONLY stored in memory, it should be loaded into the
// register before use
if (mM.hasMemory(node) && !mM.hasReg(node)) {
reg = new Reg(mM.getNodeReg(node));
Type type = checkResult.getType(node);
if (type.equals(Type.CHAR)) {
emit(OpCode.cloadAI, arp, offset(node), reg);
} else if (type.equals(Type.STRING)) {
// Cannot preload for strings
} else {
emit(OpCode.loadAI, arp, offset(node), reg);
}
} else {
reg = new Reg(mM.getNodeReg(node));
}
return reg;
}
// -----------Program-----------
@Override
public String visitProgram(ProgramContext ctx) {
emit(new Label("Program"), OpCode.nop);
mM.openScope();
visit(ctx.expr());
mM.closeScope();
return null;
}
// -----------Expression-----------
@Override
public String visitParExpr(ParExprContext ctx) {
visitH(ctx.expr());
emit(OpCode.i2i, reg(ctx.expr()), reg(ctx));
return null;
}
@Override
public String visitCompExpr(CompExprContext ctx) {
String id1 = visitH(ctx.expr(0));
String id2 = visitH(ctx.expr(1));
if (id1 != null) {
typedLoad(ctx.expr(0), id1);
}
if (id2 != null) {
typedLoad(ctx.expr(1), id2);
}
String compOp = ctx.compOp().getText();
switch (compOp) {
case ("<="):
emit(OpCode.cmp_LE, reg(ctx.expr(0)), reg(ctx.expr(1)), reg(ctx));
break;
case ("<"):
emit(OpCode.cmp_LT, reg(ctx.expr(0)), reg(ctx.expr(1)), reg(ctx));
break;
case ("<>"):
emit(OpCode.cmp_NE, reg(ctx.expr(0)), reg(ctx.expr(1)), reg(ctx));
break;
case (">="):
emit(OpCode.cmp_GE, reg(ctx.expr(0)), reg(ctx.expr(1)), reg(ctx));
break;
case (">"):
emit(OpCode.cmp_GT, reg(ctx.expr(0)), reg(ctx.expr(1)), reg(ctx));
break;
case ("=="):
emit(OpCode.cmp_EQ, reg(ctx.expr(0)), reg(ctx.expr(1)), reg(ctx));
break;
}
return null;
}
@Override
public String visitIfExpr(IfExprContext ctx) {
visitH(ctx.expr(0));
Label endIf = createLabel(ctx, "endIf");
boolean elseExists = ctx.expr(2) != null;
Label elsez = elseExists ? label(ctx.expr(2)) : endIf;
emit(OpCode.cbr, reg(ctx.expr(0)), label(ctx.expr(1)), elsez);
emit(label(ctx.expr(1)), OpCode.nop);
String id = visitH(ctx.expr(1));
if (id != null) {
typedLoad(ctx.expr(1), id);
}
returnResult(ctx.expr(1), ctx, id, id);
emit(OpCode.jumpI, endIf);
if (elseExists) {
emit(elsez, OpCode.nop);
id = visitH(ctx.expr(2));
if (id != null) {
typedLoad(ctx.expr(1), id);
}
returnResult(ctx.expr(2), ctx, id, id);
}
emit(endIf, OpCode.nop);
return null;
}
@Override
public String visitBlockExpr(BlockExprContext ctx) {
int last = ctx.expr().size() - 1;
mM.openScope();
for (int i = 0; i < ctx.expr().size() - 1; i++) {
visitH(ctx.expr(i));
}
String id = visitH(ctx.expr(last));
if (id != null) {
typedLoad(ctx.expr(last), id);
}
typedStore(ctx.expr(last), ctx, true, id);
return null;
}
@Override
public String visitPrintExpr(PrintExprContext ctx) {
Type type;
if (ctx.expr().size() > 1) {
for (int i = 0; i < ctx.expr().size(); i++) {
String id = visitH(ctx.expr(i));
if (id != null) {
typedLoad(ctx.expr(i), id);
}
type = checkResult.getType(ctx.expr(i));
if (type.equals(Type.CHAR)) {
emit(OpCode.loadI, new Num(1), reg(ctx));
emit(OpCode.cpush, reg(ctx.expr(i)));
emit(OpCode.push, reg(ctx));
emit(OpCode.cout, new Str(ctx.expr(i).getText() + ": "));
} else if (type.equals(Type.STRING)) {
int[] stringData = mM.getSizeAndOffset(ctx.expr(i), id);
// Push chars
for (int j = stringData[0]; j > 0; j--) {
emit(OpCode.cloadAI, arp, new Num(stringData[1] + j * Machine.DEFAULT_CHAR_SIZE - 1), reg(ctx));
emit(OpCode.cpush, reg(ctx));
}
// Push size
emit(OpCode.loadI, new Num(stringData[0]), reg(ctx));
emit(OpCode.push, reg(ctx));
emit(OpCode.cout, new Str(ctx.expr(i).getText() + ": "));
} else {
emit(OpCode.out, new Str(ctx.expr(i).getText() + ": "), reg(ctx.expr(i)));
storeString(ctx.expr(0), ctx, false, id, null);
}
}
} else {
String id = visitH(ctx.expr(0));
if (id != null) {
typedLoad(ctx.expr(0), id);
}
type = checkResult.getType(ctx.expr(0));
if (type.equals(Type.CHAR)) {
emit(OpCode.loadI, new Num(1), reg(ctx));
emit(OpCode.cpush, reg(ctx.expr(0)));
emit(OpCode.push, reg(ctx));
emit(OpCode.cout, new Str(ctx.expr(0).getText() + ": "));
returnResult(ctx.expr(0), ctx, null, null);
} else if (type.equals(Type.STRING)) {
int[] stringData = mM.getSizeAndOffset(ctx.expr(0), id);
// Push chars
for (int j = stringData[0]; j > 0; j--) {
emit(OpCode.cloadAI, arp, new Num(stringData[1] + j * Machine.DEFAULT_CHAR_SIZE - 1), reg(ctx));
emit(OpCode.cpush, reg(ctx));
}
// Push size
emit(OpCode.loadI, new Num(stringData[0]), reg(ctx));
emit(OpCode.push, reg(ctx));
emit(OpCode.cout, new Str(ctx.expr(0).getText() + ": "));
storeString(ctx.expr(0), ctx, false, id, null);
} else {
emit(OpCode.out, new Str(ctx.expr(0).getText() + ": "), reg(ctx.expr(0)));
returnResult(ctx.expr(0), ctx, null, null);
}
}
return null;
}
@Override
public String visitReadExpr(ReadExprContext ctx) {
Type[] types = checkResult.getReadTypes(ctx);
for (int i = 0; i < ctx.ID().size(); i++) {
if (types[i].equals(Type.CHAR)) {
emit(OpCode.cin, new Str(ctx.ID(i).getText() + "? : "));
emit(OpCode.pop, reg(ctx));
emit(OpCode.cpop, reg(ctx));
emit(OpCode.cstoreAI, reg(ctx), arp, offset(ctx, ctx.ID(i).getText()));
} else if (types[i].equals(Type.STRING)) {
// Not supported by our memory/registry manager, too much
// work to edit it in properly
} else {
emit(OpCode.in, new Str(ctx.ID(i).getText() + "? : "), reg(ctx));
emit(OpCode.storeAI, reg(ctx), arp, offset(ctx, ctx.ID(i).getText()));
}
}
if (ctx.ID().size() == 1) {
return ctx.ID(0).getText();
}
return null;
}
@Override
public String visitMultExpr(MultExprContext ctx) {
String id1 = visitH(ctx.expr(0));
String id2 = visitH(ctx.expr(1));
if (id1 != null) {
typedLoad(ctx.expr(0), id1);
}
if (id2 != null) {
typedLoad(ctx.expr(1), id2);
}
if (ctx.multOp().getText().equals("*")) {
// Times
emit(OpCode.mult, reg(ctx.expr(0)), reg(ctx.expr(1)), reg(ctx));
} else if (ctx.multOp().getText().equals("/")) {
// Division
emit(OpCode.div, reg(ctx.expr(0)), reg(ctx.expr(1)), reg(ctx));
} else {
// Modulo
String str1 = mM.getConstReg();
Reg r1 = new Reg(str1);
emit(OpCode.div, reg(ctx.expr(0)), reg(ctx.expr(1)), r1);
emit(OpCode.mult, r1, reg(ctx.expr(1)), r1);
emit(OpCode.sub, reg(ctx.expr(0)), r1, reg(ctx));
}
return null;
}
@Override
public String visitPlusExpr(PlusExprContext ctx) {
String id1 = visitH(ctx.expr(0));
String id2 = visitH(ctx.expr(1));
if (id1 != null) {
typedLoad(ctx.expr(0), id1);
}
if (id2 != null) {
typedLoad(ctx.expr(1), id2);
}
if (checkResult.getType(ctx).equals(Type.INT)) {
if (ctx.plusOp().getText().equals("+")) {
emit(OpCode.add, reg(ctx.expr(0)), reg(ctx.expr(1)), reg(ctx));
} else {
emit(OpCode.sub, reg(ctx.expr(0)), reg(ctx.expr(1)), reg(ctx));
}
} else {
// concat string+string or string+char
int[] stringData1 = mM.getSizeAndOffset(ctx.expr(0), id1);
int[] stringData2 = mM.getSizeAndOffset(ctx.expr(1), id2);
int offset = mM.getOffset(ctx, stringData1[0] + stringData2[0], null);
for (int i = 0; i < stringData1[0]; i += Machine.DEFAULT_CHAR_SIZE, offset += Machine.DEFAULT_CHAR_SIZE) {
emit(OpCode.cloadAI, arp, new Num(stringData1[1] + i), reg(ctx));
emit(OpCode.cstoreAI, reg(ctx), arp, new Num(offset));
}
for (int i = 0; i < stringData2[0]; i += Machine.DEFAULT_CHAR_SIZE, offset += Machine.DEFAULT_CHAR_SIZE) {
emit(OpCode.cloadAI, arp, new Num(stringData2[1] + i), reg(ctx));
emit(OpCode.cstoreAI, reg(ctx), arp, new Num(offset));
}
}
return null;
}
@Override
public String visitPrfExpr(PrfExprContext ctx) {
String id = visitH(ctx.expr());
if (id != null) {
typedLoad(ctx.expr(), id);
}
if (ctx.prfOp().getText().equals("-")) {
emit(OpCode.rsubI, reg(ctx.expr()), new Num(0), reg(ctx));
} else {
emit(OpCode.addI, reg(ctx.expr()), new Num(1), reg(ctx));
emit(OpCode.rsubI, reg(ctx), new Num(0), reg(ctx));
}
return null;
}
@Override
public String visitDeclExpr(DeclExprContext ctx) {
if (ctx.expr() != null) {
visitH(ctx.expr());
Type type = checkResult.getType(ctx);
if (type.equals(Type.CHAR)) {
emit(OpCode.cstoreAI, reg(ctx.expr()), arp, offset(ctx.ID(), ctx.ID().getText()));
} else if (type.equals(Type.STRING)) {
storeString(ctx.expr(), ctx, false, null, ctx.ID().getText());
} else {
emit(OpCode.storeAI, reg(ctx.expr()), arp, offset(ctx.ID(), ctx.ID().getText()));
}
}
return ctx.ID().getText();
}
@Override
public String visitWhileExpr(WhileExprContext ctx) {
emit(label(ctx), OpCode.nop);
visitH(ctx.expr(0));
Label endLabel = createLabel(ctx, "end");
emit(OpCode.cbr, reg(ctx.expr(0)), label(ctx.expr(1)), endLabel);
emit(label(ctx.expr(1)), OpCode.nop);
visitH(ctx.expr(1));
emit(OpCode.jumpI, label(ctx));
emit(endLabel, OpCode.nop);
return null;
}
@Override
public String visitAssExpr(AssExprContext ctx) {
String id = visitH(ctx.expr());
if (id != null) {
typedLoad(ctx.expr(), id);
}
if (checkResult.getType(ctx).equals(Type.CHAR)) {
emit(OpCode.cstoreAI, reg(ctx.expr()), this.arp, offset(ctx.target(), ctx.target().getText()));
} else if (checkResult.getType(ctx).equals(Type.STRING)) {
storeString(ctx.expr(), ctx, false, id, ctx.target().getText());
} else {
emit(OpCode.storeAI, reg(ctx.expr()), this.arp, offset(ctx.target(), ctx.target().getText()));
}
return ctx.target().getText();
}
@Override
public String visitBoolExpr(BoolExprContext ctx) {
String id1 = visitH(ctx.expr(0));
String id2 = visitH(ctx.expr(1));
if (id1 != null) {
typedLoad(ctx.expr(0), id1);
}
if (id2 != null) {
typedLoad(ctx.expr(1), id2);
}
if (ctx.boolOp().getText().contains("o") || ctx.boolOp().getText().contains("O")) {
emit(OpCode.or, reg(ctx.expr(0)), reg(ctx.expr(1)), reg(ctx));
} else {
emit(OpCode.and, reg(ctx.expr(0)), reg(ctx.expr(1)), reg(ctx));
}
return null;
}
// -----------Terminal expressions-----------
@Override
public String visitIdExpr(IdExprContext ctx) {
return ctx.ID().getText();
}
@Override
public String visitNumExpr(NumExprContext ctx) {
emit(OpCode.loadI, new Num(Integer.parseInt(ctx.NUM().getText())), reg(ctx));
return null;
}
@Override
public String visitCharExpr(CharExprContext ctx) {
int chara = (int) ctx.CHR().getText().charAt(1);
emit(OpCode.loadI, new Num(chara), reg(ctx));
emit(OpCode.i2c, reg(ctx), reg(ctx));
return null;
}
@Override
public String visitStringExpr(StringExprContext ctx) {
String str = ctx.STR().getText();
str = str.substring(1, str.length() - 1);
int offset = mM.getOffset(ctx, Machine.DEFAULT_CHAR_SIZE * str.length(), null);
for (int i = 0; i < str.length(); i++) {
int chara = (int) str.charAt(i);
emit(OpCode.loadI, new Num(chara), reg(ctx));
emit(OpCode.i2c, reg(ctx), reg(ctx));
emit(OpCode.cstoreAI, reg(ctx), arp, new Num(offset + i * Machine.DEFAULT_CHAR_SIZE));
}
return null;
}
@Override
public String visitTrueExpr(TrueExprContext ctx) {
emit(OpCode.loadI, TRUE_VALUE, reg(ctx));
return null;
}
@Override
public String visitFalseExpr(FalseExprContext ctx) {
emit(OpCode.loadI, FALSE_VALUE, reg(ctx));
return null;
}
}
| JeroenBrinkman/CCeind | src/generator/Generator.java | 7,058 | // hoeft volgens mij niet | line_comment | nl | package generator;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeProperty;
import iloc.eval.Machine;
import iloc.model.*;
import iloc.Simulator;
import checker.Result;
import checker.Type;
import grammar.TempNameBaseVisitor;
import grammar.TempNameParser.*;
public class Generator extends TempNameBaseVisitor<String> {
/** The representation of the boolean value <code>false</code>. */
public final static Num FALSE_VALUE = new Num(Simulator.FALSE);
/** The representation of the boolean value <code>true</code>. */
public final static Num TRUE_VALUE = new Num(Simulator.TRUE);
/** The base register. */
private Reg arp = new Reg("r_arp");
/** The outcome of the checker phase. */
private Result checkResult;
/** Association of statement nodes to labels. */
private ParseTreeProperty<Label> labels;
/** The program being built. */
private Program prog;
/** The memory manager of this generator */
private MemoryManager mM;
/**
* Generates ILOC code for a given parse tree, given a pre-computed checker
* result.
*/
public Program generate(ParseTree tree, Result checkResult) {
this.prog = new Program();
this.checkResult = checkResult;
this.labels = new ParseTreeProperty<>();
this.mM = new MemoryManager();
tree.accept(this);
return this.prog;
}
/**
* Helpfunction for TypedStore stores a string
*/
private void storeString(ParseTree from, ParseTree to, boolean closeScope, String fromid, String toid) {
// SETUP
int[] stringData = mM.getSizeAndOffset(from, fromid);
if (closeScope) {
mM.closeScope();
}
int parentoff = mM.getOffset(to, stringData[0], toid);
Reg helpreg = new Reg(mM.getConstReg());
// MOVE ALL CHARS
for (int i = 0; i < stringData[0]; i = i + Machine.DEFAULT_CHAR_SIZE) {
emit(OpCode.cloadAI, arp, new Num(i + stringData[1]), helpreg);
emit(OpCode.cstoreAI, helpreg, arp, new Num(i + parentoff));
}
}
/**
* Store the result of a child ctx as the result of the parent ctx (another
* ctx). IF an id is know it will store the value of the id as the result of
* the parent.
*
* Closes the scope if necesary
*
* @requires from != null
* @requires to != null
*/
private void typedStore(ParseTree from, ParseTree to, boolean closeScope, String id) {
if (id != null) {
// hoeft volgens<SUF>
} else if (mM.hasMemory(from)) {
if (checkResult.getType(from).equals(Type.CHAR)) {
emit(OpCode.cloadAI, arp, offset(from), reg(to));
if (closeScope)
mM.closeScope();
emit(OpCode.cstoreAI, reg(to), arp, offset(to));
} else if (checkResult.getType(from).equals(Type.STRING)) {
this.storeString(from, to, closeScope, null, id);
} else {
emit(OpCode.loadAI, arp, offset(from), reg(to));
if (closeScope)
mM.closeScope();
emit(OpCode.storeAI, reg(to), arp, offset(to));
}
} else {
if (checkResult.getType(from).equals(Type.CHAR)) {
if (closeScope)
mM.closeScope();
emit(OpCode.cstoreAI, reg(from), arp, offset(to));
} else if (checkResult.getType(from).equals(Type.STRING)) {
System.out.println("this state should not happen");
} else {
mM.closeScope();
emit(OpCode.storeAI, reg(from), arp, offset(to));
}
}
}
/**
* Loads an id from memory for use by the given node
*
* @requires id != null
* @requires ctx != null
*/
private void typedLoad(ParseTree ctx, String id) {
Type type = checkResult.getType(ctx);
if (type.equals(Type.CHAR)) {
emit(OpCode.cloadAI, arp, offset(ctx, id), reg(ctx));
} else if (type.equals(Type.STRING)) {
// Strings cant be loaded into a single register
} else {
emit(OpCode.loadAI, arp, offset(ctx, id), reg(ctx));
}
}
/**
* Improved visit method. Visits the node and if the result of the node was
* stored to an id loads that value into the register of the node.
*
* @requires ctx != null
* @return
*/
private String visitH(ParseTree ctx) {
String id0 = visit(ctx);
if (id0 != null && mM.hasMemory(ctx)) {
typedLoad(ctx, id0);
}
return id0;
}
/**
* Generates the necesary iloc code to return the result of one node and
* load it as input into the other node. If an id is known it will use that
* instead of the node.
*
* @requires from != null
* @requires to != null
*/
private void returnResult(ParseTree from, ParseTree to, String fromid, String toid) {
Type type = checkResult.getType(from);
if (mM.hasReg(from) || fromid != null || mM.hasMemory(from)) {
if (type.equals(Type.CHAR)) {
emit(OpCode.cstoreAI, reg(from), arp, offset(to, toid));
} else if (type.equals(Type.STRING)) {
storeString(from, to, false, fromid, toid);
} else {
emit(OpCode.storeAI, reg(from), arp, offset(to, toid));
}
} else {
// No return needed
}
}
/**
* Constructs an operation from the parameters and adds it to the program
* under construction.
*/
private Op emit(Label label, OpCode opCode, Operand... args) {
Op result = new Op(label, opCode, args);
this.prog.addInstr(result);
return result;
}
/**
* Constructs an operation from the parameters and adds it to the program
* under construction.
*/
private Op emit(OpCode opCode, Operand... args) {
return emit((Label) null, opCode, args);
}
/**
* Looks up the label for a given parse tree node, creating it if none has
* been created before. The label is actually constructed from the entry
* node in the flow graph, as stored in the checker result.
*/
private Label label(ParserRuleContext node) {
Label result = this.labels.get(node);
if (result == null) {
ParserRuleContext entry = this.checkResult.getEntry(node);
result = createLabel(entry, "n");
this.labels.put(node, result);
}
return result;
}
/** Creates a label for a given parse tree node and prefix. */
private Label createLabel(ParserRuleContext node, String prefix) {
Token token = node.getStart();
int line = token.getLine();
int column = token.getCharPositionInLine();
String result = prefix + "_" + line + "_" + column;
return new Label(result);
}
/**
* If the id is not null it will look up the memory offset of this id, or
* create a new one if it doesnt exist.
*
* If the id is null it will look up the memory offset of the return value
* of the node, or create a new one if it doesnt exist.
*
* @requires node != null
* @ensures result>0
*/
private Num offset(ParseTree node, String id) {
int size = 0;
if (checkResult.getType(node).equals(Type.INT) || checkResult.getType(node).equals(Type.BOOL)) {
size = Machine.INT_SIZE;
} else if (checkResult.getType(node).equals(Type.CHAR)) {
size = Machine.DEFAULT_CHAR_SIZE;
}
Num offset = new Num(mM.getOffset(node, size, id));
return offset;
}
/**
* @see offset(node, null);
*/
private Num offset(ParseTree node) {
return offset(node, null);
}
/**
* Gives the reg that belongs to this node, reserves a new reg if the node
* does not have a reg.
*
* @requires node != null
* @ensure result != null
*/
private Reg reg(ParseTree node) {
Reg reg;
// IF the value is ONLY stored in memory, it should be loaded into the
// register before use
if (mM.hasMemory(node) && !mM.hasReg(node)) {
reg = new Reg(mM.getNodeReg(node));
Type type = checkResult.getType(node);
if (type.equals(Type.CHAR)) {
emit(OpCode.cloadAI, arp, offset(node), reg);
} else if (type.equals(Type.STRING)) {
// Cannot preload for strings
} else {
emit(OpCode.loadAI, arp, offset(node), reg);
}
} else {
reg = new Reg(mM.getNodeReg(node));
}
return reg;
}
// -----------Program-----------
@Override
public String visitProgram(ProgramContext ctx) {
emit(new Label("Program"), OpCode.nop);
mM.openScope();
visit(ctx.expr());
mM.closeScope();
return null;
}
// -----------Expression-----------
@Override
public String visitParExpr(ParExprContext ctx) {
visitH(ctx.expr());
emit(OpCode.i2i, reg(ctx.expr()), reg(ctx));
return null;
}
@Override
public String visitCompExpr(CompExprContext ctx) {
String id1 = visitH(ctx.expr(0));
String id2 = visitH(ctx.expr(1));
if (id1 != null) {
typedLoad(ctx.expr(0), id1);
}
if (id2 != null) {
typedLoad(ctx.expr(1), id2);
}
String compOp = ctx.compOp().getText();
switch (compOp) {
case ("<="):
emit(OpCode.cmp_LE, reg(ctx.expr(0)), reg(ctx.expr(1)), reg(ctx));
break;
case ("<"):
emit(OpCode.cmp_LT, reg(ctx.expr(0)), reg(ctx.expr(1)), reg(ctx));
break;
case ("<>"):
emit(OpCode.cmp_NE, reg(ctx.expr(0)), reg(ctx.expr(1)), reg(ctx));
break;
case (">="):
emit(OpCode.cmp_GE, reg(ctx.expr(0)), reg(ctx.expr(1)), reg(ctx));
break;
case (">"):
emit(OpCode.cmp_GT, reg(ctx.expr(0)), reg(ctx.expr(1)), reg(ctx));
break;
case ("=="):
emit(OpCode.cmp_EQ, reg(ctx.expr(0)), reg(ctx.expr(1)), reg(ctx));
break;
}
return null;
}
@Override
public String visitIfExpr(IfExprContext ctx) {
visitH(ctx.expr(0));
Label endIf = createLabel(ctx, "endIf");
boolean elseExists = ctx.expr(2) != null;
Label elsez = elseExists ? label(ctx.expr(2)) : endIf;
emit(OpCode.cbr, reg(ctx.expr(0)), label(ctx.expr(1)), elsez);
emit(label(ctx.expr(1)), OpCode.nop);
String id = visitH(ctx.expr(1));
if (id != null) {
typedLoad(ctx.expr(1), id);
}
returnResult(ctx.expr(1), ctx, id, id);
emit(OpCode.jumpI, endIf);
if (elseExists) {
emit(elsez, OpCode.nop);
id = visitH(ctx.expr(2));
if (id != null) {
typedLoad(ctx.expr(1), id);
}
returnResult(ctx.expr(2), ctx, id, id);
}
emit(endIf, OpCode.nop);
return null;
}
@Override
public String visitBlockExpr(BlockExprContext ctx) {
int last = ctx.expr().size() - 1;
mM.openScope();
for (int i = 0; i < ctx.expr().size() - 1; i++) {
visitH(ctx.expr(i));
}
String id = visitH(ctx.expr(last));
if (id != null) {
typedLoad(ctx.expr(last), id);
}
typedStore(ctx.expr(last), ctx, true, id);
return null;
}
@Override
public String visitPrintExpr(PrintExprContext ctx) {
Type type;
if (ctx.expr().size() > 1) {
for (int i = 0; i < ctx.expr().size(); i++) {
String id = visitH(ctx.expr(i));
if (id != null) {
typedLoad(ctx.expr(i), id);
}
type = checkResult.getType(ctx.expr(i));
if (type.equals(Type.CHAR)) {
emit(OpCode.loadI, new Num(1), reg(ctx));
emit(OpCode.cpush, reg(ctx.expr(i)));
emit(OpCode.push, reg(ctx));
emit(OpCode.cout, new Str(ctx.expr(i).getText() + ": "));
} else if (type.equals(Type.STRING)) {
int[] stringData = mM.getSizeAndOffset(ctx.expr(i), id);
// Push chars
for (int j = stringData[0]; j > 0; j--) {
emit(OpCode.cloadAI, arp, new Num(stringData[1] + j * Machine.DEFAULT_CHAR_SIZE - 1), reg(ctx));
emit(OpCode.cpush, reg(ctx));
}
// Push size
emit(OpCode.loadI, new Num(stringData[0]), reg(ctx));
emit(OpCode.push, reg(ctx));
emit(OpCode.cout, new Str(ctx.expr(i).getText() + ": "));
} else {
emit(OpCode.out, new Str(ctx.expr(i).getText() + ": "), reg(ctx.expr(i)));
storeString(ctx.expr(0), ctx, false, id, null);
}
}
} else {
String id = visitH(ctx.expr(0));
if (id != null) {
typedLoad(ctx.expr(0), id);
}
type = checkResult.getType(ctx.expr(0));
if (type.equals(Type.CHAR)) {
emit(OpCode.loadI, new Num(1), reg(ctx));
emit(OpCode.cpush, reg(ctx.expr(0)));
emit(OpCode.push, reg(ctx));
emit(OpCode.cout, new Str(ctx.expr(0).getText() + ": "));
returnResult(ctx.expr(0), ctx, null, null);
} else if (type.equals(Type.STRING)) {
int[] stringData = mM.getSizeAndOffset(ctx.expr(0), id);
// Push chars
for (int j = stringData[0]; j > 0; j--) {
emit(OpCode.cloadAI, arp, new Num(stringData[1] + j * Machine.DEFAULT_CHAR_SIZE - 1), reg(ctx));
emit(OpCode.cpush, reg(ctx));
}
// Push size
emit(OpCode.loadI, new Num(stringData[0]), reg(ctx));
emit(OpCode.push, reg(ctx));
emit(OpCode.cout, new Str(ctx.expr(0).getText() + ": "));
storeString(ctx.expr(0), ctx, false, id, null);
} else {
emit(OpCode.out, new Str(ctx.expr(0).getText() + ": "), reg(ctx.expr(0)));
returnResult(ctx.expr(0), ctx, null, null);
}
}
return null;
}
@Override
public String visitReadExpr(ReadExprContext ctx) {
Type[] types = checkResult.getReadTypes(ctx);
for (int i = 0; i < ctx.ID().size(); i++) {
if (types[i].equals(Type.CHAR)) {
emit(OpCode.cin, new Str(ctx.ID(i).getText() + "? : "));
emit(OpCode.pop, reg(ctx));
emit(OpCode.cpop, reg(ctx));
emit(OpCode.cstoreAI, reg(ctx), arp, offset(ctx, ctx.ID(i).getText()));
} else if (types[i].equals(Type.STRING)) {
// Not supported by our memory/registry manager, too much
// work to edit it in properly
} else {
emit(OpCode.in, new Str(ctx.ID(i).getText() + "? : "), reg(ctx));
emit(OpCode.storeAI, reg(ctx), arp, offset(ctx, ctx.ID(i).getText()));
}
}
if (ctx.ID().size() == 1) {
return ctx.ID(0).getText();
}
return null;
}
@Override
public String visitMultExpr(MultExprContext ctx) {
String id1 = visitH(ctx.expr(0));
String id2 = visitH(ctx.expr(1));
if (id1 != null) {
typedLoad(ctx.expr(0), id1);
}
if (id2 != null) {
typedLoad(ctx.expr(1), id2);
}
if (ctx.multOp().getText().equals("*")) {
// Times
emit(OpCode.mult, reg(ctx.expr(0)), reg(ctx.expr(1)), reg(ctx));
} else if (ctx.multOp().getText().equals("/")) {
// Division
emit(OpCode.div, reg(ctx.expr(0)), reg(ctx.expr(1)), reg(ctx));
} else {
// Modulo
String str1 = mM.getConstReg();
Reg r1 = new Reg(str1);
emit(OpCode.div, reg(ctx.expr(0)), reg(ctx.expr(1)), r1);
emit(OpCode.mult, r1, reg(ctx.expr(1)), r1);
emit(OpCode.sub, reg(ctx.expr(0)), r1, reg(ctx));
}
return null;
}
@Override
public String visitPlusExpr(PlusExprContext ctx) {
String id1 = visitH(ctx.expr(0));
String id2 = visitH(ctx.expr(1));
if (id1 != null) {
typedLoad(ctx.expr(0), id1);
}
if (id2 != null) {
typedLoad(ctx.expr(1), id2);
}
if (checkResult.getType(ctx).equals(Type.INT)) {
if (ctx.plusOp().getText().equals("+")) {
emit(OpCode.add, reg(ctx.expr(0)), reg(ctx.expr(1)), reg(ctx));
} else {
emit(OpCode.sub, reg(ctx.expr(0)), reg(ctx.expr(1)), reg(ctx));
}
} else {
// concat string+string or string+char
int[] stringData1 = mM.getSizeAndOffset(ctx.expr(0), id1);
int[] stringData2 = mM.getSizeAndOffset(ctx.expr(1), id2);
int offset = mM.getOffset(ctx, stringData1[0] + stringData2[0], null);
for (int i = 0; i < stringData1[0]; i += Machine.DEFAULT_CHAR_SIZE, offset += Machine.DEFAULT_CHAR_SIZE) {
emit(OpCode.cloadAI, arp, new Num(stringData1[1] + i), reg(ctx));
emit(OpCode.cstoreAI, reg(ctx), arp, new Num(offset));
}
for (int i = 0; i < stringData2[0]; i += Machine.DEFAULT_CHAR_SIZE, offset += Machine.DEFAULT_CHAR_SIZE) {
emit(OpCode.cloadAI, arp, new Num(stringData2[1] + i), reg(ctx));
emit(OpCode.cstoreAI, reg(ctx), arp, new Num(offset));
}
}
return null;
}
@Override
public String visitPrfExpr(PrfExprContext ctx) {
String id = visitH(ctx.expr());
if (id != null) {
typedLoad(ctx.expr(), id);
}
if (ctx.prfOp().getText().equals("-")) {
emit(OpCode.rsubI, reg(ctx.expr()), new Num(0), reg(ctx));
} else {
emit(OpCode.addI, reg(ctx.expr()), new Num(1), reg(ctx));
emit(OpCode.rsubI, reg(ctx), new Num(0), reg(ctx));
}
return null;
}
@Override
public String visitDeclExpr(DeclExprContext ctx) {
if (ctx.expr() != null) {
visitH(ctx.expr());
Type type = checkResult.getType(ctx);
if (type.equals(Type.CHAR)) {
emit(OpCode.cstoreAI, reg(ctx.expr()), arp, offset(ctx.ID(), ctx.ID().getText()));
} else if (type.equals(Type.STRING)) {
storeString(ctx.expr(), ctx, false, null, ctx.ID().getText());
} else {
emit(OpCode.storeAI, reg(ctx.expr()), arp, offset(ctx.ID(), ctx.ID().getText()));
}
}
return ctx.ID().getText();
}
@Override
public String visitWhileExpr(WhileExprContext ctx) {
emit(label(ctx), OpCode.nop);
visitH(ctx.expr(0));
Label endLabel = createLabel(ctx, "end");
emit(OpCode.cbr, reg(ctx.expr(0)), label(ctx.expr(1)), endLabel);
emit(label(ctx.expr(1)), OpCode.nop);
visitH(ctx.expr(1));
emit(OpCode.jumpI, label(ctx));
emit(endLabel, OpCode.nop);
return null;
}
@Override
public String visitAssExpr(AssExprContext ctx) {
String id = visitH(ctx.expr());
if (id != null) {
typedLoad(ctx.expr(), id);
}
if (checkResult.getType(ctx).equals(Type.CHAR)) {
emit(OpCode.cstoreAI, reg(ctx.expr()), this.arp, offset(ctx.target(), ctx.target().getText()));
} else if (checkResult.getType(ctx).equals(Type.STRING)) {
storeString(ctx.expr(), ctx, false, id, ctx.target().getText());
} else {
emit(OpCode.storeAI, reg(ctx.expr()), this.arp, offset(ctx.target(), ctx.target().getText()));
}
return ctx.target().getText();
}
@Override
public String visitBoolExpr(BoolExprContext ctx) {
String id1 = visitH(ctx.expr(0));
String id2 = visitH(ctx.expr(1));
if (id1 != null) {
typedLoad(ctx.expr(0), id1);
}
if (id2 != null) {
typedLoad(ctx.expr(1), id2);
}
if (ctx.boolOp().getText().contains("o") || ctx.boolOp().getText().contains("O")) {
emit(OpCode.or, reg(ctx.expr(0)), reg(ctx.expr(1)), reg(ctx));
} else {
emit(OpCode.and, reg(ctx.expr(0)), reg(ctx.expr(1)), reg(ctx));
}
return null;
}
// -----------Terminal expressions-----------
@Override
public String visitIdExpr(IdExprContext ctx) {
return ctx.ID().getText();
}
@Override
public String visitNumExpr(NumExprContext ctx) {
emit(OpCode.loadI, new Num(Integer.parseInt(ctx.NUM().getText())), reg(ctx));
return null;
}
@Override
public String visitCharExpr(CharExprContext ctx) {
int chara = (int) ctx.CHR().getText().charAt(1);
emit(OpCode.loadI, new Num(chara), reg(ctx));
emit(OpCode.i2c, reg(ctx), reg(ctx));
return null;
}
@Override
public String visitStringExpr(StringExprContext ctx) {
String str = ctx.STR().getText();
str = str.substring(1, str.length() - 1);
int offset = mM.getOffset(ctx, Machine.DEFAULT_CHAR_SIZE * str.length(), null);
for (int i = 0; i < str.length(); i++) {
int chara = (int) str.charAt(i);
emit(OpCode.loadI, new Num(chara), reg(ctx));
emit(OpCode.i2c, reg(ctx), reg(ctx));
emit(OpCode.cstoreAI, reg(ctx), arp, new Num(offset + i * Machine.DEFAULT_CHAR_SIZE));
}
return null;
}
@Override
public String visitTrueExpr(TrueExprContext ctx) {
emit(OpCode.loadI, TRUE_VALUE, reg(ctx));
return null;
}
@Override
public String visitFalseExpr(FalseExprContext ctx) {
emit(OpCode.loadI, FALSE_VALUE, reg(ctx));
return null;
}
}
|
60700_2 | package model;
import global.Globals;
import global.Logger;
import global.Misc;
import java.net.InetSocketAddress;
import java.sql.Connection;
import java.sql.SQLException;
import model.intelligence.Intelligence.ClosedException;
import model.intelligence.ManagerIntelligence;
/**
* Represents a clustermanager in the query system
*
* @author Jeroen
*
*/
public class Manager extends Component {
/**
* Constructor
*
* @requires addr != null
* @requires con != null
* @requires mod != null
* @throws ClosedException
* if the database fails during the construction
*/
public Manager(InetSocketAddress addr, Connection con, Model mod)
throws ClosedException {
super(addr, con);
intel = new ManagerIntelligence(this, mod, con);
collumnList = Misc.concat(Globals.MANAGER_CALLS, Globals.MANAGER_STATS);
String sql = "INSERT INTO " + getTableName() + " VALUES( ?, ?";
for (int i = 0; i < collumnList.length; ++i) {
sql += ", ?";
}
sql += ")";
try {
insert = conn.prepareStatement(sql);
} catch (SQLException e) {
intel.databaseError(e);
}
Logger.log("Constructor for " + getTableName() + " completed");
}
@Override
public long[] parseInput(String message) {
String[] parts;
String[] lines = message.split("\n");
long[] result = new long[Globals.MANAGER_STATS.length];
String currentLine;
for (int i = 0; i < Globals.MANAGER_STATS.length; i++) {
currentLine = lines[i];
// regels met w[X] erin komen als het goed is alleen voor na alle
// relevante informatie.
// if(!currentLine.contains("[w")){
parts = currentLine.split(":");
currentLine = parts[1];
currentLine = currentLine.replaceAll("\\s+", "");
// niet toepasbaar als w[X] voorkomt voor relevante informatie
result[i] = Long.parseLong(currentLine);
}
return result;
}
@Override
public String getTableName() {
return "m" + super.getTableName();
}
@Override
public String[] getCalls() {
return Globals.MANAGER_CALLS;
}
@Override
public int getType() {
return Globals.ID_MANAGER;
}
}
| JeroenBrinkman/ontwerpproject | ontwerpproject/src/model/Manager.java | 710 | // regels met w[X] erin komen als het goed is alleen voor na alle | line_comment | nl | package model;
import global.Globals;
import global.Logger;
import global.Misc;
import java.net.InetSocketAddress;
import java.sql.Connection;
import java.sql.SQLException;
import model.intelligence.Intelligence.ClosedException;
import model.intelligence.ManagerIntelligence;
/**
* Represents a clustermanager in the query system
*
* @author Jeroen
*
*/
public class Manager extends Component {
/**
* Constructor
*
* @requires addr != null
* @requires con != null
* @requires mod != null
* @throws ClosedException
* if the database fails during the construction
*/
public Manager(InetSocketAddress addr, Connection con, Model mod)
throws ClosedException {
super(addr, con);
intel = new ManagerIntelligence(this, mod, con);
collumnList = Misc.concat(Globals.MANAGER_CALLS, Globals.MANAGER_STATS);
String sql = "INSERT INTO " + getTableName() + " VALUES( ?, ?";
for (int i = 0; i < collumnList.length; ++i) {
sql += ", ?";
}
sql += ")";
try {
insert = conn.prepareStatement(sql);
} catch (SQLException e) {
intel.databaseError(e);
}
Logger.log("Constructor for " + getTableName() + " completed");
}
@Override
public long[] parseInput(String message) {
String[] parts;
String[] lines = message.split("\n");
long[] result = new long[Globals.MANAGER_STATS.length];
String currentLine;
for (int i = 0; i < Globals.MANAGER_STATS.length; i++) {
currentLine = lines[i];
// regels met<SUF>
// relevante informatie.
// if(!currentLine.contains("[w")){
parts = currentLine.split(":");
currentLine = parts[1];
currentLine = currentLine.replaceAll("\\s+", "");
// niet toepasbaar als w[X] voorkomt voor relevante informatie
result[i] = Long.parseLong(currentLine);
}
return result;
}
@Override
public String getTableName() {
return "m" + super.getTableName();
}
@Override
public String[] getCalls() {
return Globals.MANAGER_CALLS;
}
@Override
public int getType() {
return Globals.ID_MANAGER;
}
}
|
60479_9 | import dao.Adres.AdresDAOsql;
import dao.Ov_chipkaart.Ov_chipkaartDAOsql;
import dao.Reiziger.ReizigerDAOsql;
import domein.Adres;
import domein.Ov_chipkaart;
import domein.Reiziger;
import java.sql.*;
import java.util.List;
public class main {
public static void main(String[] args){
String url = "jdbc:postgresql://localhost:5432/ovchip";
String username = "postgres";
String password = "postgres";
try {
Connection connection = DriverManager.getConnection(url, username, password);
ReizigerDAOsql reizigerDAOsql = new ReizigerDAOsql(connection);
AdresDAOsql adresDAOsql = new AdresDAOsql(connection);
Ov_chipkaartDAOsql ov_chipkaartDAOsql = new Ov_chipkaartDAOsql(connection);
adresDAOsql.setReizigerDAOsql(reizigerDAOsql);
reizigerDAOsql.setAdresDAOsql(adresDAOsql);
reizigerDAOsql.setOv_chipkaartDAOsql(ov_chipkaartDAOsql);
ov_chipkaartDAOsql.setReizigerDAOsql(reizigerDAOsql);
// save test
String gbdatum = "1981-03-14";
Reiziger sietske = new Reiziger(78, "S", "", "Boers", java.sql.Date.valueOf(gbdatum));
System.out.println("\nreiziger aanmaken test, TRUE al gaat het goed:\n");
System.out.println(reizigerDAOsql.save(sietske));
// update test
Reiziger updatedSietske = new Reiziger(78, "S", "van", "Specht", java.sql.Date.valueOf(gbdatum));
System.out.println("\nreiziger update test, TRUE al gaat het goed:\n");
System.out.println((reizigerDAOsql.update(updatedSietske)));
// delete test
System.out.println("\nreiziger delete test, TRUE al gaat het goed:\n");
System.out.println(reizigerDAOsql.delete(updatedSietske));
// find by id test
System.out.println("\nreiziger find by id, gegevens van reiziger met id 1 al gaat het goed:\n");
System.out.println(reizigerDAOsql.findById(1).toString());
// find by datum test
List<Reiziger> reizigers = reizigerDAOsql.findByGbdatum("2002-12-03");
System.out.println("\nreiziger find by datum test, gegevens van reiziger met geboortedatum 2002-12-3 al gaat het goed\n");
for (Reiziger perReiziger : reizigers) {
System.out.println(perReiziger.toString());
System.out.println("\n");
}
// findall test
List<Reiziger> reizigers2 = reizigerDAOsql.findAll();
System.out.println("\nfindall test\n");
for (Reiziger perReiziger : reizigers2) {
System.out.println(perReiziger.toString());
System.out.println("\n");
}
// adres tests
// reiziger aanmaken om mee te testen en linken
Reiziger reiziger = new Reiziger(10, "A", "van", "Zwan", Date.valueOf("2003-07-30"));
reizigerDAOsql.save(reiziger);
//adres save test
Adres adres = new Adres(reizigerDAOsql.findById(10), 10, "2420DH", "20", "Winde", "Gouda");
System.out.println("\nadres save test, TRUE al gaat het goed\n");
System.out.println(adresDAOsql.save(adres));
//adres update test
Adres nieuwAdres = new Adres(reizigerDAOsql.findById(10), 10, "2420DH", "30", "Winde", "Rotterdam");
System.out.println("\nadres update test, TRUE al gaat het goed\n");
System.out.println(adresDAOsql.update(nieuwAdres));
// adres delete test
System.out.println("\nadres delete test, TRUE al gaat het goed\n");
System.out.println(adresDAOsql.delete(nieuwAdres));
// reiziger met id 10 verwijderen omdat die is aangemaakt puur voor het testen
reizigerDAOsql.delete(reiziger);
//adres find by id test
System.out.println("\nadres find by id test, gegevens van reiziger met id 5 al gaat het goed\n");
Adres adres5 = adresDAOsql.findById(5);
System.out.println(adres5);
// adres find by reiziger test
System.out.println("\nadres find by reiziger test, gegevens van reiziger met id 5 al gaat het goed\n");
Reiziger reiziger5 = reizigerDAOsql.findById(adres5.getReiziger().getReizigerId());
System.out.println(adresDAOsql.findByReiziger(reiziger5));
//adres findall
System.out.println("\n adres find all, meerdere adres.toString al gaat het goed\n");
for (Adres perAdres : adresDAOsql.findAll()) {
System.out.println(perAdres);
}
//p4 testing
Reiziger reizigerp4 = new Reiziger(12, "J", "null", "Fredriksz", Date.valueOf("2003-07-30"));
reizigerDAOsql.save(reizigerp4);
System.out.println("\ntesting p4\n");
// ov_chipkaart save test
Ov_chipkaart ov_chipkaart = new Ov_chipkaart(12, Date.valueOf("2025-01-01"), 2, 50.00, reizigerDAOsql.findById(12));
System.out.println("\nov_chipkaart save test, TRUE al gaat het goed\n");
System.out.println(ov_chipkaartDAOsql.save(ov_chipkaart));
// ov_chipkaart update test
Ov_chipkaart ov_chipkaart2 = new Ov_chipkaart(12, Date.valueOf("2025-01-01"), 3, 50.00, reizigerDAOsql.findById(12));
System.out.println("\nov_chipkaart update test, TRUE al gaat het goed\n");
System.out.println(ov_chipkaartDAOsql.update(ov_chipkaart2));
// ov_chipkaart findById test
System.out.println("\nov_chipkaart findById test, toString van ov_chipkaart met kaartnummer 12 al gaat het goed\n");
System.out.println(ov_chipkaartDAOsql.findById(12));
// ov_chipkaart find by reiziger test
System.out.println("\nov_chipkaart find by reiziger test, gegevens van ov_chipkaart met kaartnummer 12 al gaat het goed\n");
List<Ov_chipkaart> chipkaarten = ov_chipkaartDAOsql.findByReiziger(reizigerp4);
for (Ov_chipkaart perChipkaart : chipkaarten) {
System.out.println(perChipkaart);
}
// ov_chipkaart find all test
System.out.println("\nov_chipkaart find all test, gegevens van alle kaarten al gaat het goed\n");
List<Ov_chipkaart> chipkaarten2 = ov_chipkaartDAOsql.findAll();
for (Ov_chipkaart perChipkaart : chipkaarten2) {
System.out.println(perChipkaart);
}
// ov_chipkaart delete test
System.out.println("\nov_chipkaart delete test, TRUE al gaat het goed\n");
System.out.println(ov_chipkaartDAOsql.delete(ov_chipkaart2));
//cleanup
reizigerDAOsql.delete(reizigerDAOsql.findById(12));
connection.close();
} catch (Exception e) {
System.out.println("er is iets fout gegaan:");
System.out.println(e);
}
}
}
| JeroenFredriksz/ovchip | src/main/java/main.java | 2,280 | // ov_chipkaart save test | line_comment | nl | import dao.Adres.AdresDAOsql;
import dao.Ov_chipkaart.Ov_chipkaartDAOsql;
import dao.Reiziger.ReizigerDAOsql;
import domein.Adres;
import domein.Ov_chipkaart;
import domein.Reiziger;
import java.sql.*;
import java.util.List;
public class main {
public static void main(String[] args){
String url = "jdbc:postgresql://localhost:5432/ovchip";
String username = "postgres";
String password = "postgres";
try {
Connection connection = DriverManager.getConnection(url, username, password);
ReizigerDAOsql reizigerDAOsql = new ReizigerDAOsql(connection);
AdresDAOsql adresDAOsql = new AdresDAOsql(connection);
Ov_chipkaartDAOsql ov_chipkaartDAOsql = new Ov_chipkaartDAOsql(connection);
adresDAOsql.setReizigerDAOsql(reizigerDAOsql);
reizigerDAOsql.setAdresDAOsql(adresDAOsql);
reizigerDAOsql.setOv_chipkaartDAOsql(ov_chipkaartDAOsql);
ov_chipkaartDAOsql.setReizigerDAOsql(reizigerDAOsql);
// save test
String gbdatum = "1981-03-14";
Reiziger sietske = new Reiziger(78, "S", "", "Boers", java.sql.Date.valueOf(gbdatum));
System.out.println("\nreiziger aanmaken test, TRUE al gaat het goed:\n");
System.out.println(reizigerDAOsql.save(sietske));
// update test
Reiziger updatedSietske = new Reiziger(78, "S", "van", "Specht", java.sql.Date.valueOf(gbdatum));
System.out.println("\nreiziger update test, TRUE al gaat het goed:\n");
System.out.println((reizigerDAOsql.update(updatedSietske)));
// delete test
System.out.println("\nreiziger delete test, TRUE al gaat het goed:\n");
System.out.println(reizigerDAOsql.delete(updatedSietske));
// find by id test
System.out.println("\nreiziger find by id, gegevens van reiziger met id 1 al gaat het goed:\n");
System.out.println(reizigerDAOsql.findById(1).toString());
// find by datum test
List<Reiziger> reizigers = reizigerDAOsql.findByGbdatum("2002-12-03");
System.out.println("\nreiziger find by datum test, gegevens van reiziger met geboortedatum 2002-12-3 al gaat het goed\n");
for (Reiziger perReiziger : reizigers) {
System.out.println(perReiziger.toString());
System.out.println("\n");
}
// findall test
List<Reiziger> reizigers2 = reizigerDAOsql.findAll();
System.out.println("\nfindall test\n");
for (Reiziger perReiziger : reizigers2) {
System.out.println(perReiziger.toString());
System.out.println("\n");
}
// adres tests
// reiziger aanmaken om mee te testen en linken
Reiziger reiziger = new Reiziger(10, "A", "van", "Zwan", Date.valueOf("2003-07-30"));
reizigerDAOsql.save(reiziger);
//adres save test
Adres adres = new Adres(reizigerDAOsql.findById(10), 10, "2420DH", "20", "Winde", "Gouda");
System.out.println("\nadres save test, TRUE al gaat het goed\n");
System.out.println(adresDAOsql.save(adres));
//adres update test
Adres nieuwAdres = new Adres(reizigerDAOsql.findById(10), 10, "2420DH", "30", "Winde", "Rotterdam");
System.out.println("\nadres update test, TRUE al gaat het goed\n");
System.out.println(adresDAOsql.update(nieuwAdres));
// adres delete test
System.out.println("\nadres delete test, TRUE al gaat het goed\n");
System.out.println(adresDAOsql.delete(nieuwAdres));
// reiziger met id 10 verwijderen omdat die is aangemaakt puur voor het testen
reizigerDAOsql.delete(reiziger);
//adres find by id test
System.out.println("\nadres find by id test, gegevens van reiziger met id 5 al gaat het goed\n");
Adres adres5 = adresDAOsql.findById(5);
System.out.println(adres5);
// adres find by reiziger test
System.out.println("\nadres find by reiziger test, gegevens van reiziger met id 5 al gaat het goed\n");
Reiziger reiziger5 = reizigerDAOsql.findById(adres5.getReiziger().getReizigerId());
System.out.println(adresDAOsql.findByReiziger(reiziger5));
//adres findall
System.out.println("\n adres find all, meerdere adres.toString al gaat het goed\n");
for (Adres perAdres : adresDAOsql.findAll()) {
System.out.println(perAdres);
}
//p4 testing
Reiziger reizigerp4 = new Reiziger(12, "J", "null", "Fredriksz", Date.valueOf("2003-07-30"));
reizigerDAOsql.save(reizigerp4);
System.out.println("\ntesting p4\n");
// ov_chipkaart save<SUF>
Ov_chipkaart ov_chipkaart = new Ov_chipkaart(12, Date.valueOf("2025-01-01"), 2, 50.00, reizigerDAOsql.findById(12));
System.out.println("\nov_chipkaart save test, TRUE al gaat het goed\n");
System.out.println(ov_chipkaartDAOsql.save(ov_chipkaart));
// ov_chipkaart update test
Ov_chipkaart ov_chipkaart2 = new Ov_chipkaart(12, Date.valueOf("2025-01-01"), 3, 50.00, reizigerDAOsql.findById(12));
System.out.println("\nov_chipkaart update test, TRUE al gaat het goed\n");
System.out.println(ov_chipkaartDAOsql.update(ov_chipkaart2));
// ov_chipkaart findById test
System.out.println("\nov_chipkaart findById test, toString van ov_chipkaart met kaartnummer 12 al gaat het goed\n");
System.out.println(ov_chipkaartDAOsql.findById(12));
// ov_chipkaart find by reiziger test
System.out.println("\nov_chipkaart find by reiziger test, gegevens van ov_chipkaart met kaartnummer 12 al gaat het goed\n");
List<Ov_chipkaart> chipkaarten = ov_chipkaartDAOsql.findByReiziger(reizigerp4);
for (Ov_chipkaart perChipkaart : chipkaarten) {
System.out.println(perChipkaart);
}
// ov_chipkaart find all test
System.out.println("\nov_chipkaart find all test, gegevens van alle kaarten al gaat het goed\n");
List<Ov_chipkaart> chipkaarten2 = ov_chipkaartDAOsql.findAll();
for (Ov_chipkaart perChipkaart : chipkaarten2) {
System.out.println(perChipkaart);
}
// ov_chipkaart delete test
System.out.println("\nov_chipkaart delete test, TRUE al gaat het goed\n");
System.out.println(ov_chipkaartDAOsql.delete(ov_chipkaart2));
//cleanup
reizigerDAOsql.delete(reizigerDAOsql.findById(12));
connection.close();
} catch (Exception e) {
System.out.println("er is iets fout gegaan:");
System.out.println(e);
}
}
}
|
69082_0 |
import domein.Adres;
import domein.Product;
import domein.Reiziger;
import domein.dao.Adres.AdresDAO;
import domein.dao.Adres.AdresDAOhibernate;
import domein.dao.Reiziger.ReizigerDAOhibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import javax.persistence.metamodel.EntityType;
import javax.persistence.metamodel.Metamodel;
import java.sql.Date;
import java.sql.SQLException;
/**
* Testklasse - deze klasse test alle andere klassen in deze package.
*
* System.out.println() is alleen in deze klasse toegestaan (behalve voor exceptions).
*
* @author [email protected]
*/
public class Main {
// Creëer een factory voor Hibernate sessions.
private static final SessionFactory factory;
static {
try {
// Create a Hibernate session factory
factory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
/**
* Retouneer een Hibernate session.
*
* @return Hibernate session
* @throws HibernateException
*/
private static Session getSession() throws HibernateException {
return factory.openSession();
}
public static void main(String[] args) throws SQLException {
testFetchAll();
testDAOhibernate();
}
/**
* P6. Haal alle (geannoteerde) entiteiten uit de database.
*/
private static void testFetchAll() {
Session session = getSession();
try {
Metamodel metamodel = session.getSessionFactory().getMetamodel();
for (EntityType<?> entityType : metamodel.getEntities()) {
Query query = session.createQuery("from " + entityType.getName());
System.out.println("[Test] Alle objecten van type " + entityType.getName() + " uit database:");
for (Object o : query.list()) {
System.out.println(" " + o);
}
System.out.println();
}
} finally {
session.close();
}
}
private static void testDAOhibernate() {
Session session = getSession();
session.beginTransaction();
ReizigerDAOhibernate reizigerDAOhibernate = new ReizigerDAOhibernate(session);
AdresDAOhibernate adresDAOhibernate = new AdresDAOhibernate(session, reizigerDAOhibernate);
reizigerDAOhibernate.setAdresDAO(adresDAOhibernate);
Reiziger reiziger = new Reiziger(7, "test", "test", "test", Date.valueOf("2002-02-02"));
Adres adres = new Adres(reiziger, 7, "test", "test", "test", "test");
reizigerDAOhibernate.save(reiziger);
}
}
| JeroenFredriksz/ovchipHibernate | src/main/java/Main.java | 887 | /**
* Testklasse - deze klasse test alle andere klassen in deze package.
*
* System.out.println() is alleen in deze klasse toegestaan (behalve voor exceptions).
*
* @author [email protected]
*/ | block_comment | nl |
import domein.Adres;
import domein.Product;
import domein.Reiziger;
import domein.dao.Adres.AdresDAO;
import domein.dao.Adres.AdresDAOhibernate;
import domein.dao.Reiziger.ReizigerDAOhibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import javax.persistence.metamodel.EntityType;
import javax.persistence.metamodel.Metamodel;
import java.sql.Date;
import java.sql.SQLException;
/**
* Testklasse - deze<SUF>*/
public class Main {
// Creëer een factory voor Hibernate sessions.
private static final SessionFactory factory;
static {
try {
// Create a Hibernate session factory
factory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
/**
* Retouneer een Hibernate session.
*
* @return Hibernate session
* @throws HibernateException
*/
private static Session getSession() throws HibernateException {
return factory.openSession();
}
public static void main(String[] args) throws SQLException {
testFetchAll();
testDAOhibernate();
}
/**
* P6. Haal alle (geannoteerde) entiteiten uit de database.
*/
private static void testFetchAll() {
Session session = getSession();
try {
Metamodel metamodel = session.getSessionFactory().getMetamodel();
for (EntityType<?> entityType : metamodel.getEntities()) {
Query query = session.createQuery("from " + entityType.getName());
System.out.println("[Test] Alle objecten van type " + entityType.getName() + " uit database:");
for (Object o : query.list()) {
System.out.println(" " + o);
}
System.out.println();
}
} finally {
session.close();
}
}
private static void testDAOhibernate() {
Session session = getSession();
session.beginTransaction();
ReizigerDAOhibernate reizigerDAOhibernate = new ReizigerDAOhibernate(session);
AdresDAOhibernate adresDAOhibernate = new AdresDAOhibernate(session, reizigerDAOhibernate);
reizigerDAOhibernate.setAdresDAO(adresDAOhibernate);
Reiziger reiziger = new Reiziger(7, "test", "test", "test", Date.valueOf("2002-02-02"));
Adres adres = new Adres(reiziger, 7, "test", "test", "test", "test");
reizigerDAOhibernate.save(reiziger);
}
}
|
50598_1 | package controller;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import model.ChoosePatternCardModel;
public class ChoosePatternCardController {
private int counterRand;
private ArrayList<ChoosePatternCardModel> patternCards;
public ChoosePatternCardController(DatabaseController dbController) {
// query kiest 1 random van de 24 van idpatterncard ALS de volgende kaart
// NIET dezelfde difficulty heeft -> kies
patternCards = new ArrayList<ChoosePatternCardModel>();
ResultSet rs = dbController.doQuery("SELECT * " + "FROM patterncard " + "ORDER BY RAND()" + "LIMIT 4");
try {
counterRand = 0;
while (rs.next()) {
counterRand += 1;
int idpatterncard = rs.getInt("idpatterncard");
int difficulty = rs.getInt("difficulty");
ChoosePatternCardModel newChoosePatternCardModel = new ChoosePatternCardModel(idpatterncard, difficulty,
counterRand);
patternCards.add(newChoosePatternCardModel);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public ArrayList<ChoosePatternCardModel> getPatternCard() {
return patternCards;
}
}
| JeromeNL/Sagrada | src/controller/ChoosePatternCardController.java | 348 | // NIET dezelfde difficulty heeft -> kies | line_comment | nl | package controller;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import model.ChoosePatternCardModel;
public class ChoosePatternCardController {
private int counterRand;
private ArrayList<ChoosePatternCardModel> patternCards;
public ChoosePatternCardController(DatabaseController dbController) {
// query kiest 1 random van de 24 van idpatterncard ALS de volgende kaart
// NIET dezelfde<SUF>
patternCards = new ArrayList<ChoosePatternCardModel>();
ResultSet rs = dbController.doQuery("SELECT * " + "FROM patterncard " + "ORDER BY RAND()" + "LIMIT 4");
try {
counterRand = 0;
while (rs.next()) {
counterRand += 1;
int idpatterncard = rs.getInt("idpatterncard");
int difficulty = rs.getInt("difficulty");
ChoosePatternCardModel newChoosePatternCardModel = new ChoosePatternCardModel(idpatterncard, difficulty,
counterRand);
patternCards.add(newChoosePatternCardModel);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public ArrayList<ChoosePatternCardModel> getPatternCard() {
return patternCards;
}
}
|
194208_6 | /*
* Copyright 2017 JessYan
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jess.arms.integration;
import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.base.delegate.ActivityDelegate;
import com.jess.arms.base.delegate.ActivityDelegateImpl;
import com.jess.arms.base.delegate.FragmentDelegate;
import com.jess.arms.base.delegate.IActivity;
import com.jess.arms.integration.cache.Cache;
import com.jess.arms.integration.cache.IntelligentCache;
import com.jess.arms.utils.Preconditions;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
import dagger.Lazy;
/**
* ================================================
* {@link Application.ActivityLifecycleCallbacks} 默认实现类
* 通过 {@link ActivityDelegate} 管理 {@link Activity}
*
* @see <a href="http://www.jianshu.com/p/75a5c24174b2">ActivityLifecycleCallbacks 分析文章</a>
* Created by JessYan on 21/02/2017 14:23
* <a href="mailto:[email protected]">Contact me</a>
* <a href="https://github.com/JessYanCoding">Follow me</a>
* ================================================
*/
@Singleton
public class ActivityLifecycle implements Application.ActivityLifecycleCallbacks {
@Inject
AppManager mAppManager;
@Inject
Application mApplication;
@Inject
Cache<String, Object> mExtras;
@Inject
Lazy<FragmentManager.FragmentLifecycleCallbacks> mFragmentLifecycle;
@Inject
Lazy<List<FragmentManager.FragmentLifecycleCallbacks>> mFragmentLifecycles;
@Inject
public ActivityLifecycle() {
}
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
//如果 intent 包含了此字段,并且为 true 说明不加入到 list 进行统一管理
boolean isNotAdd = false;
if (activity.getIntent() != null) {
isNotAdd = activity.getIntent().getBooleanExtra(AppManager.IS_NOT_ADD_ACTIVITY_LIST, false);
}
if (!isNotAdd) {
mAppManager.addActivity(activity);
}
//配置ActivityDelegate
if (activity instanceof IActivity) {
ActivityDelegate activityDelegate = fetchActivityDelegate(activity);
if (activityDelegate == null) {
Cache<String, Object> cache = getCacheFromActivity((IActivity) activity);
activityDelegate = new ActivityDelegateImpl(activity);
//使用 IntelligentCache.KEY_KEEP 作为 key 的前缀, 可以使储存的数据永久存储在内存中
//否则存储在 LRU 算法的存储空间中, 前提是 Activity 使用的是 IntelligentCache (框架默认使用)
cache.put(IntelligentCache.getKeyOfKeep(ActivityDelegate.ACTIVITY_DELEGATE), activityDelegate);
}
activityDelegate.onCreate(savedInstanceState);
}
registerFragmentCallbacks(activity);
}
@Override
public void onActivityStarted(Activity activity) {
ActivityDelegate activityDelegate = fetchActivityDelegate(activity);
if (activityDelegate != null) {
activityDelegate.onStart();
}
}
@Override
public void onActivityResumed(Activity activity) {
mAppManager.setCurrentActivity(activity);
ActivityDelegate activityDelegate = fetchActivityDelegate(activity);
if (activityDelegate != null) {
activityDelegate.onResume();
}
}
@Override
public void onActivityPaused(Activity activity) {
ActivityDelegate activityDelegate = fetchActivityDelegate(activity);
if (activityDelegate != null) {
activityDelegate.onPause();
}
}
@Override
public void onActivityStopped(Activity activity) {
if (mAppManager.getCurrentActivity() == activity) {
mAppManager.setCurrentActivity(null);
}
ActivityDelegate activityDelegate = fetchActivityDelegate(activity);
if (activityDelegate != null) {
activityDelegate.onStop();
}
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
ActivityDelegate activityDelegate = fetchActivityDelegate(activity);
if (activityDelegate != null) {
activityDelegate.onSaveInstanceState(outState);
}
}
@Override
public void onActivityDestroyed(Activity activity) {
mAppManager.removeActivity(activity);
ActivityDelegate activityDelegate = fetchActivityDelegate(activity);
if (activityDelegate != null) {
activityDelegate.onDestroy();
getCacheFromActivity((IActivity) activity).clear();
}
}
/**
* 给每个 Activity 的所有 Fragment 设置监听其生命周期, Activity 可以通过 {@link IActivity#useFragment()}
* 设置是否使用监听,如果这个 Activity 返回 false 的话,这个 Activity 下面的所有 Fragment 将不能使用 {@link FragmentDelegate}
* 意味着 {@link BaseFragment} 也不能使用
*
* @param activity
*/
private void registerFragmentCallbacks(Activity activity) {
boolean useFragment = !(activity instanceof IActivity) || ((IActivity) activity).useFragment();
if (activity instanceof FragmentActivity && useFragment) {
//mFragmentLifecycle 为 Fragment 生命周期实现类, 用于框架内部对每个 Fragment 的必要操作, 如给每个 Fragment 配置 FragmentDelegate
//注册框架内部已实现的 Fragment 生命周期逻辑
((FragmentActivity) activity).getSupportFragmentManager().registerFragmentLifecycleCallbacks(mFragmentLifecycle.get(), true);
if (mExtras.containsKey(IntelligentCache.getKeyOfKeep(ConfigModule.class.getName()))) {
@SuppressWarnings("unchecked")
List<ConfigModule> modules = (List<ConfigModule>) mExtras.get(IntelligentCache.getKeyOfKeep(ConfigModule.class.getName()));
if (modules != null) {
for (ConfigModule module : modules) {
module.injectFragmentLifecycle(mApplication, mFragmentLifecycles.get());
}
}
mExtras.remove(IntelligentCache.getKeyOfKeep(ConfigModule.class.getName()));
}
//注册框架外部, 开发者扩展的 Fragment 生命周期逻辑
for (FragmentManager.FragmentLifecycleCallbacks fragmentLifecycle : mFragmentLifecycles.get()) {
((FragmentActivity) activity).getSupportFragmentManager().registerFragmentLifecycleCallbacks(fragmentLifecycle, true);
}
}
}
private ActivityDelegate fetchActivityDelegate(Activity activity) {
ActivityDelegate activityDelegate = null;
if (activity instanceof IActivity) {
Cache<String, Object> cache = getCacheFromActivity((IActivity) activity);
activityDelegate = (ActivityDelegate) cache.get(IntelligentCache.getKeyOfKeep(ActivityDelegate.ACTIVITY_DELEGATE));
}
return activityDelegate;
}
@NonNull
private Cache<String, Object> getCacheFromActivity(IActivity activity) {
Cache<String, Object> cache = activity.provideCache();
Preconditions.checkNotNull(cache, "%s cannot be null on Activity", Cache.class.getName());
return cache;
}
}
| JessYanCoding/MVPArms | arms/src/main/java/com/jess/arms/integration/ActivityLifecycle.java | 2,083 | //mFragmentLifecycle 为 Fragment 生命周期实现类, 用于框架内部对每个 Fragment 的必要操作, 如给每个 Fragment 配置 FragmentDelegate | line_comment | nl | /*
* Copyright 2017 JessYan
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jess.arms.integration;
import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.base.delegate.ActivityDelegate;
import com.jess.arms.base.delegate.ActivityDelegateImpl;
import com.jess.arms.base.delegate.FragmentDelegate;
import com.jess.arms.base.delegate.IActivity;
import com.jess.arms.integration.cache.Cache;
import com.jess.arms.integration.cache.IntelligentCache;
import com.jess.arms.utils.Preconditions;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
import dagger.Lazy;
/**
* ================================================
* {@link Application.ActivityLifecycleCallbacks} 默认实现类
* 通过 {@link ActivityDelegate} 管理 {@link Activity}
*
* @see <a href="http://www.jianshu.com/p/75a5c24174b2">ActivityLifecycleCallbacks 分析文章</a>
* Created by JessYan on 21/02/2017 14:23
* <a href="mailto:[email protected]">Contact me</a>
* <a href="https://github.com/JessYanCoding">Follow me</a>
* ================================================
*/
@Singleton
public class ActivityLifecycle implements Application.ActivityLifecycleCallbacks {
@Inject
AppManager mAppManager;
@Inject
Application mApplication;
@Inject
Cache<String, Object> mExtras;
@Inject
Lazy<FragmentManager.FragmentLifecycleCallbacks> mFragmentLifecycle;
@Inject
Lazy<List<FragmentManager.FragmentLifecycleCallbacks>> mFragmentLifecycles;
@Inject
public ActivityLifecycle() {
}
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
//如果 intent 包含了此字段,并且为 true 说明不加入到 list 进行统一管理
boolean isNotAdd = false;
if (activity.getIntent() != null) {
isNotAdd = activity.getIntent().getBooleanExtra(AppManager.IS_NOT_ADD_ACTIVITY_LIST, false);
}
if (!isNotAdd) {
mAppManager.addActivity(activity);
}
//配置ActivityDelegate
if (activity instanceof IActivity) {
ActivityDelegate activityDelegate = fetchActivityDelegate(activity);
if (activityDelegate == null) {
Cache<String, Object> cache = getCacheFromActivity((IActivity) activity);
activityDelegate = new ActivityDelegateImpl(activity);
//使用 IntelligentCache.KEY_KEEP 作为 key 的前缀, 可以使储存的数据永久存储在内存中
//否则存储在 LRU 算法的存储空间中, 前提是 Activity 使用的是 IntelligentCache (框架默认使用)
cache.put(IntelligentCache.getKeyOfKeep(ActivityDelegate.ACTIVITY_DELEGATE), activityDelegate);
}
activityDelegate.onCreate(savedInstanceState);
}
registerFragmentCallbacks(activity);
}
@Override
public void onActivityStarted(Activity activity) {
ActivityDelegate activityDelegate = fetchActivityDelegate(activity);
if (activityDelegate != null) {
activityDelegate.onStart();
}
}
@Override
public void onActivityResumed(Activity activity) {
mAppManager.setCurrentActivity(activity);
ActivityDelegate activityDelegate = fetchActivityDelegate(activity);
if (activityDelegate != null) {
activityDelegate.onResume();
}
}
@Override
public void onActivityPaused(Activity activity) {
ActivityDelegate activityDelegate = fetchActivityDelegate(activity);
if (activityDelegate != null) {
activityDelegate.onPause();
}
}
@Override
public void onActivityStopped(Activity activity) {
if (mAppManager.getCurrentActivity() == activity) {
mAppManager.setCurrentActivity(null);
}
ActivityDelegate activityDelegate = fetchActivityDelegate(activity);
if (activityDelegate != null) {
activityDelegate.onStop();
}
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
ActivityDelegate activityDelegate = fetchActivityDelegate(activity);
if (activityDelegate != null) {
activityDelegate.onSaveInstanceState(outState);
}
}
@Override
public void onActivityDestroyed(Activity activity) {
mAppManager.removeActivity(activity);
ActivityDelegate activityDelegate = fetchActivityDelegate(activity);
if (activityDelegate != null) {
activityDelegate.onDestroy();
getCacheFromActivity((IActivity) activity).clear();
}
}
/**
* 给每个 Activity 的所有 Fragment 设置监听其生命周期, Activity 可以通过 {@link IActivity#useFragment()}
* 设置是否使用监听,如果这个 Activity 返回 false 的话,这个 Activity 下面的所有 Fragment 将不能使用 {@link FragmentDelegate}
* 意味着 {@link BaseFragment} 也不能使用
*
* @param activity
*/
private void registerFragmentCallbacks(Activity activity) {
boolean useFragment = !(activity instanceof IActivity) || ((IActivity) activity).useFragment();
if (activity instanceof FragmentActivity && useFragment) {
//mFragmentLifecycle 为<SUF>
//注册框架内部已实现的 Fragment 生命周期逻辑
((FragmentActivity) activity).getSupportFragmentManager().registerFragmentLifecycleCallbacks(mFragmentLifecycle.get(), true);
if (mExtras.containsKey(IntelligentCache.getKeyOfKeep(ConfigModule.class.getName()))) {
@SuppressWarnings("unchecked")
List<ConfigModule> modules = (List<ConfigModule>) mExtras.get(IntelligentCache.getKeyOfKeep(ConfigModule.class.getName()));
if (modules != null) {
for (ConfigModule module : modules) {
module.injectFragmentLifecycle(mApplication, mFragmentLifecycles.get());
}
}
mExtras.remove(IntelligentCache.getKeyOfKeep(ConfigModule.class.getName()));
}
//注册框架外部, 开发者扩展的 Fragment 生命周期逻辑
for (FragmentManager.FragmentLifecycleCallbacks fragmentLifecycle : mFragmentLifecycles.get()) {
((FragmentActivity) activity).getSupportFragmentManager().registerFragmentLifecycleCallbacks(fragmentLifecycle, true);
}
}
}
private ActivityDelegate fetchActivityDelegate(Activity activity) {
ActivityDelegate activityDelegate = null;
if (activity instanceof IActivity) {
Cache<String, Object> cache = getCacheFromActivity((IActivity) activity);
activityDelegate = (ActivityDelegate) cache.get(IntelligentCache.getKeyOfKeep(ActivityDelegate.ACTIVITY_DELEGATE));
}
return activityDelegate;
}
@NonNull
private Cache<String, Object> getCacheFromActivity(IActivity activity) {
Cache<String, Object> cache = activity.provideCache();
Preconditions.checkNotNull(cache, "%s cannot be null on Activity", Cache.class.getName());
return cache;
}
}
|
25401_24 | package bab_conversie;
import java.util.ArrayList;
import java.util.HashMap;
public class Tokenizer {
boolean addSpaces = false;
// constructor
// add spaces inbetween punctuation signs of not
public Tokenizer(boolean addSpaces){
this.addSpaces = addSpaces;
}
public ArrayList<String[]> tokenize(String content){
ArrayList<String[]> tokens = new ArrayList<String[]>();
String tokenizedText = content;
// in a final step, we will separate the different tokens by splitting around each space
// but before being able to do that, we must put spaces where we expect those to be
// able to split around those.
// replace known abbreviations by a code
// (so we will be able to process the other dots without
// possible errors since the dots of abbreviations are not
// visible anymore, at least temporarily)
for (int i =0; i< Constants.KNOWN_ABBREVIATIONS.length; i++)
{
// build abbreviation regex
String abbreviation = Constants.KNOWN_ABBREVIATIONS[i].replaceAll("(\\.)", "\\\\$1");
// replace group [anything but end of a word][abbreviation][anything but begin of a word] by
// [anything but end of a word]<abbreviation_nr>[anything but begin of a word]
// beware: end of a previous word attached can consist of a (double) dot, when the
// whole thing is actually a bigger abbreviation
String regex = "(\\s|[^-\\.:%&a-zA-ZáéíóúýàèìòùâêîôûäëïöüñçÁÉÍÓÚÝÀÈÌÒÙÂÊÎÔÛÄËÏÖÜ])" +
"(" + abbreviation + ")([^-%&a-zA-ZáéíóúýàèìòùâêîôûäëïöüñçÁÉÍÓÚÝÀÈÌÒÙÂÊÎÔÛÄËÏÖÜ])";
//System.out.println(abbreviation+" "+regex);
tokenizedText =
tokenizedText.replaceAll(regex, "$1@@@"+i+"@@@$3");
}
// replace first letters (initial) followed by a dot by first letter + something else
tokenizedText = hideTheDotsAndDoubleDotsFromInitials(tokenizedText);
// *************************************************************
// ** NOW the dots from abbreviations and initials are hidden **
// *************************************************************
// now process the remaining dots and such
// all punctuation now gets spaces on the right and left
if (addSpaces)
tokenizedText = tokenizedText.replaceAll("([^-%&0-9a-zA-ZáéíóúýàèìòùâêîôûäëïöüñçÁÉÍÓÚÝÀÈÌÒÙÂÊÎÔÛÄËÏÖÜ])"," $1 ");
// remove double spaces and such
tokenizedText = tokenizedText.replaceAll("\\s+", " ");
// Build tokens array:
// This consists of an array of array's.
// Each subarray consists of a token, its original form and its canonical form.
// Normally the original token is empty since the token has not been modified.
// But when the token contains undesired tags and such, we remove those but
// keep the original token (which is empty otherwise).
//
// eg:
// a<supplied>m</supplied>ij -> bareToken="amij" originalToken="a<supplied>m</supplied>ij"
// meneer -> bareToken="meneer" originalToken=""
for (String oneToken : tokenizedText.split("\\s"))
{
String bareToken = oneToken;
String originalToken = "";
// if there are tags, remove all tags
// but remember the token with tags in 'originalToken'
if (oneToken.matches("(.*)\\<(.*?)\\>(.*)") )
{
bareToken = oneToken.replaceAll("(\\<)(.*?)(\\>)", "");
originalToken = oneToken;
}
// compute a nForm (canonical form) which is the bare word without any punctuation
// in front or at the end (word may contain tags)
// we need this nForm only if the bare token actually has any punctuation in it
// we compute it here because a that point the abbreviation dots and such
// are hidden, so that only punctuation dots are visible
String nForm = getNForm(bareToken);
nForm = (nForm.equals(bareToken)) ? "" : nForm;
// ******************************
// ** PUT BACK the hidden dots **
// ******************************
// replace abbreviation marks back with abbreviations.
// we do this only now, because that way we are sure that
// we won't wrongly remove dots (t.i. from abbreviations) when getting nforms
if (oneToken.matches("(.*@@@)(\\d+)(@@@.*)"))
{
String abbrNumberStr = oneToken.replaceAll("(.*@@@)(\\d+)(@@@.*)", "$2");
int abbrNumber = Integer.parseInt(abbrNumberStr);
String abbreviation = Constants.KNOWN_ABBREVIATIONS[abbrNumber];
originalToken =
originalToken.replaceAll("(@@@"+abbrNumber+"@@@)", abbreviation);
bareToken =
bareToken.replaceAll("(@@@"+abbrNumber+"@@@)", abbreviation);
nForm =
nForm.replaceAll("(@@@"+abbrNumber+"@@@)", abbreviation);
}
// put first letters (initials) dots back
bareToken = getBackTheDotsAndDoubleDotsFromInitials(bareToken);
originalToken = getBackTheDotsAndDoubleDotsFromInitials(originalToken);
nForm = getBackTheDotsAndDoubleDotsFromInitials(nForm);
String[] tokenArray = new String[]{
transformIllegalSigns(bareToken),
transformIllegalSigns(originalToken),
transformIllegalSigns(nForm)
};
//System.out.println("token "+bareToken+"\t"+originalToken+"\t"+nForm);
tokens.add(tokenArray);
}
return tokens;
}
private String hideTheDotsAndDoubleDotsFromInitials(String str){
// don't put % and & in there
str = str
.replaceAll("(\\.)([A-Za-z])(\\.)", "EenPunt$2EenPunt")
.replaceAll("(\\s)([A-Za-z])(\\.)", "$1$2EenPunt")
.replaceAll("^([A-Za-z])(\\.)", "$1EenPunt");
str = str
.replaceAll("(:)([A-Za-z])(:)", "DubbelePunt$2DubbelePunt")
.replaceAll("(\\s)([A-Za-z])(:)", "$1$2DubbelePunt")
.replaceAll("^([A-Za-z])(:)", "$1DubbelePunt");
return str;
}
private String getBackTheDotsAndDoubleDotsFromInitials(String str){
// don't put % and & in there
str = str.replaceAll("([A-Za-z])(EenPunt)", "$1.");
//str = str.replaceAll("([^-0-9a-zA-ZáéíóúýàèìòùâêîôûäëïöüñçÁÉÍÓÚÝÀÈÌÒÙÂÊÎÔÛÄËÏÖÜ])([A-Za-z])(EenPunt)", "$1$2.");
str = str.replaceAll("([A-Za-z])(DubbelePunt)", "$1:");
//str = str.replaceAll("([^-0-9a-zA-ZáéíóúýàèìòùâêîôûäëïöüñçÁÉÍÓÚÝÀÈÌÒÙÂÊÎÔÛÄËÏÖÜ])([A-Za-z])(DubbelePunt)", "$1$2:");
return str;
}
private String transformIllegalSigns(String str){
return str.replaceAll("&", "&")
.replaceAll("\"", """)
.replaceAll("\\<", "<")
.replaceAll("\\>", ">");
}
public static String getNForm(String nForm){
nForm = nForm.replaceAll("^([^-@<92>'<91>%&0-9a-zA-ZáéíóúýàèìòùâêîôûäëïöüñçÁÉÍÓÚÝÀÈÌÒÙÂÊÎÔÛÄËÏÖÜ]+)(.+?)$", "$2");
nForm = nForm.replaceAll("^(.+?)([^-@<92>'<91>%&0-9a-zA-ZáéíóúýàèìòùâêîôûäëïöüñçÁÉÍÓÚÝÀÈÌÒÙÂÊÎÔÛÄËÏÖÜ]+)$", "$1");
return nForm;
}
}
| JessedeDoes/CorpusProcessing | src/main/java/bab_conversie/Tokenizer.java | 2,590 | // a<supplied>m</supplied>ij -> bareToken="amij" originalToken="a<supplied>m</supplied>ij"
| line_comment | nl | package bab_conversie;
import java.util.ArrayList;
import java.util.HashMap;
public class Tokenizer {
boolean addSpaces = false;
// constructor
// add spaces inbetween punctuation signs of not
public Tokenizer(boolean addSpaces){
this.addSpaces = addSpaces;
}
public ArrayList<String[]> tokenize(String content){
ArrayList<String[]> tokens = new ArrayList<String[]>();
String tokenizedText = content;
// in a final step, we will separate the different tokens by splitting around each space
// but before being able to do that, we must put spaces where we expect those to be
// able to split around those.
// replace known abbreviations by a code
// (so we will be able to process the other dots without
// possible errors since the dots of abbreviations are not
// visible anymore, at least temporarily)
for (int i =0; i< Constants.KNOWN_ABBREVIATIONS.length; i++)
{
// build abbreviation regex
String abbreviation = Constants.KNOWN_ABBREVIATIONS[i].replaceAll("(\\.)", "\\\\$1");
// replace group [anything but end of a word][abbreviation][anything but begin of a word] by
// [anything but end of a word]<abbreviation_nr>[anything but begin of a word]
// beware: end of a previous word attached can consist of a (double) dot, when the
// whole thing is actually a bigger abbreviation
String regex = "(\\s|[^-\\.:%&a-zA-ZáéíóúýàèìòùâêîôûäëïöüñçÁÉÍÓÚÝÀÈÌÒÙÂÊÎÔÛÄËÏÖÜ])" +
"(" + abbreviation + ")([^-%&a-zA-ZáéíóúýàèìòùâêîôûäëïöüñçÁÉÍÓÚÝÀÈÌÒÙÂÊÎÔÛÄËÏÖÜ])";
//System.out.println(abbreviation+" "+regex);
tokenizedText =
tokenizedText.replaceAll(regex, "$1@@@"+i+"@@@$3");
}
// replace first letters (initial) followed by a dot by first letter + something else
tokenizedText = hideTheDotsAndDoubleDotsFromInitials(tokenizedText);
// *************************************************************
// ** NOW the dots from abbreviations and initials are hidden **
// *************************************************************
// now process the remaining dots and such
// all punctuation now gets spaces on the right and left
if (addSpaces)
tokenizedText = tokenizedText.replaceAll("([^-%&0-9a-zA-ZáéíóúýàèìòùâêîôûäëïöüñçÁÉÍÓÚÝÀÈÌÒÙÂÊÎÔÛÄËÏÖÜ])"," $1 ");
// remove double spaces and such
tokenizedText = tokenizedText.replaceAll("\\s+", " ");
// Build tokens array:
// This consists of an array of array's.
// Each subarray consists of a token, its original form and its canonical form.
// Normally the original token is empty since the token has not been modified.
// But when the token contains undesired tags and such, we remove those but
// keep the original token (which is empty otherwise).
//
// eg:
// a<supplied>m</supplied>ij <SUF>
// meneer -> bareToken="meneer" originalToken=""
for (String oneToken : tokenizedText.split("\\s"))
{
String bareToken = oneToken;
String originalToken = "";
// if there are tags, remove all tags
// but remember the token with tags in 'originalToken'
if (oneToken.matches("(.*)\\<(.*?)\\>(.*)") )
{
bareToken = oneToken.replaceAll("(\\<)(.*?)(\\>)", "");
originalToken = oneToken;
}
// compute a nForm (canonical form) which is the bare word without any punctuation
// in front or at the end (word may contain tags)
// we need this nForm only if the bare token actually has any punctuation in it
// we compute it here because a that point the abbreviation dots and such
// are hidden, so that only punctuation dots are visible
String nForm = getNForm(bareToken);
nForm = (nForm.equals(bareToken)) ? "" : nForm;
// ******************************
// ** PUT BACK the hidden dots **
// ******************************
// replace abbreviation marks back with abbreviations.
// we do this only now, because that way we are sure that
// we won't wrongly remove dots (t.i. from abbreviations) when getting nforms
if (oneToken.matches("(.*@@@)(\\d+)(@@@.*)"))
{
String abbrNumberStr = oneToken.replaceAll("(.*@@@)(\\d+)(@@@.*)", "$2");
int abbrNumber = Integer.parseInt(abbrNumberStr);
String abbreviation = Constants.KNOWN_ABBREVIATIONS[abbrNumber];
originalToken =
originalToken.replaceAll("(@@@"+abbrNumber+"@@@)", abbreviation);
bareToken =
bareToken.replaceAll("(@@@"+abbrNumber+"@@@)", abbreviation);
nForm =
nForm.replaceAll("(@@@"+abbrNumber+"@@@)", abbreviation);
}
// put first letters (initials) dots back
bareToken = getBackTheDotsAndDoubleDotsFromInitials(bareToken);
originalToken = getBackTheDotsAndDoubleDotsFromInitials(originalToken);
nForm = getBackTheDotsAndDoubleDotsFromInitials(nForm);
String[] tokenArray = new String[]{
transformIllegalSigns(bareToken),
transformIllegalSigns(originalToken),
transformIllegalSigns(nForm)
};
//System.out.println("token "+bareToken+"\t"+originalToken+"\t"+nForm);
tokens.add(tokenArray);
}
return tokens;
}
private String hideTheDotsAndDoubleDotsFromInitials(String str){
// don't put % and & in there
str = str
.replaceAll("(\\.)([A-Za-z])(\\.)", "EenPunt$2EenPunt")
.replaceAll("(\\s)([A-Za-z])(\\.)", "$1$2EenPunt")
.replaceAll("^([A-Za-z])(\\.)", "$1EenPunt");
str = str
.replaceAll("(:)([A-Za-z])(:)", "DubbelePunt$2DubbelePunt")
.replaceAll("(\\s)([A-Za-z])(:)", "$1$2DubbelePunt")
.replaceAll("^([A-Za-z])(:)", "$1DubbelePunt");
return str;
}
private String getBackTheDotsAndDoubleDotsFromInitials(String str){
// don't put % and & in there
str = str.replaceAll("([A-Za-z])(EenPunt)", "$1.");
//str = str.replaceAll("([^-0-9a-zA-ZáéíóúýàèìòùâêîôûäëïöüñçÁÉÍÓÚÝÀÈÌÒÙÂÊÎÔÛÄËÏÖÜ])([A-Za-z])(EenPunt)", "$1$2.");
str = str.replaceAll("([A-Za-z])(DubbelePunt)", "$1:");
//str = str.replaceAll("([^-0-9a-zA-ZáéíóúýàèìòùâêîôûäëïöüñçÁÉÍÓÚÝÀÈÌÒÙÂÊÎÔÛÄËÏÖÜ])([A-Za-z])(DubbelePunt)", "$1$2:");
return str;
}
private String transformIllegalSigns(String str){
return str.replaceAll("&", "&")
.replaceAll("\"", """)
.replaceAll("\\<", "<")
.replaceAll("\\>", ">");
}
public static String getNForm(String nForm){
nForm = nForm.replaceAll("^([^-@<92>'<91>%&0-9a-zA-ZáéíóúýàèìòùâêîôûäëïöüñçÁÉÍÓÚÝÀÈÌÒÙÂÊÎÔÛÄËÏÖÜ]+)(.+?)$", "$2");
nForm = nForm.replaceAll("^(.+?)([^-@<92>'<91>%&0-9a-zA-ZáéíóúýàèìòùâêîôûäëïöüñçÁÉÍÓÚÝÀÈÌÒÙÂÊÎÔÛÄËÏÖÜ]+)$", "$1");
return nForm;
}
}
|
198127_8 | /*
* Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.lwawt.macosx;
import sun.awt.SunToolkit;
import sun.awt.event.KeyEventProcessing;
import sun.lwawt.LWWindowPeer;
import sun.lwawt.PlatformEventNotifier;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.event.InputEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.KeyEvent;
import java.util.Arrays;
import java.util.Locale;
/**
* Translates NSEvents/NPCocoaEvents into AWT events.
*/
final class CPlatformResponder {
private final PlatformEventNotifier eventNotifier;
private final boolean isNpapiCallback;
private int lastKeyPressCode = KeyEvent.VK_UNDEFINED;
private final DeltaAccumulator deltaAccumulatorX = new DeltaAccumulator();
private final DeltaAccumulator deltaAccumulatorY = new DeltaAccumulator();
private boolean momentumStarted;
private int momentumX;
private int momentumY;
private int momentumModifiers;
private int lastDraggedAbsoluteX;
private int lastDraggedAbsoluteY;
private int lastDraggedRelativeX;
private int lastDraggedRelativeY;
CPlatformResponder(final PlatformEventNotifier eventNotifier,
final boolean isNpapiCallback) {
this.eventNotifier = eventNotifier;
this.isNpapiCallback = isNpapiCallback;
}
/**
* Handles mouse events.
*/
void handleMouseEvent(int eventType, int modifierFlags, int buttonNumber,
int clickCount, int x, int y, int absX, int absY) {
final SunToolkit tk = (SunToolkit)Toolkit.getDefaultToolkit();
if ((buttonNumber > 2 && !tk.areExtraMouseButtonsEnabled())
|| buttonNumber > tk.getNumberOfButtons() - 1) {
return;
}
int jeventType = isNpapiCallback ? NSEvent.npToJavaEventType(eventType) :
NSEvent.nsToJavaEventType(eventType);
boolean dragged = jeventType == MouseEvent.MOUSE_DRAGGED;
if (dragged // ignore dragged event that does not change any location
&& lastDraggedAbsoluteX == absX && lastDraggedRelativeX == x
&& lastDraggedAbsoluteY == absY && lastDraggedRelativeY == y) return;
if (dragged || jeventType == MouseEvent.MOUSE_PRESSED) {
lastDraggedAbsoluteX = absX;
lastDraggedAbsoluteY = absY;
lastDraggedRelativeX = x;
lastDraggedRelativeY = y;
}
int jbuttonNumber = MouseEvent.NOBUTTON;
int jclickCount = 0;
if (jeventType != MouseEvent.MOUSE_MOVED &&
jeventType != MouseEvent.MOUSE_ENTERED &&
jeventType != MouseEvent.MOUSE_EXITED)
{
jbuttonNumber = NSEvent.nsToJavaButton(buttonNumber);
jclickCount = clickCount;
}
int jmodifiers = NSEvent.nsToJavaModifiers(modifierFlags);
boolean jpopupTrigger = NSEvent.isPopupTrigger(jmodifiers);
eventNotifier.notifyMouseEvent(jeventType, System.currentTimeMillis(), jbuttonNumber,
x, y, absX, absY, jmodifiers, jclickCount,
jpopupTrigger, null);
}
/**
* Handles scroll events.
*/
void handleScrollEvent(int x, int y, final int absX,
final int absY, final int modifierFlags,
final double deltaX, final double deltaY,
final int scrollPhase) {
int jmodifiers = NSEvent.nsToJavaModifiers(modifierFlags);
if (scrollPhase > NSEvent.SCROLL_PHASE_UNSUPPORTED) {
if (scrollPhase == NSEvent.SCROLL_PHASE_BEGAN) {
momentumStarted = false;
} else if (scrollPhase == NSEvent.SCROLL_PHASE_MOMENTUM_BEGAN) {
momentumStarted = true;
momentumX = x;
momentumY = y;
momentumModifiers = jmodifiers;
} else if (momentumStarted) {
x = momentumX;
y = momentumY;
jmodifiers = momentumModifiers;
}
}
final boolean isShift = (jmodifiers & InputEvent.SHIFT_DOWN_MASK) != 0;
int roundDeltaX = deltaAccumulatorX.getRoundedDelta(deltaX, scrollPhase);
int roundDeltaY = deltaAccumulatorY.getRoundedDelta(deltaY, scrollPhase);
// Vertical scroll.
if (!isShift && (deltaY != 0.0 || roundDeltaY != 0)) {
dispatchScrollEvent(x, y, absX, absY, jmodifiers, roundDeltaY, deltaY);
}
// Horizontal scroll or shirt+vertical scroll.
final double delta = isShift && deltaY != 0.0 ? deltaY : deltaX;
final int roundDelta = isShift && roundDeltaY != 0 ? roundDeltaY : roundDeltaX;
if (delta != 0.0 || roundDelta != 0) {
jmodifiers |= InputEvent.SHIFT_DOWN_MASK;
dispatchScrollEvent(x, y, absX, absY, jmodifiers, roundDelta, delta);
}
}
private void dispatchScrollEvent(final int x, final int y, final int absX,
final int absY, final int modifiers,
final int roundDelta, final double delta) {
final long when = System.currentTimeMillis();
final int scrollType = MouseWheelEvent.WHEEL_UNIT_SCROLL;
final int scrollAmount = 1;
// invert the wheelRotation for the peer
eventNotifier.notifyMouseWheelEvent(when, x, y, absX, absY, modifiers,
scrollType, scrollAmount,
-roundDelta, -delta, null);
}
private static final String [] cyrillicKeyboardLayouts = new String [] {
"com.apple.keylayout.Russian",
"com.apple.keylayout.RussianWin",
"com.apple.keylayout.Russian-Phonetic",
"com.apple.keylayout.Byelorussian",
"com.apple.keylayout.Ukrainian",
"com.apple.keylayout.UkrainianWin",
"com.apple.keylayout.Bulgarian",
"com.apple.keylayout.Serbian"
};
private static boolean isCyrillicKeyboardLayout() {
return Arrays.stream(cyrillicKeyboardLayouts).anyMatch(l -> l.equals(LWCToolkit.getKeyboardLayoutId()));
}
void handleInputEvent(String text) {
if (text != null) {
int index = 0, length = text.length();
char c = 0;
while (index < length) {
c = text.charAt(index);
eventNotifier.notifyKeyEvent(KeyEvent.KEY_TYPED,
System.currentTimeMillis(),
0, KeyEvent.VK_UNDEFINED, c,
KeyEvent.KEY_LOCATION_UNKNOWN);
index++;
}
eventNotifier.notifyKeyEvent(KeyEvent.KEY_RELEASED,
System.currentTimeMillis(),
0, lastKeyPressCode, c,
KeyEvent.KEY_LOCATION_UNKNOWN);
}
}
/**
* Handles key events.
*/
void handleKeyEvent(int eventType, int modifierFlags, String chars,
String charsIgnoringModifiers, String charsIgnoringModifiersAndShift,
short keyCode, boolean needsKeyTyped, boolean needsKeyReleased) {
boolean isFlagsChangedEvent =
isNpapiCallback ? (eventType == CocoaConstants.NPCocoaEventFlagsChanged) :
(eventType == CocoaConstants.NSFlagsChanged);
int jeventType = KeyEvent.KEY_PRESSED;
int jkeyCode = KeyEvent.VK_UNDEFINED;
int jkeyLocation = KeyEvent.KEY_LOCATION_UNKNOWN;
boolean postsTyped = false;
boolean spaceKeyTyped = false;
int jmodifiers = NSEvent.nsToJavaModifiers(modifierFlags);
char testChar = KeyEvent.CHAR_UNDEFINED;
boolean isDeadChar = (chars!= null && chars.length() == 0);
if (isFlagsChangedEvent) {
int[] in = new int[] {modifierFlags, keyCode};
int[] out = new int[3]; // [jkeyCode, jkeyLocation, jkeyType]
NSEvent.nsKeyModifiersToJavaKeyInfo(in, out);
jkeyCode = out[0];
jkeyLocation = out[1];
jeventType = out[2];
} else {
if (chars != null && chars.length() > 0) {
testChar = chars.charAt(0);
//Check if String chars contains SPACE character.
if (chars.trim().isEmpty()) {
spaceKeyTyped = true;
}
}
// Workaround for JBR-2981
int metaAltCtrlMods = KeyEvent.META_DOWN_MASK | KeyEvent.ALT_DOWN_MASK | KeyEvent.CTRL_DOWN_MASK;
boolean metaAltCtrlAreNotPressed = (jmodifiers & metaAltCtrlMods) == 0;
boolean useShiftedCharacter = ((jmodifiers & KeyEvent.SHIFT_DOWN_MASK) == KeyEvent.SHIFT_DOWN_MASK) && metaAltCtrlAreNotPressed;
char testCharIgnoringModifiers = charsIgnoringModifiers != null && charsIgnoringModifiers.length() > 0 ?
charsIgnoringModifiers.charAt(0) : KeyEvent.CHAR_UNDEFINED;
if (!useShiftedCharacter && charsIgnoringModifiersAndShift != null && charsIgnoringModifiersAndShift.length() > 0) {
testCharIgnoringModifiers = charsIgnoringModifiersAndShift.charAt(0);
}
int useNationalLayouts = (KeyEventProcessing.useNationalLayouts && !isCyrillicKeyboardLayout()) ? 1 : 0;
int[] in = new int[] {testCharIgnoringModifiers, isDeadChar ? 1 : 0, modifierFlags, keyCode, useNationalLayouts};
int[] out = new int[3]; // [jkeyCode, jkeyLocation, deadChar]
postsTyped = NSEvent.nsToJavaKeyInfo(in, out);
if (!postsTyped) {
testChar = KeyEvent.CHAR_UNDEFINED;
}
if(isDeadChar){
testChar = (char) out[2];
jkeyCode = out[0];
if(testChar == 0 && jkeyCode == KeyEvent.VK_UNDEFINED){
return;
}
}
// If Pinyin Simplified input method is selected, CAPS_LOCK key is supposed to switch
// input to latin letters.
// It is necessary to use testCharIgnoringModifiers instead of testChar for event
// generation in such case to avoid uppercase letters in text components.
LWCToolkit lwcToolkit = (LWCToolkit)Toolkit.getDefaultToolkit();
if ((lwcToolkit.getLockingKeyState(KeyEvent.VK_CAPS_LOCK) &&
Locale.SIMPLIFIED_CHINESE.equals(lwcToolkit.getDefaultKeyboardLocale())) ||
((testChar != testCharIgnoringModifiers) &&
LWCToolkit.isCharModifierKeyInLocale(lwcToolkit.getDefaultKeyboardLocale(), testChar))) {
testChar = testCharIgnoringModifiers;
}
jkeyCode = out[0];
jkeyLocation = out[1];
jeventType = isNpapiCallback ? NSEvent.npToJavaEventType(eventType) :
NSEvent.nsToJavaEventType(eventType);
}
char javaChar = NSEvent.nsToJavaChar(testChar, modifierFlags, spaceKeyTyped);
// Some keys may generate a KEY_TYPED, but we can't determine
// what that character is. That's likely a bug, but for now we
// just check for CHAR_UNDEFINED.
if (javaChar == KeyEvent.CHAR_UNDEFINED) {
postsTyped = false;
}
long when = System.currentTimeMillis();
if (jeventType == KeyEvent.KEY_PRESSED) {
lastKeyPressCode = jkeyCode;
}
eventNotifier.notifyKeyEvent(jeventType, when, jmodifiers,
jkeyCode, javaChar, jkeyLocation);
// Current browser may be sending input events, so don't
// post the KEY_TYPED here.
postsTyped &= needsKeyTyped;
// That's the reaction on the PRESSED (not RELEASED) event as it comes to
// appear in MacOSX.
// Modifier keys (shift, etc) don't want to send TYPED events.
// On the other hand we don't want to generate keyTyped events
// for clipboard related shortcuts like Meta + [CVX]
if (jeventType == KeyEvent.KEY_PRESSED && postsTyped &&
(jmodifiers & KeyEvent.META_DOWN_MASK) == 0) {
// Enter and Space keys finish the input method processing,
// KEY_TYPED and KEY_RELEASED events for them are synthesized in handleInputEvent.
if (needsKeyReleased && (jkeyCode == KeyEvent.VK_ENTER || jkeyCode == KeyEvent.VK_SPACE)) {
return;
}
eventNotifier.notifyKeyEvent(KeyEvent.KEY_TYPED, when, jmodifiers,
KeyEvent.VK_UNDEFINED, javaChar,
KeyEvent.KEY_LOCATION_UNKNOWN);
//If events come from Firefox, released events should also be generated.
if (needsKeyReleased) {
eventNotifier.notifyKeyEvent(KeyEvent.KEY_RELEASED, when, jmodifiers,
jkeyCode, javaChar,
KeyEvent.KEY_LOCATION_UNKNOWN);
}
}
}
void handleWindowFocusEvent(boolean gained, LWWindowPeer opposite) {
eventNotifier.notifyActivation(gained, opposite);
}
static class DeltaAccumulator {
double accumulatedDelta;
boolean accumulate;
int getRoundedDelta(double delta, int scrollPhase) {
int roundDelta = (int) Math.round(delta);
if (scrollPhase == NSEvent.SCROLL_PHASE_UNSUPPORTED) { // mouse wheel
if (roundDelta == 0 && delta != 0) {
roundDelta = delta > 0 ? 1 : -1;
}
} else { // trackpad
if (scrollPhase == NSEvent.SCROLL_PHASE_BEGAN) {
accumulatedDelta = 0;
accumulate = true;
}
else if (scrollPhase == NSEvent.SCROLL_PHASE_MOMENTUM_BEGAN) {
accumulate = true;
}
if (accumulate) {
accumulatedDelta += delta;
roundDelta = (int) Math.round(accumulatedDelta);
accumulatedDelta -= roundDelta;
if (scrollPhase == NSEvent.SCROLL_PHASE_ENDED) {
accumulate = false;
}
}
}
return roundDelta;
}
}
}
| JetBrains/JetBrainsRuntime | src/java.desktop/macosx/classes/sun/lwawt/macosx/CPlatformResponder.java | 4,563 | // [jkeyCode, jkeyLocation, jkeyType] | line_comment | nl | /*
* Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.lwawt.macosx;
import sun.awt.SunToolkit;
import sun.awt.event.KeyEventProcessing;
import sun.lwawt.LWWindowPeer;
import sun.lwawt.PlatformEventNotifier;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.event.InputEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.KeyEvent;
import java.util.Arrays;
import java.util.Locale;
/**
* Translates NSEvents/NPCocoaEvents into AWT events.
*/
final class CPlatformResponder {
private final PlatformEventNotifier eventNotifier;
private final boolean isNpapiCallback;
private int lastKeyPressCode = KeyEvent.VK_UNDEFINED;
private final DeltaAccumulator deltaAccumulatorX = new DeltaAccumulator();
private final DeltaAccumulator deltaAccumulatorY = new DeltaAccumulator();
private boolean momentumStarted;
private int momentumX;
private int momentumY;
private int momentumModifiers;
private int lastDraggedAbsoluteX;
private int lastDraggedAbsoluteY;
private int lastDraggedRelativeX;
private int lastDraggedRelativeY;
CPlatformResponder(final PlatformEventNotifier eventNotifier,
final boolean isNpapiCallback) {
this.eventNotifier = eventNotifier;
this.isNpapiCallback = isNpapiCallback;
}
/**
* Handles mouse events.
*/
void handleMouseEvent(int eventType, int modifierFlags, int buttonNumber,
int clickCount, int x, int y, int absX, int absY) {
final SunToolkit tk = (SunToolkit)Toolkit.getDefaultToolkit();
if ((buttonNumber > 2 && !tk.areExtraMouseButtonsEnabled())
|| buttonNumber > tk.getNumberOfButtons() - 1) {
return;
}
int jeventType = isNpapiCallback ? NSEvent.npToJavaEventType(eventType) :
NSEvent.nsToJavaEventType(eventType);
boolean dragged = jeventType == MouseEvent.MOUSE_DRAGGED;
if (dragged // ignore dragged event that does not change any location
&& lastDraggedAbsoluteX == absX && lastDraggedRelativeX == x
&& lastDraggedAbsoluteY == absY && lastDraggedRelativeY == y) return;
if (dragged || jeventType == MouseEvent.MOUSE_PRESSED) {
lastDraggedAbsoluteX = absX;
lastDraggedAbsoluteY = absY;
lastDraggedRelativeX = x;
lastDraggedRelativeY = y;
}
int jbuttonNumber = MouseEvent.NOBUTTON;
int jclickCount = 0;
if (jeventType != MouseEvent.MOUSE_MOVED &&
jeventType != MouseEvent.MOUSE_ENTERED &&
jeventType != MouseEvent.MOUSE_EXITED)
{
jbuttonNumber = NSEvent.nsToJavaButton(buttonNumber);
jclickCount = clickCount;
}
int jmodifiers = NSEvent.nsToJavaModifiers(modifierFlags);
boolean jpopupTrigger = NSEvent.isPopupTrigger(jmodifiers);
eventNotifier.notifyMouseEvent(jeventType, System.currentTimeMillis(), jbuttonNumber,
x, y, absX, absY, jmodifiers, jclickCount,
jpopupTrigger, null);
}
/**
* Handles scroll events.
*/
void handleScrollEvent(int x, int y, final int absX,
final int absY, final int modifierFlags,
final double deltaX, final double deltaY,
final int scrollPhase) {
int jmodifiers = NSEvent.nsToJavaModifiers(modifierFlags);
if (scrollPhase > NSEvent.SCROLL_PHASE_UNSUPPORTED) {
if (scrollPhase == NSEvent.SCROLL_PHASE_BEGAN) {
momentumStarted = false;
} else if (scrollPhase == NSEvent.SCROLL_PHASE_MOMENTUM_BEGAN) {
momentumStarted = true;
momentumX = x;
momentumY = y;
momentumModifiers = jmodifiers;
} else if (momentumStarted) {
x = momentumX;
y = momentumY;
jmodifiers = momentumModifiers;
}
}
final boolean isShift = (jmodifiers & InputEvent.SHIFT_DOWN_MASK) != 0;
int roundDeltaX = deltaAccumulatorX.getRoundedDelta(deltaX, scrollPhase);
int roundDeltaY = deltaAccumulatorY.getRoundedDelta(deltaY, scrollPhase);
// Vertical scroll.
if (!isShift && (deltaY != 0.0 || roundDeltaY != 0)) {
dispatchScrollEvent(x, y, absX, absY, jmodifiers, roundDeltaY, deltaY);
}
// Horizontal scroll or shirt+vertical scroll.
final double delta = isShift && deltaY != 0.0 ? deltaY : deltaX;
final int roundDelta = isShift && roundDeltaY != 0 ? roundDeltaY : roundDeltaX;
if (delta != 0.0 || roundDelta != 0) {
jmodifiers |= InputEvent.SHIFT_DOWN_MASK;
dispatchScrollEvent(x, y, absX, absY, jmodifiers, roundDelta, delta);
}
}
private void dispatchScrollEvent(final int x, final int y, final int absX,
final int absY, final int modifiers,
final int roundDelta, final double delta) {
final long when = System.currentTimeMillis();
final int scrollType = MouseWheelEvent.WHEEL_UNIT_SCROLL;
final int scrollAmount = 1;
// invert the wheelRotation for the peer
eventNotifier.notifyMouseWheelEvent(when, x, y, absX, absY, modifiers,
scrollType, scrollAmount,
-roundDelta, -delta, null);
}
private static final String [] cyrillicKeyboardLayouts = new String [] {
"com.apple.keylayout.Russian",
"com.apple.keylayout.RussianWin",
"com.apple.keylayout.Russian-Phonetic",
"com.apple.keylayout.Byelorussian",
"com.apple.keylayout.Ukrainian",
"com.apple.keylayout.UkrainianWin",
"com.apple.keylayout.Bulgarian",
"com.apple.keylayout.Serbian"
};
private static boolean isCyrillicKeyboardLayout() {
return Arrays.stream(cyrillicKeyboardLayouts).anyMatch(l -> l.equals(LWCToolkit.getKeyboardLayoutId()));
}
void handleInputEvent(String text) {
if (text != null) {
int index = 0, length = text.length();
char c = 0;
while (index < length) {
c = text.charAt(index);
eventNotifier.notifyKeyEvent(KeyEvent.KEY_TYPED,
System.currentTimeMillis(),
0, KeyEvent.VK_UNDEFINED, c,
KeyEvent.KEY_LOCATION_UNKNOWN);
index++;
}
eventNotifier.notifyKeyEvent(KeyEvent.KEY_RELEASED,
System.currentTimeMillis(),
0, lastKeyPressCode, c,
KeyEvent.KEY_LOCATION_UNKNOWN);
}
}
/**
* Handles key events.
*/
void handleKeyEvent(int eventType, int modifierFlags, String chars,
String charsIgnoringModifiers, String charsIgnoringModifiersAndShift,
short keyCode, boolean needsKeyTyped, boolean needsKeyReleased) {
boolean isFlagsChangedEvent =
isNpapiCallback ? (eventType == CocoaConstants.NPCocoaEventFlagsChanged) :
(eventType == CocoaConstants.NSFlagsChanged);
int jeventType = KeyEvent.KEY_PRESSED;
int jkeyCode = KeyEvent.VK_UNDEFINED;
int jkeyLocation = KeyEvent.KEY_LOCATION_UNKNOWN;
boolean postsTyped = false;
boolean spaceKeyTyped = false;
int jmodifiers = NSEvent.nsToJavaModifiers(modifierFlags);
char testChar = KeyEvent.CHAR_UNDEFINED;
boolean isDeadChar = (chars!= null && chars.length() == 0);
if (isFlagsChangedEvent) {
int[] in = new int[] {modifierFlags, keyCode};
int[] out = new int[3]; // [jkeyCode, jkeyLocation,<SUF>
NSEvent.nsKeyModifiersToJavaKeyInfo(in, out);
jkeyCode = out[0];
jkeyLocation = out[1];
jeventType = out[2];
} else {
if (chars != null && chars.length() > 0) {
testChar = chars.charAt(0);
//Check if String chars contains SPACE character.
if (chars.trim().isEmpty()) {
spaceKeyTyped = true;
}
}
// Workaround for JBR-2981
int metaAltCtrlMods = KeyEvent.META_DOWN_MASK | KeyEvent.ALT_DOWN_MASK | KeyEvent.CTRL_DOWN_MASK;
boolean metaAltCtrlAreNotPressed = (jmodifiers & metaAltCtrlMods) == 0;
boolean useShiftedCharacter = ((jmodifiers & KeyEvent.SHIFT_DOWN_MASK) == KeyEvent.SHIFT_DOWN_MASK) && metaAltCtrlAreNotPressed;
char testCharIgnoringModifiers = charsIgnoringModifiers != null && charsIgnoringModifiers.length() > 0 ?
charsIgnoringModifiers.charAt(0) : KeyEvent.CHAR_UNDEFINED;
if (!useShiftedCharacter && charsIgnoringModifiersAndShift != null && charsIgnoringModifiersAndShift.length() > 0) {
testCharIgnoringModifiers = charsIgnoringModifiersAndShift.charAt(0);
}
int useNationalLayouts = (KeyEventProcessing.useNationalLayouts && !isCyrillicKeyboardLayout()) ? 1 : 0;
int[] in = new int[] {testCharIgnoringModifiers, isDeadChar ? 1 : 0, modifierFlags, keyCode, useNationalLayouts};
int[] out = new int[3]; // [jkeyCode, jkeyLocation, deadChar]
postsTyped = NSEvent.nsToJavaKeyInfo(in, out);
if (!postsTyped) {
testChar = KeyEvent.CHAR_UNDEFINED;
}
if(isDeadChar){
testChar = (char) out[2];
jkeyCode = out[0];
if(testChar == 0 && jkeyCode == KeyEvent.VK_UNDEFINED){
return;
}
}
// If Pinyin Simplified input method is selected, CAPS_LOCK key is supposed to switch
// input to latin letters.
// It is necessary to use testCharIgnoringModifiers instead of testChar for event
// generation in such case to avoid uppercase letters in text components.
LWCToolkit lwcToolkit = (LWCToolkit)Toolkit.getDefaultToolkit();
if ((lwcToolkit.getLockingKeyState(KeyEvent.VK_CAPS_LOCK) &&
Locale.SIMPLIFIED_CHINESE.equals(lwcToolkit.getDefaultKeyboardLocale())) ||
((testChar != testCharIgnoringModifiers) &&
LWCToolkit.isCharModifierKeyInLocale(lwcToolkit.getDefaultKeyboardLocale(), testChar))) {
testChar = testCharIgnoringModifiers;
}
jkeyCode = out[0];
jkeyLocation = out[1];
jeventType = isNpapiCallback ? NSEvent.npToJavaEventType(eventType) :
NSEvent.nsToJavaEventType(eventType);
}
char javaChar = NSEvent.nsToJavaChar(testChar, modifierFlags, spaceKeyTyped);
// Some keys may generate a KEY_TYPED, but we can't determine
// what that character is. That's likely a bug, but for now we
// just check for CHAR_UNDEFINED.
if (javaChar == KeyEvent.CHAR_UNDEFINED) {
postsTyped = false;
}
long when = System.currentTimeMillis();
if (jeventType == KeyEvent.KEY_PRESSED) {
lastKeyPressCode = jkeyCode;
}
eventNotifier.notifyKeyEvent(jeventType, when, jmodifiers,
jkeyCode, javaChar, jkeyLocation);
// Current browser may be sending input events, so don't
// post the KEY_TYPED here.
postsTyped &= needsKeyTyped;
// That's the reaction on the PRESSED (not RELEASED) event as it comes to
// appear in MacOSX.
// Modifier keys (shift, etc) don't want to send TYPED events.
// On the other hand we don't want to generate keyTyped events
// for clipboard related shortcuts like Meta + [CVX]
if (jeventType == KeyEvent.KEY_PRESSED && postsTyped &&
(jmodifiers & KeyEvent.META_DOWN_MASK) == 0) {
// Enter and Space keys finish the input method processing,
// KEY_TYPED and KEY_RELEASED events for them are synthesized in handleInputEvent.
if (needsKeyReleased && (jkeyCode == KeyEvent.VK_ENTER || jkeyCode == KeyEvent.VK_SPACE)) {
return;
}
eventNotifier.notifyKeyEvent(KeyEvent.KEY_TYPED, when, jmodifiers,
KeyEvent.VK_UNDEFINED, javaChar,
KeyEvent.KEY_LOCATION_UNKNOWN);
//If events come from Firefox, released events should also be generated.
if (needsKeyReleased) {
eventNotifier.notifyKeyEvent(KeyEvent.KEY_RELEASED, when, jmodifiers,
jkeyCode, javaChar,
KeyEvent.KEY_LOCATION_UNKNOWN);
}
}
}
void handleWindowFocusEvent(boolean gained, LWWindowPeer opposite) {
eventNotifier.notifyActivation(gained, opposite);
}
static class DeltaAccumulator {
double accumulatedDelta;
boolean accumulate;
int getRoundedDelta(double delta, int scrollPhase) {
int roundDelta = (int) Math.round(delta);
if (scrollPhase == NSEvent.SCROLL_PHASE_UNSUPPORTED) { // mouse wheel
if (roundDelta == 0 && delta != 0) {
roundDelta = delta > 0 ? 1 : -1;
}
} else { // trackpad
if (scrollPhase == NSEvent.SCROLL_PHASE_BEGAN) {
accumulatedDelta = 0;
accumulate = true;
}
else if (scrollPhase == NSEvent.SCROLL_PHASE_MOMENTUM_BEGAN) {
accumulate = true;
}
if (accumulate) {
accumulatedDelta += delta;
roundDelta = (int) Math.round(accumulatedDelta);
accumulatedDelta -= roundDelta;
if (scrollPhase == NSEvent.SCROLL_PHASE_ENDED) {
accumulate = false;
}
}
}
return roundDelta;
}
}
}
|
151571_22 | /*
* Copyright 2003-2024 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.mps.ide.projectPane;
import com.intellij.ide.CopyProvider;
import com.intellij.ide.CutProvider;
import com.intellij.ide.PasteProvider;
import com.intellij.ide.dnd.aware.DnDAwareTree;
import com.intellij.ide.projectView.ProjectView;
import com.intellij.ide.projectView.impl.BaseProjectViewPaneWithAsyncSupport;
import com.intellij.ide.projectView.impl.ProjectViewState;
import com.intellij.ide.util.treeView.AbstractTreeStructureBase;
import com.intellij.openapi.actionSystem.ActionPlaces;
import com.intellij.openapi.actionSystem.ActionUpdateThread;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.DefaultActionGroup;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.ActionCallback;
import com.intellij.openapi.vcs.VcsDataKeys;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.concurrency.EdtExecutorService;
import com.intellij.util.containers.ContainerUtil;
import jetbrains.mps.classloading.ClassLoaderManager;
import jetbrains.mps.classloading.DeployListener;
import jetbrains.mps.extapi.persistence.FileSystemBasedDataSource;
import jetbrains.mps.generator.TransientModelsModule;
import jetbrains.mps.ide.actions.CopyNode_Action;
import jetbrains.mps.ide.actions.CutNode_Action;
import jetbrains.mps.ide.actions.PasteNode_Action;
import jetbrains.mps.ide.actions.SModelActionData;
import jetbrains.mps.ide.actions.SModuleActionData;
import jetbrains.mps.ide.actions.SNodeActionData;
import jetbrains.mps.ide.project.ProjectHelper;
import jetbrains.mps.ide.ui.tree.ContextValueProvider;
import jetbrains.mps.ide.ui.tree.VirtualFolder;
import jetbrains.mps.ide.ui.tree.VirtualFolder.Models;
import jetbrains.mps.ide.ui.tree.VirtualFolder.Modules;
import jetbrains.mps.ide.ui.tree.VirtualFolder.Nodes;
import jetbrains.mps.ide.ui.tree.smodel.PackageNode;
import jetbrains.mps.ide.vfs.FileSystemBridge;
import jetbrains.mps.ide.vfs.IdeaFileSystem;
import jetbrains.mps.logging.Logger;
import jetbrains.mps.make.IMakeNotificationListener;
import jetbrains.mps.make.IMakeNotificationListener.Stub;
import jetbrains.mps.make.MakeNotification;
import jetbrains.mps.make.MakeServiceComponent;
import jetbrains.mps.module.ReloadableModule;
import jetbrains.mps.project.AbstractModule;
import jetbrains.mps.project.DevKit;
import jetbrains.mps.project.MPSProject;
import jetbrains.mps.project.Solution;
import jetbrains.mps.smodel.Generator;
import jetbrains.mps.smodel.Language;
import jetbrains.mps.smodel.RepoListenerRegistrar;
import jetbrains.mps.smodel.SModelAdapter;
import jetbrains.mps.smodel.SModelInternal;
import jetbrains.mps.smodel.tempmodel.TempModule;
import jetbrains.mps.smodel.tempmodel.TempModule2;
import jetbrains.mps.util.Pair;
import jetbrains.mps.vfs.IFile;
import jetbrains.mps.workbench.ActionPlace;
import jetbrains.mps.workbench.FileSystemModelHelper;
import jetbrains.mps.workbench.MPSDataKeys;
import jetbrains.mps.workbench.action.ActionUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.mps.openapi.model.SModel;
import org.jetbrains.mps.openapi.model.SModelReference;
import org.jetbrains.mps.openapi.model.SNode;
import org.jetbrains.mps.openapi.module.SModule;
import org.jetbrains.mps.openapi.module.SModuleReference;
import org.jetbrains.mps.openapi.module.SRepository;
import org.jetbrains.mps.openapi.module.SRepositoryContentAdapter;
import org.jetbrains.mps.openapi.persistence.DataSource;
import org.jetbrains.mps.openapi.repository.CommandListener;
import org.jetbrains.mps.openapi.util.ProgressMonitor;
import javax.swing.JTree;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
public abstract class BaseLogicalViewProjectPane extends BaseProjectViewPaneWithAsyncSupport {
private static final Logger LOG = Logger.getLogger(BaseLogicalViewProjectPane.class);
private final MyRepositoryListener myRepositoryListener = new MyRepositoryListener();
private final MyModelChangeListener myModelChangeListener = new MyModelChangeListener();
protected boolean myDisposed;
private final DeployListener myClassesListener = new DeployListener() {
@Override
public void onUnloaded(@NotNull Set<ReloadableModule> unloadedModules, @NotNull ProgressMonitor monitor) {
}
@Override
public void onLoaded(@NotNull Set<ReloadableModule> loadedModules, @NotNull ProgressMonitor monitor) {
rebuild();
}
};
private final IMakeNotificationListener myMakeNotificationListener = new Stub() {
@Override
public void sessionClosed(MakeNotification notification) {
// rebuild tree in case of 'cancel' too (need to get 'transient models' node rebuilt)
rebuild();
}
};
@Override
public @NotNull ActionCallback selectCB(Object element, VirtualFile file, boolean requestFocus) {
ActionCallback callback = new ActionCallback();
EdtExecutorService.getScheduledExecutorInstance()
.schedule(() -> super.selectCB(element, file, requestFocus).notify(callback), 100, TimeUnit.MILLISECONDS);
return callback;
}
/**
* Intentionally made non-abstract to enable compilation of dependent code.
*/
@Override
protected @NotNull AbstractTreeStructureBase createStructure() {
throw new UnsupportedOperationException("no implementation provided");
}
/**
* Intentionally made non-abstract to enable compilation of dependent code.
*/
@Override
protected @NotNull DnDAwareTree createTree(@NotNull DefaultTreeModel treeModel) {
throw new UnsupportedOperationException("no implementation provided");
}
protected BaseLogicalViewProjectPane(Project project) {
super(project);
}
public Project getProject() {
return myProject;
}
public ProjectView getProjectView() {
return ProjectView.getInstance(myProject);
}
/*package*/ ProjectViewState getProjectViewState() {
// FIXME
return ProjectViewState.getInstance(getProject());
}
protected void forEachFile(SModule module, Consumer<IFile> fun) {
if (module instanceof AbstractModule) {
IFile iFile = ((AbstractModule) module).getDescriptorFile();
fun.accept(iFile);
}
}
protected void forEachFile(SModel model, Consumer<IFile> fun) {
DataSource source = model.getSource();
if (source instanceof FileSystemBasedDataSource) {
for (IFile iFile : ((FileSystemBasedDataSource) source).getAffectedFiles()) {
fun.accept(iFile);
}
}
}
@SuppressWarnings("removal")
protected void updateFrom(IFile iFile, boolean updateStructure) {
MPSProject mpsProject = ProjectHelper.fromIdeaProject(getProject());
IdeaFileSystem fileSystem = mpsProject.getFileSystem();
VirtualFile virtualFile = fileSystem.asVirtualFile(iFile);
if (virtualFile != null) {
updateFrom(virtualFile, false, updateStructure);
}
}
public abstract void rebuild();
@Override
public Object getData(@NotNull String dataId) {
if (SNodeActionData.KEY.is(dataId)) {
List<SNode> nodes = ContainerUtil.filterIsInstance(getSelectedValues(getSelectedUserObjects()), SNode.class);
if (nodes.isEmpty()) {
return null;
} else if (nodes.size() == 1) {
return SNodeActionData.from(nodes.get(0).getReference());
} else {
return SNodeActionData.from(nodes.stream().map(SNode::getReference));
}
}
if (SModelActionData.KEY.is(dataId)) {
List<SModel> models = ContainerUtil.filterIsInstance(getSelectedValues(getSelectedUserObjects()), SModel.class);
if (models.isEmpty()) {
return null;
} else if (models.size() == 1) {
return SModelActionData.from(models.get(0).getReference());
} else {
return SModelActionData.from(models.stream().map(SModel::getReference));
}
}
if (SModuleActionData.KEY.is(dataId)) {
List<SModule> modules = ContainerUtil.filterIsInstance(getSelectedValues(getSelectedUserObjects()), SModule.class);
if (modules.isEmpty()) {
return null;
} else if (modules.size() == 1) {
return SModuleActionData.from(modules.get(0).getModuleReference());
} else {
return SModuleActionData.from(modules.stream().map(SModule::getModuleReference));
}
}
//MPSDK
if (MPSDataKeys.CONTEXT_MODEL.is(dataId)) {
return getContextModel();
}
if (MPSDataKeys.CONTEXT_MODULE.is(dataId)) {
return getContextModule();
}
if (MPSDataKeys.VIRTUAL_PACKAGES.is(dataId)) {
// FIXME getSelectedPackages() requires model read (resolves model references)
final List<Pair<SModel, String>> rv = getSelectedPackages();
return rv.isEmpty() ? null : rv;
}
if (MPSDataKeys.NAMESPACE.is(dataId)) {
Object firstSelected = Arrays.stream(getSelectedValues(getSelectedUserObjects())).findFirst().orElseGet(() -> null);
if (firstSelected instanceof VirtualFolder) {
return ((VirtualFolder)firstSelected).getName();
}
return null;
}
if (MPSDataKeys.USER_OBJECT.is(dataId)) {
return Arrays.stream(getSelectedUserObjects()).findFirst().orElseGet(() -> null);
}
if (MPSDataKeys.USER_OBJECTS.is(dataId)) {
return Arrays.asList(getSelectedUserObjects());
}
if (MPSDataKeys.VALUE.is(dataId)) {
return Arrays.stream(getSelectedValues(getSelectedUserObjects())).findFirst().orElseGet(() -> null);
}
if (MPSDataKeys.VALUES.is(dataId)) {
return Arrays.asList(getSelectedValues(getSelectedUserObjects()));
}
if (MPSDataKeys.TREE_SELECTION_SIZE.is(dataId)) {
return getSelectionSize();
}
if (MPSDataKeys.PLACE.is(dataId)) {
return getPlace(Arrays.stream(getSelectedValues(getSelectedUserObjects())).findFirst().orElseGet(() -> null));
}
//PDK
if (PlatformDataKeys.COPY_PROVIDER.is(dataId)) {
return new MyCopyProvider();
}
if (PlatformDataKeys.PASTE_PROVIDER.is(dataId)) {
return new MyPasteProvider();
}
if (PlatformDataKeys.CUT_PROVIDER.is(dataId)) {
return new MyCutProvider();
}
if (PlatformDataKeys.VIRTUAL_FILE_ARRAY.is(dataId)) {
// XXX perhaps, has to move to SLOW_DATA_PROVIDERS (i.e. collect selected elements in EDT and return
// another DataProvider instance that would transformed selected models/modules into VirtualFile?
return getSelectedFiles(true, true);
}
if (VcsDataKeys.VIRTUAL_FILES.is(dataId)) {
VirtualFile[] selection = getSelectedFiles(false, true);
return selection != null ? Arrays.asList(selection) : null;
}
// if project pane doesn't answer its Project, chances are some LocationRule could start looking
// for a project in inappropriate DataProvider, and end up producing MPSLocation solely with MPSProject
// (as it could not obtain node/model/module from any other DataProvider in Project View hierarchy)
if (CommonDataKeys.PROJECT.is(dataId)) {
return getProject();
}
if (MPSDataKeys.MPS_PROJECT.is(dataId)) {
return ProjectHelper.fromIdeaProject(getProject());
}
//not found
return super.getData(dataId);
}
public boolean isDisposed() {
return myDisposed;
}
@Override
public void dispose() {
if (isComponentCreated()) {
removeListeners();
}
myDisposed = true;
super.dispose();
}
public boolean showNodeStructure() {
// re-use IDEA's 'show members' for 'show node structure'
return !isDisposed() && getProjectView().isShowMembers(getId());
}
/**
* @deprecated use {@link jetbrains.mps.ide.projectView.MPSProjectViewSettings} instead.
*/
@Deprecated
public boolean isSortByConcept() {
return getProjectViewState().getSortByType();
}
@Override
public void installComparator() {
// FIXME why is this NOP?
// Overrode to avoid NPE
}
@Override
public boolean supportsSortByType() {
return true;
}
@Override
public boolean supportsManualOrder() {
return false;
}
@Override
public boolean supportsSortByTime() {
return false;
}
@Override
public void addToolbarActions(final DefaultActionGroup group) {
super.addToolbarActions(group);
}
protected void removeListeners() {
jetbrains.mps.project.Project mpsProject = ProjectHelper.fromIdeaProject(getProject());
mpsProject.getComponent(ClassLoaderManager.class).removeListener(myClassesListener);
mpsProject.getModelAccess().removeCommandListener(myRepositoryListener);
new RepoListenerRegistrar(mpsProject.getRepository(), myRepositoryListener).detach();
mpsProject.getComponent(MakeServiceComponent.class).get().removeListener(myMakeNotificationListener);
}
protected void addListeners() {
jetbrains.mps.project.Project mpsProject = ProjectHelper.fromIdeaProject(getProject());
new RepoListenerRegistrar(mpsProject.getRepository(), myRepositoryListener).attach();
mpsProject.getModelAccess().addCommandListener(myRepositoryListener);
// XXX here used to be a hasMakeService() check, which I found superfluous,
// as we always have make service in UI (at least, we never check for it in other locations)
// However, the idea to keep listeners inside MakeServiceComponent and install them into active
// IMakeService once it's updated looks nice
mpsProject.getComponent(MakeServiceComponent.class).get().addListener(myMakeNotificationListener);
mpsProject.getComponent(ClassLoaderManager.class).addListener(myClassesListener);
}
/**
* expects model read lock at least
*
* @deprecated don't use, prefer {@code SNodeReference} and {@code DataContext.getData()}
*/
@Deprecated(forRemoval = true, since = "2021.3")
public SNode getSelectedSNode() {
List<SNode> result = getSelectedSNodes();
if (result.size() != 1) {
return null;
}
return result.get(0);
}
/**
* NB! The implementation of this method has been altered to rely on the modern implementation of underlying
* tree. The following comments may not be relevant.
* <p>
* expects model read lock at least
*
* @deprecated don't use, prefer {@code SNodeReference} and {@code DataContext.getData()}
*/
@NotNull
@Deprecated(forRemoval = true, since = "2021.3")
public List<SNode> getSelectedSNodes() {
return ContainerUtil.filterIsInstance(getSelectedValues(getSelectedUserObjects()), SNode.class);
}
@NotNull
public List<SModel> getSelectedModels() {
return ContainerUtil.filterIsInstance(getSelectedValues(getSelectedUserObjects()), SModel.class);
}
@Nullable
public SModel getSelectedModel() {
return ContainerUtil.findInstance(getSelectedValues(getSelectedUserObjects()), SModel.class);
}
@Nullable
public SModel getContextModel() {
@Nullable Object[] userObjects = getSingleSelectedPathUserObjects();
if (userObjects == null || userObjects.length == 0) {
return null;
}
Object lastUserObject = userObjects[userObjects.length - 1];
if (lastUserObject instanceof ContextValueProvider) {
return ((ContextValueProvider) lastUserObject).contextValueOfType(SModel.class).orElseGet(() -> null);
}
return null;
}
@NotNull
public List<SModule> getSelectedModules() {
return ContainerUtil.filterIsInstance(getSelectedValues(getSelectedUserObjects()), SModule.class);
}
@Nullable
public SModule getContextModule() {
@Nullable Object[] userObjects = getSingleSelectedPathUserObjects();
if (userObjects == null || userObjects.length == 0) {
return null;
}
Object lastUserObject = userObjects[userObjects.length - 1];
if (lastUserObject instanceof ContextValueProvider) {
return ((ContextValueProvider) lastUserObject).contextValueOfType(SModule.class).orElseGet(() -> null);
}
return null;
}
@NotNull
public List<Pair<SModel, String>> getSelectedPackages() {
// FIXME update the implementation or drop
JTree tree = getTree();
if (tree == null) {
return Collections.emptyList();
}
TreePath[] paths = tree.getSelectionPaths();
SRepository projectRepo = ProjectHelper.getProjectRepository(getProject());
if (paths == null || paths.length == 0 || projectRepo == null) {
return Collections.emptyList();
}
List<Pair<SModel, String>> result = new ArrayList<>();
for (TreePath path : paths) {
if (path.getLastPathComponent() instanceof PackageNode) {
PackageNode pn = (PackageNode) path.getLastPathComponent();
projectRepo.getModelAccess().runReadAction(new Runnable() {
@Override
public void run() {
result.add(new Pair<>(pn.getModelReference().resolve(projectRepo), pn.getFullPackage()));
}
});
}
}
return result;
}
public int getSelectionSize() {
TreePath[] selection = getSelectionPaths();
return selection == null ? 0 : selection.length;
}
protected ActionPlace getPlace(@Nullable Object selectedValue) {
if (selectedValue instanceof SNode) {
return ActionPlace.PROJECT_PANE_SNODE;
} else if (selectedValue instanceof SModel) {
return ActionPlace.PROJECT_PANE_SMODEL;
} else if (selectedValue instanceof MPSProject) {
return ActionPlace.PROJECT_PANE_PROJECT;
} else if (selectedValue instanceof Generator) {
return ActionPlace.PROJECT_PANE_GENERATOR;
} else if (selectedValue instanceof TransientModelsModule) {
return ActionPlace.PROJECT_PANE_TRANSIENT_MODULES;
} else if (selectedValue instanceof Nodes) {
return ActionPlace.PROJECT_PANE_PACKAGE;
} else if (selectedValue instanceof Models) {
return ActionPlace.PROJECT_PANE_NAMESPACE;
} else if (selectedValue instanceof Modules) {
return ActionPlace.PROJECT_PANE_NAMESPACE;
} else if (selectedValue instanceof Language) {
return ActionPlace.PROJECT_PANE_LANGUAGE;
} else if (selectedValue instanceof DevKit) {
return ActionPlace.PROJECT_PANE_DEVKIT;
} else if (selectedValue instanceof Solution) {
return ActionPlace.PROJECT_PANE_SOLUTION;
}
return null;
}
/**
* A simplified alternative to {@link #getSelectedTreeNodes(Class)}
* <p>
* NB! Both these methods deprecated and are to be removed in one of the upcoming releases.
* Please use other means to find the selected objects/values in the tree.
* The use of swing interfaces is discouraged, since they require the UI thread.
*/
@Nullable
@Deprecated(forRemoval = true)
protected final <T extends TreeNode> T getSelectedTreeNode(Class<T> nodeClass) {
JTree tree = getTree();
if (tree == null) {
return null;
}
TreePath selectionPath = tree.getSelectionPath();
if (selectionPath == null) {
return null;
}
Object selectedNode = selectionPath.getLastPathComponent();
return nodeClass.isInstance(selectedNode) ? nodeClass.cast(selectedNode) : null;
}
/**
* See {@link #getSelectedTreeNode(Class)}.
*
*/
@NotNull
@Deprecated(forRemoval = true)
public <T extends TreeNode> List<T> getSelectedTreeNodes(Class<T> nodeClass) {
JTree tree = getTree();
if (tree == null) {
return Collections.emptyList();
}
TreePath[] selectionPaths = tree.getSelectionPaths();
if (selectionPaths == null || selectionPaths.length == 0) {
return Collections.emptyList();
}
List<T> selectedTreeNodes = new ArrayList<>(selectionPaths.length);
for (TreePath selectionPath : selectionPaths) {
if (selectionPath == null) {
continue;
}
Object selectedNode = selectionPath.getLastPathComponent();
if (nodeClass.isInstance(selectedNode)) {
selectedTreeNodes.add(nodeClass.cast(selectedNode));
}
}
return selectedTreeNodes;
}
@Nullable
private VirtualFile[] getSelectedFiles(boolean addModuleFile, boolean addModuleDir) {
List<IFile> selectedFilesList = new LinkedList<>();
// add selected model files
List<SModel> descriptors = getSelectedModels();
if (descriptors != null) {
for (SModel descriptor : descriptors) {
selectedFilesList.addAll(new FileSystemModelHelper(descriptor).getFiles());
}
}
// add selected modules files
List<SModule> modules = getSelectedModules();
if (modules != null) {
for (SModule m : modules) {
if (!(m instanceof AbstractModule)) {
continue;
}
AbstractModule module = (AbstractModule) m;
IFile home = module.getModuleSourceDir();
if (home != null && addModuleDir) {
selectedFilesList.add(home);
}
IFile ifile = module.getDescriptorFile();
if (ifile != null && addModuleFile) {
selectedFilesList.add(ifile);
}
}
}
if (selectedFilesList.isEmpty()) {
return null;
}
final FileSystemBridge fs = ProjectHelper.fromIdeaProject(myProject).getFileSystem();
return selectedFilesList.stream().map(fs::asVirtualFile).filter(Objects::nonNull).toArray(VirtualFile[]::new);
}
/*package*/
static AnActionEvent createEvent(DataContext context) {
return ActionUtils.createEvent(ActionPlaces.PROJECT_VIEW_POPUP, context);
}
protected abstract boolean isComponentCreated();
private static class MyCopyProvider implements CopyProvider {
private CopyNode_Action myAction = new CopyNode_Action();
@Override
public void performCopy(@NotNull DataContext dataContext) {
AnActionEvent event = createEvent(dataContext);
ActionUtils.updateAndPerformAction(myAction, event);
}
@Override
public boolean isCopyEnabled(@NotNull DataContext dataContext) {
AnActionEvent event = createEvent(dataContext);
myAction.update(event);
return event.getPresentation().isEnabled();
}
@Override
public boolean isCopyVisible(@NotNull DataContext dataContext) {
return true;
}
@Override
@NotNull
public ActionUpdateThread getActionUpdateThread() {
return myAction.getActionUpdateThread();
}
}
private static class MyPasteProvider implements PasteProvider {
private PasteNode_Action myAction = new PasteNode_Action();
@Override
public void performPaste(@NotNull DataContext dataContext) {
AnActionEvent event = createEvent(dataContext);
ActionUtils.updateAndPerformAction(myAction, event);
}
@Override
public boolean isPastePossible(@NotNull DataContext dataContext) {
return true;
}
@Override
public boolean isPasteEnabled(@NotNull DataContext dataContext) {
AnActionEvent event = createEvent(dataContext);
myAction.update(event);
return event.getPresentation().isEnabled();
}
@Override
@NotNull
public ActionUpdateThread getActionUpdateThread() {
// PasteNode_Action update uses EDT, is it correct?
return myAction.getActionUpdateThread();
}
}
private static class MyCutProvider implements CutProvider {
private CutNode_Action myAction = new CutNode_Action();
@Override
public void performCut(@NotNull DataContext dataContext) {
AnActionEvent event = createEvent(dataContext);
ActionUtils.updateAndPerformAction(myAction, event);
}
@Override
public boolean isCutEnabled(@NotNull DataContext dataContext) {
AnActionEvent event = createEvent(dataContext);
myAction.update(event);
return event.getPresentation().isEnabled();
}
@Override
public boolean isCutVisible(@NotNull DataContext dataContext) {
return true;
}
@Override
@NotNull
public ActionUpdateThread getActionUpdateThread() {
return myAction.getActionUpdateThread();
}
}
private class MyRepositoryListener extends SRepositoryContentAdapter implements CommandListener {
@Override
protected void startListening(SModel model) {
model.addModelListener(this);
((SModelInternal) model).addModelListener(myModelChangeListener);
}
@Override
protected void stopListening(SModel model) {
model.removeModelListener(this);
((SModelInternal) model).removeModelListener(myModelChangeListener);
}
@Override
public void moduleAdded(@NotNull SModule module) {
if (!(module instanceof TempModule || module instanceof TempModule2)) {
updateFromRoot(true);
}
}
@Override
public void moduleRenamed(@NotNull SModule module, @NotNull SModuleReference oldRef) {
updateFromRoot(true);
}
@Override
public void beforeModuleRemoved(@NotNull SModule module) {
if (!(module instanceof TempModule || module instanceof TempModule2)) {
updateFromRoot(true);
}
}
@Override
public void modelRenamed(SModule module, SModel model, SModelReference oldRef) {
forEachFile(module, f -> updateFrom(f, true));
}
@Override
public void modelRemoved(SModule module, SModelReference ref) {
forEachFile(module, f -> updateFrom(f, true));
}
@Override
public void modelAdded(SModule module, SModel model) {
forEachFile(module, f -> updateFrom(f, true));
}
@Override
public void modelReplaced(SModel model) {
forEachFile(model, f -> updateFrom(f, true));
}
}
private class MyModelChangeListener extends SModelAdapter {
@Override
public void modelChangedDramatically(SModel model) {
forEachFile(model, f -> updateFrom(f, true));
}
@Override
public void modelChanged(SModel model) {
forEachFile(model, f -> updateFrom(f, true));
}
}
}
| JetBrains/MPS | workbench/mps-workbench/source/jetbrains/mps/ide/projectPane/BaseLogicalViewProjectPane.java | 7,923 | /**
* See {@link #getSelectedTreeNode(Class)}.
*
*/ | block_comment | nl | /*
* Copyright 2003-2024 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.mps.ide.projectPane;
import com.intellij.ide.CopyProvider;
import com.intellij.ide.CutProvider;
import com.intellij.ide.PasteProvider;
import com.intellij.ide.dnd.aware.DnDAwareTree;
import com.intellij.ide.projectView.ProjectView;
import com.intellij.ide.projectView.impl.BaseProjectViewPaneWithAsyncSupport;
import com.intellij.ide.projectView.impl.ProjectViewState;
import com.intellij.ide.util.treeView.AbstractTreeStructureBase;
import com.intellij.openapi.actionSystem.ActionPlaces;
import com.intellij.openapi.actionSystem.ActionUpdateThread;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.DefaultActionGroup;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.ActionCallback;
import com.intellij.openapi.vcs.VcsDataKeys;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.concurrency.EdtExecutorService;
import com.intellij.util.containers.ContainerUtil;
import jetbrains.mps.classloading.ClassLoaderManager;
import jetbrains.mps.classloading.DeployListener;
import jetbrains.mps.extapi.persistence.FileSystemBasedDataSource;
import jetbrains.mps.generator.TransientModelsModule;
import jetbrains.mps.ide.actions.CopyNode_Action;
import jetbrains.mps.ide.actions.CutNode_Action;
import jetbrains.mps.ide.actions.PasteNode_Action;
import jetbrains.mps.ide.actions.SModelActionData;
import jetbrains.mps.ide.actions.SModuleActionData;
import jetbrains.mps.ide.actions.SNodeActionData;
import jetbrains.mps.ide.project.ProjectHelper;
import jetbrains.mps.ide.ui.tree.ContextValueProvider;
import jetbrains.mps.ide.ui.tree.VirtualFolder;
import jetbrains.mps.ide.ui.tree.VirtualFolder.Models;
import jetbrains.mps.ide.ui.tree.VirtualFolder.Modules;
import jetbrains.mps.ide.ui.tree.VirtualFolder.Nodes;
import jetbrains.mps.ide.ui.tree.smodel.PackageNode;
import jetbrains.mps.ide.vfs.FileSystemBridge;
import jetbrains.mps.ide.vfs.IdeaFileSystem;
import jetbrains.mps.logging.Logger;
import jetbrains.mps.make.IMakeNotificationListener;
import jetbrains.mps.make.IMakeNotificationListener.Stub;
import jetbrains.mps.make.MakeNotification;
import jetbrains.mps.make.MakeServiceComponent;
import jetbrains.mps.module.ReloadableModule;
import jetbrains.mps.project.AbstractModule;
import jetbrains.mps.project.DevKit;
import jetbrains.mps.project.MPSProject;
import jetbrains.mps.project.Solution;
import jetbrains.mps.smodel.Generator;
import jetbrains.mps.smodel.Language;
import jetbrains.mps.smodel.RepoListenerRegistrar;
import jetbrains.mps.smodel.SModelAdapter;
import jetbrains.mps.smodel.SModelInternal;
import jetbrains.mps.smodel.tempmodel.TempModule;
import jetbrains.mps.smodel.tempmodel.TempModule2;
import jetbrains.mps.util.Pair;
import jetbrains.mps.vfs.IFile;
import jetbrains.mps.workbench.ActionPlace;
import jetbrains.mps.workbench.FileSystemModelHelper;
import jetbrains.mps.workbench.MPSDataKeys;
import jetbrains.mps.workbench.action.ActionUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.mps.openapi.model.SModel;
import org.jetbrains.mps.openapi.model.SModelReference;
import org.jetbrains.mps.openapi.model.SNode;
import org.jetbrains.mps.openapi.module.SModule;
import org.jetbrains.mps.openapi.module.SModuleReference;
import org.jetbrains.mps.openapi.module.SRepository;
import org.jetbrains.mps.openapi.module.SRepositoryContentAdapter;
import org.jetbrains.mps.openapi.persistence.DataSource;
import org.jetbrains.mps.openapi.repository.CommandListener;
import org.jetbrains.mps.openapi.util.ProgressMonitor;
import javax.swing.JTree;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
public abstract class BaseLogicalViewProjectPane extends BaseProjectViewPaneWithAsyncSupport {
private static final Logger LOG = Logger.getLogger(BaseLogicalViewProjectPane.class);
private final MyRepositoryListener myRepositoryListener = new MyRepositoryListener();
private final MyModelChangeListener myModelChangeListener = new MyModelChangeListener();
protected boolean myDisposed;
private final DeployListener myClassesListener = new DeployListener() {
@Override
public void onUnloaded(@NotNull Set<ReloadableModule> unloadedModules, @NotNull ProgressMonitor monitor) {
}
@Override
public void onLoaded(@NotNull Set<ReloadableModule> loadedModules, @NotNull ProgressMonitor monitor) {
rebuild();
}
};
private final IMakeNotificationListener myMakeNotificationListener = new Stub() {
@Override
public void sessionClosed(MakeNotification notification) {
// rebuild tree in case of 'cancel' too (need to get 'transient models' node rebuilt)
rebuild();
}
};
@Override
public @NotNull ActionCallback selectCB(Object element, VirtualFile file, boolean requestFocus) {
ActionCallback callback = new ActionCallback();
EdtExecutorService.getScheduledExecutorInstance()
.schedule(() -> super.selectCB(element, file, requestFocus).notify(callback), 100, TimeUnit.MILLISECONDS);
return callback;
}
/**
* Intentionally made non-abstract to enable compilation of dependent code.
*/
@Override
protected @NotNull AbstractTreeStructureBase createStructure() {
throw new UnsupportedOperationException("no implementation provided");
}
/**
* Intentionally made non-abstract to enable compilation of dependent code.
*/
@Override
protected @NotNull DnDAwareTree createTree(@NotNull DefaultTreeModel treeModel) {
throw new UnsupportedOperationException("no implementation provided");
}
protected BaseLogicalViewProjectPane(Project project) {
super(project);
}
public Project getProject() {
return myProject;
}
public ProjectView getProjectView() {
return ProjectView.getInstance(myProject);
}
/*package*/ ProjectViewState getProjectViewState() {
// FIXME
return ProjectViewState.getInstance(getProject());
}
protected void forEachFile(SModule module, Consumer<IFile> fun) {
if (module instanceof AbstractModule) {
IFile iFile = ((AbstractModule) module).getDescriptorFile();
fun.accept(iFile);
}
}
protected void forEachFile(SModel model, Consumer<IFile> fun) {
DataSource source = model.getSource();
if (source instanceof FileSystemBasedDataSource) {
for (IFile iFile : ((FileSystemBasedDataSource) source).getAffectedFiles()) {
fun.accept(iFile);
}
}
}
@SuppressWarnings("removal")
protected void updateFrom(IFile iFile, boolean updateStructure) {
MPSProject mpsProject = ProjectHelper.fromIdeaProject(getProject());
IdeaFileSystem fileSystem = mpsProject.getFileSystem();
VirtualFile virtualFile = fileSystem.asVirtualFile(iFile);
if (virtualFile != null) {
updateFrom(virtualFile, false, updateStructure);
}
}
public abstract void rebuild();
@Override
public Object getData(@NotNull String dataId) {
if (SNodeActionData.KEY.is(dataId)) {
List<SNode> nodes = ContainerUtil.filterIsInstance(getSelectedValues(getSelectedUserObjects()), SNode.class);
if (nodes.isEmpty()) {
return null;
} else if (nodes.size() == 1) {
return SNodeActionData.from(nodes.get(0).getReference());
} else {
return SNodeActionData.from(nodes.stream().map(SNode::getReference));
}
}
if (SModelActionData.KEY.is(dataId)) {
List<SModel> models = ContainerUtil.filterIsInstance(getSelectedValues(getSelectedUserObjects()), SModel.class);
if (models.isEmpty()) {
return null;
} else if (models.size() == 1) {
return SModelActionData.from(models.get(0).getReference());
} else {
return SModelActionData.from(models.stream().map(SModel::getReference));
}
}
if (SModuleActionData.KEY.is(dataId)) {
List<SModule> modules = ContainerUtil.filterIsInstance(getSelectedValues(getSelectedUserObjects()), SModule.class);
if (modules.isEmpty()) {
return null;
} else if (modules.size() == 1) {
return SModuleActionData.from(modules.get(0).getModuleReference());
} else {
return SModuleActionData.from(modules.stream().map(SModule::getModuleReference));
}
}
//MPSDK
if (MPSDataKeys.CONTEXT_MODEL.is(dataId)) {
return getContextModel();
}
if (MPSDataKeys.CONTEXT_MODULE.is(dataId)) {
return getContextModule();
}
if (MPSDataKeys.VIRTUAL_PACKAGES.is(dataId)) {
// FIXME getSelectedPackages() requires model read (resolves model references)
final List<Pair<SModel, String>> rv = getSelectedPackages();
return rv.isEmpty() ? null : rv;
}
if (MPSDataKeys.NAMESPACE.is(dataId)) {
Object firstSelected = Arrays.stream(getSelectedValues(getSelectedUserObjects())).findFirst().orElseGet(() -> null);
if (firstSelected instanceof VirtualFolder) {
return ((VirtualFolder)firstSelected).getName();
}
return null;
}
if (MPSDataKeys.USER_OBJECT.is(dataId)) {
return Arrays.stream(getSelectedUserObjects()).findFirst().orElseGet(() -> null);
}
if (MPSDataKeys.USER_OBJECTS.is(dataId)) {
return Arrays.asList(getSelectedUserObjects());
}
if (MPSDataKeys.VALUE.is(dataId)) {
return Arrays.stream(getSelectedValues(getSelectedUserObjects())).findFirst().orElseGet(() -> null);
}
if (MPSDataKeys.VALUES.is(dataId)) {
return Arrays.asList(getSelectedValues(getSelectedUserObjects()));
}
if (MPSDataKeys.TREE_SELECTION_SIZE.is(dataId)) {
return getSelectionSize();
}
if (MPSDataKeys.PLACE.is(dataId)) {
return getPlace(Arrays.stream(getSelectedValues(getSelectedUserObjects())).findFirst().orElseGet(() -> null));
}
//PDK
if (PlatformDataKeys.COPY_PROVIDER.is(dataId)) {
return new MyCopyProvider();
}
if (PlatformDataKeys.PASTE_PROVIDER.is(dataId)) {
return new MyPasteProvider();
}
if (PlatformDataKeys.CUT_PROVIDER.is(dataId)) {
return new MyCutProvider();
}
if (PlatformDataKeys.VIRTUAL_FILE_ARRAY.is(dataId)) {
// XXX perhaps, has to move to SLOW_DATA_PROVIDERS (i.e. collect selected elements in EDT and return
// another DataProvider instance that would transformed selected models/modules into VirtualFile?
return getSelectedFiles(true, true);
}
if (VcsDataKeys.VIRTUAL_FILES.is(dataId)) {
VirtualFile[] selection = getSelectedFiles(false, true);
return selection != null ? Arrays.asList(selection) : null;
}
// if project pane doesn't answer its Project, chances are some LocationRule could start looking
// for a project in inappropriate DataProvider, and end up producing MPSLocation solely with MPSProject
// (as it could not obtain node/model/module from any other DataProvider in Project View hierarchy)
if (CommonDataKeys.PROJECT.is(dataId)) {
return getProject();
}
if (MPSDataKeys.MPS_PROJECT.is(dataId)) {
return ProjectHelper.fromIdeaProject(getProject());
}
//not found
return super.getData(dataId);
}
public boolean isDisposed() {
return myDisposed;
}
@Override
public void dispose() {
if (isComponentCreated()) {
removeListeners();
}
myDisposed = true;
super.dispose();
}
public boolean showNodeStructure() {
// re-use IDEA's 'show members' for 'show node structure'
return !isDisposed() && getProjectView().isShowMembers(getId());
}
/**
* @deprecated use {@link jetbrains.mps.ide.projectView.MPSProjectViewSettings} instead.
*/
@Deprecated
public boolean isSortByConcept() {
return getProjectViewState().getSortByType();
}
@Override
public void installComparator() {
// FIXME why is this NOP?
// Overrode to avoid NPE
}
@Override
public boolean supportsSortByType() {
return true;
}
@Override
public boolean supportsManualOrder() {
return false;
}
@Override
public boolean supportsSortByTime() {
return false;
}
@Override
public void addToolbarActions(final DefaultActionGroup group) {
super.addToolbarActions(group);
}
protected void removeListeners() {
jetbrains.mps.project.Project mpsProject = ProjectHelper.fromIdeaProject(getProject());
mpsProject.getComponent(ClassLoaderManager.class).removeListener(myClassesListener);
mpsProject.getModelAccess().removeCommandListener(myRepositoryListener);
new RepoListenerRegistrar(mpsProject.getRepository(), myRepositoryListener).detach();
mpsProject.getComponent(MakeServiceComponent.class).get().removeListener(myMakeNotificationListener);
}
protected void addListeners() {
jetbrains.mps.project.Project mpsProject = ProjectHelper.fromIdeaProject(getProject());
new RepoListenerRegistrar(mpsProject.getRepository(), myRepositoryListener).attach();
mpsProject.getModelAccess().addCommandListener(myRepositoryListener);
// XXX here used to be a hasMakeService() check, which I found superfluous,
// as we always have make service in UI (at least, we never check for it in other locations)
// However, the idea to keep listeners inside MakeServiceComponent and install them into active
// IMakeService once it's updated looks nice
mpsProject.getComponent(MakeServiceComponent.class).get().addListener(myMakeNotificationListener);
mpsProject.getComponent(ClassLoaderManager.class).addListener(myClassesListener);
}
/**
* expects model read lock at least
*
* @deprecated don't use, prefer {@code SNodeReference} and {@code DataContext.getData()}
*/
@Deprecated(forRemoval = true, since = "2021.3")
public SNode getSelectedSNode() {
List<SNode> result = getSelectedSNodes();
if (result.size() != 1) {
return null;
}
return result.get(0);
}
/**
* NB! The implementation of this method has been altered to rely on the modern implementation of underlying
* tree. The following comments may not be relevant.
* <p>
* expects model read lock at least
*
* @deprecated don't use, prefer {@code SNodeReference} and {@code DataContext.getData()}
*/
@NotNull
@Deprecated(forRemoval = true, since = "2021.3")
public List<SNode> getSelectedSNodes() {
return ContainerUtil.filterIsInstance(getSelectedValues(getSelectedUserObjects()), SNode.class);
}
@NotNull
public List<SModel> getSelectedModels() {
return ContainerUtil.filterIsInstance(getSelectedValues(getSelectedUserObjects()), SModel.class);
}
@Nullable
public SModel getSelectedModel() {
return ContainerUtil.findInstance(getSelectedValues(getSelectedUserObjects()), SModel.class);
}
@Nullable
public SModel getContextModel() {
@Nullable Object[] userObjects = getSingleSelectedPathUserObjects();
if (userObjects == null || userObjects.length == 0) {
return null;
}
Object lastUserObject = userObjects[userObjects.length - 1];
if (lastUserObject instanceof ContextValueProvider) {
return ((ContextValueProvider) lastUserObject).contextValueOfType(SModel.class).orElseGet(() -> null);
}
return null;
}
@NotNull
public List<SModule> getSelectedModules() {
return ContainerUtil.filterIsInstance(getSelectedValues(getSelectedUserObjects()), SModule.class);
}
@Nullable
public SModule getContextModule() {
@Nullable Object[] userObjects = getSingleSelectedPathUserObjects();
if (userObjects == null || userObjects.length == 0) {
return null;
}
Object lastUserObject = userObjects[userObjects.length - 1];
if (lastUserObject instanceof ContextValueProvider) {
return ((ContextValueProvider) lastUserObject).contextValueOfType(SModule.class).orElseGet(() -> null);
}
return null;
}
@NotNull
public List<Pair<SModel, String>> getSelectedPackages() {
// FIXME update the implementation or drop
JTree tree = getTree();
if (tree == null) {
return Collections.emptyList();
}
TreePath[] paths = tree.getSelectionPaths();
SRepository projectRepo = ProjectHelper.getProjectRepository(getProject());
if (paths == null || paths.length == 0 || projectRepo == null) {
return Collections.emptyList();
}
List<Pair<SModel, String>> result = new ArrayList<>();
for (TreePath path : paths) {
if (path.getLastPathComponent() instanceof PackageNode) {
PackageNode pn = (PackageNode) path.getLastPathComponent();
projectRepo.getModelAccess().runReadAction(new Runnable() {
@Override
public void run() {
result.add(new Pair<>(pn.getModelReference().resolve(projectRepo), pn.getFullPackage()));
}
});
}
}
return result;
}
public int getSelectionSize() {
TreePath[] selection = getSelectionPaths();
return selection == null ? 0 : selection.length;
}
protected ActionPlace getPlace(@Nullable Object selectedValue) {
if (selectedValue instanceof SNode) {
return ActionPlace.PROJECT_PANE_SNODE;
} else if (selectedValue instanceof SModel) {
return ActionPlace.PROJECT_PANE_SMODEL;
} else if (selectedValue instanceof MPSProject) {
return ActionPlace.PROJECT_PANE_PROJECT;
} else if (selectedValue instanceof Generator) {
return ActionPlace.PROJECT_PANE_GENERATOR;
} else if (selectedValue instanceof TransientModelsModule) {
return ActionPlace.PROJECT_PANE_TRANSIENT_MODULES;
} else if (selectedValue instanceof Nodes) {
return ActionPlace.PROJECT_PANE_PACKAGE;
} else if (selectedValue instanceof Models) {
return ActionPlace.PROJECT_PANE_NAMESPACE;
} else if (selectedValue instanceof Modules) {
return ActionPlace.PROJECT_PANE_NAMESPACE;
} else if (selectedValue instanceof Language) {
return ActionPlace.PROJECT_PANE_LANGUAGE;
} else if (selectedValue instanceof DevKit) {
return ActionPlace.PROJECT_PANE_DEVKIT;
} else if (selectedValue instanceof Solution) {
return ActionPlace.PROJECT_PANE_SOLUTION;
}
return null;
}
/**
* A simplified alternative to {@link #getSelectedTreeNodes(Class)}
* <p>
* NB! Both these methods deprecated and are to be removed in one of the upcoming releases.
* Please use other means to find the selected objects/values in the tree.
* The use of swing interfaces is discouraged, since they require the UI thread.
*/
@Nullable
@Deprecated(forRemoval = true)
protected final <T extends TreeNode> T getSelectedTreeNode(Class<T> nodeClass) {
JTree tree = getTree();
if (tree == null) {
return null;
}
TreePath selectionPath = tree.getSelectionPath();
if (selectionPath == null) {
return null;
}
Object selectedNode = selectionPath.getLastPathComponent();
return nodeClass.isInstance(selectedNode) ? nodeClass.cast(selectedNode) : null;
}
/**
* See {@link #getSelectedTreeNode(Class)}.<SUF>*/
@NotNull
@Deprecated(forRemoval = true)
public <T extends TreeNode> List<T> getSelectedTreeNodes(Class<T> nodeClass) {
JTree tree = getTree();
if (tree == null) {
return Collections.emptyList();
}
TreePath[] selectionPaths = tree.getSelectionPaths();
if (selectionPaths == null || selectionPaths.length == 0) {
return Collections.emptyList();
}
List<T> selectedTreeNodes = new ArrayList<>(selectionPaths.length);
for (TreePath selectionPath : selectionPaths) {
if (selectionPath == null) {
continue;
}
Object selectedNode = selectionPath.getLastPathComponent();
if (nodeClass.isInstance(selectedNode)) {
selectedTreeNodes.add(nodeClass.cast(selectedNode));
}
}
return selectedTreeNodes;
}
@Nullable
private VirtualFile[] getSelectedFiles(boolean addModuleFile, boolean addModuleDir) {
List<IFile> selectedFilesList = new LinkedList<>();
// add selected model files
List<SModel> descriptors = getSelectedModels();
if (descriptors != null) {
for (SModel descriptor : descriptors) {
selectedFilesList.addAll(new FileSystemModelHelper(descriptor).getFiles());
}
}
// add selected modules files
List<SModule> modules = getSelectedModules();
if (modules != null) {
for (SModule m : modules) {
if (!(m instanceof AbstractModule)) {
continue;
}
AbstractModule module = (AbstractModule) m;
IFile home = module.getModuleSourceDir();
if (home != null && addModuleDir) {
selectedFilesList.add(home);
}
IFile ifile = module.getDescriptorFile();
if (ifile != null && addModuleFile) {
selectedFilesList.add(ifile);
}
}
}
if (selectedFilesList.isEmpty()) {
return null;
}
final FileSystemBridge fs = ProjectHelper.fromIdeaProject(myProject).getFileSystem();
return selectedFilesList.stream().map(fs::asVirtualFile).filter(Objects::nonNull).toArray(VirtualFile[]::new);
}
/*package*/
static AnActionEvent createEvent(DataContext context) {
return ActionUtils.createEvent(ActionPlaces.PROJECT_VIEW_POPUP, context);
}
protected abstract boolean isComponentCreated();
private static class MyCopyProvider implements CopyProvider {
private CopyNode_Action myAction = new CopyNode_Action();
@Override
public void performCopy(@NotNull DataContext dataContext) {
AnActionEvent event = createEvent(dataContext);
ActionUtils.updateAndPerformAction(myAction, event);
}
@Override
public boolean isCopyEnabled(@NotNull DataContext dataContext) {
AnActionEvent event = createEvent(dataContext);
myAction.update(event);
return event.getPresentation().isEnabled();
}
@Override
public boolean isCopyVisible(@NotNull DataContext dataContext) {
return true;
}
@Override
@NotNull
public ActionUpdateThread getActionUpdateThread() {
return myAction.getActionUpdateThread();
}
}
private static class MyPasteProvider implements PasteProvider {
private PasteNode_Action myAction = new PasteNode_Action();
@Override
public void performPaste(@NotNull DataContext dataContext) {
AnActionEvent event = createEvent(dataContext);
ActionUtils.updateAndPerformAction(myAction, event);
}
@Override
public boolean isPastePossible(@NotNull DataContext dataContext) {
return true;
}
@Override
public boolean isPasteEnabled(@NotNull DataContext dataContext) {
AnActionEvent event = createEvent(dataContext);
myAction.update(event);
return event.getPresentation().isEnabled();
}
@Override
@NotNull
public ActionUpdateThread getActionUpdateThread() {
// PasteNode_Action update uses EDT, is it correct?
return myAction.getActionUpdateThread();
}
}
private static class MyCutProvider implements CutProvider {
private CutNode_Action myAction = new CutNode_Action();
@Override
public void performCut(@NotNull DataContext dataContext) {
AnActionEvent event = createEvent(dataContext);
ActionUtils.updateAndPerformAction(myAction, event);
}
@Override
public boolean isCutEnabled(@NotNull DataContext dataContext) {
AnActionEvent event = createEvent(dataContext);
myAction.update(event);
return event.getPresentation().isEnabled();
}
@Override
public boolean isCutVisible(@NotNull DataContext dataContext) {
return true;
}
@Override
@NotNull
public ActionUpdateThread getActionUpdateThread() {
return myAction.getActionUpdateThread();
}
}
private class MyRepositoryListener extends SRepositoryContentAdapter implements CommandListener {
@Override
protected void startListening(SModel model) {
model.addModelListener(this);
((SModelInternal) model).addModelListener(myModelChangeListener);
}
@Override
protected void stopListening(SModel model) {
model.removeModelListener(this);
((SModelInternal) model).removeModelListener(myModelChangeListener);
}
@Override
public void moduleAdded(@NotNull SModule module) {
if (!(module instanceof TempModule || module instanceof TempModule2)) {
updateFromRoot(true);
}
}
@Override
public void moduleRenamed(@NotNull SModule module, @NotNull SModuleReference oldRef) {
updateFromRoot(true);
}
@Override
public void beforeModuleRemoved(@NotNull SModule module) {
if (!(module instanceof TempModule || module instanceof TempModule2)) {
updateFromRoot(true);
}
}
@Override
public void modelRenamed(SModule module, SModel model, SModelReference oldRef) {
forEachFile(module, f -> updateFrom(f, true));
}
@Override
public void modelRemoved(SModule module, SModelReference ref) {
forEachFile(module, f -> updateFrom(f, true));
}
@Override
public void modelAdded(SModule module, SModel model) {
forEachFile(module, f -> updateFrom(f, true));
}
@Override
public void modelReplaced(SModel model) {
forEachFile(model, f -> updateFrom(f, true));
}
}
private class MyModelChangeListener extends SModelAdapter {
@Override
public void modelChangedDramatically(SModel model) {
forEachFile(model, f -> updateFrom(f, true));
}
@Override
public void modelChanged(SModel model) {
forEachFile(model, f -> updateFrom(f, true));
}
}
}
|
81667_2 | /*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.inspectors.common.api.ide.stacktrace;
import com.android.tools.adtui.model.AspectObserver;
import com.android.tools.adtui.stdui.ContextMenuItem;
import com.android.tools.adtui.stdui.StandardColors;
import com.android.tools.idea.codenavigation.CodeLocation;
import com.android.tools.inspectors.common.api.stacktrace.CodeElement;
import com.android.tools.inspectors.common.api.stacktrace.StackElement;
import com.android.tools.inspectors.common.api.stacktrace.StackTraceModel;
import com.android.tools.inspectors.common.api.stacktrace.ThreadElement;
import com.android.tools.inspectors.common.api.stacktrace.ThreadId;
import com.android.tools.inspectors.common.ui.ContextMenuInstaller;
import com.android.tools.inspectors.common.ui.stacktrace.StackTraceView;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.intellij.icons.AllIcons;
import com.intellij.ide.CopyProvider;
import com.intellij.ide.DataManager;
import com.intellij.openapi.actionSystem.ActionUpdateThread;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.DataProvider;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.ide.CopyPasteManager;
import com.intellij.openapi.project.Project;
import com.intellij.ui.ColoredListCellRenderer;
import com.intellij.ui.DoubleClickListener;
import com.intellij.ui.IconManager;
import com.intellij.ui.PlatformIcons;
import com.intellij.ui.SimpleTextAttributes;
import com.intellij.ui.components.JBList;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.util.ui.JBUI;
import java.awt.Insets;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.nio.file.Paths;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Supplier;
import javax.swing.DefaultListModel;
import javax.swing.JComponent;
import javax.swing.JList;
import javax.swing.ListSelectionModel;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionListener;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class IntelliJStackTraceView extends AspectObserver implements StackTraceView, DataProvider, CopyProvider {
private static final Insets LIST_ROW_INSETS = JBUI.insets(2, 10, 0, 0);
@NotNull
private final Project myProject;
@NotNull
private final StackTraceModel myModel;
@NotNull
private final BiFunction<Project, CodeLocation, CodeElement> myGenerator;
@NotNull
private final JBScrollPane myScrollPane;
@NotNull
private final DefaultListModel<StackElement> myListModel;
@NotNull
private final JBList myListView;
@NotNull
private final StackElementRenderer myRenderer;
public IntelliJStackTraceView(@NotNull Project project,
@NotNull StackTraceModel model) {
this(project, model, IntelliJCodeElement::new);
}
@VisibleForTesting
IntelliJStackTraceView(@NotNull Project project,
@NotNull StackTraceModel model,
@NotNull BiFunction<Project, CodeLocation, CodeElement> stackNavigationGenerator) {
myProject = project;
myModel = model;
myGenerator = stackNavigationGenerator;
myListModel = new DefaultListModel<>();
myListView = new JBList(myListModel);
myListView.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
myListView.setBackground(StandardColors.DEFAULT_CONTENT_BACKGROUND_COLOR);
myRenderer = new StackElementRenderer();
myListView.setCellRenderer(myRenderer);
myScrollPane = new JBScrollPane(myListView);
myScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
myScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
DataManager.registerDataProvider(myListView, this);
myListView.addListSelectionListener(e -> {
if (myListView.getSelectedValue() == null) {
myModel.clearSelection();
}
});
Supplier<Boolean> navigationHandler = () -> {
int index = myListView.getSelectedIndex();
if (index >= 0 && index < myListView.getItemsCount()) {
myModel.setSelectedIndex(index);
return true;
}
else {
return false;
}
};
myListView.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
// On Windows we don't get a KeyCode so checking the getKeyCode doesn't work. Instead we get the code from the char
// we are given.
int keyCode = KeyEvent.getExtendedKeyCodeForChar(e.getKeyChar());
if (keyCode == KeyEvent.VK_ENTER) {
if (navigationHandler.get()) {
e.consume();
}
}
}
});
new DoubleClickListener() {
@Override
protected boolean onDoubleClick(MouseEvent event) {
return navigationHandler.get();
}
}.installOn(myListView);
myListView.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
int row = myListView.locationToIndex(e.getPoint());
if (row != -1) {
myListView.setSelectedIndex(row);
}
}
}
});
myModel.addDependency(this).
onChange(StackTraceModel.Aspect.STACK_FRAMES, () -> {
List<CodeLocation> stackFrames = myModel.getCodeLocations();
myListModel.removeAllElements();
myListView.clearSelection();
stackFrames.forEach(stackFrame -> myListModel.addElement(myGenerator.apply(myProject, stackFrame)));
ThreadId threadId = myModel.getThreadId();
if (!threadId.equals(ThreadId.INVALID_THREAD_ID)) {
myListModel.addElement(new ThreadElement(threadId));
}
})
.onChange(StackTraceModel.Aspect.SELECTED_LOCATION, () -> {
int index = myModel.getSelectedIndex();
if (myModel.getSelectedType() == StackTraceModel.Type.INVALID) {
if (myListView.getSelectedIndex() != -1) {
myListView.clearSelection();
}
}
else if (index >= 0 && index < myListView.getItemsCount()) {
if (myListView.getSelectedIndex() != index) {
myListView.setSelectedIndex(index);
}
}
else {
throw new IndexOutOfBoundsException(
"View has " + myListView.getItemsCount() + " elements while aspect is changing to index " + index);
}
});
}
public void installNavigationContextMenu(@NotNull ContextMenuInstaller contextMenuInstaller) {
contextMenuInstaller.installNavigationContextMenu(myListView, myModel.getCodeNavigator(), () -> {
int index = myListView.getSelectedIndex();
if (index >= 0 && index < myListView.getItemsCount()) {
return myModel.getCodeLocations().get(index);
}
return null;
});
}
public void installGenericContextMenu(@NotNull ContextMenuInstaller installer, @NotNull ContextMenuItem contextMenuItem) {
installer.installGenericContextMenu(myListView, contextMenuItem);
}
@NotNull
@Override
public StackTraceModel getModel() {
return myModel;
}
@NotNull
@Override
public JComponent getComponent() {
return myScrollPane;
}
public void addListSelectionListener(@NotNull ListSelectionListener listener) {
myListView.addListSelectionListener(listener);
}
public void clearSelection() {
myListView.clearSelection();
}
@NotNull
@Override
public ActionUpdateThread getActionUpdateThread() {
return ActionUpdateThread.BGT;
}
@Override
public boolean isCopyEnabled(@NotNull DataContext dataContext) {
return true;
}
@Override
public boolean isCopyVisible(@NotNull DataContext dataContext) {
return true;
}
/**
* Copies the selected list item to the clipboard. The copied text rendering is the same as the list rendering.
*/
@Override
public void performCopy(@NotNull DataContext dataContext) {
int selectedIndex = myListView.getSelectedIndex();
if (selectedIndex >= 0 && selectedIndex < myListView.getItemsCount()) {
myRenderer.getListCellRendererComponent(myListView, myListModel.getElementAt(selectedIndex), selectedIndex, true, false);
String data = String.valueOf(myRenderer.getCharSequence(false));
CopyPasteManager.getInstance().setContents(new StringSelection(data));
}
}
@Nullable
@Override
public Object getData(String dataId) {
if (PlatformDataKeys.COPY_PROVIDER.is(dataId)) {
return this;
}
return null;
}
public int getSelectedIndex() {
return myListView.getSelectedIndex();
}
@VisibleForTesting
@NotNull
public JBList getListView() {
return myListView;
}
/**
* Renderer for a JList of {@link StackElement} instances.
*/
private static final class StackElementRenderer extends ColoredListCellRenderer<StackElement> {
@Override
protected void customizeCellRenderer(@NotNull JList list,
StackElement value,
int index,
boolean selected,
boolean hasFocus) {
if (value == null) {
return;
}
setIpad(LIST_ROW_INSETS);
if (value instanceof CodeElement) {
CodeElement element = (CodeElement)value;
if (element.getCodeLocation().isNativeCode()) {
renderNativeStackFrame(element, selected);
}
else {
renderJavaStackFrame(element, selected);
}
}
else if (value instanceof ThreadElement) {
renderThreadElement((ThreadElement)value, selected);
}
else {
append(value.toString(), SimpleTextAttributes.ERROR_ATTRIBUTES);
}
}
private void renderJavaStackFrame(@NotNull CodeElement codeElement, boolean selected) {
setIcon(IconManager.getInstance().getPlatformIcon(PlatformIcons.Method));
SimpleTextAttributes textAttribute =
selected || codeElement.isInUserCode() ? SimpleTextAttributes.REGULAR_ATTRIBUTES : SimpleTextAttributes.GRAY_ATTRIBUTES;
CodeLocation location = codeElement.getCodeLocation();
StringBuilder methodBuilder = new StringBuilder(codeElement.getMethodName());
if (location.getLineNumber() != CodeLocation.INVALID_LINE_NUMBER) {
methodBuilder.append(":");
methodBuilder.append(location.getLineNumber() + 1);
}
methodBuilder.append(", ");
methodBuilder.append(codeElement.getSimpleClassName());
String methodName = methodBuilder.toString();
append(methodName, textAttribute, methodName);
String packageName = " (" + codeElement.getPackageName() + ")";
append(packageName, selected ? SimpleTextAttributes.REGULAR_ITALIC_ATTRIBUTES : SimpleTextAttributes.GRAYED_ITALIC_ATTRIBUTES,
packageName);
}
private void renderNativeStackFrame(@NotNull CodeElement codeElement, boolean selected) {
setIcon(IconManager.getInstance().getPlatformIcon(PlatformIcons.Method));
CodeLocation location = codeElement.getCodeLocation();
StringBuilder methodBuilder = new StringBuilder();
if (!Strings.isNullOrEmpty(location.getClassName())) {
methodBuilder.append(location.getClassName());
methodBuilder.append("::");
}
methodBuilder.append(location.getMethodName());
methodBuilder.append("(" + String.join(",", location.getMethodParameters()) + ") ");
String methodName = methodBuilder.toString();
append(methodName, SimpleTextAttributes.REGULAR_ATTRIBUTES, methodName);
if (!Strings.isNullOrEmpty(location.getFileName())) {
String sourceLocation = Paths.get(location.getFileName()).getFileName().toString();
if (location.getLineNumber() != CodeLocation.INVALID_LINE_NUMBER) {
sourceLocation += ":" + String.valueOf(location.getLineNumber() + 1);
}
append(sourceLocation, SimpleTextAttributes.REGULAR_ATTRIBUTES, sourceLocation);
}
String moduleName = " " + Paths.get(location.getNativeModuleName()).getFileName().toString();
append(moduleName, selected ? SimpleTextAttributes.REGULAR_ITALIC_ATTRIBUTES : SimpleTextAttributes.GRAYED_ITALIC_ATTRIBUTES,
moduleName);
}
private void renderThreadElement(@NotNull ThreadElement threadElement, boolean selected) {
setIcon(AllIcons.Debugger.ThreadSuspended);
String text = threadElement.getThreadId().toString();
append(text, selected ? SimpleTextAttributes.REGULAR_ATTRIBUTES : SimpleTextAttributes.GRAY_ATTRIBUTES, text);
}
}
}
| JetBrains/android | inspectors-common/api-ide/src/com/android/tools/inspectors/common/api/ide/stacktrace/IntelliJStackTraceView.java | 3,882 | // we are given. | line_comment | nl | /*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.inspectors.common.api.ide.stacktrace;
import com.android.tools.adtui.model.AspectObserver;
import com.android.tools.adtui.stdui.ContextMenuItem;
import com.android.tools.adtui.stdui.StandardColors;
import com.android.tools.idea.codenavigation.CodeLocation;
import com.android.tools.inspectors.common.api.stacktrace.CodeElement;
import com.android.tools.inspectors.common.api.stacktrace.StackElement;
import com.android.tools.inspectors.common.api.stacktrace.StackTraceModel;
import com.android.tools.inspectors.common.api.stacktrace.ThreadElement;
import com.android.tools.inspectors.common.api.stacktrace.ThreadId;
import com.android.tools.inspectors.common.ui.ContextMenuInstaller;
import com.android.tools.inspectors.common.ui.stacktrace.StackTraceView;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.intellij.icons.AllIcons;
import com.intellij.ide.CopyProvider;
import com.intellij.ide.DataManager;
import com.intellij.openapi.actionSystem.ActionUpdateThread;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.DataProvider;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.ide.CopyPasteManager;
import com.intellij.openapi.project.Project;
import com.intellij.ui.ColoredListCellRenderer;
import com.intellij.ui.DoubleClickListener;
import com.intellij.ui.IconManager;
import com.intellij.ui.PlatformIcons;
import com.intellij.ui.SimpleTextAttributes;
import com.intellij.ui.components.JBList;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.util.ui.JBUI;
import java.awt.Insets;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.nio.file.Paths;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Supplier;
import javax.swing.DefaultListModel;
import javax.swing.JComponent;
import javax.swing.JList;
import javax.swing.ListSelectionModel;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionListener;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class IntelliJStackTraceView extends AspectObserver implements StackTraceView, DataProvider, CopyProvider {
private static final Insets LIST_ROW_INSETS = JBUI.insets(2, 10, 0, 0);
@NotNull
private final Project myProject;
@NotNull
private final StackTraceModel myModel;
@NotNull
private final BiFunction<Project, CodeLocation, CodeElement> myGenerator;
@NotNull
private final JBScrollPane myScrollPane;
@NotNull
private final DefaultListModel<StackElement> myListModel;
@NotNull
private final JBList myListView;
@NotNull
private final StackElementRenderer myRenderer;
public IntelliJStackTraceView(@NotNull Project project,
@NotNull StackTraceModel model) {
this(project, model, IntelliJCodeElement::new);
}
@VisibleForTesting
IntelliJStackTraceView(@NotNull Project project,
@NotNull StackTraceModel model,
@NotNull BiFunction<Project, CodeLocation, CodeElement> stackNavigationGenerator) {
myProject = project;
myModel = model;
myGenerator = stackNavigationGenerator;
myListModel = new DefaultListModel<>();
myListView = new JBList(myListModel);
myListView.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
myListView.setBackground(StandardColors.DEFAULT_CONTENT_BACKGROUND_COLOR);
myRenderer = new StackElementRenderer();
myListView.setCellRenderer(myRenderer);
myScrollPane = new JBScrollPane(myListView);
myScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
myScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
DataManager.registerDataProvider(myListView, this);
myListView.addListSelectionListener(e -> {
if (myListView.getSelectedValue() == null) {
myModel.clearSelection();
}
});
Supplier<Boolean> navigationHandler = () -> {
int index = myListView.getSelectedIndex();
if (index >= 0 && index < myListView.getItemsCount()) {
myModel.setSelectedIndex(index);
return true;
}
else {
return false;
}
};
myListView.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
// On Windows we don't get a KeyCode so checking the getKeyCode doesn't work. Instead we get the code from the char
// we are<SUF>
int keyCode = KeyEvent.getExtendedKeyCodeForChar(e.getKeyChar());
if (keyCode == KeyEvent.VK_ENTER) {
if (navigationHandler.get()) {
e.consume();
}
}
}
});
new DoubleClickListener() {
@Override
protected boolean onDoubleClick(MouseEvent event) {
return navigationHandler.get();
}
}.installOn(myListView);
myListView.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
int row = myListView.locationToIndex(e.getPoint());
if (row != -1) {
myListView.setSelectedIndex(row);
}
}
}
});
myModel.addDependency(this).
onChange(StackTraceModel.Aspect.STACK_FRAMES, () -> {
List<CodeLocation> stackFrames = myModel.getCodeLocations();
myListModel.removeAllElements();
myListView.clearSelection();
stackFrames.forEach(stackFrame -> myListModel.addElement(myGenerator.apply(myProject, stackFrame)));
ThreadId threadId = myModel.getThreadId();
if (!threadId.equals(ThreadId.INVALID_THREAD_ID)) {
myListModel.addElement(new ThreadElement(threadId));
}
})
.onChange(StackTraceModel.Aspect.SELECTED_LOCATION, () -> {
int index = myModel.getSelectedIndex();
if (myModel.getSelectedType() == StackTraceModel.Type.INVALID) {
if (myListView.getSelectedIndex() != -1) {
myListView.clearSelection();
}
}
else if (index >= 0 && index < myListView.getItemsCount()) {
if (myListView.getSelectedIndex() != index) {
myListView.setSelectedIndex(index);
}
}
else {
throw new IndexOutOfBoundsException(
"View has " + myListView.getItemsCount() + " elements while aspect is changing to index " + index);
}
});
}
public void installNavigationContextMenu(@NotNull ContextMenuInstaller contextMenuInstaller) {
contextMenuInstaller.installNavigationContextMenu(myListView, myModel.getCodeNavigator(), () -> {
int index = myListView.getSelectedIndex();
if (index >= 0 && index < myListView.getItemsCount()) {
return myModel.getCodeLocations().get(index);
}
return null;
});
}
public void installGenericContextMenu(@NotNull ContextMenuInstaller installer, @NotNull ContextMenuItem contextMenuItem) {
installer.installGenericContextMenu(myListView, contextMenuItem);
}
@NotNull
@Override
public StackTraceModel getModel() {
return myModel;
}
@NotNull
@Override
public JComponent getComponent() {
return myScrollPane;
}
public void addListSelectionListener(@NotNull ListSelectionListener listener) {
myListView.addListSelectionListener(listener);
}
public void clearSelection() {
myListView.clearSelection();
}
@NotNull
@Override
public ActionUpdateThread getActionUpdateThread() {
return ActionUpdateThread.BGT;
}
@Override
public boolean isCopyEnabled(@NotNull DataContext dataContext) {
return true;
}
@Override
public boolean isCopyVisible(@NotNull DataContext dataContext) {
return true;
}
/**
* Copies the selected list item to the clipboard. The copied text rendering is the same as the list rendering.
*/
@Override
public void performCopy(@NotNull DataContext dataContext) {
int selectedIndex = myListView.getSelectedIndex();
if (selectedIndex >= 0 && selectedIndex < myListView.getItemsCount()) {
myRenderer.getListCellRendererComponent(myListView, myListModel.getElementAt(selectedIndex), selectedIndex, true, false);
String data = String.valueOf(myRenderer.getCharSequence(false));
CopyPasteManager.getInstance().setContents(new StringSelection(data));
}
}
@Nullable
@Override
public Object getData(String dataId) {
if (PlatformDataKeys.COPY_PROVIDER.is(dataId)) {
return this;
}
return null;
}
public int getSelectedIndex() {
return myListView.getSelectedIndex();
}
@VisibleForTesting
@NotNull
public JBList getListView() {
return myListView;
}
/**
* Renderer for a JList of {@link StackElement} instances.
*/
private static final class StackElementRenderer extends ColoredListCellRenderer<StackElement> {
@Override
protected void customizeCellRenderer(@NotNull JList list,
StackElement value,
int index,
boolean selected,
boolean hasFocus) {
if (value == null) {
return;
}
setIpad(LIST_ROW_INSETS);
if (value instanceof CodeElement) {
CodeElement element = (CodeElement)value;
if (element.getCodeLocation().isNativeCode()) {
renderNativeStackFrame(element, selected);
}
else {
renderJavaStackFrame(element, selected);
}
}
else if (value instanceof ThreadElement) {
renderThreadElement((ThreadElement)value, selected);
}
else {
append(value.toString(), SimpleTextAttributes.ERROR_ATTRIBUTES);
}
}
private void renderJavaStackFrame(@NotNull CodeElement codeElement, boolean selected) {
setIcon(IconManager.getInstance().getPlatformIcon(PlatformIcons.Method));
SimpleTextAttributes textAttribute =
selected || codeElement.isInUserCode() ? SimpleTextAttributes.REGULAR_ATTRIBUTES : SimpleTextAttributes.GRAY_ATTRIBUTES;
CodeLocation location = codeElement.getCodeLocation();
StringBuilder methodBuilder = new StringBuilder(codeElement.getMethodName());
if (location.getLineNumber() != CodeLocation.INVALID_LINE_NUMBER) {
methodBuilder.append(":");
methodBuilder.append(location.getLineNumber() + 1);
}
methodBuilder.append(", ");
methodBuilder.append(codeElement.getSimpleClassName());
String methodName = methodBuilder.toString();
append(methodName, textAttribute, methodName);
String packageName = " (" + codeElement.getPackageName() + ")";
append(packageName, selected ? SimpleTextAttributes.REGULAR_ITALIC_ATTRIBUTES : SimpleTextAttributes.GRAYED_ITALIC_ATTRIBUTES,
packageName);
}
private void renderNativeStackFrame(@NotNull CodeElement codeElement, boolean selected) {
setIcon(IconManager.getInstance().getPlatformIcon(PlatformIcons.Method));
CodeLocation location = codeElement.getCodeLocation();
StringBuilder methodBuilder = new StringBuilder();
if (!Strings.isNullOrEmpty(location.getClassName())) {
methodBuilder.append(location.getClassName());
methodBuilder.append("::");
}
methodBuilder.append(location.getMethodName());
methodBuilder.append("(" + String.join(",", location.getMethodParameters()) + ") ");
String methodName = methodBuilder.toString();
append(methodName, SimpleTextAttributes.REGULAR_ATTRIBUTES, methodName);
if (!Strings.isNullOrEmpty(location.getFileName())) {
String sourceLocation = Paths.get(location.getFileName()).getFileName().toString();
if (location.getLineNumber() != CodeLocation.INVALID_LINE_NUMBER) {
sourceLocation += ":" + String.valueOf(location.getLineNumber() + 1);
}
append(sourceLocation, SimpleTextAttributes.REGULAR_ATTRIBUTES, sourceLocation);
}
String moduleName = " " + Paths.get(location.getNativeModuleName()).getFileName().toString();
append(moduleName, selected ? SimpleTextAttributes.REGULAR_ITALIC_ATTRIBUTES : SimpleTextAttributes.GRAYED_ITALIC_ATTRIBUTES,
moduleName);
}
private void renderThreadElement(@NotNull ThreadElement threadElement, boolean selected) {
setIcon(AllIcons.Debugger.ThreadSuspended);
String text = threadElement.getThreadId().toString();
append(text, selected ? SimpleTextAttributes.REGULAR_ATTRIBUTES : SimpleTextAttributes.GRAY_ATTRIBUTES, text);
}
}
}
|
45867_19 | // Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.jetbrains.python.sdk;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.execution.target.TargetEnvironmentConfiguration;
import com.intellij.ide.DataManager;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationListener;
import com.intellij.notification.NotificationType;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.*;
import com.intellij.openapi.roots.OrderRootType;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.KeyWithDefaultValue;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.HtmlBuilder;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.JarFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.reference.SoftReference;
import com.intellij.remote.ExceptionFix;
import com.intellij.remote.VagrantNotStartedException;
import com.intellij.remote.ext.LanguageCaseCollector;
import com.intellij.util.Consumer;
import com.intellij.util.ExceptionUtil;
import com.intellij.util.PlatformUtils;
import com.intellij.util.containers.ContainerUtil;
import com.jetbrains.python.PyBundle;
import com.jetbrains.python.PyNames;
import com.jetbrains.python.psi.LanguageLevel;
import com.jetbrains.python.psi.icons.PythonPsiApiIcons;
import com.jetbrains.python.remote.PyCredentialsContribution;
import com.jetbrains.python.remote.PyRemoteInterpreterUtil;
import com.jetbrains.python.remote.PyRemoteSdkAdditionalDataBase;
import com.jetbrains.python.remote.PythonRemoteInterpreterManager;
import com.jetbrains.python.sdk.add.PyAddSdkDialog;
import com.jetbrains.python.sdk.add.target.PyDetectedSdkAdditionalData;
import com.jetbrains.python.sdk.flavors.CPythonSdkFlavor;
import com.jetbrains.python.sdk.flavors.PythonSdkFlavor;
import com.jetbrains.python.target.PyInterpreterVersionUtil;
import com.jetbrains.python.target.PyTargetAwareAdditionalData;
import one.util.streamex.StreamEx;
import org.jdom.Element;
import org.jetbrains.annotations.*;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.lang.ref.WeakReference;
import java.nio.file.Paths;
import java.util.List;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import static com.intellij.execution.target.TargetBasedSdks.loadTargetConfiguration;
/**
* Class should be final and singleton since some code checks its instance by ref.
*/
public final class PythonSdkType extends SdkType {
@ApiStatus.Internal public static final @NotNull Key<List<String>> MOCK_SYS_PATH_KEY = Key.create("PY_MOCK_SYS_PATH_KEY");
@ApiStatus.Internal public static final @NotNull Key<String> MOCK_PY_VERSION_KEY = Key.create("PY_MOCK_PY_VERSION_KEY");
@ApiStatus.Internal public static final @NotNull Key<Boolean> MOCK_PY_MARKER_KEY = KeyWithDefaultValue.create("MOCK_PY_MARKER_KEY", true);
private static final Logger LOG = Logger.getInstance(PythonSdkType.class);
private static final int MINUTE = 60 * 1000; // 60 seconds, used with script timeouts
private static final @NonNls String SKELETONS_TOPIC = "Skeletons";
private static final Key<WeakReference<Component>> SDK_CREATOR_COMPONENT_KEY = Key.create("#com.jetbrains.python.sdk.creatorComponent");
/**
* Old configuration may have this prefix in homepath. We must remove it
*/
private static final @NotNull String LEGACY_TARGET_PREFIX = "target://";
public static PythonSdkType getInstance() {
return SdkType.findInstance(PythonSdkType.class);
}
private PythonSdkType() {
super(PyNames.PYTHON_SDK_ID_NAME); //don't change this call as the string used for comparison
}
@Override
public Icon getIcon() {
return PythonPsiApiIcons.Python;
}
@Override
public @NotNull String getHelpTopic() {
return "reference.project.structure.sdk.python";
}
@Override
public @NonNls @Nullable String suggestHomePath() {
return null;
}
@Override
public @NotNull Collection<String> suggestHomePaths() {
final Sdk[] existingSdks = ReadAction.compute(() -> ProjectJdkTable.getInstance().getAllJdks());
final List<PyDetectedSdk> sdks = PySdkExtKt.detectSystemWideSdks(null, Arrays.asList(existingSdks));
//return all detected items after PY-41218 is fixed
final PyDetectedSdk latest = StreamEx.of(sdks).findFirst().orElse(null);
if (latest != null) {
return Collections.singleton(latest.getHomePath());
}
return Collections.emptyList();
}
@Override
public boolean isValidSdkHome(final @NotNull String path) {
return PythonSdkFlavor.getFlavor(path) != null;
}
@Override
public @NotNull FileChooserDescriptor getHomeChooserDescriptor() {
final var descriptor = new FileChooserDescriptor(true, false, false, false, false, false) {
@Override
public void validateSelectedFiles(VirtualFile @NotNull [] files) throws Exception {
if (files.length != 0) {
VirtualFile file = files[0];
if (!isLocatedInWsl(file) && !isValidSdkHome(file.getPath())) {
throw new Exception(PyBundle.message("python.sdk.error.invalid.interpreter.name", file.getName()));
}
}
}
@Override
public boolean isFileVisible(VirtualFile file, boolean showHiddenFiles) {
// TODO: add a better, customizable filtering
if (!file.isDirectory()) {
if (isLocatedInLocalWindowsFS(file)) {
String path = file.getPath();
boolean looksExecutable = false;
for (String ext : PythonSdkUtil.WINDOWS_EXECUTABLE_SUFFIXES) {
if (path.endsWith(ext)) {
looksExecutable = true;
break;
}
}
return looksExecutable && super.isFileVisible(file, showHiddenFiles);
}
}
return super.isFileVisible(file, showHiddenFiles);
}
}.withTitle(PyBundle.message("sdk.select.path")).withShowHiddenFiles(SystemInfo.isUnix);
// XXX: Workaround for PY-21787 and PY-43507 since the native macOS dialog always follows symlinks
if (SystemInfo.isMac) {
descriptor.setForcedToUseIdeaFileChooser(true);
}
return descriptor;
}
private static boolean isLocatedInLocalWindowsFS(@NotNull VirtualFile file) {
return SystemInfo.isWindows && !isCustomPythonSdkHomePath(file.getPath());
}
private static boolean isLocatedInWsl(@NotNull VirtualFile file) {
return SystemInfo.isWindows && isCustomPythonSdkHomePath(file.getPath());
}
@Override
public boolean supportsCustomCreateUI() {
return true;
}
@Override
public void showCustomCreateUI(@NotNull SdkModel sdkModel,
@NotNull JComponent parentComponent,
@Nullable Sdk selectedSdk,
@NotNull Consumer<? super Sdk> sdkCreatedCallback) {
Project project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(parentComponent));
PyAddSdkDialog.show(project, null, Arrays.asList(sdkModel.getSdks()), sdk -> {
if (sdk != null) {
sdk.putUserData(SDK_CREATOR_COMPONENT_KEY, new WeakReference<>(parentComponent));
sdkCreatedCallback.consume(sdk);
}
});
}
/**
* Alters PATH so that a virtualenv is activated, if present.
*
* @param commandLine what to patch
* @param sdk SDK we're using
*/
public static void patchCommandLineForVirtualenv(@NotNull GeneralCommandLine commandLine,
@NotNull Sdk sdk) {
patchEnvironmentVariablesForVirtualenv(commandLine.getEnvironment(), sdk);
}
/**
* Alters PATH so that a virtualenv is activated, if present.
*
* @param environment the environment to patch
* @param sdk SDK we're using
*/
public static void patchEnvironmentVariablesForVirtualenv(@NotNull Map<String, String> environment,
@NotNull Sdk sdk) {
final Map<String, String> virtualEnv = PySdkUtil.activateVirtualEnv(sdk);
if (!virtualEnv.isEmpty()) {
for (Map.Entry<String, String> entry : virtualEnv.entrySet()) {
final String key = entry.getKey();
final String value = entry.getValue();
if (environment.containsKey(key)) {
if (key.equalsIgnoreCase(PySdkUtil.PATH_ENV_VARIABLE)) {
PythonEnvUtil.addToPathEnvVar(environment.get(key), value, false);
}
}
else {
environment.put(key, value);
}
}
}
}
@Override
public @NotNull String suggestSdkName(final @Nullable String currentSdkName, final @NotNull String sdkHome) {
final String name = StringUtil.notNullize(suggestBaseSdkName(sdkHome), "Unknown");
final File virtualEnvRoot = PythonSdkUtil.getVirtualEnvRoot(sdkHome);
if (virtualEnvRoot != null) {
final String path = FileUtil.getLocationRelativeToUserHome(virtualEnvRoot.getAbsolutePath());
return name + " virtualenv at " + path;
}
else {
return name;
}
}
public static @Nullable String suggestBaseSdkName(@NotNull String sdkHome) {
final PythonSdkFlavor flavor = PythonSdkFlavor.getFlavor(sdkHome);
if (flavor == null) return null;
return flavor.getName() + " " + flavor.getLanguageLevel(sdkHome);
}
@Override
public @Nullable AdditionalDataConfigurable createAdditionalDataConfigurable(final @NotNull SdkModel sdkModel,
final @NotNull SdkModificator sdkModificator) {
return null;
}
@Override
public void saveAdditionalData(final @NotNull SdkAdditionalData additionalData, final @NotNull Element additional) {
if (additionalData instanceof PythonSdkAdditionalData) {
((PythonSdkAdditionalData)additionalData).save(additional);
}
}
@Override
public SdkAdditionalData loadAdditionalData(final @NotNull Sdk currentSdk, final @NotNull Element additional) {
String homePath = currentSdk.getHomePath();
if (homePath != null) {
// We decided to get rid of this prefix
if (homePath.startsWith(LEGACY_TARGET_PREFIX)) {
((SdkModificator)currentSdk).setHomePath(homePath.substring(LEGACY_TARGET_PREFIX.length()));
}
if (additional.getAttributeBooleanValue(PyDetectedSdkAdditionalData.PY_DETECTED_SDK_MARKER)) {
PyDetectedSdkAdditionalData data = new PyDetectedSdkAdditionalData(null, null);
data.load(additional);
TargetEnvironmentConfiguration targetEnvironmentConfiguration = loadTargetConfiguration(additional);
if (targetEnvironmentConfiguration != null) {
data.setTargetEnvironmentConfiguration(targetEnvironmentConfiguration);
}
return data;
}
var targetAdditionalData = PyTargetAwareAdditionalData.loadTargetAwareData(currentSdk, additional);
if (targetAdditionalData != null) {
return targetAdditionalData;
}
else if (isCustomPythonSdkHomePath(homePath)) {
PythonRemoteInterpreterManager manager = PythonRemoteInterpreterManager.getInstance();
if (manager != null) {
return manager.loadRemoteSdkData(currentSdk, additional);
}
// TODO we should have "remote" SDK data with unknown credentials anyway!
}
}
var additionalData = PySdkProvider.EP_NAME.getExtensionList().stream()
.map(ext -> ext.loadAdditionalDataForSdk(additional))
.filter(data -> data != null)
.findFirst()
.orElseGet(() -> PythonSdkAdditionalData.loadFromElement(additional));
// Convert legacy conda SDK, temporary fix.
PyCondaSdkFixKt.fixPythonCondaSdk(currentSdk, additionalData);
return additionalData;
}
/**
* Returns whether provided Python interpreter path corresponds to custom
* Python SDK.
*
* @param homePath SDK home path
* @return whether provided Python interpreter path corresponds to custom Python SDK
*/
@Contract(pure = true)
static boolean isCustomPythonSdkHomePath(@NotNull String homePath) {
return PythonSdkUtil.isCustomPythonSdkHomePath(homePath);
}
public static boolean isSkeletonsPath(String path) {
return path.contains(PythonSdkUtil.SKELETON_DIR_NAME);
}
@Override
public @NotNull @NonNls String getPresentableName() {
return "Python SDK";
}
@Override
public @NotNull String sdkPath(@NotNull VirtualFile homePath) {
String path = super.sdkPath(homePath);
PythonSdkFlavor flavor = PythonSdkFlavor.getFlavor(path);
if (flavor != null) {
VirtualFile sdkPath = flavor.getSdkPath(homePath);
if (sdkPath != null) {
return FileUtil.toSystemDependentName(sdkPath.getPath());
}
}
return FileUtil.toSystemDependentName(path);
}
@Override
public void setupSdkPaths(@NotNull Sdk sdk) {
if (PlatformUtils.isFleetBackend()) return;
final WeakReference<Component> ownerComponentRef = sdk.getUserData(SDK_CREATOR_COMPONENT_KEY);
final Component ownerComponent = SoftReference.dereference(ownerComponentRef);
AtomicReference<Project> projectRef = new AtomicReference<>();
ApplicationManager.getApplication().invokeAndWait(() -> {
if (ownerComponent != null) {
projectRef.set(CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(ownerComponent)));
}
else {
projectRef.set(CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext()));
}
});
PythonSdkUpdater.updateOrShowError(sdk, projectRef.get(), ownerComponent);
}
@Override
public boolean setupSdkPaths(@NotNull Sdk sdk, @NotNull SdkModel sdkModel) {
return true; // run setupSdkPaths only once (from PythonSdkDetailsStep). Skip this from showCustomCreateUI
}
public static void notifyRemoteSdkSkeletonsFail(final InvalidSdkException e, final @Nullable Runnable restartAction) {
NotificationListener notificationListener;
String notificationMessage;
if (e.getCause() instanceof VagrantNotStartedException) {
notificationListener =
(notification, event) -> {
final PythonRemoteInterpreterManager manager = PythonRemoteInterpreterManager.getInstance();
if (manager != null) {
try {
VagrantNotStartedException cause = (VagrantNotStartedException)e.getCause();
manager.runVagrant(cause.getVagrantFolder(), cause.getMachineName());
}
catch (ExecutionException e1) {
throw new RuntimeException(e1);
}
}
if (restartAction != null) {
restartAction.run();
}
};
notificationMessage = new HtmlBuilder()
.append(e.getMessage())
.appendLink("#", PyBundle.message("python.vagrant.refresh.skeletons"))
.toString();
}
else if (ExceptionUtil.causedBy(e, ExceptionFix.class)) {
final ExceptionFix fix = ExceptionUtil.findCause(e, ExceptionFix.class);
notificationListener =
(notification, event) -> {
fix.apply();
if (restartAction != null) {
restartAction.run();
}
};
notificationMessage = fix.getNotificationMessage(e.getMessage());
}
else {
notificationListener = null;
notificationMessage = e.getMessage();
}
Notification notification =
new Notification("Python SDK Updater", PyBundle.message("sdk.gen.failed.notification.title"), notificationMessage,
NotificationType.WARNING);
if (notificationListener != null) notification.setListener(notificationListener);
notification.notify(null);
}
public static @NotNull VirtualFile getSdkRootVirtualFile(@NotNull VirtualFile path) {
String suffix = path.getExtension();
if (suffix != null) {
suffix = StringUtil.toLowerCase(suffix); // Why on earth empty suffix is null and not ""?
}
if (!path.isDirectory() && ("zip".equals(suffix) || "egg".equals(suffix))) {
// a .zip / .egg file must have its root extracted first
final VirtualFile jar = JarFileSystem.getInstance().getJarRootForLocalFile(path);
if (jar != null) {
return jar;
}
}
return path;
}
@Override
public String getVersionString(@NotNull Sdk sdk) {
SdkAdditionalData sdkAdditionalData = sdk.getSdkAdditionalData();
if (sdkAdditionalData instanceof PyTargetAwareAdditionalData) {
// TODO [targets] Cache version as for `PyRemoteSdkAdditionalDataBase`
String versionString;
try {
versionString = PyInterpreterVersionUtil.getInterpreterVersion((PyTargetAwareAdditionalData)sdkAdditionalData, null, true);
}
catch (Exception e) {
versionString = "undefined";
}
return versionString;
}
else if (sdkAdditionalData instanceof PyRemoteSdkAdditionalDataBase data) {
assert data != null;
String versionString = data.getVersionString();
if (StringUtil.isEmpty(versionString)) {
try {
versionString =
PyRemoteInterpreterUtil.getInterpreterVersion(null, data, true);
}
catch (Exception e) {
LOG.warn("Couldn't get interpreter version:" + e.getMessage(), e);
versionString = "undefined";
}
data.setVersionString(versionString);
}
return versionString;
}
else {
if (ApplicationManager.getApplication().isUnitTestMode()) {
final var version = sdk.getUserData(MOCK_PY_VERSION_KEY);
if (version != null) {
return version;
}
}
String homePath = sdk.getHomePath();
return homePath == null ? null : getVersionString(homePath);
}
}
@Override
public @Nullable String getVersionString(final @NotNull String sdkHome) {
// Paths like \\wsl and ssh:// can't be used here
if (isCustomPythonSdkHomePath(sdkHome)) {
return null;
}
final PythonSdkFlavor flavor = PythonSdkFlavor.getFlavor(sdkHome);
return flavor != null ? flavor.getVersionString(sdkHome) : null;
}
@Override
public boolean isRootTypeApplicable(final @NotNull OrderRootType type) {
return type == OrderRootType.CLASSES;
}
@Override
public boolean sdkHasValidPath(@NotNull Sdk sdk) {
if (PythonSdkUtil.isRemote(sdk)) {
return true;
}
VirtualFile homeDir = sdk.getHomeDirectory();
return homeDir != null && homeDir.isValid();
}
public static boolean isIncompleteRemote(@NotNull Sdk sdk) {
if (sdk.getSdkAdditionalData() instanceof PyRemoteSdkAdditionalDataBase) {
if (!((PyRemoteSdkAdditionalDataBase)sdk.getSdkAdditionalData()).isValid()) {
return true;
}
}
return false;
}
public static boolean isRunAsRootViaSudo(@NotNull Sdk sdk) {
SdkAdditionalData data = sdk.getSdkAdditionalData();
return data instanceof PyRemoteSdkAdditionalDataBase pyRemoteSdkAdditionalData && pyRemoteSdkAdditionalData.isRunAsRootViaSudo() ||
data instanceof PyTargetAwareAdditionalData pyTargetAwareAdditionalData && pyTargetAwareAdditionalData.isRunAsRootViaSudo();
}
public static boolean hasInvalidRemoteCredentials(@NotNull Sdk sdk) {
if (sdk.getSdkAdditionalData() instanceof PyRemoteSdkAdditionalDataBase) {
final Ref<Boolean> result = Ref.create(false);
((PyRemoteSdkAdditionalDataBase)sdk.getSdkAdditionalData()).switchOnConnectionType(
new LanguageCaseCollector<PyCredentialsContribution>() {
@Override
protected void processLanguageContribution(PyCredentialsContribution languageContribution, Object credentials) {
result.set(!languageContribution.isValid(credentials));
}
}.collectCases(PyCredentialsContribution.class));
return result.get();
}
return false;
}
public static @NotNull String getSdkKey(@NotNull Sdk sdk) {
return sdk.getName();
}
@Override
public boolean isLocalSdk(@NotNull Sdk sdk) {
return !PythonSdkUtil.isRemote(sdk);
}
public static @Nullable Sdk findLocalCPython(@Nullable Module module) {
final Sdk moduleSDK = PythonSdkUtil.findPythonSdk(module);
return findLocalCPythonForSdk(moduleSDK);
}
public static @Nullable Sdk findLocalCPythonForSdk(@Nullable Sdk existingSdk) {
if (existingSdk != null && !PythonSdkUtil.isRemote(existingSdk) && PythonSdkFlavor.getFlavor(existingSdk) instanceof CPythonSdkFlavor) {
return existingSdk;
}
for (Sdk sdk : ContainerUtil.sorted(PythonSdkUtil.getAllSdks(), PreferredSdkComparator.INSTANCE)) {
if (!PythonSdkUtil.isRemote(sdk)) {
return sdk;
}
}
return null;
}
/**
* @deprecated use {@link PySdkUtil#getLanguageLevelForSdk(com.intellij.openapi.projectRoots.Sdk)} instead
*/
@Deprecated(forRemoval = true)
public static @NotNull LanguageLevel getLanguageLevelForSdk(@Nullable Sdk sdk) {
return PySdkUtil.getLanguageLevelForSdk(sdk);
}
public static @Nullable Sdk findPython2Sdk(@Nullable Module module) {
final Sdk moduleSDK = PythonSdkUtil.findPythonSdk(module);
if (moduleSDK != null && getLanguageLevelForSdk(moduleSDK).isPython2()) {
return moduleSDK;
}
return findPython2Sdk(PythonSdkUtil.getAllSdks());
}
public static @Nullable Sdk findPython2Sdk(@NotNull List<? extends Sdk> sdks) {
for (Sdk sdk : ContainerUtil.sorted(sdks, PreferredSdkComparator.INSTANCE)) {
if (getLanguageLevelForSdk(sdk).isPython2()) {
return sdk;
}
}
return null;
}
@Override
public boolean allowWslSdkForLocalProject() {
return true;
}
/**
* @return if SDK is mock (used by tests only)
*/
@SuppressWarnings("TestOnlyProblems")
public static boolean isMock(@NotNull Sdk sdk) {
return (sdk.getUserData(MOCK_PY_VERSION_KEY) != null) ||
(sdk.getUserData(MOCK_SYS_PATH_KEY) != null) ||
(sdk.getUserData(MOCK_PY_MARKER_KEY) != null);
}
/**
* Returns mocked path (stored in sdk with {@link #MOCK_SYS_PATH_KEY} in test)
*/
public static @NotNull List<String> getMockPath(@NotNull Sdk sdk) {
var workDir = Paths.get(Objects.requireNonNull(sdk.getHomePath())).getParent().toString();
var mockPaths = sdk.getUserData(MOCK_SYS_PATH_KEY);
return mockPaths != null ? Collections.unmodifiableList(mockPaths) : Collections.singletonList(workDir);
}
}
| JetBrains/intellij-community | python/src/com/jetbrains/python/sdk/PythonSdkType.java | 7,016 | /**
* @deprecated use {@link PySdkUtil#getLanguageLevelForSdk(com.intellij.openapi.projectRoots.Sdk)} instead
*/ | block_comment | nl | // Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.jetbrains.python.sdk;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.execution.target.TargetEnvironmentConfiguration;
import com.intellij.ide.DataManager;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationListener;
import com.intellij.notification.NotificationType;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.*;
import com.intellij.openapi.roots.OrderRootType;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.KeyWithDefaultValue;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.HtmlBuilder;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.JarFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.reference.SoftReference;
import com.intellij.remote.ExceptionFix;
import com.intellij.remote.VagrantNotStartedException;
import com.intellij.remote.ext.LanguageCaseCollector;
import com.intellij.util.Consumer;
import com.intellij.util.ExceptionUtil;
import com.intellij.util.PlatformUtils;
import com.intellij.util.containers.ContainerUtil;
import com.jetbrains.python.PyBundle;
import com.jetbrains.python.PyNames;
import com.jetbrains.python.psi.LanguageLevel;
import com.jetbrains.python.psi.icons.PythonPsiApiIcons;
import com.jetbrains.python.remote.PyCredentialsContribution;
import com.jetbrains.python.remote.PyRemoteInterpreterUtil;
import com.jetbrains.python.remote.PyRemoteSdkAdditionalDataBase;
import com.jetbrains.python.remote.PythonRemoteInterpreterManager;
import com.jetbrains.python.sdk.add.PyAddSdkDialog;
import com.jetbrains.python.sdk.add.target.PyDetectedSdkAdditionalData;
import com.jetbrains.python.sdk.flavors.CPythonSdkFlavor;
import com.jetbrains.python.sdk.flavors.PythonSdkFlavor;
import com.jetbrains.python.target.PyInterpreterVersionUtil;
import com.jetbrains.python.target.PyTargetAwareAdditionalData;
import one.util.streamex.StreamEx;
import org.jdom.Element;
import org.jetbrains.annotations.*;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.lang.ref.WeakReference;
import java.nio.file.Paths;
import java.util.List;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import static com.intellij.execution.target.TargetBasedSdks.loadTargetConfiguration;
/**
* Class should be final and singleton since some code checks its instance by ref.
*/
public final class PythonSdkType extends SdkType {
@ApiStatus.Internal public static final @NotNull Key<List<String>> MOCK_SYS_PATH_KEY = Key.create("PY_MOCK_SYS_PATH_KEY");
@ApiStatus.Internal public static final @NotNull Key<String> MOCK_PY_VERSION_KEY = Key.create("PY_MOCK_PY_VERSION_KEY");
@ApiStatus.Internal public static final @NotNull Key<Boolean> MOCK_PY_MARKER_KEY = KeyWithDefaultValue.create("MOCK_PY_MARKER_KEY", true);
private static final Logger LOG = Logger.getInstance(PythonSdkType.class);
private static final int MINUTE = 60 * 1000; // 60 seconds, used with script timeouts
private static final @NonNls String SKELETONS_TOPIC = "Skeletons";
private static final Key<WeakReference<Component>> SDK_CREATOR_COMPONENT_KEY = Key.create("#com.jetbrains.python.sdk.creatorComponent");
/**
* Old configuration may have this prefix in homepath. We must remove it
*/
private static final @NotNull String LEGACY_TARGET_PREFIX = "target://";
public static PythonSdkType getInstance() {
return SdkType.findInstance(PythonSdkType.class);
}
private PythonSdkType() {
super(PyNames.PYTHON_SDK_ID_NAME); //don't change this call as the string used for comparison
}
@Override
public Icon getIcon() {
return PythonPsiApiIcons.Python;
}
@Override
public @NotNull String getHelpTopic() {
return "reference.project.structure.sdk.python";
}
@Override
public @NonNls @Nullable String suggestHomePath() {
return null;
}
@Override
public @NotNull Collection<String> suggestHomePaths() {
final Sdk[] existingSdks = ReadAction.compute(() -> ProjectJdkTable.getInstance().getAllJdks());
final List<PyDetectedSdk> sdks = PySdkExtKt.detectSystemWideSdks(null, Arrays.asList(existingSdks));
//return all detected items after PY-41218 is fixed
final PyDetectedSdk latest = StreamEx.of(sdks).findFirst().orElse(null);
if (latest != null) {
return Collections.singleton(latest.getHomePath());
}
return Collections.emptyList();
}
@Override
public boolean isValidSdkHome(final @NotNull String path) {
return PythonSdkFlavor.getFlavor(path) != null;
}
@Override
public @NotNull FileChooserDescriptor getHomeChooserDescriptor() {
final var descriptor = new FileChooserDescriptor(true, false, false, false, false, false) {
@Override
public void validateSelectedFiles(VirtualFile @NotNull [] files) throws Exception {
if (files.length != 0) {
VirtualFile file = files[0];
if (!isLocatedInWsl(file) && !isValidSdkHome(file.getPath())) {
throw new Exception(PyBundle.message("python.sdk.error.invalid.interpreter.name", file.getName()));
}
}
}
@Override
public boolean isFileVisible(VirtualFile file, boolean showHiddenFiles) {
// TODO: add a better, customizable filtering
if (!file.isDirectory()) {
if (isLocatedInLocalWindowsFS(file)) {
String path = file.getPath();
boolean looksExecutable = false;
for (String ext : PythonSdkUtil.WINDOWS_EXECUTABLE_SUFFIXES) {
if (path.endsWith(ext)) {
looksExecutable = true;
break;
}
}
return looksExecutable && super.isFileVisible(file, showHiddenFiles);
}
}
return super.isFileVisible(file, showHiddenFiles);
}
}.withTitle(PyBundle.message("sdk.select.path")).withShowHiddenFiles(SystemInfo.isUnix);
// XXX: Workaround for PY-21787 and PY-43507 since the native macOS dialog always follows symlinks
if (SystemInfo.isMac) {
descriptor.setForcedToUseIdeaFileChooser(true);
}
return descriptor;
}
private static boolean isLocatedInLocalWindowsFS(@NotNull VirtualFile file) {
return SystemInfo.isWindows && !isCustomPythonSdkHomePath(file.getPath());
}
private static boolean isLocatedInWsl(@NotNull VirtualFile file) {
return SystemInfo.isWindows && isCustomPythonSdkHomePath(file.getPath());
}
@Override
public boolean supportsCustomCreateUI() {
return true;
}
@Override
public void showCustomCreateUI(@NotNull SdkModel sdkModel,
@NotNull JComponent parentComponent,
@Nullable Sdk selectedSdk,
@NotNull Consumer<? super Sdk> sdkCreatedCallback) {
Project project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(parentComponent));
PyAddSdkDialog.show(project, null, Arrays.asList(sdkModel.getSdks()), sdk -> {
if (sdk != null) {
sdk.putUserData(SDK_CREATOR_COMPONENT_KEY, new WeakReference<>(parentComponent));
sdkCreatedCallback.consume(sdk);
}
});
}
/**
* Alters PATH so that a virtualenv is activated, if present.
*
* @param commandLine what to patch
* @param sdk SDK we're using
*/
public static void patchCommandLineForVirtualenv(@NotNull GeneralCommandLine commandLine,
@NotNull Sdk sdk) {
patchEnvironmentVariablesForVirtualenv(commandLine.getEnvironment(), sdk);
}
/**
* Alters PATH so that a virtualenv is activated, if present.
*
* @param environment the environment to patch
* @param sdk SDK we're using
*/
public static void patchEnvironmentVariablesForVirtualenv(@NotNull Map<String, String> environment,
@NotNull Sdk sdk) {
final Map<String, String> virtualEnv = PySdkUtil.activateVirtualEnv(sdk);
if (!virtualEnv.isEmpty()) {
for (Map.Entry<String, String> entry : virtualEnv.entrySet()) {
final String key = entry.getKey();
final String value = entry.getValue();
if (environment.containsKey(key)) {
if (key.equalsIgnoreCase(PySdkUtil.PATH_ENV_VARIABLE)) {
PythonEnvUtil.addToPathEnvVar(environment.get(key), value, false);
}
}
else {
environment.put(key, value);
}
}
}
}
@Override
public @NotNull String suggestSdkName(final @Nullable String currentSdkName, final @NotNull String sdkHome) {
final String name = StringUtil.notNullize(suggestBaseSdkName(sdkHome), "Unknown");
final File virtualEnvRoot = PythonSdkUtil.getVirtualEnvRoot(sdkHome);
if (virtualEnvRoot != null) {
final String path = FileUtil.getLocationRelativeToUserHome(virtualEnvRoot.getAbsolutePath());
return name + " virtualenv at " + path;
}
else {
return name;
}
}
public static @Nullable String suggestBaseSdkName(@NotNull String sdkHome) {
final PythonSdkFlavor flavor = PythonSdkFlavor.getFlavor(sdkHome);
if (flavor == null) return null;
return flavor.getName() + " " + flavor.getLanguageLevel(sdkHome);
}
@Override
public @Nullable AdditionalDataConfigurable createAdditionalDataConfigurable(final @NotNull SdkModel sdkModel,
final @NotNull SdkModificator sdkModificator) {
return null;
}
@Override
public void saveAdditionalData(final @NotNull SdkAdditionalData additionalData, final @NotNull Element additional) {
if (additionalData instanceof PythonSdkAdditionalData) {
((PythonSdkAdditionalData)additionalData).save(additional);
}
}
@Override
public SdkAdditionalData loadAdditionalData(final @NotNull Sdk currentSdk, final @NotNull Element additional) {
String homePath = currentSdk.getHomePath();
if (homePath != null) {
// We decided to get rid of this prefix
if (homePath.startsWith(LEGACY_TARGET_PREFIX)) {
((SdkModificator)currentSdk).setHomePath(homePath.substring(LEGACY_TARGET_PREFIX.length()));
}
if (additional.getAttributeBooleanValue(PyDetectedSdkAdditionalData.PY_DETECTED_SDK_MARKER)) {
PyDetectedSdkAdditionalData data = new PyDetectedSdkAdditionalData(null, null);
data.load(additional);
TargetEnvironmentConfiguration targetEnvironmentConfiguration = loadTargetConfiguration(additional);
if (targetEnvironmentConfiguration != null) {
data.setTargetEnvironmentConfiguration(targetEnvironmentConfiguration);
}
return data;
}
var targetAdditionalData = PyTargetAwareAdditionalData.loadTargetAwareData(currentSdk, additional);
if (targetAdditionalData != null) {
return targetAdditionalData;
}
else if (isCustomPythonSdkHomePath(homePath)) {
PythonRemoteInterpreterManager manager = PythonRemoteInterpreterManager.getInstance();
if (manager != null) {
return manager.loadRemoteSdkData(currentSdk, additional);
}
// TODO we should have "remote" SDK data with unknown credentials anyway!
}
}
var additionalData = PySdkProvider.EP_NAME.getExtensionList().stream()
.map(ext -> ext.loadAdditionalDataForSdk(additional))
.filter(data -> data != null)
.findFirst()
.orElseGet(() -> PythonSdkAdditionalData.loadFromElement(additional));
// Convert legacy conda SDK, temporary fix.
PyCondaSdkFixKt.fixPythonCondaSdk(currentSdk, additionalData);
return additionalData;
}
/**
* Returns whether provided Python interpreter path corresponds to custom
* Python SDK.
*
* @param homePath SDK home path
* @return whether provided Python interpreter path corresponds to custom Python SDK
*/
@Contract(pure = true)
static boolean isCustomPythonSdkHomePath(@NotNull String homePath) {
return PythonSdkUtil.isCustomPythonSdkHomePath(homePath);
}
public static boolean isSkeletonsPath(String path) {
return path.contains(PythonSdkUtil.SKELETON_DIR_NAME);
}
@Override
public @NotNull @NonNls String getPresentableName() {
return "Python SDK";
}
@Override
public @NotNull String sdkPath(@NotNull VirtualFile homePath) {
String path = super.sdkPath(homePath);
PythonSdkFlavor flavor = PythonSdkFlavor.getFlavor(path);
if (flavor != null) {
VirtualFile sdkPath = flavor.getSdkPath(homePath);
if (sdkPath != null) {
return FileUtil.toSystemDependentName(sdkPath.getPath());
}
}
return FileUtil.toSystemDependentName(path);
}
@Override
public void setupSdkPaths(@NotNull Sdk sdk) {
if (PlatformUtils.isFleetBackend()) return;
final WeakReference<Component> ownerComponentRef = sdk.getUserData(SDK_CREATOR_COMPONENT_KEY);
final Component ownerComponent = SoftReference.dereference(ownerComponentRef);
AtomicReference<Project> projectRef = new AtomicReference<>();
ApplicationManager.getApplication().invokeAndWait(() -> {
if (ownerComponent != null) {
projectRef.set(CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(ownerComponent)));
}
else {
projectRef.set(CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext()));
}
});
PythonSdkUpdater.updateOrShowError(sdk, projectRef.get(), ownerComponent);
}
@Override
public boolean setupSdkPaths(@NotNull Sdk sdk, @NotNull SdkModel sdkModel) {
return true; // run setupSdkPaths only once (from PythonSdkDetailsStep). Skip this from showCustomCreateUI
}
public static void notifyRemoteSdkSkeletonsFail(final InvalidSdkException e, final @Nullable Runnable restartAction) {
NotificationListener notificationListener;
String notificationMessage;
if (e.getCause() instanceof VagrantNotStartedException) {
notificationListener =
(notification, event) -> {
final PythonRemoteInterpreterManager manager = PythonRemoteInterpreterManager.getInstance();
if (manager != null) {
try {
VagrantNotStartedException cause = (VagrantNotStartedException)e.getCause();
manager.runVagrant(cause.getVagrantFolder(), cause.getMachineName());
}
catch (ExecutionException e1) {
throw new RuntimeException(e1);
}
}
if (restartAction != null) {
restartAction.run();
}
};
notificationMessage = new HtmlBuilder()
.append(e.getMessage())
.appendLink("#", PyBundle.message("python.vagrant.refresh.skeletons"))
.toString();
}
else if (ExceptionUtil.causedBy(e, ExceptionFix.class)) {
final ExceptionFix fix = ExceptionUtil.findCause(e, ExceptionFix.class);
notificationListener =
(notification, event) -> {
fix.apply();
if (restartAction != null) {
restartAction.run();
}
};
notificationMessage = fix.getNotificationMessage(e.getMessage());
}
else {
notificationListener = null;
notificationMessage = e.getMessage();
}
Notification notification =
new Notification("Python SDK Updater", PyBundle.message("sdk.gen.failed.notification.title"), notificationMessage,
NotificationType.WARNING);
if (notificationListener != null) notification.setListener(notificationListener);
notification.notify(null);
}
public static @NotNull VirtualFile getSdkRootVirtualFile(@NotNull VirtualFile path) {
String suffix = path.getExtension();
if (suffix != null) {
suffix = StringUtil.toLowerCase(suffix); // Why on earth empty suffix is null and not ""?
}
if (!path.isDirectory() && ("zip".equals(suffix) || "egg".equals(suffix))) {
// a .zip / .egg file must have its root extracted first
final VirtualFile jar = JarFileSystem.getInstance().getJarRootForLocalFile(path);
if (jar != null) {
return jar;
}
}
return path;
}
@Override
public String getVersionString(@NotNull Sdk sdk) {
SdkAdditionalData sdkAdditionalData = sdk.getSdkAdditionalData();
if (sdkAdditionalData instanceof PyTargetAwareAdditionalData) {
// TODO [targets] Cache version as for `PyRemoteSdkAdditionalDataBase`
String versionString;
try {
versionString = PyInterpreterVersionUtil.getInterpreterVersion((PyTargetAwareAdditionalData)sdkAdditionalData, null, true);
}
catch (Exception e) {
versionString = "undefined";
}
return versionString;
}
else if (sdkAdditionalData instanceof PyRemoteSdkAdditionalDataBase data) {
assert data != null;
String versionString = data.getVersionString();
if (StringUtil.isEmpty(versionString)) {
try {
versionString =
PyRemoteInterpreterUtil.getInterpreterVersion(null, data, true);
}
catch (Exception e) {
LOG.warn("Couldn't get interpreter version:" + e.getMessage(), e);
versionString = "undefined";
}
data.setVersionString(versionString);
}
return versionString;
}
else {
if (ApplicationManager.getApplication().isUnitTestMode()) {
final var version = sdk.getUserData(MOCK_PY_VERSION_KEY);
if (version != null) {
return version;
}
}
String homePath = sdk.getHomePath();
return homePath == null ? null : getVersionString(homePath);
}
}
@Override
public @Nullable String getVersionString(final @NotNull String sdkHome) {
// Paths like \\wsl and ssh:// can't be used here
if (isCustomPythonSdkHomePath(sdkHome)) {
return null;
}
final PythonSdkFlavor flavor = PythonSdkFlavor.getFlavor(sdkHome);
return flavor != null ? flavor.getVersionString(sdkHome) : null;
}
@Override
public boolean isRootTypeApplicable(final @NotNull OrderRootType type) {
return type == OrderRootType.CLASSES;
}
@Override
public boolean sdkHasValidPath(@NotNull Sdk sdk) {
if (PythonSdkUtil.isRemote(sdk)) {
return true;
}
VirtualFile homeDir = sdk.getHomeDirectory();
return homeDir != null && homeDir.isValid();
}
public static boolean isIncompleteRemote(@NotNull Sdk sdk) {
if (sdk.getSdkAdditionalData() instanceof PyRemoteSdkAdditionalDataBase) {
if (!((PyRemoteSdkAdditionalDataBase)sdk.getSdkAdditionalData()).isValid()) {
return true;
}
}
return false;
}
public static boolean isRunAsRootViaSudo(@NotNull Sdk sdk) {
SdkAdditionalData data = sdk.getSdkAdditionalData();
return data instanceof PyRemoteSdkAdditionalDataBase pyRemoteSdkAdditionalData && pyRemoteSdkAdditionalData.isRunAsRootViaSudo() ||
data instanceof PyTargetAwareAdditionalData pyTargetAwareAdditionalData && pyTargetAwareAdditionalData.isRunAsRootViaSudo();
}
public static boolean hasInvalidRemoteCredentials(@NotNull Sdk sdk) {
if (sdk.getSdkAdditionalData() instanceof PyRemoteSdkAdditionalDataBase) {
final Ref<Boolean> result = Ref.create(false);
((PyRemoteSdkAdditionalDataBase)sdk.getSdkAdditionalData()).switchOnConnectionType(
new LanguageCaseCollector<PyCredentialsContribution>() {
@Override
protected void processLanguageContribution(PyCredentialsContribution languageContribution, Object credentials) {
result.set(!languageContribution.isValid(credentials));
}
}.collectCases(PyCredentialsContribution.class));
return result.get();
}
return false;
}
public static @NotNull String getSdkKey(@NotNull Sdk sdk) {
return sdk.getName();
}
@Override
public boolean isLocalSdk(@NotNull Sdk sdk) {
return !PythonSdkUtil.isRemote(sdk);
}
public static @Nullable Sdk findLocalCPython(@Nullable Module module) {
final Sdk moduleSDK = PythonSdkUtil.findPythonSdk(module);
return findLocalCPythonForSdk(moduleSDK);
}
public static @Nullable Sdk findLocalCPythonForSdk(@Nullable Sdk existingSdk) {
if (existingSdk != null && !PythonSdkUtil.isRemote(existingSdk) && PythonSdkFlavor.getFlavor(existingSdk) instanceof CPythonSdkFlavor) {
return existingSdk;
}
for (Sdk sdk : ContainerUtil.sorted(PythonSdkUtil.getAllSdks(), PreferredSdkComparator.INSTANCE)) {
if (!PythonSdkUtil.isRemote(sdk)) {
return sdk;
}
}
return null;
}
/**
* @deprecated use {@link<SUF>*/
@Deprecated(forRemoval = true)
public static @NotNull LanguageLevel getLanguageLevelForSdk(@Nullable Sdk sdk) {
return PySdkUtil.getLanguageLevelForSdk(sdk);
}
public static @Nullable Sdk findPython2Sdk(@Nullable Module module) {
final Sdk moduleSDK = PythonSdkUtil.findPythonSdk(module);
if (moduleSDK != null && getLanguageLevelForSdk(moduleSDK).isPython2()) {
return moduleSDK;
}
return findPython2Sdk(PythonSdkUtil.getAllSdks());
}
public static @Nullable Sdk findPython2Sdk(@NotNull List<? extends Sdk> sdks) {
for (Sdk sdk : ContainerUtil.sorted(sdks, PreferredSdkComparator.INSTANCE)) {
if (getLanguageLevelForSdk(sdk).isPython2()) {
return sdk;
}
}
return null;
}
@Override
public boolean allowWslSdkForLocalProject() {
return true;
}
/**
* @return if SDK is mock (used by tests only)
*/
@SuppressWarnings("TestOnlyProblems")
public static boolean isMock(@NotNull Sdk sdk) {
return (sdk.getUserData(MOCK_PY_VERSION_KEY) != null) ||
(sdk.getUserData(MOCK_SYS_PATH_KEY) != null) ||
(sdk.getUserData(MOCK_PY_MARKER_KEY) != null);
}
/**
* Returns mocked path (stored in sdk with {@link #MOCK_SYS_PATH_KEY} in test)
*/
public static @NotNull List<String> getMockPath(@NotNull Sdk sdk) {
var workDir = Paths.get(Objects.requireNonNull(sdk.getHomePath())).getParent().toString();
var mockPaths = sdk.getUserData(MOCK_SYS_PATH_KEY);
return mockPaths != null ? Collections.unmodifiableList(mockPaths) : Collections.singletonList(workDir);
}
}
|
98791_43 | // Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
package org.cef.browser;
import org.cef.CefClient;
import org.cef.callback.CefPdfPrintCallback;
import org.cef.callback.CefRunFileDialogCallback;
import org.cef.callback.CefStringVisitor;
import org.cef.handler.CefDialogHandler.FileDialogMode;
import org.cef.handler.CefRenderHandler;
import org.cef.handler.CefWindowHandler;
import org.cef.misc.CefPdfPrintSettings;
import org.cef.network.CefRequest;
import java.awt.Component;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.image.BufferedImage;
import java.util.Vector;
import java.util.concurrent.CompletableFuture;
/**
* Interface representing a browser.
*/
public interface CefBrowser {
/**
* Call to immediately create the underlying browser object. By default the
* browser object will be created when the parent container is displayed for
* the first time.
*/
public void createImmediately();
/**
* Get the underlying UI component (e.g. java.awt.Canvas).
* @return The underlying UI component.
*/
public Component getUIComponent();
/**
* Get the client associated with this browser.
* @return The browser client.
*/
public CefClient getClient();
/**
* Get an implementation of CefRenderHandler if any.
* @return An instance of CefRenderHandler or null.
*/
public CefRenderHandler getRenderHandler();
/**
* Get an implementation of CefWindowHandler if any.
* @return An instance of CefWindowHandler or null.
*/
public CefWindowHandler getWindowHandler();
//
// The following methods are forwarded to CefBrowser.
//
/**
* Tests if the browser can navigate backwards.
* @return true if the browser can navigate backwards.
*/
public boolean canGoBack();
/**
* Go back.
*/
public void goBack();
/**
* Tests if the browser can navigate forwards.
* @return true if the browser can navigate forwards.
*/
public boolean canGoForward();
/**
* Go forward.
*/
public void goForward();
/**
* Tests if the browser is currently loading.
* @return true if the browser is currently loading.
*/
public boolean isLoading();
/**
* Reload the current page.
*/
public void reload();
/**
* Reload the current page ignoring any cached data.
*/
public void reloadIgnoreCache();
/**
* Stop loading the page.
*/
public void stopLoad();
/**
* Returns the unique browser identifier.
* @return The browser identifier
*/
public int getIdentifier();
/**
* Returns the main (top-level) frame for the browser window.
* @return The main frame
*/
public CefFrame getMainFrame();
/**
* Returns the focused frame for the browser window.
* @return The focused frame
*/
public CefFrame getFocusedFrame();
/**
* Returns the frame with the specified identifier, or NULL if not found.
* @param identifier The unique frame identifier
* @return The frame or NULL if not found
*/
public CefFrame getFrame(long identifier);
/**
* Returns the frame with the specified name, or NULL if not found.
* @param name The specified name
* @return The frame or NULL if not found
*/
public CefFrame getFrame(String name);
/**
* Returns the identifiers of all existing frames.
* @return All identifiers of existing frames.
*/
public Vector<Long> getFrameIdentifiers();
/**
* Returns the names of all existing frames.
* @return The names of all existing frames.
*/
public Vector<String> getFrameNames();
/**
* Returns the number of frames that currently exist.
* @return The number of frames
*/
public int getFrameCount();
/**
* Tests if the window is a popup window.
* @return true if the window is a popup window.
*/
public boolean isPopup();
/**
* Tests if a document has been loaded in the browser.
* @return true if a document has been loaded in the browser.
*/
public boolean hasDocument();
//
// The following methods are forwarded to the mainFrame.
//
/**
* Save this frame's HTML source to a temporary file and open it in the
* default text viewing application. This method can only be called from the
* browser process.
*/
public void viewSource();
/**
* Retrieve this frame's HTML source as a string sent to the specified
* visitor.
*
* @param visitor
*/
public void getSource(CefStringVisitor visitor);
/**
* Retrieve this frame's display text as a string sent to the specified
* visitor.
*
* @param visitor
*/
public void getText(CefStringVisitor visitor);
/**
* Load the request represented by the request object.
*
* @param request The request object.
*/
public void loadRequest(CefRequest request);
/**
* Load the specified URL in the main frame.
* @param url The URL to load.
*/
public void loadURL(String url);
/**
* Execute a string of JavaScript code in this frame. The url
* parameter is the URL where the script in question can be found, if any.
* The renderer may request this URL to show the developer the source of the
* error. The line parameter is the base line number to use for error
* reporting.
*
* @param code The code to be executed.
* @param url The URL where the script in question can be found.
* @param line The base line number to use for error reporting.
*/
public void executeJavaScript(String code, String url, int line);
/**
* Emits the URL currently loaded in this frame.
* @return the URL currently loaded in this frame.
*/
public String getURL();
// The following methods are forwarded to CefBrowserHost.
/**
* Request that the browser close.
* @param force force the close.
*/
public void close(boolean force);
/**
* Allow the browser to close.
*/
public void setCloseAllowed();
/**
* Called from CefClient.doClose.
*/
public boolean doClose();
/**
* Called from CefClient.onBeforeClose.
*/
public void onBeforeClose();
/**
* Set or remove keyboard focus to/from the browser window.
* @param enable set to true to give the focus to the browser
**/
public void setFocus(boolean enable);
/**
* Set whether the window containing the browser is visible
* (minimized/unminimized, app hidden/unhidden, etc). Only used on Mac OS X.
* @param visible
*/
public void setWindowVisibility(boolean visible);
/**
* Get the current zoom level. The default zoom level is 0.0.
* @return The current zoom level.
*/
public double getZoomLevel();
/**
* Change the zoom level to the specified value. Specify 0.0 to reset the
* zoom level.
*
* @param zoomLevel The zoom level to be set.
*/
public void setZoomLevel(double zoomLevel);
/**
* Call to run a file chooser dialog. Only a single file chooser dialog may be
* pending at any given time.The dialog will be initiated asynchronously on
* the UI thread.
*
* @param mode represents the type of dialog to display.
* @param title to be used for the dialog and may be empty to show the
* default title ("Open" or "Save" depending on the mode).
* @param defaultFilePath is the path with optional directory and/or file name
* component that should be initially selected in the dialog.
* @param acceptFilters are used to restrict the selectable file types and may
* any combination of (a) valid lower-cased MIME types (e.g. "text/*" or
* "image/*"), (b) individual file extensions (e.g. ".txt" or ".png"), or (c)
* combined description and file extension delimited using "|" and ";" (e.g.
* "Image Types|.png;.gif;.jpg").
* @param selectedAcceptFilter is the 0-based index of the filter that should
* be selected by default.
* @param callback will be executed after the dialog is dismissed or
* immediately if another dialog is already pending.
*/
public void runFileDialog(FileDialogMode mode, String title, String defaultFilePath,
Vector<String> acceptFilters, int selectedAcceptFilter,
CefRunFileDialogCallback callback);
/**
* Download the file at url using CefDownloadHandler.
*
* @param url URL to download that file.
*/
public void startDownload(String url);
/**
* Print the current browser contents.
*/
public void print();
/**
* Print the current browser contents to a PDF.
*
* @param path The path of the file to write to (will be overwritten if it
* already exists). Cannot be null.
* @param settings The pdf print settings to use. If null then defaults
* will be used.
* @param callback Called when the pdf print job has completed.
*/
public void printToPDF(String path, CefPdfPrintSettings settings, CefPdfPrintCallback callback);
/**
* Search for some kind of text on the page.
*
* @param identifier can be used to have multiple searches running simultaniously.
* @param searchText to be searched for.
* @param forward indicates whether to search forward or backward within the page.
* @param matchCase indicates whether the search should be case-sensitive.
* @param findNext indicates whether this is the first request or a follow-up.
*/
public void find(int identifier, String searchText, boolean forward, boolean matchCase,
boolean findNext);
/**
* Cancel all searches that are currently going on.
* @param clearSelection Set to true to reset selection.
*/
public void stopFinding(boolean clearSelection);
/**
* Get an instance of the dev tools to be displayed in its own window or to be
* embedded within your UI. Only one instance per browser is available.
*/
public CefBrowser getDevTools();
/**
* Get an instance of the dev tools to be displayed in its own window or to be
* embedded within your UI. Only one instance per browser is available.
*
* @param inspectAt a position in the UI which should be inspected.
*/
public CefBrowser getDevTools(Point inspectAt);
/**
* If a misspelled word is currently selected in an editable node calling
* this method will replace it with the specified |word|.
*
* @param word replace selected word with this word.
*/
public void replaceMisspelling(String word);
/**
* @since api-1.2
*/
void wasResized(int width, int height);
/**
* @since api-1.2
*/
void sendKeyEvent(KeyEvent e);
/**
* @since api-1.2
*/
void sendMouseEvent(MouseEvent e);
/**
* @since api-1.2
*/
void sendMouseWheelEvent(MouseWheelEvent e);
/**
* Captures a screenshot-like image of the currently displayed content and returns it.
* <p>
* If executed on the AWT Event Thread, this returns an immediately resolved {@link
* java.util.concurrent.CompletableFuture}. If executed from another thread, the {@link
* java.util.concurrent.CompletableFuture} returned is resolved as soon as the screenshot
* has been taken (which must happen on the event thread).
* <p>
* The generated screenshot can either be returned as-is, containing all natively-rendered
* pixels, or it can be scaled to match the logical width and height of the window.
* This distinction is only relevant in case of differing logical and physical resolutions
* (for example with HiDPI/Retina displays, which have a scaling factor of for example 2
* between the logical width of a window (ex. 400px) and the actual number of pixels in
* each row (ex. 800px with a scaling factor of 2)).
*
* @param nativeResolution whether to return an image at full native resolution (true)
* or a scaled-down version whose width and height are equal to the logical size
* of the screenshotted browser window
* @return the screenshot image
* @throws UnsupportedOperationException if not supported
*/
public CompletableFuture<BufferedImage> createScreenshot(boolean nativeResolution);
}
| JetBrains/jcef | java/org/cef/browser/CefBrowser.java | 3,380 | /**
* Get the current zoom level. The default zoom level is 0.0.
* @return The current zoom level.
*/ | block_comment | nl | // Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
package org.cef.browser;
import org.cef.CefClient;
import org.cef.callback.CefPdfPrintCallback;
import org.cef.callback.CefRunFileDialogCallback;
import org.cef.callback.CefStringVisitor;
import org.cef.handler.CefDialogHandler.FileDialogMode;
import org.cef.handler.CefRenderHandler;
import org.cef.handler.CefWindowHandler;
import org.cef.misc.CefPdfPrintSettings;
import org.cef.network.CefRequest;
import java.awt.Component;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.image.BufferedImage;
import java.util.Vector;
import java.util.concurrent.CompletableFuture;
/**
* Interface representing a browser.
*/
public interface CefBrowser {
/**
* Call to immediately create the underlying browser object. By default the
* browser object will be created when the parent container is displayed for
* the first time.
*/
public void createImmediately();
/**
* Get the underlying UI component (e.g. java.awt.Canvas).
* @return The underlying UI component.
*/
public Component getUIComponent();
/**
* Get the client associated with this browser.
* @return The browser client.
*/
public CefClient getClient();
/**
* Get an implementation of CefRenderHandler if any.
* @return An instance of CefRenderHandler or null.
*/
public CefRenderHandler getRenderHandler();
/**
* Get an implementation of CefWindowHandler if any.
* @return An instance of CefWindowHandler or null.
*/
public CefWindowHandler getWindowHandler();
//
// The following methods are forwarded to CefBrowser.
//
/**
* Tests if the browser can navigate backwards.
* @return true if the browser can navigate backwards.
*/
public boolean canGoBack();
/**
* Go back.
*/
public void goBack();
/**
* Tests if the browser can navigate forwards.
* @return true if the browser can navigate forwards.
*/
public boolean canGoForward();
/**
* Go forward.
*/
public void goForward();
/**
* Tests if the browser is currently loading.
* @return true if the browser is currently loading.
*/
public boolean isLoading();
/**
* Reload the current page.
*/
public void reload();
/**
* Reload the current page ignoring any cached data.
*/
public void reloadIgnoreCache();
/**
* Stop loading the page.
*/
public void stopLoad();
/**
* Returns the unique browser identifier.
* @return The browser identifier
*/
public int getIdentifier();
/**
* Returns the main (top-level) frame for the browser window.
* @return The main frame
*/
public CefFrame getMainFrame();
/**
* Returns the focused frame for the browser window.
* @return The focused frame
*/
public CefFrame getFocusedFrame();
/**
* Returns the frame with the specified identifier, or NULL if not found.
* @param identifier The unique frame identifier
* @return The frame or NULL if not found
*/
public CefFrame getFrame(long identifier);
/**
* Returns the frame with the specified name, or NULL if not found.
* @param name The specified name
* @return The frame or NULL if not found
*/
public CefFrame getFrame(String name);
/**
* Returns the identifiers of all existing frames.
* @return All identifiers of existing frames.
*/
public Vector<Long> getFrameIdentifiers();
/**
* Returns the names of all existing frames.
* @return The names of all existing frames.
*/
public Vector<String> getFrameNames();
/**
* Returns the number of frames that currently exist.
* @return The number of frames
*/
public int getFrameCount();
/**
* Tests if the window is a popup window.
* @return true if the window is a popup window.
*/
public boolean isPopup();
/**
* Tests if a document has been loaded in the browser.
* @return true if a document has been loaded in the browser.
*/
public boolean hasDocument();
//
// The following methods are forwarded to the mainFrame.
//
/**
* Save this frame's HTML source to a temporary file and open it in the
* default text viewing application. This method can only be called from the
* browser process.
*/
public void viewSource();
/**
* Retrieve this frame's HTML source as a string sent to the specified
* visitor.
*
* @param visitor
*/
public void getSource(CefStringVisitor visitor);
/**
* Retrieve this frame's display text as a string sent to the specified
* visitor.
*
* @param visitor
*/
public void getText(CefStringVisitor visitor);
/**
* Load the request represented by the request object.
*
* @param request The request object.
*/
public void loadRequest(CefRequest request);
/**
* Load the specified URL in the main frame.
* @param url The URL to load.
*/
public void loadURL(String url);
/**
* Execute a string of JavaScript code in this frame. The url
* parameter is the URL where the script in question can be found, if any.
* The renderer may request this URL to show the developer the source of the
* error. The line parameter is the base line number to use for error
* reporting.
*
* @param code The code to be executed.
* @param url The URL where the script in question can be found.
* @param line The base line number to use for error reporting.
*/
public void executeJavaScript(String code, String url, int line);
/**
* Emits the URL currently loaded in this frame.
* @return the URL currently loaded in this frame.
*/
public String getURL();
// The following methods are forwarded to CefBrowserHost.
/**
* Request that the browser close.
* @param force force the close.
*/
public void close(boolean force);
/**
* Allow the browser to close.
*/
public void setCloseAllowed();
/**
* Called from CefClient.doClose.
*/
public boolean doClose();
/**
* Called from CefClient.onBeforeClose.
*/
public void onBeforeClose();
/**
* Set or remove keyboard focus to/from the browser window.
* @param enable set to true to give the focus to the browser
**/
public void setFocus(boolean enable);
/**
* Set whether the window containing the browser is visible
* (minimized/unminimized, app hidden/unhidden, etc). Only used on Mac OS X.
* @param visible
*/
public void setWindowVisibility(boolean visible);
/**
* Get the current<SUF>*/
public double getZoomLevel();
/**
* Change the zoom level to the specified value. Specify 0.0 to reset the
* zoom level.
*
* @param zoomLevel The zoom level to be set.
*/
public void setZoomLevel(double zoomLevel);
/**
* Call to run a file chooser dialog. Only a single file chooser dialog may be
* pending at any given time.The dialog will be initiated asynchronously on
* the UI thread.
*
* @param mode represents the type of dialog to display.
* @param title to be used for the dialog and may be empty to show the
* default title ("Open" or "Save" depending on the mode).
* @param defaultFilePath is the path with optional directory and/or file name
* component that should be initially selected in the dialog.
* @param acceptFilters are used to restrict the selectable file types and may
* any combination of (a) valid lower-cased MIME types (e.g. "text/*" or
* "image/*"), (b) individual file extensions (e.g. ".txt" or ".png"), or (c)
* combined description and file extension delimited using "|" and ";" (e.g.
* "Image Types|.png;.gif;.jpg").
* @param selectedAcceptFilter is the 0-based index of the filter that should
* be selected by default.
* @param callback will be executed after the dialog is dismissed or
* immediately if another dialog is already pending.
*/
public void runFileDialog(FileDialogMode mode, String title, String defaultFilePath,
Vector<String> acceptFilters, int selectedAcceptFilter,
CefRunFileDialogCallback callback);
/**
* Download the file at url using CefDownloadHandler.
*
* @param url URL to download that file.
*/
public void startDownload(String url);
/**
* Print the current browser contents.
*/
public void print();
/**
* Print the current browser contents to a PDF.
*
* @param path The path of the file to write to (will be overwritten if it
* already exists). Cannot be null.
* @param settings The pdf print settings to use. If null then defaults
* will be used.
* @param callback Called when the pdf print job has completed.
*/
public void printToPDF(String path, CefPdfPrintSettings settings, CefPdfPrintCallback callback);
/**
* Search for some kind of text on the page.
*
* @param identifier can be used to have multiple searches running simultaniously.
* @param searchText to be searched for.
* @param forward indicates whether to search forward or backward within the page.
* @param matchCase indicates whether the search should be case-sensitive.
* @param findNext indicates whether this is the first request or a follow-up.
*/
public void find(int identifier, String searchText, boolean forward, boolean matchCase,
boolean findNext);
/**
* Cancel all searches that are currently going on.
* @param clearSelection Set to true to reset selection.
*/
public void stopFinding(boolean clearSelection);
/**
* Get an instance of the dev tools to be displayed in its own window or to be
* embedded within your UI. Only one instance per browser is available.
*/
public CefBrowser getDevTools();
/**
* Get an instance of the dev tools to be displayed in its own window or to be
* embedded within your UI. Only one instance per browser is available.
*
* @param inspectAt a position in the UI which should be inspected.
*/
public CefBrowser getDevTools(Point inspectAt);
/**
* If a misspelled word is currently selected in an editable node calling
* this method will replace it with the specified |word|.
*
* @param word replace selected word with this word.
*/
public void replaceMisspelling(String word);
/**
* @since api-1.2
*/
void wasResized(int width, int height);
/**
* @since api-1.2
*/
void sendKeyEvent(KeyEvent e);
/**
* @since api-1.2
*/
void sendMouseEvent(MouseEvent e);
/**
* @since api-1.2
*/
void sendMouseWheelEvent(MouseWheelEvent e);
/**
* Captures a screenshot-like image of the currently displayed content and returns it.
* <p>
* If executed on the AWT Event Thread, this returns an immediately resolved {@link
* java.util.concurrent.CompletableFuture}. If executed from another thread, the {@link
* java.util.concurrent.CompletableFuture} returned is resolved as soon as the screenshot
* has been taken (which must happen on the event thread).
* <p>
* The generated screenshot can either be returned as-is, containing all natively-rendered
* pixels, or it can be scaled to match the logical width and height of the window.
* This distinction is only relevant in case of differing logical and physical resolutions
* (for example with HiDPI/Retina displays, which have a scaling factor of for example 2
* between the logical width of a window (ex. 400px) and the actual number of pixels in
* each row (ex. 800px with a scaling factor of 2)).
*
* @param nativeResolution whether to return an image at full native resolution (true)
* or a scaled-down version whose width and height are equal to the logical size
* of the screenshotted browser window
* @return the screenshot image
* @throws UnsupportedOperationException if not supported
*/
public CompletableFuture<BufferedImage> createScreenshot(boolean nativeResolution);
}
|
37543_14 | // Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
package org.jetbrains.kotlin.js.backend;
import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet;
import java.util.Collections;
import java.util.Set;
/**
* Determines whether or not a particular string is a JavaScript keyword or not.
*/
public class JsReservedIdentifiers {
public static final Set<String> reservedGlobalSymbols;
static {
String[] commonBuiltins = new String[] {
// 15.1.1 Value Properties of the Global Object
"NaN", "Infinity", "undefined",
// 15.1.2 Function Properties of the Global Object
"eval", "parseInt", "parseFloat", "isNan", "isFinite",
// 15.1.3 URI Handling Function Properties
"decodeURI", "decodeURIComponent",
"encodeURI",
"encodeURIComponent",
// 15.1.4 Constructor Properties of the Global Object
"Object", "Function", "Array", "String", "Boolean", "Number", "Date",
"RegExp", "Error", "EvalError", "RangeError", "ReferenceError",
"SyntaxError", "TypeError", "URIError",
// 15.1.5 Other Properties of the Global Object
"Math",
// 10.1.6 Activation Object
"arguments",
// B.2 Additional Properties (non-normative)
"escape", "unescape",
// Window props (https://developer.mozilla.org/en/DOM/window)
"applicationCache", "closed", "Components", "content", "controllers",
"crypto", "defaultStatus", "dialogArguments", "directories",
"document", "frameElement", "frames", "fullScreen", "globalStorage",
"history", "innerHeight", "innerWidth", "length",
"location", "locationbar", "localStorage", "menubar",
"mozInnerScreenX", "mozInnerScreenY", "mozScreenPixelsPerCssPixel",
"name", "navigator", "opener", "outerHeight", "outerWidth",
"pageXOffset", "pageYOffset", "parent", "personalbar", "pkcs11",
"returnValue", "screen", "scrollbars", "scrollMaxX", "scrollMaxY",
"self", "sessionStorage", "sidebar", "status", "statusbar", "toolbar",
"top", "window",
// Window methods (https://developer.mozilla.org/en/DOM/window)
"alert", "addEventListener", "atob", "back", "blur", "btoa",
"captureEvents", "clearInterval", "clearTimeout", "close", "confirm",
"disableExternalCapture", "dispatchEvent", "dump",
"enableExternalCapture", "escape", "find", "focus", "forward",
"GeckoActiveXObject", "getAttention", "getAttentionWithCycleCount",
"getComputedStyle", "getSelection", "home", "maximize", "minimize",
"moveBy", "moveTo", "open", "openDialog", "postMessage", "print",
"prompt", "QueryInterface", "releaseEvents", "removeEventListener",
"resizeBy", "resizeTo", "restore", "routeEvent", "scroll", "scrollBy",
"scrollByLines", "scrollByPages", "scrollTo", "setInterval",
"setResizeable", "setTimeout", "showModalDialog", "sizeToContent",
"stop", "uuescape", "updateCommands", "XPCNativeWrapper",
"XPCSafeJSOjbectWrapper",
// Mozilla Window event handlers, same cite
"onabort", "onbeforeunload", "onchange", "onclick", "onclose",
"oncontextmenu", "ondragdrop", "onerror", "onfocus", "onhashchange",
"onkeydown", "onkeypress", "onkeyup", "onload", "onmousedown",
"onmousemove", "onmouseout", "onmouseover", "onmouseup",
"onmozorientation", "onpaint", "onreset", "onresize", "onscroll",
"onselect", "onsubmit", "onunload",
// Safari Web Content Guide
// http://developer.apple.com/library/safari/#documentation/AppleApplications/Reference/SafariWebContent/SafariWebContent.pdf
// WebKit Window member data, from WebKit DOM Reference
// (http://developer.apple.com/safari/library/documentation/AppleApplications/Reference/WebKitDOMRef/DOMWindow_idl/Classes/DOMWindow/index.html)
// TODO(fredsa) Many, many more functions and member data to add
"ontouchcancel", "ontouchend", "ontouchmove", "ontouchstart",
"ongesturestart", "ongesturechange", "ongestureend",
// extra window methods
"uneval",
// keywords https://developer.mozilla.org/en/New_in_JavaScript_1.7,
// https://developer.mozilla.org/en/New_in_JavaScript_1.8.1
"getPrototypeOf", "let", "yield",
// "future reserved words"
"abstract", "int", "short", "boolean", "interface", "static", "byte",
"long", "char", "final", "native", "synchronized", "float", "package",
"throws", "goto", "private", "transient", "implements", "protected",
"volatile", "double", "public",
// IE methods
// (http://msdn.microsoft.com/en-us/library/ms535873(VS.85).aspx#)
"attachEvent", "clientInformation", "clipboardData", "createPopup",
"dialogHeight", "dialogLeft", "dialogTop", "dialogWidth",
"onafterprint", "onbeforedeactivate", "onbeforeprint",
"oncontrolselect", "ondeactivate", "onhelp", "onresizeend",
// Common browser-defined identifiers not defined in ECMAScript
"event", "external", "Debug", "Enumerator", "Global", "Image",
"ActiveXObject", "VBArray", "Components",
// Functions commonly defined on Object
"toString", "getClass", "constructor", "prototype", "valueOf",
// Client-side JavaScript identifiers, which are needed for linkers
// that don't ensure GWT's window != $wnd, document != $doc, etc.
// Taken from the Rhino book, pg 715
"Anchor", "Applet", "Attr", "Canvas", "CanvasGradient",
"CanvasPattern", "CanvasRenderingContext2D", "CDATASection",
"CharacterData", "Comment", "CSS2Properties", "CSSRule",
"CSSStyleSheet", "Document", "DocumentFragment", "DocumentType",
"DOMException", "DOMImplementation", "DOMParser", "Element", "Event",
"ExternalInterface", "FlashPlayer", "Form", "Frame", "History",
"HTMLCollection", "HTMLDocument", "HTMLElement", "IFrame", "Image",
"Input", "JSObject", "KeyEvent", "Link", "Location", "MimeType",
"MouseEvent", "Navigator", "Node", "NodeList", "Option", "Plugin",
"ProcessingInstruction", "Range", "RangeException", "Screen", "Select",
"Table", "TableCell", "TableRow", "TableSelection", "Text", "TextArea",
"UIEvent", "Window", "XMLHttpRequest", "XMLSerializer",
"XPathException", "XPathResult", "XSLTProcessor",
// These keywords trigger the loading of the java-plugin. For the
// next-generation plugin, this results in starting a new Java process.
"java", "Packages", "netscape", "sun", "JavaObject", "JavaClass",
"JavaArray", "JavaMember",
// GWT-defined identifiers
"$wnd", "$doc", "$entry", "$moduleName", "$moduleBase", "$gwt_version", "$sessionId",
// Identifiers used by JsStackEmulator; later set to obfuscatable
"$stack", "$stackDepth", "$location",
};
reservedGlobalSymbols = new ObjectOpenHashSet<>(commonBuiltins.length);
Collections.addAll(reservedGlobalSymbols, commonBuiltins);
}
private JsReservedIdentifiers() {
}
}
| JetBrains/kotlin | js/js.ast/src/org/jetbrains/kotlin/js/backend/JsReservedIdentifiers.java | 2,301 | // Safari Web Content Guide | line_comment | nl | // Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
package org.jetbrains.kotlin.js.backend;
import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet;
import java.util.Collections;
import java.util.Set;
/**
* Determines whether or not a particular string is a JavaScript keyword or not.
*/
public class JsReservedIdentifiers {
public static final Set<String> reservedGlobalSymbols;
static {
String[] commonBuiltins = new String[] {
// 15.1.1 Value Properties of the Global Object
"NaN", "Infinity", "undefined",
// 15.1.2 Function Properties of the Global Object
"eval", "parseInt", "parseFloat", "isNan", "isFinite",
// 15.1.3 URI Handling Function Properties
"decodeURI", "decodeURIComponent",
"encodeURI",
"encodeURIComponent",
// 15.1.4 Constructor Properties of the Global Object
"Object", "Function", "Array", "String", "Boolean", "Number", "Date",
"RegExp", "Error", "EvalError", "RangeError", "ReferenceError",
"SyntaxError", "TypeError", "URIError",
// 15.1.5 Other Properties of the Global Object
"Math",
// 10.1.6 Activation Object
"arguments",
// B.2 Additional Properties (non-normative)
"escape", "unescape",
// Window props (https://developer.mozilla.org/en/DOM/window)
"applicationCache", "closed", "Components", "content", "controllers",
"crypto", "defaultStatus", "dialogArguments", "directories",
"document", "frameElement", "frames", "fullScreen", "globalStorage",
"history", "innerHeight", "innerWidth", "length",
"location", "locationbar", "localStorage", "menubar",
"mozInnerScreenX", "mozInnerScreenY", "mozScreenPixelsPerCssPixel",
"name", "navigator", "opener", "outerHeight", "outerWidth",
"pageXOffset", "pageYOffset", "parent", "personalbar", "pkcs11",
"returnValue", "screen", "scrollbars", "scrollMaxX", "scrollMaxY",
"self", "sessionStorage", "sidebar", "status", "statusbar", "toolbar",
"top", "window",
// Window methods (https://developer.mozilla.org/en/DOM/window)
"alert", "addEventListener", "atob", "back", "blur", "btoa",
"captureEvents", "clearInterval", "clearTimeout", "close", "confirm",
"disableExternalCapture", "dispatchEvent", "dump",
"enableExternalCapture", "escape", "find", "focus", "forward",
"GeckoActiveXObject", "getAttention", "getAttentionWithCycleCount",
"getComputedStyle", "getSelection", "home", "maximize", "minimize",
"moveBy", "moveTo", "open", "openDialog", "postMessage", "print",
"prompt", "QueryInterface", "releaseEvents", "removeEventListener",
"resizeBy", "resizeTo", "restore", "routeEvent", "scroll", "scrollBy",
"scrollByLines", "scrollByPages", "scrollTo", "setInterval",
"setResizeable", "setTimeout", "showModalDialog", "sizeToContent",
"stop", "uuescape", "updateCommands", "XPCNativeWrapper",
"XPCSafeJSOjbectWrapper",
// Mozilla Window event handlers, same cite
"onabort", "onbeforeunload", "onchange", "onclick", "onclose",
"oncontextmenu", "ondragdrop", "onerror", "onfocus", "onhashchange",
"onkeydown", "onkeypress", "onkeyup", "onload", "onmousedown",
"onmousemove", "onmouseout", "onmouseover", "onmouseup",
"onmozorientation", "onpaint", "onreset", "onresize", "onscroll",
"onselect", "onsubmit", "onunload",
// Safari Web<SUF>
// http://developer.apple.com/library/safari/#documentation/AppleApplications/Reference/SafariWebContent/SafariWebContent.pdf
// WebKit Window member data, from WebKit DOM Reference
// (http://developer.apple.com/safari/library/documentation/AppleApplications/Reference/WebKitDOMRef/DOMWindow_idl/Classes/DOMWindow/index.html)
// TODO(fredsa) Many, many more functions and member data to add
"ontouchcancel", "ontouchend", "ontouchmove", "ontouchstart",
"ongesturestart", "ongesturechange", "ongestureend",
// extra window methods
"uneval",
// keywords https://developer.mozilla.org/en/New_in_JavaScript_1.7,
// https://developer.mozilla.org/en/New_in_JavaScript_1.8.1
"getPrototypeOf", "let", "yield",
// "future reserved words"
"abstract", "int", "short", "boolean", "interface", "static", "byte",
"long", "char", "final", "native", "synchronized", "float", "package",
"throws", "goto", "private", "transient", "implements", "protected",
"volatile", "double", "public",
// IE methods
// (http://msdn.microsoft.com/en-us/library/ms535873(VS.85).aspx#)
"attachEvent", "clientInformation", "clipboardData", "createPopup",
"dialogHeight", "dialogLeft", "dialogTop", "dialogWidth",
"onafterprint", "onbeforedeactivate", "onbeforeprint",
"oncontrolselect", "ondeactivate", "onhelp", "onresizeend",
// Common browser-defined identifiers not defined in ECMAScript
"event", "external", "Debug", "Enumerator", "Global", "Image",
"ActiveXObject", "VBArray", "Components",
// Functions commonly defined on Object
"toString", "getClass", "constructor", "prototype", "valueOf",
// Client-side JavaScript identifiers, which are needed for linkers
// that don't ensure GWT's window != $wnd, document != $doc, etc.
// Taken from the Rhino book, pg 715
"Anchor", "Applet", "Attr", "Canvas", "CanvasGradient",
"CanvasPattern", "CanvasRenderingContext2D", "CDATASection",
"CharacterData", "Comment", "CSS2Properties", "CSSRule",
"CSSStyleSheet", "Document", "DocumentFragment", "DocumentType",
"DOMException", "DOMImplementation", "DOMParser", "Element", "Event",
"ExternalInterface", "FlashPlayer", "Form", "Frame", "History",
"HTMLCollection", "HTMLDocument", "HTMLElement", "IFrame", "Image",
"Input", "JSObject", "KeyEvent", "Link", "Location", "MimeType",
"MouseEvent", "Navigator", "Node", "NodeList", "Option", "Plugin",
"ProcessingInstruction", "Range", "RangeException", "Screen", "Select",
"Table", "TableCell", "TableRow", "TableSelection", "Text", "TextArea",
"UIEvent", "Window", "XMLHttpRequest", "XMLSerializer",
"XPathException", "XPathResult", "XSLTProcessor",
// These keywords trigger the loading of the java-plugin. For the
// next-generation plugin, this results in starting a new Java process.
"java", "Packages", "netscape", "sun", "JavaObject", "JavaClass",
"JavaArray", "JavaMember",
// GWT-defined identifiers
"$wnd", "$doc", "$entry", "$moduleName", "$moduleBase", "$gwt_version", "$sessionId",
// Identifiers used by JsStackEmulator; later set to obfuscatable
"$stack", "$stackDepth", "$location",
};
reservedGlobalSymbols = new ObjectOpenHashSet<>(commonBuiltins.length);
Collections.addAll(reservedGlobalSymbols, commonBuiltins);
}
private JsReservedIdentifiers() {
}
}
|
11137_1 | package Model;
/**
* Created by jayfeurich on 28/01/15.
*/
public class ContextCategory {
private String description;
private String categoryName;
public ContextCategory(String des, String catName){
this.description = des;
this.categoryName = catName;
}
/*de naamgeving van deze klasse komt uit een tijd dat een contextcategorie of scope of purpose of iets anders kon zijn dat
* vrij te definieren was in het systeem. Helaas bleek de implementatie van een variabele hoeveelheid van contextcategorieen
* in het systeem niet praktisch vanwege technische problemen.*/
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public String getDescription(){
return description;
}
public void setDescription(String des){ this.description = des;}
}
| Jfeurich/Ass2 | src/Model/ContextCategory.java | 243 | /*de naamgeving van deze klasse komt uit een tijd dat een contextcategorie of scope of purpose of iets anders kon zijn dat
* vrij te definieren was in het systeem. Helaas bleek de implementatie van een variabele hoeveelheid van contextcategorieen
* in het systeem niet praktisch vanwege technische problemen.*/ | block_comment | nl | package Model;
/**
* Created by jayfeurich on 28/01/15.
*/
public class ContextCategory {
private String description;
private String categoryName;
public ContextCategory(String des, String catName){
this.description = des;
this.categoryName = catName;
}
/*de naamgeving van<SUF>*/
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public String getDescription(){
return description;
}
public void setDescription(String des){ this.description = des;}
}
|
43372_5 | package nl.hu.tho6.persistence;
import nl.hu.tho6.domain.businessrule.Attribute;
import nl.hu.tho6.domain.businessrule.BusinessRule;
import nl.hu.tho6.domain.businessrule.Operator;
import nl.hu.tho6.domain.businessrule.Value;
import nl.hu.tho6.persistence.connection.ConnectionFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
//import java.util.Optional;
/*
* Deze methode moet bevatten:
* connect() Maak verbinding met de Oracle DB
* getBusinessrule() Haal Businessrule op
* saveBusinessrule() Sla Businessrule op
* getongegenereerdeBusinessrules() Haal de te genereren Businessrules op
* searchBusinessrule() Zoek een businessrule op naam/tabel/etc
*
*/
public class ConnectDBBusinessRule {
private Connection con;
public ConnectDBBusinessRule(Connection c) {
con = c;
}
/**
* Haalt alle ongegenereerde businessrules op uit de database.
*/
public ArrayList<BusinessRule> getOngegenereerdeBusinessRules() {
//Haal de businessrules op uit de ruledatabase
ArrayList<BusinessRule> rules = new ArrayList<BusinessRule>();
try {
String sql = "select BUSINESSRULE.RULEID as RULEID,\n" +
"BUSINESSRULE.RULENAAM as RULENAAM,\n" +
"BUSINESSRULE.ERROR as ERROR,\n" +
"BUSINESSRULE.ERRORTYPE as ERRORTYPE,\n" +
"BUSINESSRULE.OPERATOR as OPERATOR,\n" +
"BUSINESSRULE.BUSINESSRULETYPE as BUSINESSRULETYPE \n," +
"ONGEGENEREERDE_BUSINESSRULE.LANGUAGENAAM as LANGUAGE\n " +
" from ONGEGENEREERDE_BUSINESSRULE ,\n" +
"BUSINESSRULE \n" +
" where BUSINESSRULE.RULEID=ONGEGENEREERDE_BUSINESSRULE.BUSINESSRULERULEID\n" +
" and ONGEGENEREERDE_BUSINESSRULE.STATUS = 'NOT_GENERATED'";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
BusinessRule r = new BusinessRule();
int id = rs.getInt("RULEID");
String rulenaam = rs.getString("RULENAAM");
String error = rs.getString("ERROR");
String errortype = rs.getString("ERRORTYPE");
String language = rs.getString("LANGUAGE");
int operator = rs.getInt("OPERATOR");
int ruletype = rs.getInt("BUSINESSRULETYPE");
String code = "";
//TODO dit gaat waarschijnlijk nog nullpointer excpetions opleveren
// maar even kijken of dit handiger kan
// TODO kijken of optional hier een optie is.
ConnectDBBusinessRule con2 = new ConnectDBBusinessRule(con);
ArrayList<Value> values = con2.getValue(id);
ConnectDBBusinessRule con3 = new ConnectDBBusinessRule(con);
Operator o = con3.getOperator(id);
ConnectDBBusinessRule con4 = new ConnectDBBusinessRule(con);
ArrayList<Attribute> attributes = con4.getAttribute(id);
Attribute a1 = null;
Attribute a2 = null;
Value v1 = null;
Value v2 = null;
if (attributes.size() > 0) {
a1 = attributes.get(0);
if (attributes.size() > 1) {
a2 = attributes.get(1);
}
}
if (values.size() > 0) {
v1 = values.get(0);
if (values.size() > 1) {
v2 = values.get(1);
}
}
String output = "RuleID: " + id + ", " + attributes.size() + " ATT, " + values.size() + " VAL \t" + rulenaam;
System.out.println(output);
// r = BusinessRule(rulenaam,error,errortype,code,o,v1,v2,a1,a2)
r.setRuleNaam(rulenaam);
r.setError(error);
r.setErrorType(errortype);
r.setCode(code);
r.setOperator(o);
r.setBusinessruletype(ruletype);
if(a1 != null && a2 != null){
if(!a1.getTabel().equals(a2.getTabel())){
setReferences(a1,a2);
}
}
if(nulltest(v1)){
r.setValue1(v1);
}
if(nulltest(v2)){
r.setValue2(v2);
}
if(nulltest(a1)) {
r.setAttribute1(a1);
}
if(nulltest(a2)){
r.setAttribute2(a2);
}
r.setRuleID(id);
r.setLanguage(language);
rules.add(r);
}
stmt.close();
} catch (Exception ex) {
System.out.println("Kan geen businessrules halen uit de database" + ex);
ex.printStackTrace();
}
return rules;
}
public void saveToErrorLog(String error, String businessruleid){
try {
PreparedStatement updateStatement = con.prepareStatement("INSERT INTO ERROR_LOG (ERRORID,ERRORMESSAGE,DATUM,\"user\",TABLENAME) VALUES (SEQ_ERROR_LOG.NEXTVAL,?,SYSDATE,'JAVA',?)");
updateStatement.setString(1,error);
updateStatement.setString(2,businessruleid);
updateStatement.executeQuery();
updateStatement.close();
} catch (Exception ex) {
System.out.println("Kan gemaakte businessrule niet opslaan in de database" + ex);
ex.printStackTrace();
}
}
private void setReferences(Attribute a1, Attribute a2) {
System.out.println("Getting references for the attributes");
try {
String URL = "jdbc:oracle:thin:@//ondora01.hu.nl:8521/cursus01.hu.nl";
String USER = "tho6_2014_2b_team3_target";
String PASSWORD = " tho6_2014_2b_team3_target";
Connection tempcon = ConnectionFactory.getTargetConnection(URL,USER,PASSWORD);
String sql = "SELECT UCC1.TABLE_NAME||'.'||UCC1.COLUMN_NAME CONSTRAINT_SOURCE,\n" +
"UCC2.TABLE_NAME||'.'||UCC2.COLUMN_NAME REFERENCES_COLUMN\n" +
"FROM USER_CONSTRAINTS uc,\n" +
"USER_CONS_COLUMNS ucc1,\n" +
"USER_CONS_COLUMNS ucc2\n" +
"WHERE UC.CONSTRAINT_NAME = UCC1.CONSTRAINT_NAME\n" +
"AND UC.R_CONSTRAINT_NAME = UCC2.CONSTRAINT_NAME\n" +
"AND UCC1.POSITION = UCC2.POSITION\n" +
"AND UC.CONSTRAINT_TYPE = 'R'\n" +
"AND (UCC1.TABLE_NAME = '" + a1.getTabel() + "' OR UCC2.TABLE_NAME = '" + a1.getTabel() + "')\n" +
"AND (UCC1.TABLE_NAME = '" + a2.getTabel() + "' OR UCC2.TABLE_NAME = '" + a2.getTabel() + "')\n";
Statement stmt = tempcon.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
String source1 = rs.getString("CONSTRAINT_SOURCE");
String source2 = rs.getString("REFERENCES_COLUMN");
System.out.println(source1);
System.out.println(source2);
String[] sourceSplit = source1.split("\\.");
String[] sourceSplit2 = source2.split("\\.");
if(a1.getTabel().equals(sourceSplit[0])){
a1.setReference(sourceSplit[1]);
a2.setReference(sourceSplit2[1]);
} else {
a1.setReference(sourceSplit2[1]);
a2.setReference(sourceSplit[1]);
}
System.out.println("A1 reference: " + a1.getReference());
System.out.println("A2 reference: " + a2.getReference());
}
stmt.close();
} catch (Exception ex) {
System.out.println("Het lukt niet om de references op te halen" + ex);
ex.printStackTrace();
}
}
/*Haalt alle attributes behorende bij de businessrule uit de DB*/
public ArrayList<Attribute> getAttribute(int businessruleID){
ArrayList<Attribute> attributes = new ArrayList<Attribute>();
try {
String sql = "select ATTRIBUTE.ATTRIBUTENAAM as ATTRIBUTENAAM,\n" +
" ATTRIBUTE.DBSCHEMA as DBSCHEMA,\n" +
" ATTRIBUTE.TABEL as TABEL,\n" +
" ATTRIBUTE.KOLOM as KOLOM,\n" +
" ATTRIBUTE.ATTRIBUTEID as ATTRIBUTEID \n" +
" from BUSINESSRULE_ATTRIBUTE BUSINESSRULE_ATTRIBUTE,\n" +
" ATTRIBUTE ATTRIBUTE \n" +
" where BUSINESSRULE_ATTRIBUTE.BUSINESSRULE="+ businessruleID + "\n" +
" and BUSINESSRULE_ATTRIBUTE.ATTRIBUTE=ATTRIBUTE.ATTRIBUTEID";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
int attributeid = rs.getInt("ATTRIBUTEID");
String attributenaam = rs.getString("ATTRIBUTENAAM");
String dbschema = rs.getString("DBSCHEMA");
String tabel = rs.getString("TABEL");
String kolom = rs.getString("KOLOM");
Attribute a = new Attribute(attributenaam,dbschema,tabel,kolom,attributeid);
attributes.add(a);
}
stmt.close();
} catch (Exception ex) {
System.out.println("Kan geen attributes halen uit de database" + ex);
}
return attributes;
}
/*haal values uit de database behordende bij de database*/
public ArrayList<Value> getValue(int businessruleID){
ArrayList<Value> v = new ArrayList<Value>();
try {
String sql = "select VALUE.VALUEID as VALUEID,\n" +
" VALUE.WAARDENAAM as WAARDENAAM,\n" +
" VALUE.VALUETYPE as VALUETYPE,\n" +
" VALUE.VALUE as VALUECONTENT,\n" +
" VALUE.BUSINESSRULE as BUSINESSRULE \n" +
" from VALUE VALUE \n" +
" where VALUE.BUSINESSRULE = " + businessruleID;
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
int valueID = rs.getInt("VALUEID");
String waardenaam = rs.getString("WAARDENAAM");
String valuetype = rs.getString("VALUETYPE");
String value = rs.getString("VALUECONTENT");
Value val = new Value(waardenaam,valuetype,value);
v.add(val);
}
stmt.close();
} catch (Exception ex) {
System.out.println("Kan geen values halen uit de database" + ex);
ex.printStackTrace();
}
return v;
}
/*Haal de operator behorende bijde businessrule uit de database*/
public Operator getOperator(int businessruleID){
Operator op = null;
try {
String sql = "select OPERATOR.OPERATORNAAM as OPERATORNAAM," +
"OPERATOR.OPERATORTYPE as OPERATORTYPE \n" +
"from BUSINESSRULE BUSINESSRULE,\n" +
"OPERATOR OPERATOR \n" +
"where OPERATOR.OPERATORID=BUSINESSRULE.OPERATOR\n" +
"and BUSINESSRULE.RULEID ="+businessruleID;
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
String naam = rs.getString("OPERATORNAAM");
String operatortype = rs.getString("OPERATORTYPE");
op = new Operator(naam,operatortype);
}
stmt.close();
} catch (Exception ex) {
System.out.println("Kan geen operator halen uit de database" + ex);
}
return op;
}
/*Controleer of een object null returnt */
public boolean nulltest(Object o){
return o != null;
}
/*Sla de gemaakte businessrule op in de oracle database.*/
// TODO: pas de savebusinessrule aan zodat hij de businessrule als string opslaat in de apex database.
public void saveBusinessRule(String BUSINESSRULENAAM,String LANGUAGENAAM, String CODE){
try {
String sql = "SELECT *\n" +
"FROM GEGENEREERDE_BUSINESSRULE\n" +
"WHERE GEGENEREERDE_BUSINESSRULE.BUSINESSRULENAAM = '" + BUSINESSRULENAAM + "'\n" +
"AND GEGENEREERDE_BUSINESSRULE.LANGUAGENAAM = '" + LANGUAGENAAM + "'";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
if(rs.next()) {
PreparedStatement updateStatement = con.prepareStatement("UPDATE GEGENEREERDE_BUSINESSRULE \n" +
"SET CODE = ? \n" +
"WHERE GEGENEREERDE_BUSINESSRULE.BUSINESSRULENAAM = ?\n" +
"AND GEGENEREERDE_BUSINESSRULE.LANGUAGENAAM = ?");
updateStatement.setString(1, CODE);
updateStatement.setString(2, BUSINESSRULENAAM);
updateStatement.setString(3, LANGUAGENAAM);
updateStatement.executeQuery();
updateStatement.close();
} else {
try {
PreparedStatement updateStatement = con.prepareStatement("INSERT INTO GEGENEREERDE_BUSINESSRULE (GENID,BUSINESSRULENAAM,LANGUAGENAAM,CODE) VALUES (SEQ_GEGENEREERDE_BUSINESSRULE.NEXTVAL,?,?,?)");
updateStatement.setString(1, BUSINESSRULENAAM);
updateStatement.setString(2, LANGUAGENAAM);
updateStatement.setString(3, CODE);
updateStatement.executeQuery();
updateStatement.close();
} catch (Exception ex) {
System.out.println("Kan gemaakte businessrule niet opslaan in de database" + ex);
ex.printStackTrace();
}
}
stmt.close();
} catch (Exception ex) {
System.out.println("Kan gemaakte businessrule niet opslaan in de database" + ex);
ex.printStackTrace();
}
}
public void runCode(String code){
try {
String URL = "jdbc:oracle:thin:@//ondora01.hu.nl:8521/cursus01.hu.nl";
String USER = "tho6_2014_2b_team3_target";
String PASSWORD = " tho6_2014_2b_team3_target";
Connection tempcon = ConnectionFactory.getTargetConnection(URL,USER,PASSWORD);
Statement stmt = tempcon.createStatement();
stmt.executeUpdate(code);
stmt.close();
} catch (Exception ex) {
System.out.println("Het lukt niet om de references op te halen" + ex);
ex.printStackTrace();
}
}
/*Verander de status van de gegenereerde businessrule in de database.*/
public void changeBusinessRuleStatus(int businessruleid, String status){
try {
String sql ="UPDATE ONGEGENEREERDE_BUSINESSRULE \n" +
"SET STATUS = '" + status + "' \n" +
"WHERE ONGEGENEREERDE_BUSINESSRULE.BUSINESSRULERULEID = " + businessruleid;
Statement stmt = con.createStatement();
stmt.executeUpdate(sql);
stmt.close();
}
catch(Exception ex){
System.out.println("Kan de status van de ongegenereerde businessrule niet veranderen");
ex.printStackTrace();
}
}
}
| Jfeurich/THO6 | src/main/java/nl/hu/tho6/persistence/ConnectDBBusinessRule.java | 4,827 | // TODO kijken of optional hier een optie is. | line_comment | nl | package nl.hu.tho6.persistence;
import nl.hu.tho6.domain.businessrule.Attribute;
import nl.hu.tho6.domain.businessrule.BusinessRule;
import nl.hu.tho6.domain.businessrule.Operator;
import nl.hu.tho6.domain.businessrule.Value;
import nl.hu.tho6.persistence.connection.ConnectionFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
//import java.util.Optional;
/*
* Deze methode moet bevatten:
* connect() Maak verbinding met de Oracle DB
* getBusinessrule() Haal Businessrule op
* saveBusinessrule() Sla Businessrule op
* getongegenereerdeBusinessrules() Haal de te genereren Businessrules op
* searchBusinessrule() Zoek een businessrule op naam/tabel/etc
*
*/
public class ConnectDBBusinessRule {
private Connection con;
public ConnectDBBusinessRule(Connection c) {
con = c;
}
/**
* Haalt alle ongegenereerde businessrules op uit de database.
*/
public ArrayList<BusinessRule> getOngegenereerdeBusinessRules() {
//Haal de businessrules op uit de ruledatabase
ArrayList<BusinessRule> rules = new ArrayList<BusinessRule>();
try {
String sql = "select BUSINESSRULE.RULEID as RULEID,\n" +
"BUSINESSRULE.RULENAAM as RULENAAM,\n" +
"BUSINESSRULE.ERROR as ERROR,\n" +
"BUSINESSRULE.ERRORTYPE as ERRORTYPE,\n" +
"BUSINESSRULE.OPERATOR as OPERATOR,\n" +
"BUSINESSRULE.BUSINESSRULETYPE as BUSINESSRULETYPE \n," +
"ONGEGENEREERDE_BUSINESSRULE.LANGUAGENAAM as LANGUAGE\n " +
" from ONGEGENEREERDE_BUSINESSRULE ,\n" +
"BUSINESSRULE \n" +
" where BUSINESSRULE.RULEID=ONGEGENEREERDE_BUSINESSRULE.BUSINESSRULERULEID\n" +
" and ONGEGENEREERDE_BUSINESSRULE.STATUS = 'NOT_GENERATED'";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
BusinessRule r = new BusinessRule();
int id = rs.getInt("RULEID");
String rulenaam = rs.getString("RULENAAM");
String error = rs.getString("ERROR");
String errortype = rs.getString("ERRORTYPE");
String language = rs.getString("LANGUAGE");
int operator = rs.getInt("OPERATOR");
int ruletype = rs.getInt("BUSINESSRULETYPE");
String code = "";
//TODO dit gaat waarschijnlijk nog nullpointer excpetions opleveren
// maar even kijken of dit handiger kan
// TODO kijken<SUF>
ConnectDBBusinessRule con2 = new ConnectDBBusinessRule(con);
ArrayList<Value> values = con2.getValue(id);
ConnectDBBusinessRule con3 = new ConnectDBBusinessRule(con);
Operator o = con3.getOperator(id);
ConnectDBBusinessRule con4 = new ConnectDBBusinessRule(con);
ArrayList<Attribute> attributes = con4.getAttribute(id);
Attribute a1 = null;
Attribute a2 = null;
Value v1 = null;
Value v2 = null;
if (attributes.size() > 0) {
a1 = attributes.get(0);
if (attributes.size() > 1) {
a2 = attributes.get(1);
}
}
if (values.size() > 0) {
v1 = values.get(0);
if (values.size() > 1) {
v2 = values.get(1);
}
}
String output = "RuleID: " + id + ", " + attributes.size() + " ATT, " + values.size() + " VAL \t" + rulenaam;
System.out.println(output);
// r = BusinessRule(rulenaam,error,errortype,code,o,v1,v2,a1,a2)
r.setRuleNaam(rulenaam);
r.setError(error);
r.setErrorType(errortype);
r.setCode(code);
r.setOperator(o);
r.setBusinessruletype(ruletype);
if(a1 != null && a2 != null){
if(!a1.getTabel().equals(a2.getTabel())){
setReferences(a1,a2);
}
}
if(nulltest(v1)){
r.setValue1(v1);
}
if(nulltest(v2)){
r.setValue2(v2);
}
if(nulltest(a1)) {
r.setAttribute1(a1);
}
if(nulltest(a2)){
r.setAttribute2(a2);
}
r.setRuleID(id);
r.setLanguage(language);
rules.add(r);
}
stmt.close();
} catch (Exception ex) {
System.out.println("Kan geen businessrules halen uit de database" + ex);
ex.printStackTrace();
}
return rules;
}
public void saveToErrorLog(String error, String businessruleid){
try {
PreparedStatement updateStatement = con.prepareStatement("INSERT INTO ERROR_LOG (ERRORID,ERRORMESSAGE,DATUM,\"user\",TABLENAME) VALUES (SEQ_ERROR_LOG.NEXTVAL,?,SYSDATE,'JAVA',?)");
updateStatement.setString(1,error);
updateStatement.setString(2,businessruleid);
updateStatement.executeQuery();
updateStatement.close();
} catch (Exception ex) {
System.out.println("Kan gemaakte businessrule niet opslaan in de database" + ex);
ex.printStackTrace();
}
}
private void setReferences(Attribute a1, Attribute a2) {
System.out.println("Getting references for the attributes");
try {
String URL = "jdbc:oracle:thin:@//ondora01.hu.nl:8521/cursus01.hu.nl";
String USER = "tho6_2014_2b_team3_target";
String PASSWORD = " tho6_2014_2b_team3_target";
Connection tempcon = ConnectionFactory.getTargetConnection(URL,USER,PASSWORD);
String sql = "SELECT UCC1.TABLE_NAME||'.'||UCC1.COLUMN_NAME CONSTRAINT_SOURCE,\n" +
"UCC2.TABLE_NAME||'.'||UCC2.COLUMN_NAME REFERENCES_COLUMN\n" +
"FROM USER_CONSTRAINTS uc,\n" +
"USER_CONS_COLUMNS ucc1,\n" +
"USER_CONS_COLUMNS ucc2\n" +
"WHERE UC.CONSTRAINT_NAME = UCC1.CONSTRAINT_NAME\n" +
"AND UC.R_CONSTRAINT_NAME = UCC2.CONSTRAINT_NAME\n" +
"AND UCC1.POSITION = UCC2.POSITION\n" +
"AND UC.CONSTRAINT_TYPE = 'R'\n" +
"AND (UCC1.TABLE_NAME = '" + a1.getTabel() + "' OR UCC2.TABLE_NAME = '" + a1.getTabel() + "')\n" +
"AND (UCC1.TABLE_NAME = '" + a2.getTabel() + "' OR UCC2.TABLE_NAME = '" + a2.getTabel() + "')\n";
Statement stmt = tempcon.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
String source1 = rs.getString("CONSTRAINT_SOURCE");
String source2 = rs.getString("REFERENCES_COLUMN");
System.out.println(source1);
System.out.println(source2);
String[] sourceSplit = source1.split("\\.");
String[] sourceSplit2 = source2.split("\\.");
if(a1.getTabel().equals(sourceSplit[0])){
a1.setReference(sourceSplit[1]);
a2.setReference(sourceSplit2[1]);
} else {
a1.setReference(sourceSplit2[1]);
a2.setReference(sourceSplit[1]);
}
System.out.println("A1 reference: " + a1.getReference());
System.out.println("A2 reference: " + a2.getReference());
}
stmt.close();
} catch (Exception ex) {
System.out.println("Het lukt niet om de references op te halen" + ex);
ex.printStackTrace();
}
}
/*Haalt alle attributes behorende bij de businessrule uit de DB*/
public ArrayList<Attribute> getAttribute(int businessruleID){
ArrayList<Attribute> attributes = new ArrayList<Attribute>();
try {
String sql = "select ATTRIBUTE.ATTRIBUTENAAM as ATTRIBUTENAAM,\n" +
" ATTRIBUTE.DBSCHEMA as DBSCHEMA,\n" +
" ATTRIBUTE.TABEL as TABEL,\n" +
" ATTRIBUTE.KOLOM as KOLOM,\n" +
" ATTRIBUTE.ATTRIBUTEID as ATTRIBUTEID \n" +
" from BUSINESSRULE_ATTRIBUTE BUSINESSRULE_ATTRIBUTE,\n" +
" ATTRIBUTE ATTRIBUTE \n" +
" where BUSINESSRULE_ATTRIBUTE.BUSINESSRULE="+ businessruleID + "\n" +
" and BUSINESSRULE_ATTRIBUTE.ATTRIBUTE=ATTRIBUTE.ATTRIBUTEID";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
int attributeid = rs.getInt("ATTRIBUTEID");
String attributenaam = rs.getString("ATTRIBUTENAAM");
String dbschema = rs.getString("DBSCHEMA");
String tabel = rs.getString("TABEL");
String kolom = rs.getString("KOLOM");
Attribute a = new Attribute(attributenaam,dbschema,tabel,kolom,attributeid);
attributes.add(a);
}
stmt.close();
} catch (Exception ex) {
System.out.println("Kan geen attributes halen uit de database" + ex);
}
return attributes;
}
/*haal values uit de database behordende bij de database*/
public ArrayList<Value> getValue(int businessruleID){
ArrayList<Value> v = new ArrayList<Value>();
try {
String sql = "select VALUE.VALUEID as VALUEID,\n" +
" VALUE.WAARDENAAM as WAARDENAAM,\n" +
" VALUE.VALUETYPE as VALUETYPE,\n" +
" VALUE.VALUE as VALUECONTENT,\n" +
" VALUE.BUSINESSRULE as BUSINESSRULE \n" +
" from VALUE VALUE \n" +
" where VALUE.BUSINESSRULE = " + businessruleID;
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
int valueID = rs.getInt("VALUEID");
String waardenaam = rs.getString("WAARDENAAM");
String valuetype = rs.getString("VALUETYPE");
String value = rs.getString("VALUECONTENT");
Value val = new Value(waardenaam,valuetype,value);
v.add(val);
}
stmt.close();
} catch (Exception ex) {
System.out.println("Kan geen values halen uit de database" + ex);
ex.printStackTrace();
}
return v;
}
/*Haal de operator behorende bijde businessrule uit de database*/
public Operator getOperator(int businessruleID){
Operator op = null;
try {
String sql = "select OPERATOR.OPERATORNAAM as OPERATORNAAM," +
"OPERATOR.OPERATORTYPE as OPERATORTYPE \n" +
"from BUSINESSRULE BUSINESSRULE,\n" +
"OPERATOR OPERATOR \n" +
"where OPERATOR.OPERATORID=BUSINESSRULE.OPERATOR\n" +
"and BUSINESSRULE.RULEID ="+businessruleID;
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
String naam = rs.getString("OPERATORNAAM");
String operatortype = rs.getString("OPERATORTYPE");
op = new Operator(naam,operatortype);
}
stmt.close();
} catch (Exception ex) {
System.out.println("Kan geen operator halen uit de database" + ex);
}
return op;
}
/*Controleer of een object null returnt */
public boolean nulltest(Object o){
return o != null;
}
/*Sla de gemaakte businessrule op in de oracle database.*/
// TODO: pas de savebusinessrule aan zodat hij de businessrule als string opslaat in de apex database.
public void saveBusinessRule(String BUSINESSRULENAAM,String LANGUAGENAAM, String CODE){
try {
String sql = "SELECT *\n" +
"FROM GEGENEREERDE_BUSINESSRULE\n" +
"WHERE GEGENEREERDE_BUSINESSRULE.BUSINESSRULENAAM = '" + BUSINESSRULENAAM + "'\n" +
"AND GEGENEREERDE_BUSINESSRULE.LANGUAGENAAM = '" + LANGUAGENAAM + "'";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
if(rs.next()) {
PreparedStatement updateStatement = con.prepareStatement("UPDATE GEGENEREERDE_BUSINESSRULE \n" +
"SET CODE = ? \n" +
"WHERE GEGENEREERDE_BUSINESSRULE.BUSINESSRULENAAM = ?\n" +
"AND GEGENEREERDE_BUSINESSRULE.LANGUAGENAAM = ?");
updateStatement.setString(1, CODE);
updateStatement.setString(2, BUSINESSRULENAAM);
updateStatement.setString(3, LANGUAGENAAM);
updateStatement.executeQuery();
updateStatement.close();
} else {
try {
PreparedStatement updateStatement = con.prepareStatement("INSERT INTO GEGENEREERDE_BUSINESSRULE (GENID,BUSINESSRULENAAM,LANGUAGENAAM,CODE) VALUES (SEQ_GEGENEREERDE_BUSINESSRULE.NEXTVAL,?,?,?)");
updateStatement.setString(1, BUSINESSRULENAAM);
updateStatement.setString(2, LANGUAGENAAM);
updateStatement.setString(3, CODE);
updateStatement.executeQuery();
updateStatement.close();
} catch (Exception ex) {
System.out.println("Kan gemaakte businessrule niet opslaan in de database" + ex);
ex.printStackTrace();
}
}
stmt.close();
} catch (Exception ex) {
System.out.println("Kan gemaakte businessrule niet opslaan in de database" + ex);
ex.printStackTrace();
}
}
public void runCode(String code){
try {
String URL = "jdbc:oracle:thin:@//ondora01.hu.nl:8521/cursus01.hu.nl";
String USER = "tho6_2014_2b_team3_target";
String PASSWORD = " tho6_2014_2b_team3_target";
Connection tempcon = ConnectionFactory.getTargetConnection(URL,USER,PASSWORD);
Statement stmt = tempcon.createStatement();
stmt.executeUpdate(code);
stmt.close();
} catch (Exception ex) {
System.out.println("Het lukt niet om de references op te halen" + ex);
ex.printStackTrace();
}
}
/*Verander de status van de gegenereerde businessrule in de database.*/
public void changeBusinessRuleStatus(int businessruleid, String status){
try {
String sql ="UPDATE ONGEGENEREERDE_BUSINESSRULE \n" +
"SET STATUS = '" + status + "' \n" +
"WHERE ONGEGENEREERDE_BUSINESSRULE.BUSINESSRULERULEID = " + businessruleid;
Statement stmt = con.createStatement();
stmt.executeUpdate(sql);
stmt.close();
}
catch(Exception ex){
System.out.println("Kan de status van de ongegenereerde businessrule niet veranderen");
ex.printStackTrace();
}
}
}
|
57662_0 | package servlets;
import java.io.IOException;
import java.sql.Connection;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import database.ConnectDBProduct;
import domeinklassen.Product;
public class ProductServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Connection con = (Connection)req.getSession().getAttribute("verbinding");
String knop = req.getParameter("knop");
ConnectDBProduct conn = new ConnectDBProduct(con);
ArrayList<Product> deVoorraad = conn.getProducten();
RequestDispatcher rd = req.getRequestDispatcher("product.jsp"); //stuur bij default naar voorraadoverzicht
//forward voorraadlijst naar de overzicht-pagina.
if(knop.equals("overzicht")){
if(deVoorraad.size() == 0){
req.setAttribute("msg", "Geen producten beschikbaar!");
}
else{
req.setAttribute("voorraadlijst", deVoorraad);
rd = req.getRequestDispatcher("productenoverzicht.jsp");
}
}
//forward lijst producten onder min voorraad
else if (knop.equals("OnderVoorraad")){
ArrayList<Product> ondermin = conn.getProductenOnderMinimum();
if(ondermin.size() == 0){
req.setAttribute("msg", "Alle producten zijn op voorraad!");
}
else{
req.setAttribute("voorraadlijst", ondermin);
rd = req.getRequestDispatcher("productenoverzicht.jsp");
}
}
//bestel producten onder min voorraad
else if(knop.equals("WerkVoorraadBij")){
ArrayList<Product> ondermin = conn.getProductenOnderMinimum();
if(ondermin.size() == 0){
req.setAttribute("msg", "Alle producten zijn op voorraad!");
}
else{
rd = req.getRequestDispatcher("nieuwebestelling.jsp");
req.setAttribute("stap1", "Done");
req.setAttribute("teBestellenProducten", ondermin);
}
}
//maak een nieuw product aan
else if(knop.equals("nieuw")){
String nm = req.getParameter("naam");
String ma = req.getParameter("minaantal");
String eh = req.getParameter("eenheid");
String pps = req.getParameter("pps");
ArrayList<String> velden = new ArrayList<String>();
velden.add(nm); velden.add(ma); velden.add(eh); velden.add("pps");
//check of nodige velden in zijn gevuld (artikelnummer bestaat niet meer omdat de database die straks gaat aanmaken)
boolean allesIngevuld = true;
for(String s : velden){
if(s.equals("")){
allesIngevuld = false;
req.setAttribute("error", "Vul alle velden in!");
break;
}
}
//als gegevens ingevuld
if(allesIngevuld){
try{ //check voor geldige nummers
//maak product aan in database en haal op
Product nieuw = conn.nieuwProduct(nm, Integer.parseInt(ma), eh, Double.parseDouble(pps));
//stuur toString() van nieuwe product terug
String terug = "Nieuw product aangemaakt: " + nieuw.toString();
req.setAttribute("msg", terug);
}
catch(Exception ex){
System.out.println(ex);
req.setAttribute("error", "Voer geldige nummers in!");
}
}
}
//zoek product op naam of artikelnummer
else if(knop.equals("zoek")){
String nm = req.getParameter("zoeknaam");
String eh = req.getParameter("zoekeenheid");
String anr = req.getParameter("zoeknummer");
ArrayList<Product> terug = new ArrayList<Product>();
//check welke zoekterm er in is gevoerd
if(!anr.equals("")){
//check voor geldig artikelnummer (int)
try{
int nummer = Integer.parseInt(anr);
terug.add(conn.zoekProduct(nummer));
}catch(NumberFormatException e){
req.setAttribute("error", "Vul een geldig artikelnummer in!");
}
}
if(!nm.equals("")){
for(Product p : conn.zoekProductNaam(nm)){
terug.add(p);
}
}
if(!eh.equals("")){
for(Product p : conn.zoekProductEenheid(eh)){
terug.add(p);
}
}
else{
req.setAttribute("error", "Vul een zoekcriterium in!");
}
if(terug.size() == 0){
req.setAttribute("zoekmsg", "Geen producten gevonden met ingevulde criteria");
}
else{
req.setAttribute("zoekmsg", "Product(en) gevonden!");
req.setAttribute("arraygevonden", terug);
}
}
//wijzig gezochte product
else if(knop.equals("wijzig")){
String productnummer = req.getParameter("product");
Product hetProduct = conn.zoekProduct(Integer.parseInt(productnummer));
req.setAttribute("product", hetProduct);
rd = req.getRequestDispatcher("wijzigproduct.jsp");
}
else if(knop.equals("verwijder")){
String p = req.getParameter("product");
if(conn.verwijderProduct(Integer.parseInt(p))){
req.setAttribute("msg", "Product met succes verwijderd.");
}
else{
req.setAttribute("error", "Kon product niet verwijderen!");
}
deVoorraad = conn.getProducten();
req.setAttribute("voorraadlijst", deVoorraad);
rd = req.getRequestDispatcher("productenoverzicht.jsp");
}
rd.forward(req, resp);
}
} | Jfeurich/Themaopdracht2 | Themaopdracht/src/servlets/ProductServlet.java | 1,844 | //stuur bij default naar voorraadoverzicht
| line_comment | nl | package servlets;
import java.io.IOException;
import java.sql.Connection;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import database.ConnectDBProduct;
import domeinklassen.Product;
public class ProductServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Connection con = (Connection)req.getSession().getAttribute("verbinding");
String knop = req.getParameter("knop");
ConnectDBProduct conn = new ConnectDBProduct(con);
ArrayList<Product> deVoorraad = conn.getProducten();
RequestDispatcher rd = req.getRequestDispatcher("product.jsp"); //stuur bij<SUF>
//forward voorraadlijst naar de overzicht-pagina.
if(knop.equals("overzicht")){
if(deVoorraad.size() == 0){
req.setAttribute("msg", "Geen producten beschikbaar!");
}
else{
req.setAttribute("voorraadlijst", deVoorraad);
rd = req.getRequestDispatcher("productenoverzicht.jsp");
}
}
//forward lijst producten onder min voorraad
else if (knop.equals("OnderVoorraad")){
ArrayList<Product> ondermin = conn.getProductenOnderMinimum();
if(ondermin.size() == 0){
req.setAttribute("msg", "Alle producten zijn op voorraad!");
}
else{
req.setAttribute("voorraadlijst", ondermin);
rd = req.getRequestDispatcher("productenoverzicht.jsp");
}
}
//bestel producten onder min voorraad
else if(knop.equals("WerkVoorraadBij")){
ArrayList<Product> ondermin = conn.getProductenOnderMinimum();
if(ondermin.size() == 0){
req.setAttribute("msg", "Alle producten zijn op voorraad!");
}
else{
rd = req.getRequestDispatcher("nieuwebestelling.jsp");
req.setAttribute("stap1", "Done");
req.setAttribute("teBestellenProducten", ondermin);
}
}
//maak een nieuw product aan
else if(knop.equals("nieuw")){
String nm = req.getParameter("naam");
String ma = req.getParameter("minaantal");
String eh = req.getParameter("eenheid");
String pps = req.getParameter("pps");
ArrayList<String> velden = new ArrayList<String>();
velden.add(nm); velden.add(ma); velden.add(eh); velden.add("pps");
//check of nodige velden in zijn gevuld (artikelnummer bestaat niet meer omdat de database die straks gaat aanmaken)
boolean allesIngevuld = true;
for(String s : velden){
if(s.equals("")){
allesIngevuld = false;
req.setAttribute("error", "Vul alle velden in!");
break;
}
}
//als gegevens ingevuld
if(allesIngevuld){
try{ //check voor geldige nummers
//maak product aan in database en haal op
Product nieuw = conn.nieuwProduct(nm, Integer.parseInt(ma), eh, Double.parseDouble(pps));
//stuur toString() van nieuwe product terug
String terug = "Nieuw product aangemaakt: " + nieuw.toString();
req.setAttribute("msg", terug);
}
catch(Exception ex){
System.out.println(ex);
req.setAttribute("error", "Voer geldige nummers in!");
}
}
}
//zoek product op naam of artikelnummer
else if(knop.equals("zoek")){
String nm = req.getParameter("zoeknaam");
String eh = req.getParameter("zoekeenheid");
String anr = req.getParameter("zoeknummer");
ArrayList<Product> terug = new ArrayList<Product>();
//check welke zoekterm er in is gevoerd
if(!anr.equals("")){
//check voor geldig artikelnummer (int)
try{
int nummer = Integer.parseInt(anr);
terug.add(conn.zoekProduct(nummer));
}catch(NumberFormatException e){
req.setAttribute("error", "Vul een geldig artikelnummer in!");
}
}
if(!nm.equals("")){
for(Product p : conn.zoekProductNaam(nm)){
terug.add(p);
}
}
if(!eh.equals("")){
for(Product p : conn.zoekProductEenheid(eh)){
terug.add(p);
}
}
else{
req.setAttribute("error", "Vul een zoekcriterium in!");
}
if(terug.size() == 0){
req.setAttribute("zoekmsg", "Geen producten gevonden met ingevulde criteria");
}
else{
req.setAttribute("zoekmsg", "Product(en) gevonden!");
req.setAttribute("arraygevonden", terug);
}
}
//wijzig gezochte product
else if(knop.equals("wijzig")){
String productnummer = req.getParameter("product");
Product hetProduct = conn.zoekProduct(Integer.parseInt(productnummer));
req.setAttribute("product", hetProduct);
rd = req.getRequestDispatcher("wijzigproduct.jsp");
}
else if(knop.equals("verwijder")){
String p = req.getParameter("product");
if(conn.verwijderProduct(Integer.parseInt(p))){
req.setAttribute("msg", "Product met succes verwijderd.");
}
else{
req.setAttribute("error", "Kon product niet verwijderen!");
}
deVoorraad = conn.getProducten();
req.setAttribute("voorraadlijst", deVoorraad);
rd = req.getRequestDispatcher("productenoverzicht.jsp");
}
rd.forward(req, resp);
}
} |
43361_2 | package nl.hu.tho6.persistence;
import nl.hu.tho6.domain.businessrule.Attribute;
import nl.hu.tho6.domain.businessrule.BusinessRule;
import nl.hu.tho6.domain.businessrule.Operator;
import nl.hu.tho6.domain.businessrule.Value;
import nl.hu.tho6.persistence.connection.ConnectionFactory;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
/*
* Deze methode moet bevatten:
* connect() Maak verbinding met de Oracle DB
* getBusinessrule() Haal Businessrule op
* saveBusinessrule() Sla Businessrule op
* getongegenereerdeBusinessrules() Haal de te genereren Businessrules op
* searchBusinessrule() Zoek een businessrule op naam/tabel/etc
*
*/
public class ConnectDBBusinessRule {
private Connection con;
public ConnectDBBusinessRule(Connection c) {
con = c;
}
/**
* Haalt alle ongegenereerde businessrules op uit de database.
*/
public List<BusinessRule> getOngegenereerdeBusinessRules() {
Statement stmt;
//Haal de businessrules op uit de ruledatabase
List<BusinessRule> rules = new ArrayList<>();
try {
String sql = "select BUSINESSRULE.RULEID as RULEID,\n" +
"BUSINESSRULE.RULENAAM as RULENAAM,\n" +
"BUSINESSRULE.ERROR as ERROR,\n" +
"BUSINESSRULE.ERRORTYPE as ERRORTYPE,\n" +
"BUSINESSRULE.OPERATOR as OPERATOR,\n" +
"BUSINESSRULE.BUSINESSRULETYPE as BUSINESSRULETYPE \n," +
"ONGEGENEREERDE_BUSINESSRULE.LANGUAGENAAM as LANGUAGE\n " +
" from ONGEGENEREERDE_BUSINESSRULE ,\n" +
"BUSINESSRULE \n" +
" where BUSINESSRULE.RULEID=ONGEGENEREERDE_BUSINESSRULE.BUSINESSRULERULEID\n" +
" and ONGEGENEREERDE_BUSINESSRULE.STATUS = 'NOT_GENERATED'";
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
BusinessRule r = new BusinessRule();
int id = rs.getInt("RULEID");
String rulenaam = rs.getString("RULENAAM");
String error = rs.getString("ERROR");
String errortype = rs.getString("ERRORTYPE");
String language = rs.getString("LANGUAGE");
int ruletype = rs.getInt("BUSINESSRULETYPE");
String code = "";
//TODO dit gaat waarschijnlijk nog nullpointer excpetions opleveren
// maar even kijken of dit handiger kan
// TODO kijken of optional hier een optie is.
ConnectDBBusinessRule con2 = new ConnectDBBusinessRule(con);
ArrayList<Value> values = con2.getValue(id);
ConnectDBBusinessRule con3 = new ConnectDBBusinessRule(con);
Operator o = con3.getOperator(id);
ConnectDBBusinessRule con4 = new ConnectDBBusinessRule(con);
ArrayList<Attribute> attributes = con4.getAttribute(id);
Attribute a1 = null;
Attribute a2 = null;
Value v1 = null;
Value v2 = null;
if (attributes.isEmpty()) {
a1 = attributes.get(0);
if (attributes.size() > 1) {
a2 = attributes.get(1);
}
}
if (values.isEmpty()) {
v1 = values.get(0);
if (values.size() > 1) {
v2 = values.get(1);
}
}
r.setRuleNaam(rulenaam);
r.setError(error);
r.setErrorType(errortype);
r.setCode(code);
r.setOperator(o);
r.setBusinessruletype(ruletype);
if(a1 != null && a2 != null && a1.getTabel() != a2.getTabel()){
setReferences(a1,a2);
}
if(nulltest(v1)){
r.setValue1(v1);
}
if(nulltest(v2)){
r.setValue2(v2);
}
if(nulltest(a1)) {
r.setAttribute1(a1);
}
if(nulltest(a2)){
r.setAttribute2(a2);
}
r.setRuleID(id);
r.setLanguage(language);
rules.add(r);
}
stmt.close();
} catch (Exception ex) {
ex.printStackTrace();
}
finally {
if(stmt != null) {
stmt.close();
}
}
return rules;
}
public void saveToErrorLog(String error, String businessruleid){
try {
PreparedStatement updateStatement = con.prepareStatement("INSERT INTO ERROR_LOG (ERRORID,ERRORMESSAGE,DATUM,\"user\",TABLENAME) VALUES (SEQ_ERROR_LOG.NEXTVAL,?,SYSDATE,'JAVA',?)");
updateStatement.setString(1,error);
updateStatement.setString(2,businessruleid);
updateStatement.executeQuery();
updateStatement.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void setReferences(Attribute a1, Attribute a2) {
Statement stmt;
try {
String url = "jdbc:oracle:thin:@//ondora01.hu.nl:8521/cursus01.hu.nl";
String user = "tho6_2014_2b_team3_target";
String password = " tho6_2014_2b_team3_target";
Connection tempcon = ConnectionFactory.getTargetConnection(url,user,password);
String sql = "SELECT UCC1.TABLE_NAME||'.'||UCC1.COLUMN_NAME CONSTRAINT_SOURCE,\n" +
"UCC2.TABLE_NAME||'.'||UCC2.COLUMN_NAME REFERENCES_COLUMN\n" +
"FROM USER_CONSTRAINTS uc,\n" +
"USER_CONS_COLUMNS ucc1,\n" +
"USER_CONS_COLUMNS ucc2\n" +
"WHERE UC.CONSTRAINT_NAME = UCC1.CONSTRAINT_NAME\n" +
"AND UC.R_CONSTRAINT_NAME = UCC2.CONSTRAINT_NAME\n" +
"AND UCC1.POSITION = UCC2.POSITION\n" +
"AND UC.CONSTRAINT_TYPE = 'R'\n" +
"AND (UCC1.TABLE_NAME = '" + a1.getTabel() + "' OR UCC2.TABLE_NAME = '" + a1.getTabel() + "')\n" +
"AND (UCC1.TABLE_NAME = '" + a2.getTabel() + "' OR UCC2.TABLE_NAME = '" + a2.getTabel() + "')\n";
stmt = tempcon.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
String source1 = rs.getString("CONSTRAINT_SOURCE");
String source2 = rs.getString("REFERENCES_COLUMN");
String[] sourceSplit = source1.split("\\.");
String[] sourceSplit2 = source2.split("\\.");
if(a1.getTabel().equals(sourceSplit[0])){
a1.setReference(sourceSplit[1]);
a2.setReference(sourceSplit2[1]);
} else {
a1.setReference(sourceSplit2[1]);
a2.setReference(sourceSplit[1]);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
finally {
if(stmt != null) {
stmt.close();
}
}
}
/*Haalt alle attributes behorende bij de businessrule uit de DB*/
public List<Attribute> getAttribute(int businessruleID){
Statement stmt;
List<Attribute> attributes = new ArrayList<>();
try {
String sql = "select ATTRIBUTE.ATTRIBUTENAAM as ATTRIBUTENAAM,\n" +
" ATTRIBUTE.DBSCHEMA as DBSCHEMA,\n" +
" ATTRIBUTE.TABEL as TABEL,\n" +
" ATTRIBUTE.KOLOM as KOLOM,\n" +
" ATTRIBUTE.ATTRIBUTEID as ATTRIBUTEID \n" +
" from BUSINESSRULE_ATTRIBUTE BUSINESSRULE_ATTRIBUTE,\n" +
" ATTRIBUTE ATTRIBUTE \n" +
" where BUSINESSRULE_ATTRIBUTE.BUSINESSRULE="+ businessruleID + "\n" +
" and BUSINESSRULE_ATTRIBUTE.ATTRIBUTE=ATTRIBUTE.ATTRIBUTEID";
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
int attributeid = rs.getInt("ATTRIBUTEID");
String attributenaam = rs.getString("ATTRIBUTENAAM");
String dbschema = rs.getString("DBSCHEMA");
String tabel = rs.getString("TABEL");
String kolom = rs.getString("KOLOM");
Attribute a = new Attribute(attributenaam,dbschema,tabel,kolom,attributeid);
attributes.add(a);
}
} catch (Exception ex) {
ex.printStackTrace();
}
finally {
if(stmt != null) {
stmt.close();
}
}
return attributes;
}
/*haal values uit de database behordende bij de database*/
public List<Value> getValue(int businessruleID){
Statement stmt;
List<Value> v = new ArrayList<>();
try {
String sql = "select VALUE.VALUEID as VALUEID,\n" +
" VALUE.WAARDENAAM as WAARDENAAM,\n" +
" VALUE.VALUETYPE as VALUETYPE,\n" +
" VALUE.VALUE as VALUECONTENT,\n" +
" VALUE.BUSINESSRULE as BUSINESSRULE \n" +
" from VALUE VALUE \n" +
" where VALUE.BUSINESSRULE = " + businessruleID;
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
String waardenaam = rs.getString("WAARDENAAM");
String valuetype = rs.getString("VALUETYPE");
String value = rs.getString("VALUECONTENT");
Value val = new Value(waardenaam,valuetype,value);
v.add(val);
}
} catch (Exception ex) {
ex.printStackTrace();
}
finally {
if(stmt != null) {
stmt.close();
}
}
return v;
}
/*Haal de operator behorende bijde businessrule uit de database*/
public Operator getOperator(int businessruleID){
Statement stmt;
Operator op = null;
try {
String sql = "select OPERATOR.OPERATORNAAM as OPERATORNAAM," +
"OPERATOR.OPERATORTYPE as OPERATORTYPE \n" +
"from BUSINESSRULE BUSINESSRULE,\n" +
"OPERATOR OPERATOR \n" +
"where OPERATOR.OPERATORID=BUSINESSRULE.OPERATOR\n" +
"and BUSINESSRULE.RULEID ="+businessruleID;
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
String naam = rs.getString("OPERATORNAAM");
String operatortype = rs.getString("OPERATORTYPE");
op = new Operator(naam,operatortype);
}
} catch (Exception ex) {
ex.printStackTrace();
}
finally {
if(stmt != null) {
stmt.close();
}
}
return op;
}
/*Controleer of een object null returnt */
public boolean nulltest(Object o){
if(o!=null){
return true;
}
return false;
}
/*Sla de gemaakte businessrule op in de oracle database.*/
// TODO: pas de savebusinessrule aan zodat hij de businessrule als string opslaat in de apex database.
public void saveBusinessRule(String businessrulenaam,String languagenaam, String code){
Statement stmt;
try {
String sql = "SELECT *\n" +
"FROM GEGENEREERDE_BUSINESSRULE\n" +
"WHERE GEGENEREERDE_BUSINESSRULE.BUSINESSRULENAAM = '" + businessrulenaam + "'\n" +
"AND GEGENEREERDE_BUSINESSRULE.LANGUAGENAAM = '" + languagenaam + "'";
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
if(rs.next()) {
PreparedStatement updateStatement = con.prepareStatement("UPDATE GEGENEREERDE_BUSINESSRULE \n" +
"SET CODE = ? \n" +
"WHERE GEGENEREERDE_BUSINESSRULE.BUSINESSRULENAAM = ?\n" +
"AND GEGENEREERDE_BUSINESSRULE.LANGUAGENAAM = ?");
updateStatement.setString(1, code);
updateStatement.setString(2, businessrulenaam);
updateStatement.setString(3, languagenaam);
updateStatement.executeQuery();
updateStatement.close();
} else {
try {
PreparedStatement updateStatement = con.prepareStatement("INSERT INTO GEGENEREERDE_BUSINESSRULE (GENID,BUSINESSRULENAAM,LANGUAGENAAM,CODE) VALUES (SEQ_GEGENEREERDE_BUSINESSRULE.NEXTVAL,?,?,?)");
updateStatement.setString(1, businessrulenaam);
updateStatement.setString(2, languagenaam);
updateStatement.setString(3, code);
updateStatement.executeQuery();
updateStatement.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
finally {
if(stmt != null) {
stmt.close();
}
}
}
public void runCode(String code){
Statement stmt;
try {
String url = "jdbc:oracle:thin:@//ondora01.hu.nl:8521/cursus01.hu.nl";
String user = "tho6_2014_2b_team3_target";
String password = " tho6_2014_2b_team3_target";
Connection tempcon = ConnectionFactory.getTargetConnection(url,user,password);
stmt = tempcon.createStatement();
stmt.executeUpdate(code);
} catch (Exception ex) {
ex.printStackTrace();
}
finally {
if(stmt != null) {
stmt.close();
}
}
}
/*Verander de status van de gegenereerde businessrule in de database.*/
public void changeBusinessRuleStatus(int businessruleid, String status){
Statement stmt;
try {
String sql ="UPDATE ONGEGENEREERDE_BUSINESSRULE \n" +
"SET STATUS = '" + status + "' \n" +
"WHERE ONGEGENEREERDE_BUSINESSRULE.BUSINESSRULERULEID = " + businessruleid;
stmt = con.createStatement();
stmt.executeUpdate(sql);
}
catch(Exception ex){
ex.printStackTrace();
}
finally {
if(stmt != null) {
stmt.close();
}
}
}
}
| Jfeurich/codereview | src/main/java/nl/hu/tho6/persistence/ConnectDBBusinessRule.java | 4,565 | //Haal de businessrules op uit de ruledatabase | line_comment | nl | package nl.hu.tho6.persistence;
import nl.hu.tho6.domain.businessrule.Attribute;
import nl.hu.tho6.domain.businessrule.BusinessRule;
import nl.hu.tho6.domain.businessrule.Operator;
import nl.hu.tho6.domain.businessrule.Value;
import nl.hu.tho6.persistence.connection.ConnectionFactory;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
/*
* Deze methode moet bevatten:
* connect() Maak verbinding met de Oracle DB
* getBusinessrule() Haal Businessrule op
* saveBusinessrule() Sla Businessrule op
* getongegenereerdeBusinessrules() Haal de te genereren Businessrules op
* searchBusinessrule() Zoek een businessrule op naam/tabel/etc
*
*/
public class ConnectDBBusinessRule {
private Connection con;
public ConnectDBBusinessRule(Connection c) {
con = c;
}
/**
* Haalt alle ongegenereerde businessrules op uit de database.
*/
public List<BusinessRule> getOngegenereerdeBusinessRules() {
Statement stmt;
//Haal de<SUF>
List<BusinessRule> rules = new ArrayList<>();
try {
String sql = "select BUSINESSRULE.RULEID as RULEID,\n" +
"BUSINESSRULE.RULENAAM as RULENAAM,\n" +
"BUSINESSRULE.ERROR as ERROR,\n" +
"BUSINESSRULE.ERRORTYPE as ERRORTYPE,\n" +
"BUSINESSRULE.OPERATOR as OPERATOR,\n" +
"BUSINESSRULE.BUSINESSRULETYPE as BUSINESSRULETYPE \n," +
"ONGEGENEREERDE_BUSINESSRULE.LANGUAGENAAM as LANGUAGE\n " +
" from ONGEGENEREERDE_BUSINESSRULE ,\n" +
"BUSINESSRULE \n" +
" where BUSINESSRULE.RULEID=ONGEGENEREERDE_BUSINESSRULE.BUSINESSRULERULEID\n" +
" and ONGEGENEREERDE_BUSINESSRULE.STATUS = 'NOT_GENERATED'";
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
BusinessRule r = new BusinessRule();
int id = rs.getInt("RULEID");
String rulenaam = rs.getString("RULENAAM");
String error = rs.getString("ERROR");
String errortype = rs.getString("ERRORTYPE");
String language = rs.getString("LANGUAGE");
int ruletype = rs.getInt("BUSINESSRULETYPE");
String code = "";
//TODO dit gaat waarschijnlijk nog nullpointer excpetions opleveren
// maar even kijken of dit handiger kan
// TODO kijken of optional hier een optie is.
ConnectDBBusinessRule con2 = new ConnectDBBusinessRule(con);
ArrayList<Value> values = con2.getValue(id);
ConnectDBBusinessRule con3 = new ConnectDBBusinessRule(con);
Operator o = con3.getOperator(id);
ConnectDBBusinessRule con4 = new ConnectDBBusinessRule(con);
ArrayList<Attribute> attributes = con4.getAttribute(id);
Attribute a1 = null;
Attribute a2 = null;
Value v1 = null;
Value v2 = null;
if (attributes.isEmpty()) {
a1 = attributes.get(0);
if (attributes.size() > 1) {
a2 = attributes.get(1);
}
}
if (values.isEmpty()) {
v1 = values.get(0);
if (values.size() > 1) {
v2 = values.get(1);
}
}
r.setRuleNaam(rulenaam);
r.setError(error);
r.setErrorType(errortype);
r.setCode(code);
r.setOperator(o);
r.setBusinessruletype(ruletype);
if(a1 != null && a2 != null && a1.getTabel() != a2.getTabel()){
setReferences(a1,a2);
}
if(nulltest(v1)){
r.setValue1(v1);
}
if(nulltest(v2)){
r.setValue2(v2);
}
if(nulltest(a1)) {
r.setAttribute1(a1);
}
if(nulltest(a2)){
r.setAttribute2(a2);
}
r.setRuleID(id);
r.setLanguage(language);
rules.add(r);
}
stmt.close();
} catch (Exception ex) {
ex.printStackTrace();
}
finally {
if(stmt != null) {
stmt.close();
}
}
return rules;
}
public void saveToErrorLog(String error, String businessruleid){
try {
PreparedStatement updateStatement = con.prepareStatement("INSERT INTO ERROR_LOG (ERRORID,ERRORMESSAGE,DATUM,\"user\",TABLENAME) VALUES (SEQ_ERROR_LOG.NEXTVAL,?,SYSDATE,'JAVA',?)");
updateStatement.setString(1,error);
updateStatement.setString(2,businessruleid);
updateStatement.executeQuery();
updateStatement.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void setReferences(Attribute a1, Attribute a2) {
Statement stmt;
try {
String url = "jdbc:oracle:thin:@//ondora01.hu.nl:8521/cursus01.hu.nl";
String user = "tho6_2014_2b_team3_target";
String password = " tho6_2014_2b_team3_target";
Connection tempcon = ConnectionFactory.getTargetConnection(url,user,password);
String sql = "SELECT UCC1.TABLE_NAME||'.'||UCC1.COLUMN_NAME CONSTRAINT_SOURCE,\n" +
"UCC2.TABLE_NAME||'.'||UCC2.COLUMN_NAME REFERENCES_COLUMN\n" +
"FROM USER_CONSTRAINTS uc,\n" +
"USER_CONS_COLUMNS ucc1,\n" +
"USER_CONS_COLUMNS ucc2\n" +
"WHERE UC.CONSTRAINT_NAME = UCC1.CONSTRAINT_NAME\n" +
"AND UC.R_CONSTRAINT_NAME = UCC2.CONSTRAINT_NAME\n" +
"AND UCC1.POSITION = UCC2.POSITION\n" +
"AND UC.CONSTRAINT_TYPE = 'R'\n" +
"AND (UCC1.TABLE_NAME = '" + a1.getTabel() + "' OR UCC2.TABLE_NAME = '" + a1.getTabel() + "')\n" +
"AND (UCC1.TABLE_NAME = '" + a2.getTabel() + "' OR UCC2.TABLE_NAME = '" + a2.getTabel() + "')\n";
stmt = tempcon.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
String source1 = rs.getString("CONSTRAINT_SOURCE");
String source2 = rs.getString("REFERENCES_COLUMN");
String[] sourceSplit = source1.split("\\.");
String[] sourceSplit2 = source2.split("\\.");
if(a1.getTabel().equals(sourceSplit[0])){
a1.setReference(sourceSplit[1]);
a2.setReference(sourceSplit2[1]);
} else {
a1.setReference(sourceSplit2[1]);
a2.setReference(sourceSplit[1]);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
finally {
if(stmt != null) {
stmt.close();
}
}
}
/*Haalt alle attributes behorende bij de businessrule uit de DB*/
public List<Attribute> getAttribute(int businessruleID){
Statement stmt;
List<Attribute> attributes = new ArrayList<>();
try {
String sql = "select ATTRIBUTE.ATTRIBUTENAAM as ATTRIBUTENAAM,\n" +
" ATTRIBUTE.DBSCHEMA as DBSCHEMA,\n" +
" ATTRIBUTE.TABEL as TABEL,\n" +
" ATTRIBUTE.KOLOM as KOLOM,\n" +
" ATTRIBUTE.ATTRIBUTEID as ATTRIBUTEID \n" +
" from BUSINESSRULE_ATTRIBUTE BUSINESSRULE_ATTRIBUTE,\n" +
" ATTRIBUTE ATTRIBUTE \n" +
" where BUSINESSRULE_ATTRIBUTE.BUSINESSRULE="+ businessruleID + "\n" +
" and BUSINESSRULE_ATTRIBUTE.ATTRIBUTE=ATTRIBUTE.ATTRIBUTEID";
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
int attributeid = rs.getInt("ATTRIBUTEID");
String attributenaam = rs.getString("ATTRIBUTENAAM");
String dbschema = rs.getString("DBSCHEMA");
String tabel = rs.getString("TABEL");
String kolom = rs.getString("KOLOM");
Attribute a = new Attribute(attributenaam,dbschema,tabel,kolom,attributeid);
attributes.add(a);
}
} catch (Exception ex) {
ex.printStackTrace();
}
finally {
if(stmt != null) {
stmt.close();
}
}
return attributes;
}
/*haal values uit de database behordende bij de database*/
public List<Value> getValue(int businessruleID){
Statement stmt;
List<Value> v = new ArrayList<>();
try {
String sql = "select VALUE.VALUEID as VALUEID,\n" +
" VALUE.WAARDENAAM as WAARDENAAM,\n" +
" VALUE.VALUETYPE as VALUETYPE,\n" +
" VALUE.VALUE as VALUECONTENT,\n" +
" VALUE.BUSINESSRULE as BUSINESSRULE \n" +
" from VALUE VALUE \n" +
" where VALUE.BUSINESSRULE = " + businessruleID;
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
String waardenaam = rs.getString("WAARDENAAM");
String valuetype = rs.getString("VALUETYPE");
String value = rs.getString("VALUECONTENT");
Value val = new Value(waardenaam,valuetype,value);
v.add(val);
}
} catch (Exception ex) {
ex.printStackTrace();
}
finally {
if(stmt != null) {
stmt.close();
}
}
return v;
}
/*Haal de operator behorende bijde businessrule uit de database*/
public Operator getOperator(int businessruleID){
Statement stmt;
Operator op = null;
try {
String sql = "select OPERATOR.OPERATORNAAM as OPERATORNAAM," +
"OPERATOR.OPERATORTYPE as OPERATORTYPE \n" +
"from BUSINESSRULE BUSINESSRULE,\n" +
"OPERATOR OPERATOR \n" +
"where OPERATOR.OPERATORID=BUSINESSRULE.OPERATOR\n" +
"and BUSINESSRULE.RULEID ="+businessruleID;
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
String naam = rs.getString("OPERATORNAAM");
String operatortype = rs.getString("OPERATORTYPE");
op = new Operator(naam,operatortype);
}
} catch (Exception ex) {
ex.printStackTrace();
}
finally {
if(stmt != null) {
stmt.close();
}
}
return op;
}
/*Controleer of een object null returnt */
public boolean nulltest(Object o){
if(o!=null){
return true;
}
return false;
}
/*Sla de gemaakte businessrule op in de oracle database.*/
// TODO: pas de savebusinessrule aan zodat hij de businessrule als string opslaat in de apex database.
public void saveBusinessRule(String businessrulenaam,String languagenaam, String code){
Statement stmt;
try {
String sql = "SELECT *\n" +
"FROM GEGENEREERDE_BUSINESSRULE\n" +
"WHERE GEGENEREERDE_BUSINESSRULE.BUSINESSRULENAAM = '" + businessrulenaam + "'\n" +
"AND GEGENEREERDE_BUSINESSRULE.LANGUAGENAAM = '" + languagenaam + "'";
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
if(rs.next()) {
PreparedStatement updateStatement = con.prepareStatement("UPDATE GEGENEREERDE_BUSINESSRULE \n" +
"SET CODE = ? \n" +
"WHERE GEGENEREERDE_BUSINESSRULE.BUSINESSRULENAAM = ?\n" +
"AND GEGENEREERDE_BUSINESSRULE.LANGUAGENAAM = ?");
updateStatement.setString(1, code);
updateStatement.setString(2, businessrulenaam);
updateStatement.setString(3, languagenaam);
updateStatement.executeQuery();
updateStatement.close();
} else {
try {
PreparedStatement updateStatement = con.prepareStatement("INSERT INTO GEGENEREERDE_BUSINESSRULE (GENID,BUSINESSRULENAAM,LANGUAGENAAM,CODE) VALUES (SEQ_GEGENEREERDE_BUSINESSRULE.NEXTVAL,?,?,?)");
updateStatement.setString(1, businessrulenaam);
updateStatement.setString(2, languagenaam);
updateStatement.setString(3, code);
updateStatement.executeQuery();
updateStatement.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
finally {
if(stmt != null) {
stmt.close();
}
}
}
public void runCode(String code){
Statement stmt;
try {
String url = "jdbc:oracle:thin:@//ondora01.hu.nl:8521/cursus01.hu.nl";
String user = "tho6_2014_2b_team3_target";
String password = " tho6_2014_2b_team3_target";
Connection tempcon = ConnectionFactory.getTargetConnection(url,user,password);
stmt = tempcon.createStatement();
stmt.executeUpdate(code);
} catch (Exception ex) {
ex.printStackTrace();
}
finally {
if(stmt != null) {
stmt.close();
}
}
}
/*Verander de status van de gegenereerde businessrule in de database.*/
public void changeBusinessRuleStatus(int businessruleid, String status){
Statement stmt;
try {
String sql ="UPDATE ONGEGENEREERDE_BUSINESSRULE \n" +
"SET STATUS = '" + status + "' \n" +
"WHERE ONGEGENEREERDE_BUSINESSRULE.BUSINESSRULERULEID = " + businessruleid;
stmt = con.createStatement();
stmt.executeUpdate(sql);
}
catch(Exception ex){
ex.printStackTrace();
}
finally {
if(stmt != null) {
stmt.close();
}
}
}
}
|
173320_11 | package emu.lunarcore.game.rogue;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import emu.lunarcore.GameConstants;
import emu.lunarcore.LunarCore;
import emu.lunarcore.data.GameData;
import emu.lunarcore.data.GameDepot;
import emu.lunarcore.data.excel.RogueTalentExcel;
import emu.lunarcore.game.player.BasePlayerManager;
import emu.lunarcore.game.player.Player;
import emu.lunarcore.game.player.lineup.PlayerLineup;
import emu.lunarcore.proto.ExtraLineupTypeOuterClass.ExtraLineupType;
import emu.lunarcore.proto.RogueAeonInfoOuterClass.RogueAeonInfo;
import emu.lunarcore.proto.RogueAreaOuterClass.RogueArea;
import emu.lunarcore.proto.RogueAreaStatusOuterClass.RogueAreaStatus;
import emu.lunarcore.proto.RogueInfoDataOuterClass.RogueInfoData;
import emu.lunarcore.proto.RogueInfoOuterClass.RogueInfo;
import emu.lunarcore.proto.RogueScoreRewardInfoOuterClass.RogueScoreRewardInfo;
import emu.lunarcore.proto.RogueSeasonInfoOuterClass.RogueSeasonInfo;
import emu.lunarcore.proto.RogueTalentInfoOuterClass.RogueTalentInfo;
import emu.lunarcore.proto.RogueTalentOuterClass.RogueTalent;
import emu.lunarcore.proto.RogueTalentStatusOuterClass.RogueTalentStatus;
import emu.lunarcore.server.packet.CmdId;
import emu.lunarcore.server.packet.send.PacketLeaveRogueScRsp;
import emu.lunarcore.server.packet.send.PacketStartRogueScRsp;
import emu.lunarcore.server.packet.send.PacketSyncRogueFinishScNotify;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import it.unimi.dsi.fastutil.ints.IntSet;
import lombok.Getter;
import us.hebi.quickbuf.RepeatedInt;
@Getter
public class RogueManager extends BasePlayerManager {
private IntSet talents;
public RogueManager(Player player) {
super(player);
this.talents = new IntOpenHashSet();
}
public boolean hasTalent(int talentId) {
return this.getTalents().contains(talentId);
}
public boolean enableTalent(int talentId) {
// Sanity check so we dont enable the same talent
if (this.getTalents().contains(talentId)) {
return false;
}
// Get talent excel
RogueTalentExcel excel = GameData.getRogueTalentExcelMap().get(talentId);
if (excel == null) return false;
// Verify items
if (!getPlayer().getInventory().verifyItems(excel.getCost())) {
return false;
}
// Pay items
getPlayer().getInventory().removeItemsByParams(excel.getCost());
// Add talent
RogueTalentData talent = new RogueTalentData(getPlayer(), excel.getTalentID());
talent.save();
return getTalents().add(talentId);
}
public void startRogue(int areaId, int aeonId, RepeatedInt avatarIdList) {
// Make sure player already isnt in a rogue instance
if (getPlayer().getRogueInstance() != null) {
getPlayer().sendPacket(new PacketStartRogueScRsp());
return;
}
// Get excel
var rogueAreaExcel = GameData.getRogueAreaExcelMap().get(areaId);
if (rogueAreaExcel == null || !rogueAreaExcel.isValid()) {
getPlayer().sendPacket(new PacketStartRogueScRsp());
return;
}
var aeonExcel = GameData.getRogueAeonExcelMap().get(aeonId);
// Replace lineup
getPlayer().getLineupManager().replaceLineup(0, ExtraLineupType.LINEUP_ROGUE_VALUE, Arrays.stream(avatarIdList.array()).boxed().toList());
// Get lineup
PlayerLineup lineup = getPlayer().getLineupManager().getLineupByIndex(0, ExtraLineupType.LINEUP_ROGUE_VALUE);
// Make sure this lineup has avatars set
if (lineup.getAvatars().size() == 0) {
getPlayer().sendPacket(new PacketStartRogueScRsp());
return;
}
// Get entrance id
RogueInstance instance = new RogueInstance(getPlayer(), rogueAreaExcel, aeonExcel);
getPlayer().setRogueInstance(instance);
// Set starting SP
boolean extraSP = this.hasTalent(32);
// Reset hp/sp
lineup.forEachAvatar(avatar -> {
avatar.setCurrentHp(lineup, 10000);
avatar.setCurrentSp(lineup, extraSP ? avatar.getMaxSp() : avatar.getMaxSp() / 2);
instance.getBaseAvatarIds().add(avatar.getAvatarId());
});
lineup.setMp(5); // Set technique points
// Set first lineup before we enter scenes
getPlayer().getLineupManager().setCurrentExtraLineup(ExtraLineupType.LINEUP_ROGUE, false);
// Enter rogue
RogueRoomData room = instance.enterRoom(instance.getStartSiteId());
if (room == null) {
// Reset lineup/instance if entering scene failed
getPlayer().getLineupManager().setCurrentExtraLineup(0, false);
getPlayer().setRogueInstance(null);
// Send error packet
getPlayer().sendPacket(new PacketStartRogueScRsp());
return;
}
// Done
getPlayer().sendPacket(new PacketStartRogueScRsp(getPlayer()));
}
public void leaveRogue() {
if (getPlayer().getRogueInstance() == null) {
getPlayer().getSession().send(CmdId.LeaveRogueScRsp);
return;
}
// Clear rogue instance
getPlayer().setRogueInstance(null);
// Leave scene
getPlayer().getLineupManager().setCurrentExtraLineup(0, false);
getPlayer().enterScene(GameConstants.ROGUE_ENTRANCE, 0, false); // Make sure we dont send an enter scene packet here
// Send packet
getPlayer().sendPacket(new PacketLeaveRogueScRsp(this.getPlayer()));
}
public void quitRogue() {
if (getPlayer().getRogueInstance() == null) {
getPlayer().getSession().send(CmdId.QuitRogueScRsp);
return;
}
getPlayer().getRogueInstance().onFinish();
getPlayer().getSession().send(CmdId.QuitRogueScRsp);
getPlayer().getSession().send(new PacketSyncRogueFinishScNotify(getPlayer()));
// This isnt correct behavior, but it does the job
this.leaveRogue();
}
public RogueInfo toProto() {
var schedule = GameDepot.getCurrentRogueSchedule();
int seasonId = 0;
long beginTime = (System.currentTimeMillis() / 1000) - TimeUnit.DAYS.toSeconds(1);
long endTime = beginTime + TimeUnit.DAYS.toSeconds(8);
if (schedule != null) {
seasonId = schedule.getRogueSeason();
}
var score = RogueScoreRewardInfo.newInstance()
.setPoolId(20 + getPlayer().getWorldLevel()) // TODO pool ids should not change when world level changes
.setPoolRefreshed(true)
.setHasTakenInitialScore(true);
var season = RogueSeasonInfo.newInstance()
.setBeginTime(beginTime)
.setSeasonId(seasonId)
.setEndTime(endTime);
var data = RogueInfoData.newInstance()
.setRogueScoreInfo(score)
.setRogueSeasonInfo(season);
var proto = RogueInfo.newInstance()
.setRogueScoreInfo(score)
.setRogueData(data)
.setRogueVirtualItemInfo(getPlayer().toRogueVirtualItemsProto())
.setSeasonId(seasonId)
.setBeginTime(beginTime)
.setEndTime(endTime);
// Path resonance
var aeonInfo = RogueAeonInfo.newInstance();
if (this.hasTalent(1)) {
aeonInfo = RogueAeonInfo.newInstance()
.setUnlockAeonNum(GameData.getRogueAeonExcelMap().size());
for (var aeonExcel : GameData.getRogueAeonExcelMap().values()) {
aeonInfo.addAeonIdList(aeonExcel.getAeonID());
}
proto.setRogueAeonInfo(aeonInfo);
}
// Rogue data
RogueInstance instance = this.getPlayer().getRogueInstance();
if (instance != null) {
proto.setStatus(instance.getStatus());
proto.setRogueProgress(this.getPlayer().getRogueInstance().toProto());
proto.setRoomMap(proto.getRogueProgress().getRoomMap());
for (int id : instance.getBaseAvatarIds()) {
proto.addBaseAvatarIdList(id);
}
aeonInfo.setSelectedAeonId(instance.getAeonId());
}
// Add areas
if (schedule != null) {
for (int i = 0; i < schedule.getRogueAreaIDList().length; i++) {
var excel = GameData.getRogueAreaExcelMap().get(schedule.getRogueAreaIDList()[i]);
if (excel == null) continue;
var area = RogueArea.newInstance()
.setAreaId(excel.getRogueAreaID())
.setRogueAreaStatus(RogueAreaStatus.ROGUE_AREA_STATUS_FIRST_PASS);
if (instance != null && excel == instance.getExcel()) {
area.setMapId(instance.getExcel().getMapId());
area.setCurReachRoomNum(instance.getCurrentRoomProgress());
area.setRogueStatus(instance.getStatus());
}
proto.addRogueAreaList(area);
}
}
return proto;
}
public RogueTalentInfo toTalentInfoProto() {
var proto = RogueTalentInfo.newInstance();
for (RogueTalentExcel excel : GameData.getRogueTalentExcelMap().values()) {
var talent = RogueTalent.newInstance()
.setTalentId(excel.getTalentID());
if (this.hasTalent(excel.getTalentID())) {
talent.setStatus(RogueTalentStatus.ROGUE_TALENT_STATUS_ENABLE);
} else {
talent.setStatus(RogueTalentStatus.ROGUE_TALENT_STATUS_UNLOCK);
}
proto.addRogueTalent(talent);
}
return proto;
}
// Database
public void loadFromDatabase() {
// Load talent data
var stream = LunarCore.getGameDatabase().getObjects(RogueTalentData.class, "ownerUid", this.getPlayer().getUid());
stream.forEach(talent -> {
this.getTalents().add(talent.getTalentId());
});
}
} | JimWails/LunarCore | src/main/java/emu/lunarcore/game/rogue/RogueManager.java | 3,343 | // Make sure we dont send an enter scene packet here | line_comment | nl | package emu.lunarcore.game.rogue;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import emu.lunarcore.GameConstants;
import emu.lunarcore.LunarCore;
import emu.lunarcore.data.GameData;
import emu.lunarcore.data.GameDepot;
import emu.lunarcore.data.excel.RogueTalentExcel;
import emu.lunarcore.game.player.BasePlayerManager;
import emu.lunarcore.game.player.Player;
import emu.lunarcore.game.player.lineup.PlayerLineup;
import emu.lunarcore.proto.ExtraLineupTypeOuterClass.ExtraLineupType;
import emu.lunarcore.proto.RogueAeonInfoOuterClass.RogueAeonInfo;
import emu.lunarcore.proto.RogueAreaOuterClass.RogueArea;
import emu.lunarcore.proto.RogueAreaStatusOuterClass.RogueAreaStatus;
import emu.lunarcore.proto.RogueInfoDataOuterClass.RogueInfoData;
import emu.lunarcore.proto.RogueInfoOuterClass.RogueInfo;
import emu.lunarcore.proto.RogueScoreRewardInfoOuterClass.RogueScoreRewardInfo;
import emu.lunarcore.proto.RogueSeasonInfoOuterClass.RogueSeasonInfo;
import emu.lunarcore.proto.RogueTalentInfoOuterClass.RogueTalentInfo;
import emu.lunarcore.proto.RogueTalentOuterClass.RogueTalent;
import emu.lunarcore.proto.RogueTalentStatusOuterClass.RogueTalentStatus;
import emu.lunarcore.server.packet.CmdId;
import emu.lunarcore.server.packet.send.PacketLeaveRogueScRsp;
import emu.lunarcore.server.packet.send.PacketStartRogueScRsp;
import emu.lunarcore.server.packet.send.PacketSyncRogueFinishScNotify;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import it.unimi.dsi.fastutil.ints.IntSet;
import lombok.Getter;
import us.hebi.quickbuf.RepeatedInt;
@Getter
public class RogueManager extends BasePlayerManager {
private IntSet talents;
public RogueManager(Player player) {
super(player);
this.talents = new IntOpenHashSet();
}
public boolean hasTalent(int talentId) {
return this.getTalents().contains(talentId);
}
public boolean enableTalent(int talentId) {
// Sanity check so we dont enable the same talent
if (this.getTalents().contains(talentId)) {
return false;
}
// Get talent excel
RogueTalentExcel excel = GameData.getRogueTalentExcelMap().get(talentId);
if (excel == null) return false;
// Verify items
if (!getPlayer().getInventory().verifyItems(excel.getCost())) {
return false;
}
// Pay items
getPlayer().getInventory().removeItemsByParams(excel.getCost());
// Add talent
RogueTalentData talent = new RogueTalentData(getPlayer(), excel.getTalentID());
talent.save();
return getTalents().add(talentId);
}
public void startRogue(int areaId, int aeonId, RepeatedInt avatarIdList) {
// Make sure player already isnt in a rogue instance
if (getPlayer().getRogueInstance() != null) {
getPlayer().sendPacket(new PacketStartRogueScRsp());
return;
}
// Get excel
var rogueAreaExcel = GameData.getRogueAreaExcelMap().get(areaId);
if (rogueAreaExcel == null || !rogueAreaExcel.isValid()) {
getPlayer().sendPacket(new PacketStartRogueScRsp());
return;
}
var aeonExcel = GameData.getRogueAeonExcelMap().get(aeonId);
// Replace lineup
getPlayer().getLineupManager().replaceLineup(0, ExtraLineupType.LINEUP_ROGUE_VALUE, Arrays.stream(avatarIdList.array()).boxed().toList());
// Get lineup
PlayerLineup lineup = getPlayer().getLineupManager().getLineupByIndex(0, ExtraLineupType.LINEUP_ROGUE_VALUE);
// Make sure this lineup has avatars set
if (lineup.getAvatars().size() == 0) {
getPlayer().sendPacket(new PacketStartRogueScRsp());
return;
}
// Get entrance id
RogueInstance instance = new RogueInstance(getPlayer(), rogueAreaExcel, aeonExcel);
getPlayer().setRogueInstance(instance);
// Set starting SP
boolean extraSP = this.hasTalent(32);
// Reset hp/sp
lineup.forEachAvatar(avatar -> {
avatar.setCurrentHp(lineup, 10000);
avatar.setCurrentSp(lineup, extraSP ? avatar.getMaxSp() : avatar.getMaxSp() / 2);
instance.getBaseAvatarIds().add(avatar.getAvatarId());
});
lineup.setMp(5); // Set technique points
// Set first lineup before we enter scenes
getPlayer().getLineupManager().setCurrentExtraLineup(ExtraLineupType.LINEUP_ROGUE, false);
// Enter rogue
RogueRoomData room = instance.enterRoom(instance.getStartSiteId());
if (room == null) {
// Reset lineup/instance if entering scene failed
getPlayer().getLineupManager().setCurrentExtraLineup(0, false);
getPlayer().setRogueInstance(null);
// Send error packet
getPlayer().sendPacket(new PacketStartRogueScRsp());
return;
}
// Done
getPlayer().sendPacket(new PacketStartRogueScRsp(getPlayer()));
}
public void leaveRogue() {
if (getPlayer().getRogueInstance() == null) {
getPlayer().getSession().send(CmdId.LeaveRogueScRsp);
return;
}
// Clear rogue instance
getPlayer().setRogueInstance(null);
// Leave scene
getPlayer().getLineupManager().setCurrentExtraLineup(0, false);
getPlayer().enterScene(GameConstants.ROGUE_ENTRANCE, 0, false); // Make sure<SUF>
// Send packet
getPlayer().sendPacket(new PacketLeaveRogueScRsp(this.getPlayer()));
}
public void quitRogue() {
if (getPlayer().getRogueInstance() == null) {
getPlayer().getSession().send(CmdId.QuitRogueScRsp);
return;
}
getPlayer().getRogueInstance().onFinish();
getPlayer().getSession().send(CmdId.QuitRogueScRsp);
getPlayer().getSession().send(new PacketSyncRogueFinishScNotify(getPlayer()));
// This isnt correct behavior, but it does the job
this.leaveRogue();
}
public RogueInfo toProto() {
var schedule = GameDepot.getCurrentRogueSchedule();
int seasonId = 0;
long beginTime = (System.currentTimeMillis() / 1000) - TimeUnit.DAYS.toSeconds(1);
long endTime = beginTime + TimeUnit.DAYS.toSeconds(8);
if (schedule != null) {
seasonId = schedule.getRogueSeason();
}
var score = RogueScoreRewardInfo.newInstance()
.setPoolId(20 + getPlayer().getWorldLevel()) // TODO pool ids should not change when world level changes
.setPoolRefreshed(true)
.setHasTakenInitialScore(true);
var season = RogueSeasonInfo.newInstance()
.setBeginTime(beginTime)
.setSeasonId(seasonId)
.setEndTime(endTime);
var data = RogueInfoData.newInstance()
.setRogueScoreInfo(score)
.setRogueSeasonInfo(season);
var proto = RogueInfo.newInstance()
.setRogueScoreInfo(score)
.setRogueData(data)
.setRogueVirtualItemInfo(getPlayer().toRogueVirtualItemsProto())
.setSeasonId(seasonId)
.setBeginTime(beginTime)
.setEndTime(endTime);
// Path resonance
var aeonInfo = RogueAeonInfo.newInstance();
if (this.hasTalent(1)) {
aeonInfo = RogueAeonInfo.newInstance()
.setUnlockAeonNum(GameData.getRogueAeonExcelMap().size());
for (var aeonExcel : GameData.getRogueAeonExcelMap().values()) {
aeonInfo.addAeonIdList(aeonExcel.getAeonID());
}
proto.setRogueAeonInfo(aeonInfo);
}
// Rogue data
RogueInstance instance = this.getPlayer().getRogueInstance();
if (instance != null) {
proto.setStatus(instance.getStatus());
proto.setRogueProgress(this.getPlayer().getRogueInstance().toProto());
proto.setRoomMap(proto.getRogueProgress().getRoomMap());
for (int id : instance.getBaseAvatarIds()) {
proto.addBaseAvatarIdList(id);
}
aeonInfo.setSelectedAeonId(instance.getAeonId());
}
// Add areas
if (schedule != null) {
for (int i = 0; i < schedule.getRogueAreaIDList().length; i++) {
var excel = GameData.getRogueAreaExcelMap().get(schedule.getRogueAreaIDList()[i]);
if (excel == null) continue;
var area = RogueArea.newInstance()
.setAreaId(excel.getRogueAreaID())
.setRogueAreaStatus(RogueAreaStatus.ROGUE_AREA_STATUS_FIRST_PASS);
if (instance != null && excel == instance.getExcel()) {
area.setMapId(instance.getExcel().getMapId());
area.setCurReachRoomNum(instance.getCurrentRoomProgress());
area.setRogueStatus(instance.getStatus());
}
proto.addRogueAreaList(area);
}
}
return proto;
}
public RogueTalentInfo toTalentInfoProto() {
var proto = RogueTalentInfo.newInstance();
for (RogueTalentExcel excel : GameData.getRogueTalentExcelMap().values()) {
var talent = RogueTalent.newInstance()
.setTalentId(excel.getTalentID());
if (this.hasTalent(excel.getTalentID())) {
talent.setStatus(RogueTalentStatus.ROGUE_TALENT_STATUS_ENABLE);
} else {
talent.setStatus(RogueTalentStatus.ROGUE_TALENT_STATUS_UNLOCK);
}
proto.addRogueTalent(talent);
}
return proto;
}
// Database
public void loadFromDatabase() {
// Load talent data
var stream = LunarCore.getGameDatabase().getObjects(RogueTalentData.class, "ownerUid", this.getPlayer().getUid());
stream.forEach(talent -> {
this.getTalents().add(talent.getTalentId());
});
}
} |
113783_7 | package com.baiduMap;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 根据订单的经纬度归属所在的商业区域
* @author lee
* @date: 2017年2月6日 下午2:12:02
*/
public class Polygon {
public static void main(String[] args) {
// 被检测的经纬度点
Map<String, String> orderLocation = new HashMap<String, String>();
orderLocation.put("X", "217.228117");
orderLocation.put("Y", "31.830429");
// 商业区域(百度多边形区域经纬度集合)
String partitionLocation = "31.839064_117.219116,31.83253_117.219403,31.828511_117.218146,31.826763_117.219259,31.826118_117.220517,31.822713_117.23586,31.822958_117.238375,31.838512_117.23798,31.839617_117.226194,31.839586_117.222925";
System.out.println(isInPolygon(orderLocation, partitionLocation));
}
/**
* 判断当前位置是否在多边形区域内
* @param orderLocation 当前点
* @param partitionLocation 区域顶点
* @return
*/
public static boolean isInPolygon(Map orderLocation,String partitionLocation){
double p_x =Double.parseDouble((String) orderLocation.get("X"));
double p_y =Double.parseDouble((String) orderLocation.get("Y"));
Point2D.Double point = new Point2D.Double(p_x, p_y);
List<Point2D.Double> pointList= new ArrayList<Point2D.Double>();
String[] strList = partitionLocation.split(",");
for (String str : strList){
String[] points = str.split("_");
double polygonPoint_x=Double.parseDouble(points[1]);
double polygonPoint_y=Double.parseDouble(points[0]);
Point2D.Double polygonPoint = new Point2D.Double(polygonPoint_x,polygonPoint_y);
pointList.add(polygonPoint);
}
return IsPtInPoly(point,pointList);
}
/**
* 返回一个点是否在一个多边形区域内, 如果点位于多边形的顶点或边上,不算做点在多边形内,返回false
* @param point
* @param polygon
* @return
*/
public static boolean checkWithJdkGeneralPath(Point2D.Double point, List<Point2D.Double> polygon) {
java.awt.geom.GeneralPath p = new java.awt.geom.GeneralPath();
Point2D.Double first = polygon.get(0);
p.moveTo(first.x, first.y);
polygon.remove(0);
for (Point2D.Double d : polygon) {
p.lineTo(d.x, d.y);
}
p.lineTo(first.x, first.y);
p.closePath();
return p.contains(point);
}
/**
* 判断点是否在多边形内,如果点位于多边形的顶点或边上,也算做点在多边形内,直接返回true
* @param point 检测点
* @param pts 多边形的顶点
* @return 点在多边形内返回true,否则返回false
*/
public static boolean IsPtInPoly(Point2D.Double point, List<Point2D.Double> pts){
int N = pts.size();
boolean boundOrVertex = true; //如果点位于多边形的顶点或边上,也算做点在多边形内,直接返回true
int intersectCount = 0;//cross points count of x
double precision = 2e-10; //浮点类型计算时候与0比较时候的容差
Point2D.Double p1, p2;//neighbour bound vertices
Point2D.Double p = point; //当前点
p1 = pts.get(0);//left vertex
for(int i = 1; i <= N; ++i){//check all rays
if(p.equals(p1)){
return boundOrVertex;//p is an vertex
}
p2 = pts.get(i % N);//right vertex
if(p.x < Math.min(p1.x, p2.x) || p.x > Math.max(p1.x, p2.x)){//ray is outside of our interests
p1 = p2;
continue;//next ray left point
}
if(p.x > Math.min(p1.x, p2.x) && p.x < Math.max(p1.x, p2.x)){//ray is crossing over by the algorithm (common part of)
if(p.y <= Math.max(p1.y, p2.y)){//x is before of ray
if(p1.x == p2.x && p.y >= Math.min(p1.y, p2.y)){//overlies on a horizontal ray
return boundOrVertex;
}
if(p1.y == p2.y){//ray is vertical
if(p1.y == p.y){//overlies on a vertical ray
return boundOrVertex;
}else{//before ray
++intersectCount;
}
}else{//cross point on the left side
double xinters = (p.x - p1.x) * (p2.y - p1.y) / (p2.x - p1.x) + p1.y;//cross point of y
if(Math.abs(p.y - xinters) < precision){//overlies on a ray
return boundOrVertex;
}
if(p.y < xinters){//before ray
++intersectCount;
}
}
}
}else{//special case when ray is crossing through the vertex
if(p.x == p2.x && p.y <= p2.y){//p crossing over p2
Point2D.Double p3 = pts.get((i+1) % N); //next vertex
if(p.x >= Math.min(p1.x, p3.x) && p.x <= Math.max(p1.x, p3.x)){//p.x lies between p1.x & p3.x
++intersectCount;
}else{
intersectCount += 2;
}
}
}
p1 = p2;//next ray left point
}
if(intersectCount % 2 == 0){//偶数在多边形外
return false;
} else { //奇数在多边形内
return true;
}
}
} | JimmyYangMJ/MyJAVA_DS | src/com/baiduMap/Polygon.java | 1,775 | //p is an vertex | line_comment | nl | package com.baiduMap;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 根据订单的经纬度归属所在的商业区域
* @author lee
* @date: 2017年2月6日 下午2:12:02
*/
public class Polygon {
public static void main(String[] args) {
// 被检测的经纬度点
Map<String, String> orderLocation = new HashMap<String, String>();
orderLocation.put("X", "217.228117");
orderLocation.put("Y", "31.830429");
// 商业区域(百度多边形区域经纬度集合)
String partitionLocation = "31.839064_117.219116,31.83253_117.219403,31.828511_117.218146,31.826763_117.219259,31.826118_117.220517,31.822713_117.23586,31.822958_117.238375,31.838512_117.23798,31.839617_117.226194,31.839586_117.222925";
System.out.println(isInPolygon(orderLocation, partitionLocation));
}
/**
* 判断当前位置是否在多边形区域内
* @param orderLocation 当前点
* @param partitionLocation 区域顶点
* @return
*/
public static boolean isInPolygon(Map orderLocation,String partitionLocation){
double p_x =Double.parseDouble((String) orderLocation.get("X"));
double p_y =Double.parseDouble((String) orderLocation.get("Y"));
Point2D.Double point = new Point2D.Double(p_x, p_y);
List<Point2D.Double> pointList= new ArrayList<Point2D.Double>();
String[] strList = partitionLocation.split(",");
for (String str : strList){
String[] points = str.split("_");
double polygonPoint_x=Double.parseDouble(points[1]);
double polygonPoint_y=Double.parseDouble(points[0]);
Point2D.Double polygonPoint = new Point2D.Double(polygonPoint_x,polygonPoint_y);
pointList.add(polygonPoint);
}
return IsPtInPoly(point,pointList);
}
/**
* 返回一个点是否在一个多边形区域内, 如果点位于多边形的顶点或边上,不算做点在多边形内,返回false
* @param point
* @param polygon
* @return
*/
public static boolean checkWithJdkGeneralPath(Point2D.Double point, List<Point2D.Double> polygon) {
java.awt.geom.GeneralPath p = new java.awt.geom.GeneralPath();
Point2D.Double first = polygon.get(0);
p.moveTo(first.x, first.y);
polygon.remove(0);
for (Point2D.Double d : polygon) {
p.lineTo(d.x, d.y);
}
p.lineTo(first.x, first.y);
p.closePath();
return p.contains(point);
}
/**
* 判断点是否在多边形内,如果点位于多边形的顶点或边上,也算做点在多边形内,直接返回true
* @param point 检测点
* @param pts 多边形的顶点
* @return 点在多边形内返回true,否则返回false
*/
public static boolean IsPtInPoly(Point2D.Double point, List<Point2D.Double> pts){
int N = pts.size();
boolean boundOrVertex = true; //如果点位于多边形的顶点或边上,也算做点在多边形内,直接返回true
int intersectCount = 0;//cross points count of x
double precision = 2e-10; //浮点类型计算时候与0比较时候的容差
Point2D.Double p1, p2;//neighbour bound vertices
Point2D.Double p = point; //当前点
p1 = pts.get(0);//left vertex
for(int i = 1; i <= N; ++i){//check all rays
if(p.equals(p1)){
return boundOrVertex;//p is<SUF>
}
p2 = pts.get(i % N);//right vertex
if(p.x < Math.min(p1.x, p2.x) || p.x > Math.max(p1.x, p2.x)){//ray is outside of our interests
p1 = p2;
continue;//next ray left point
}
if(p.x > Math.min(p1.x, p2.x) && p.x < Math.max(p1.x, p2.x)){//ray is crossing over by the algorithm (common part of)
if(p.y <= Math.max(p1.y, p2.y)){//x is before of ray
if(p1.x == p2.x && p.y >= Math.min(p1.y, p2.y)){//overlies on a horizontal ray
return boundOrVertex;
}
if(p1.y == p2.y){//ray is vertical
if(p1.y == p.y){//overlies on a vertical ray
return boundOrVertex;
}else{//before ray
++intersectCount;
}
}else{//cross point on the left side
double xinters = (p.x - p1.x) * (p2.y - p1.y) / (p2.x - p1.x) + p1.y;//cross point of y
if(Math.abs(p.y - xinters) < precision){//overlies on a ray
return boundOrVertex;
}
if(p.y < xinters){//before ray
++intersectCount;
}
}
}
}else{//special case when ray is crossing through the vertex
if(p.x == p2.x && p.y <= p2.y){//p crossing over p2
Point2D.Double p3 = pts.get((i+1) % N); //next vertex
if(p.x >= Math.min(p1.x, p3.x) && p.x <= Math.max(p1.x, p3.x)){//p.x lies between p1.x & p3.x
++intersectCount;
}else{
intersectCount += 2;
}
}
}
p1 = p2;//next ray left point
}
if(intersectCount % 2 == 0){//偶数在多边形外
return false;
} else { //奇数在多边形内
return true;
}
}
} |
17505_3 | package be.thomasmore.hartverlorenonderdentoren.controllers;
import be.thomasmore.hartverlorenonderdentoren.QR.QRCodeGenerator;
import be.thomasmore.hartverlorenonderdentoren.model.Event;
import be.thomasmore.hartverlorenonderdentoren.model.Match;
import be.thomasmore.hartverlorenonderdentoren.model.Person;
import be.thomasmore.hartverlorenonderdentoren.model.RecommendedMatch;
import be.thomasmore.hartverlorenonderdentoren.model.Stand;
import be.thomasmore.hartverlorenonderdentoren.repositories.*;
import com.google.zxing.WriterException;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import jakarta.mail.util.ByteArrayDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
@Configuration
@EnableScheduling
@Controller
public class MatchesController {
private final Logger logger = LoggerFactory.getLogger(MatchesController.class);
@Autowired
private PersonRepository personRepository;
@Autowired
private RecommendedMatchRepository recommendedMatchRepository;
@Autowired
private MatchRepository matchRepository;
@Autowired
private EventRepository eventRepository;
@Autowired
private StandRepository standRepository;
@Autowired
private GenderRepository genderRepository;
@Autowired
private JavaMailSender javaMailSender;
@Value("${spring.mail.username}")
private String senderEmail;
@GetMapping({"/matchmaker/matchesOverview/{id}"})
public String matchesOverview(Model model, @PathVariable String id) {
Optional<Person> personInDb = personRepository.findById(Integer.valueOf(id));
if (personInDb.isPresent()) {
List<RecommendedMatch> personMatches = recommendedMatchRepository.findAllByPerson1(personInDb.get());
RecommendedMatch firstMatch = personMatches.get(0);
personMatches.remove(0);
for (RecommendedMatch p : personMatches) {
logger.info("match: " + p.getPerson2().getName());
}
int sizeMatches = personMatches.size();
logger.info("amount of matches: " + sizeMatches);
model.addAttribute("person1", personInDb.get());
model.addAttribute("firstMatch", firstMatch);
model.addAttribute("personMatches", personMatches);
model.addAttribute("sizeMatches", sizeMatches);
}
return "matchmaker/matchesOverview";
}
@GetMapping("/matchmaker/makeMatch/{personId1}/{personId2}")
public String addMatch(Model model,
@PathVariable String personId1,
@PathVariable String personId2) {
Optional<Person> person1 = personRepository.findById(Integer.valueOf(personId1));
Optional<Person> person2 = personRepository.findById(Integer.valueOf(personId2));
if (person1.isPresent() && person2.isPresent()) {
logger.info("match: " + person1.get().getName() + " and " + person2.get().getName());
model.addAttribute("person1", person1.get());
model.addAttribute("person2", person2.get());
model.addAttribute("today", LocalDate.now());
}
return "matchmaker/makeMatch";
}
@PostMapping("/matchmaker/makeMatch/{personId1}/{personId2}")
public String sendEmail(@PathVariable String personId1,
@PathVariable String personId2) throws MessagingException, IOException, WriterException {
Optional<Person> person1 = personRepository.findById(Integer.valueOf(personId1));
Optional<Person> person2 = personRepository.findById(Integer.valueOf(personId2));
if (person1.isPresent() && person2.isPresent() && eventRepository.findByActive().isPresent()) {
logger.info("match: " + person1.get().getName() + " and " + person2.get().getName());
Match match = new Match(person1.get(), person2.get(), false, LocalTime.now(), eventRepository.findByActive().get());
match.getPerson1().setMatched(true);
match.getPerson2().setMatched(true);
matchRepository.save(match);
String bodyConfirm1 = mailConfirmBody(personId2, person1.get());
String bodyConfirm2 = mailConfirmBody(personId1, person2.get());
email(person1.get(), "Uw match is gevonden!", bodyConfirm1, false);
email(person2.get(), "Uw match is gevonden!", bodyConfirm2, false);
}
return "redirect:/index";
}
private String mailConfirmBody(@PathVariable String personId, Person person) {
return "<html> \n" +
"<head> \n" +
"<style>\n" +
"h2," +
"h3," +
"h4 {\n" +
" color:rgb(114, 28, 37)\n" +
"}" +
"button {\n" +
" background-color: #ff4d4d;\n" +
" color: #fff;\n" +
" border: none;\n" +
" border-radius: 8px;\n" +
" font-size: 15px;\n" +
" font-weight: bold;\n" +
" text-transform: uppercase;\n" +
" padding: 12px 20px;\n" +
" box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.3);\n" +
" transition: all 0.2s ease-in-out;\n" +
"} \n" +
"button:hover {\n" +
" background-color: #e60000;\n" +
" cursor: pointer;\n" +
" transform: scale(1.05);\n" +
"}\n" +
" div {\n" +
" text-align: center;\n" +
" background-color: rgb(248,186,189);\n" +
" }\n" +
"</style>\n" +
"</head>\n" +
"<body>\n" +
"<div>\n" +
"<br>\n" +
"<br>\n" +
"<h2>Beste " + person.getName() + "</h2> \n" +
"<h3>We hebben je perfecte match gevonden!</h3> \n" +
"<br>\n" +
"<h3>Klik op onderstaande knop om je match te accepteren op onze officiële website:</h3>\n" +
"<a href=https://hartverlorenonderdentoren.onrender.com/confirmMatch/" + personId + ">\n" +
"<button>Jouw match</button>\n" +
"</a>\n" +
"<h4>Met vriendelijke groet het hele OnderDenToren team.</h4>" +
"<br>\n" +
"</div>\n" +
"</body>\n" +
"</html>";
}
@GetMapping({"/confirmMatch/{personId}"})
public String confirmMatch(Model model, @PathVariable Integer personId) {
Optional<Match> match = matchRepository.findMatchByPerson1_Id(personId);
if (match.isEmpty()) {
match = matchRepository.findMatchByPerson2_Id(personId);
}
if (match.isPresent()) {
Optional<Person> matchedPerson = personRepository.findById(personId);
matchedPerson.ifPresent(person -> model.addAttribute("matchedPerson", person));
}
model.addAttribute("match", match);
return "confirmMatch";
}
@GetMapping(value = {"/confirmMatchAccept/{id}"})
public String confirmMatchAccept(@PathVariable Integer id) {
Optional<Match> matchOptional = matchRepository.findById(id);
int randomStandNumber = (int) Math.round(1 + (Math.random() * (standRepository.count() - 1)));
if (matchOptional.isPresent()) {
Match match = matchOptional.get();
if (match.getConfirmationCount() < 0.5) {
match.setConfirmationCount(0.5);
logger.info(Double.toString(match.getConfirmationCount()));
} else if (match.getConfirmationCount() == 0.5) {
match.setConfirmationCount(1);
match.setConfirmed(true);
logger.info(Boolean.toString(match.isConfirmed()));
Person person1 = matchOptional.get().getPerson1();
Person person2 = matchOptional.get().getPerson2();
try {
Optional<Stand> randomStand = standRepository.findById(randomStandNumber);
if (randomStand.isPresent()) {
logger.info("random stand : " + randomStand.get().getName());
String bodyTextQRCode1 = mailQRBody(person1, randomStand.get());
String bodyTextQRCode2 = mailQRBody(person2, randomStand.get());
email(matchOptional.get().getPerson1(), "Je match heeft geaccepteerd!", bodyTextQRCode1, true);
email(matchOptional.get().getPerson2(), "Je match heeft geaccepteerd!", bodyTextQRCode2, true);
}
//send feedback mail
String bodyFeedback1 = mailFeedbackBody(person1);
String bodyFeedback2 = mailFeedbackBody(person2);
TimerTask task = new TimerTask() {
public void run() {
try {
email(person1, "Laat ons weten wat je van de date vond", bodyFeedback1, false);
email(person2, "Laat ons weten wat je van de date vond", bodyFeedback2, false);
} catch (MessagingException | IOException | WriterException e) {
throw new RuntimeException(e);
}
}
};
Timer timer = new Timer("Timer");
long delay = 60000;
timer.schedule(task, delay);
} catch (MessagingException | WriterException | IOException e) {
throw new RuntimeException(e);
}
}
}
matchOptional.ifPresent(match -> matchRepository.save(match));
return "redirect:/index";
}
private String mailQRBody(Person person, Stand randomStand) {
return "<html>\n" +
"<head>\n" +
"<style>\n" +
"h2,\n" +
"h3,\n" +
"h4 {\n" +
" color:rgb(114, 28, 37)\n" +
"}\n" +
"div {\n" +
" text-align: center;\n" +
" background-color: rgb(248,186,189);\n" +
"}\n" +
"</style>\n" +
"</head>\n" +
"<body>\n" +
"<div>\n" +
"<br>\n" +
"<br>\n" +
"<h2>Beste " + person.getName() + "</h2>\n" +
"<h3>Om je date te beginnen wordt je verwacht bij de stand <q>" + randomStand.getName() + "</q>.</h3>\n" +
"<br>\n" +
"<h3>In bijlage kan je de QR code vinden voor je gratis drankje,</h3>\n" +
"<h3>gelieve deze code te laten scannen aan het standje <q>" + randomStand.getName() + "</q> om je drankje te krijgen.</h3>\n" +
"<br>\n" +
"<h4>Met vriendelijke groet het hele OnderDenToren team.</h4>\n" +
"<br>\n" +
"</div>\n" +
"</body>\n" +
"</html>";
}
private String mailFeedbackBody(Person person) {
return "<head> \n" +
"<style>\n" +
" h2,\n" +
" h3," +
" h4 {\n" +
" color:rgb(114, 28, 37)\n" +
" }\n" +
" button {\n" +
" background-color: #ff4d4d;\n" +
" color: #fff;\n" +
" border: none;\n" +
" border-radius: 8px;\n" +
" font-size: 15px;\n" +
" font-weight: bold;\n" +
" text-transform: uppercase;\n" +
" padding: 12px 20px;\n" +
" box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.3);\n" +
" transition: all 0.2s ease-in-out;\n" +
" } \n" +
" button:hover {\n" +
" background-color: #e60000;\n" +
" cursor: pointer;\n" +
" transform: scale(1.05);\n" +
" }\n" +
" div {\n" +
" text-align: center;\n" +
" background-color: rgb(248,186,189);\n" +
" }\n" +
"</style>\n" +
"</head>\n" +
"<body>\n" +
"<div>" +
"<br>\n" +
"<br>\n" +
"<h2>Beste " + person.getName() + "</h2> \n" +
"<h3>We zouden het zeer waarderen als u even de tijd zou willen nemen </h3> \n" +
"<h3>om ons te laten weten wat je van de date en het evenement vond.</h3>\n" +
"<br>\n" +
"<h3>Klik op de knop hieronder om ons feedback te kunnen geven op onze officiële site:</h3>\n" +
"<a href=https://hartverlorenonderdentoren.onrender.com/feedback/" + person.getId() + ">\n" +
"<button>Feedback</button>\n" +
"</a>\n" +
"<h4>Met vriendelijke groet het hele OnderDenToren team.</h4>" +
"<br>\n" +
"</div>\n" +
"</body>\n" +
"</html>";
}
@GetMapping(value = {"/confirmMatchDeny/{id}/{matchedPersonId}"})
public String confirmMatchDeny(@PathVariable Integer id,
@PathVariable Integer matchedPersonId) {
Optional<Match> matchOptional = matchRepository.findById(id);
if (matchOptional.isPresent()) {
Match match = matchOptional.get();
match.setConfirmationCount(-1);
matchRepository.save(match);
try {
Optional<Person> person1 = personRepository.findById(matchedPersonId);
if (person1.isPresent()) {
String cancellationMessage1 = mailAnnulationBody(person1.get());
email(person1.get(), "Match geannuleerd", cancellationMessage1, false);
}
} catch (MessagingException | IOException | WriterException e) {
throw new RuntimeException(e);
}
}
return "redirect:/index";
}
private String mailAnnulationBody(Person person) {
return "<head> \n" +
"<style>\n" +
" h2,\n" +
" h3," +
" h4 {\n" +
" color:rgb(114, 28, 37)\n" +
" }\n" +
" button {\n" +
" background-color: #ff4d4d;\n" +
" color: #fff;\n" +
" border: none;\n" +
" border-radius: 8px;\n" +
" font-size: 15px;\n" +
" font-weight: bold;\n" +
" text-transform: uppercase;\n" +
" padding: 12px 20px;\n" +
" box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.3);\n" +
" transition: all 0.2s ease-in-out;\n" +
" } \n" +
" button:hover {\n" +
" background-color: #e60000;\n" +
" cursor: pointer;\n" +
" transform: scale(1.05);\n" +
" }\n" +
" div {\n" +
" text-align: center;\n" +
" background-color: rgb(248,186,189);\n" +
" }\n" +
"</style>\n" +
"</head>\n" +
"<body>\n" +
"<div>" +
"<br>\n" +
"<br>\n" +
"<h2>Beste " + person.getName() + "</h2> \n" +
"<br>\n" +
"<h3>Het spijt ons om u mee te delen dat uw match heeft afgezegd,</h3>\n" +
"<h3>wij wensen u nog veel succes verder.</h3>\n" +
"<br>" +
"<h4>Met vriendelijke groet het hele OnderDenToren team.</h4>" +
"<br>\n" +
"</div>\n" +
"</body>\n" +
"</html>";
}
@GetMapping({"/matchmaker/overviewPersonWithoutMatch"})
public String overviewPeople(Model model, @RequestParam(required = false) String name, @RequestParam(required = false) String gender, @RequestParam(required = false) Integer minAge, @RequestParam(required = false) Integer maxAge, @RequestParam(required = false) Integer maxPersonAmount) {
if (maxPersonAmount == null) {
maxPersonAmount = 25;
}
if (minAge == null){
minAge = 0;
}
else {
model.addAttribute("minAge", minAge);
}
if (maxAge == null){
maxAge = 5000;
}
else {
model.addAttribute("maxAge", maxAge);
}
if (name != null){
model.addAttribute("name", name);
}
if (gender != null){
model.addAttribute("gender", gender);
}
LocalDate minBirthdate1 = LocalDate.now().minusYears(maxAge);
LocalDate maxBirthdate2 = LocalDate.now().minusYears(minAge );
Optional<Event> activeEvent = eventRepository.findByActive();
if (activeEvent.isPresent()) {
final Iterable<Person> people = personRepository.findAllByEventAndMatched(activeEvent.get(), false);
model.addAttribute("people", people);
}
final Iterable<Person> personList = personRepository.findByFilter(name, gender, minBirthdate1, maxBirthdate2);
model.addAttribute("personList", personList);
model.addAttribute("today", LocalDate.now());
model.addAttribute("maxPersonAmount", maxPersonAmount);
model.addAttribute("genders", genderRepository.findAll());
logger.info("name " + name);
logger.info("gender " + gender);
logger.info("minAge " + minAge);
logger.info("maxAge " + maxAge);
return "matchmaker/overviewPersonWithoutMatch";
}
@PostMapping("/matchmaker/overviewPersonWithoutMatch")
public String findPotentialMatches(Integer personChosen) {
return "redirect:/matchmaker/algorithm/" + personChosen;
}
public void email(Person person, String subject, String body, Boolean attachment) throws MessagingException, IOException, WriterException {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(senderEmail);
helper.setTo(person.getEmail());
helper.setSubject(subject);
helper.setText(body, true);
if (attachment) {
String url = "https://hartverlorenonderdentoren.onrender.com/qrCodeCheck/" + person.getId();
BufferedImage image = QRCodeGenerator.generateQRCodeImage(url, 250, 250);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", outputStream);
outputStream.flush();
byte[] imageInByte = outputStream.toByteArray();
ByteArrayDataSource imageAttachment = new ByteArrayDataSource(imageInByte, "application/x-any");
outputStream.close();
helper.addAttachment("QRCode.png", imageAttachment);
}
javaMailSender.send(message);
logger.info("Mail has been send!");
}
}
| Jitse2003/Team3-HartVerlorenOnderDenToren-main | src/main/java/be/thomasmore/hartverlorenonderdentoren/controllers/MatchesController.java | 5,922 | //hartverlorenonderdentoren.onrender.com/qrCodeCheck/" + person.getId(); | line_comment | nl | package be.thomasmore.hartverlorenonderdentoren.controllers;
import be.thomasmore.hartverlorenonderdentoren.QR.QRCodeGenerator;
import be.thomasmore.hartverlorenonderdentoren.model.Event;
import be.thomasmore.hartverlorenonderdentoren.model.Match;
import be.thomasmore.hartverlorenonderdentoren.model.Person;
import be.thomasmore.hartverlorenonderdentoren.model.RecommendedMatch;
import be.thomasmore.hartverlorenonderdentoren.model.Stand;
import be.thomasmore.hartverlorenonderdentoren.repositories.*;
import com.google.zxing.WriterException;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import jakarta.mail.util.ByteArrayDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
@Configuration
@EnableScheduling
@Controller
public class MatchesController {
private final Logger logger = LoggerFactory.getLogger(MatchesController.class);
@Autowired
private PersonRepository personRepository;
@Autowired
private RecommendedMatchRepository recommendedMatchRepository;
@Autowired
private MatchRepository matchRepository;
@Autowired
private EventRepository eventRepository;
@Autowired
private StandRepository standRepository;
@Autowired
private GenderRepository genderRepository;
@Autowired
private JavaMailSender javaMailSender;
@Value("${spring.mail.username}")
private String senderEmail;
@GetMapping({"/matchmaker/matchesOverview/{id}"})
public String matchesOverview(Model model, @PathVariable String id) {
Optional<Person> personInDb = personRepository.findById(Integer.valueOf(id));
if (personInDb.isPresent()) {
List<RecommendedMatch> personMatches = recommendedMatchRepository.findAllByPerson1(personInDb.get());
RecommendedMatch firstMatch = personMatches.get(0);
personMatches.remove(0);
for (RecommendedMatch p : personMatches) {
logger.info("match: " + p.getPerson2().getName());
}
int sizeMatches = personMatches.size();
logger.info("amount of matches: " + sizeMatches);
model.addAttribute("person1", personInDb.get());
model.addAttribute("firstMatch", firstMatch);
model.addAttribute("personMatches", personMatches);
model.addAttribute("sizeMatches", sizeMatches);
}
return "matchmaker/matchesOverview";
}
@GetMapping("/matchmaker/makeMatch/{personId1}/{personId2}")
public String addMatch(Model model,
@PathVariable String personId1,
@PathVariable String personId2) {
Optional<Person> person1 = personRepository.findById(Integer.valueOf(personId1));
Optional<Person> person2 = personRepository.findById(Integer.valueOf(personId2));
if (person1.isPresent() && person2.isPresent()) {
logger.info("match: " + person1.get().getName() + " and " + person2.get().getName());
model.addAttribute("person1", person1.get());
model.addAttribute("person2", person2.get());
model.addAttribute("today", LocalDate.now());
}
return "matchmaker/makeMatch";
}
@PostMapping("/matchmaker/makeMatch/{personId1}/{personId2}")
public String sendEmail(@PathVariable String personId1,
@PathVariable String personId2) throws MessagingException, IOException, WriterException {
Optional<Person> person1 = personRepository.findById(Integer.valueOf(personId1));
Optional<Person> person2 = personRepository.findById(Integer.valueOf(personId2));
if (person1.isPresent() && person2.isPresent() && eventRepository.findByActive().isPresent()) {
logger.info("match: " + person1.get().getName() + " and " + person2.get().getName());
Match match = new Match(person1.get(), person2.get(), false, LocalTime.now(), eventRepository.findByActive().get());
match.getPerson1().setMatched(true);
match.getPerson2().setMatched(true);
matchRepository.save(match);
String bodyConfirm1 = mailConfirmBody(personId2, person1.get());
String bodyConfirm2 = mailConfirmBody(personId1, person2.get());
email(person1.get(), "Uw match is gevonden!", bodyConfirm1, false);
email(person2.get(), "Uw match is gevonden!", bodyConfirm2, false);
}
return "redirect:/index";
}
private String mailConfirmBody(@PathVariable String personId, Person person) {
return "<html> \n" +
"<head> \n" +
"<style>\n" +
"h2," +
"h3," +
"h4 {\n" +
" color:rgb(114, 28, 37)\n" +
"}" +
"button {\n" +
" background-color: #ff4d4d;\n" +
" color: #fff;\n" +
" border: none;\n" +
" border-radius: 8px;\n" +
" font-size: 15px;\n" +
" font-weight: bold;\n" +
" text-transform: uppercase;\n" +
" padding: 12px 20px;\n" +
" box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.3);\n" +
" transition: all 0.2s ease-in-out;\n" +
"} \n" +
"button:hover {\n" +
" background-color: #e60000;\n" +
" cursor: pointer;\n" +
" transform: scale(1.05);\n" +
"}\n" +
" div {\n" +
" text-align: center;\n" +
" background-color: rgb(248,186,189);\n" +
" }\n" +
"</style>\n" +
"</head>\n" +
"<body>\n" +
"<div>\n" +
"<br>\n" +
"<br>\n" +
"<h2>Beste " + person.getName() + "</h2> \n" +
"<h3>We hebben je perfecte match gevonden!</h3> \n" +
"<br>\n" +
"<h3>Klik op onderstaande knop om je match te accepteren op onze officiële website:</h3>\n" +
"<a href=https://hartverlorenonderdentoren.onrender.com/confirmMatch/" + personId + ">\n" +
"<button>Jouw match</button>\n" +
"</a>\n" +
"<h4>Met vriendelijke groet het hele OnderDenToren team.</h4>" +
"<br>\n" +
"</div>\n" +
"</body>\n" +
"</html>";
}
@GetMapping({"/confirmMatch/{personId}"})
public String confirmMatch(Model model, @PathVariable Integer personId) {
Optional<Match> match = matchRepository.findMatchByPerson1_Id(personId);
if (match.isEmpty()) {
match = matchRepository.findMatchByPerson2_Id(personId);
}
if (match.isPresent()) {
Optional<Person> matchedPerson = personRepository.findById(personId);
matchedPerson.ifPresent(person -> model.addAttribute("matchedPerson", person));
}
model.addAttribute("match", match);
return "confirmMatch";
}
@GetMapping(value = {"/confirmMatchAccept/{id}"})
public String confirmMatchAccept(@PathVariable Integer id) {
Optional<Match> matchOptional = matchRepository.findById(id);
int randomStandNumber = (int) Math.round(1 + (Math.random() * (standRepository.count() - 1)));
if (matchOptional.isPresent()) {
Match match = matchOptional.get();
if (match.getConfirmationCount() < 0.5) {
match.setConfirmationCount(0.5);
logger.info(Double.toString(match.getConfirmationCount()));
} else if (match.getConfirmationCount() == 0.5) {
match.setConfirmationCount(1);
match.setConfirmed(true);
logger.info(Boolean.toString(match.isConfirmed()));
Person person1 = matchOptional.get().getPerson1();
Person person2 = matchOptional.get().getPerson2();
try {
Optional<Stand> randomStand = standRepository.findById(randomStandNumber);
if (randomStand.isPresent()) {
logger.info("random stand : " + randomStand.get().getName());
String bodyTextQRCode1 = mailQRBody(person1, randomStand.get());
String bodyTextQRCode2 = mailQRBody(person2, randomStand.get());
email(matchOptional.get().getPerson1(), "Je match heeft geaccepteerd!", bodyTextQRCode1, true);
email(matchOptional.get().getPerson2(), "Je match heeft geaccepteerd!", bodyTextQRCode2, true);
}
//send feedback mail
String bodyFeedback1 = mailFeedbackBody(person1);
String bodyFeedback2 = mailFeedbackBody(person2);
TimerTask task = new TimerTask() {
public void run() {
try {
email(person1, "Laat ons weten wat je van de date vond", bodyFeedback1, false);
email(person2, "Laat ons weten wat je van de date vond", bodyFeedback2, false);
} catch (MessagingException | IOException | WriterException e) {
throw new RuntimeException(e);
}
}
};
Timer timer = new Timer("Timer");
long delay = 60000;
timer.schedule(task, delay);
} catch (MessagingException | WriterException | IOException e) {
throw new RuntimeException(e);
}
}
}
matchOptional.ifPresent(match -> matchRepository.save(match));
return "redirect:/index";
}
private String mailQRBody(Person person, Stand randomStand) {
return "<html>\n" +
"<head>\n" +
"<style>\n" +
"h2,\n" +
"h3,\n" +
"h4 {\n" +
" color:rgb(114, 28, 37)\n" +
"}\n" +
"div {\n" +
" text-align: center;\n" +
" background-color: rgb(248,186,189);\n" +
"}\n" +
"</style>\n" +
"</head>\n" +
"<body>\n" +
"<div>\n" +
"<br>\n" +
"<br>\n" +
"<h2>Beste " + person.getName() + "</h2>\n" +
"<h3>Om je date te beginnen wordt je verwacht bij de stand <q>" + randomStand.getName() + "</q>.</h3>\n" +
"<br>\n" +
"<h3>In bijlage kan je de QR code vinden voor je gratis drankje,</h3>\n" +
"<h3>gelieve deze code te laten scannen aan het standje <q>" + randomStand.getName() + "</q> om je drankje te krijgen.</h3>\n" +
"<br>\n" +
"<h4>Met vriendelijke groet het hele OnderDenToren team.</h4>\n" +
"<br>\n" +
"</div>\n" +
"</body>\n" +
"</html>";
}
private String mailFeedbackBody(Person person) {
return "<head> \n" +
"<style>\n" +
" h2,\n" +
" h3," +
" h4 {\n" +
" color:rgb(114, 28, 37)\n" +
" }\n" +
" button {\n" +
" background-color: #ff4d4d;\n" +
" color: #fff;\n" +
" border: none;\n" +
" border-radius: 8px;\n" +
" font-size: 15px;\n" +
" font-weight: bold;\n" +
" text-transform: uppercase;\n" +
" padding: 12px 20px;\n" +
" box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.3);\n" +
" transition: all 0.2s ease-in-out;\n" +
" } \n" +
" button:hover {\n" +
" background-color: #e60000;\n" +
" cursor: pointer;\n" +
" transform: scale(1.05);\n" +
" }\n" +
" div {\n" +
" text-align: center;\n" +
" background-color: rgb(248,186,189);\n" +
" }\n" +
"</style>\n" +
"</head>\n" +
"<body>\n" +
"<div>" +
"<br>\n" +
"<br>\n" +
"<h2>Beste " + person.getName() + "</h2> \n" +
"<h3>We zouden het zeer waarderen als u even de tijd zou willen nemen </h3> \n" +
"<h3>om ons te laten weten wat je van de date en het evenement vond.</h3>\n" +
"<br>\n" +
"<h3>Klik op de knop hieronder om ons feedback te kunnen geven op onze officiële site:</h3>\n" +
"<a href=https://hartverlorenonderdentoren.onrender.com/feedback/" + person.getId() + ">\n" +
"<button>Feedback</button>\n" +
"</a>\n" +
"<h4>Met vriendelijke groet het hele OnderDenToren team.</h4>" +
"<br>\n" +
"</div>\n" +
"</body>\n" +
"</html>";
}
@GetMapping(value = {"/confirmMatchDeny/{id}/{matchedPersonId}"})
public String confirmMatchDeny(@PathVariable Integer id,
@PathVariable Integer matchedPersonId) {
Optional<Match> matchOptional = matchRepository.findById(id);
if (matchOptional.isPresent()) {
Match match = matchOptional.get();
match.setConfirmationCount(-1);
matchRepository.save(match);
try {
Optional<Person> person1 = personRepository.findById(matchedPersonId);
if (person1.isPresent()) {
String cancellationMessage1 = mailAnnulationBody(person1.get());
email(person1.get(), "Match geannuleerd", cancellationMessage1, false);
}
} catch (MessagingException | IOException | WriterException e) {
throw new RuntimeException(e);
}
}
return "redirect:/index";
}
private String mailAnnulationBody(Person person) {
return "<head> \n" +
"<style>\n" +
" h2,\n" +
" h3," +
" h4 {\n" +
" color:rgb(114, 28, 37)\n" +
" }\n" +
" button {\n" +
" background-color: #ff4d4d;\n" +
" color: #fff;\n" +
" border: none;\n" +
" border-radius: 8px;\n" +
" font-size: 15px;\n" +
" font-weight: bold;\n" +
" text-transform: uppercase;\n" +
" padding: 12px 20px;\n" +
" box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.3);\n" +
" transition: all 0.2s ease-in-out;\n" +
" } \n" +
" button:hover {\n" +
" background-color: #e60000;\n" +
" cursor: pointer;\n" +
" transform: scale(1.05);\n" +
" }\n" +
" div {\n" +
" text-align: center;\n" +
" background-color: rgb(248,186,189);\n" +
" }\n" +
"</style>\n" +
"</head>\n" +
"<body>\n" +
"<div>" +
"<br>\n" +
"<br>\n" +
"<h2>Beste " + person.getName() + "</h2> \n" +
"<br>\n" +
"<h3>Het spijt ons om u mee te delen dat uw match heeft afgezegd,</h3>\n" +
"<h3>wij wensen u nog veel succes verder.</h3>\n" +
"<br>" +
"<h4>Met vriendelijke groet het hele OnderDenToren team.</h4>" +
"<br>\n" +
"</div>\n" +
"</body>\n" +
"</html>";
}
@GetMapping({"/matchmaker/overviewPersonWithoutMatch"})
public String overviewPeople(Model model, @RequestParam(required = false) String name, @RequestParam(required = false) String gender, @RequestParam(required = false) Integer minAge, @RequestParam(required = false) Integer maxAge, @RequestParam(required = false) Integer maxPersonAmount) {
if (maxPersonAmount == null) {
maxPersonAmount = 25;
}
if (minAge == null){
minAge = 0;
}
else {
model.addAttribute("minAge", minAge);
}
if (maxAge == null){
maxAge = 5000;
}
else {
model.addAttribute("maxAge", maxAge);
}
if (name != null){
model.addAttribute("name", name);
}
if (gender != null){
model.addAttribute("gender", gender);
}
LocalDate minBirthdate1 = LocalDate.now().minusYears(maxAge);
LocalDate maxBirthdate2 = LocalDate.now().minusYears(minAge );
Optional<Event> activeEvent = eventRepository.findByActive();
if (activeEvent.isPresent()) {
final Iterable<Person> people = personRepository.findAllByEventAndMatched(activeEvent.get(), false);
model.addAttribute("people", people);
}
final Iterable<Person> personList = personRepository.findByFilter(name, gender, minBirthdate1, maxBirthdate2);
model.addAttribute("personList", personList);
model.addAttribute("today", LocalDate.now());
model.addAttribute("maxPersonAmount", maxPersonAmount);
model.addAttribute("genders", genderRepository.findAll());
logger.info("name " + name);
logger.info("gender " + gender);
logger.info("minAge " + minAge);
logger.info("maxAge " + maxAge);
return "matchmaker/overviewPersonWithoutMatch";
}
@PostMapping("/matchmaker/overviewPersonWithoutMatch")
public String findPotentialMatches(Integer personChosen) {
return "redirect:/matchmaker/algorithm/" + personChosen;
}
public void email(Person person, String subject, String body, Boolean attachment) throws MessagingException, IOException, WriterException {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(senderEmail);
helper.setTo(person.getEmail());
helper.setSubject(subject);
helper.setText(body, true);
if (attachment) {
String url = "https://hartverlorenonderdentoren.onrender.com/qrCodeCheck/" +<SUF>
BufferedImage image = QRCodeGenerator.generateQRCodeImage(url, 250, 250);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", outputStream);
outputStream.flush();
byte[] imageInByte = outputStream.toByteArray();
ByteArrayDataSource imageAttachment = new ByteArrayDataSource(imageInByte, "application/x-any");
outputStream.close();
helper.addAttachment("QRCode.png", imageAttachment);
}
javaMailSender.send(message);
logger.info("Mail has been send!");
}
}
|
164295_9 | package stocker.view;
import java.awt.*;
import stocker.model.*;
/**
*
* Die Klasse <code>FrameChartCandlePanel</code> erstellt zu einer Kerzenmenge
* eine Kerzendarstellung als JPanel in einem Chart.
*
* @author Joachim Otto
*/
public class FrameChartCandlePanel extends FrameChartContentPanel{
/**
* Das Panel wird mit der
* @param size Größe
* @param model deren Model ,
* @param annFrame dem Verweis auf das übergeordnete Chart
* @param prefer den Voreinstellungen
* initialisiert
*/
FrameChartCandlePanel(Dimension size, FrameChartModel model, FrameChart annFrame, StockerPreferences prefer){
super( size, model, annFrame, prefer);
}
/**
* Die Kerzen werden gezeichnet
*/
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
//Erst die Indikatoren sonst würden die BollingerBänder alles überdecken
paintAlarmAndIndicators(g);
//Über den CandleSet gehen und die einzelnen Abschnitte zeichen
int i=0;
for(Candle tmp : candles) {
drawCandleSlice(g, tmp, i);
i++;
}
//Erst der Content dann Scale, sonst sind die Offsets falsch
paintFixElements(g);
}
/**
* In einzelnen Abschnitten werden die jeweilige Kerze und in 5er-Schritten
* eine Beschriftung der x Achse gezeichnet.
* @param g das übergeordnete Graphic-Objekt
* @param candle die aktuelle Kerze
* @param pos die aktuelle Position in der Reihenfolge
*
*/
public void drawCandleSlice(Graphics g, Candle candle, int pos) {
/* Konstruktion einer Kerze
* Linie am opening und closing, Seitenlinien zwischen Opening und Closing
* Dochte von punkt nach oben(low) oder unten (high)
* Aber mit der Farbe (rot= op>clos) müssen die Argumente des Rechtecks belegt werden
* sonst könnte es negative höhen geben (funktioniert nicht)
* Insgesamt muss umgerechnet werden: z.B. closing :
* Höhe - unterer Offset + min = gedachte Nullinie (weit unter Fenster)
* closing = gedachte Nullinie - closing
* Slicebreite =((GesamtBreite - 2*Offset) / Kerzenzahl )
* Aktueller Offset = Offset + (akt. Kerzennummer *SliceBreite)
* Kerzenbreite = Slicebreite - 2 * Kerzenoffset
* X-Mitte (Dochtlinie) = Aktueller Offset + Kerzenoffset + 1/2 Kerzenbreite
*/
final int cBorder=5;
int sWidth = locWidth / candles.length; //Offset schon abgezogen
int cOffset = chartOffset + sWidth * pos;
int cWidth = sWidth - 2* cBorder;
int cMid = cOffset +cBorder + cWidth / 2;
//Kerze malen, annahme op<cols
Color boxColor=Color.GREEN;
int boxY2=coorFromPrice(candle.getOpening());
int boxY1=coorFromPrice(candle.getClosing());
//Annahme falsch
if (candle.getOpening()>candle.getClosing()) {
boxColor=Color.RED;
boxY2 = coorFromPrice(candle.getClosing());
boxY1 = coorFromPrice(candle.getOpening());
}
//Dochte
g.drawLine(cMid ,coorFromPrice(candle.getHigh()), cMid, boxY1);
g.drawLine(cMid ,coorFromPrice(candle.getLow()), cMid, boxY2);
//Candle und ihre Umrandung
g.setColor(boxColor);
g.fillRect(cOffset + cBorder, boxY1 , cWidth, boxY2-boxY1);
g.setColor(Color.BLACK);
g.drawRect( cOffset + cBorder, boxY1 , cWidth, boxY2-boxY1);
//Zwischenlinien
//notTODO Montagslinien rot wg. Wochenende? nein
g.setColor(Color.LIGHT_GRAY);
g.drawLine(cOffset, chartOffset, cOffset, chartOffset + locHeight);
paintScalX( g, pos, cOffset, sWidth);
}} | JoachimROtto/Stocker | src/stocker/view/FrameChartCandlePanel.java | 1,251 | //Kerze malen, annahme op<cols | line_comment | nl | package stocker.view;
import java.awt.*;
import stocker.model.*;
/**
*
* Die Klasse <code>FrameChartCandlePanel</code> erstellt zu einer Kerzenmenge
* eine Kerzendarstellung als JPanel in einem Chart.
*
* @author Joachim Otto
*/
public class FrameChartCandlePanel extends FrameChartContentPanel{
/**
* Das Panel wird mit der
* @param size Größe
* @param model deren Model ,
* @param annFrame dem Verweis auf das übergeordnete Chart
* @param prefer den Voreinstellungen
* initialisiert
*/
FrameChartCandlePanel(Dimension size, FrameChartModel model, FrameChart annFrame, StockerPreferences prefer){
super( size, model, annFrame, prefer);
}
/**
* Die Kerzen werden gezeichnet
*/
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
//Erst die Indikatoren sonst würden die BollingerBänder alles überdecken
paintAlarmAndIndicators(g);
//Über den CandleSet gehen und die einzelnen Abschnitte zeichen
int i=0;
for(Candle tmp : candles) {
drawCandleSlice(g, tmp, i);
i++;
}
//Erst der Content dann Scale, sonst sind die Offsets falsch
paintFixElements(g);
}
/**
* In einzelnen Abschnitten werden die jeweilige Kerze und in 5er-Schritten
* eine Beschriftung der x Achse gezeichnet.
* @param g das übergeordnete Graphic-Objekt
* @param candle die aktuelle Kerze
* @param pos die aktuelle Position in der Reihenfolge
*
*/
public void drawCandleSlice(Graphics g, Candle candle, int pos) {
/* Konstruktion einer Kerze
* Linie am opening und closing, Seitenlinien zwischen Opening und Closing
* Dochte von punkt nach oben(low) oder unten (high)
* Aber mit der Farbe (rot= op>clos) müssen die Argumente des Rechtecks belegt werden
* sonst könnte es negative höhen geben (funktioniert nicht)
* Insgesamt muss umgerechnet werden: z.B. closing :
* Höhe - unterer Offset + min = gedachte Nullinie (weit unter Fenster)
* closing = gedachte Nullinie - closing
* Slicebreite =((GesamtBreite - 2*Offset) / Kerzenzahl )
* Aktueller Offset = Offset + (akt. Kerzennummer *SliceBreite)
* Kerzenbreite = Slicebreite - 2 * Kerzenoffset
* X-Mitte (Dochtlinie) = Aktueller Offset + Kerzenoffset + 1/2 Kerzenbreite
*/
final int cBorder=5;
int sWidth = locWidth / candles.length; //Offset schon abgezogen
int cOffset = chartOffset + sWidth * pos;
int cWidth = sWidth - 2* cBorder;
int cMid = cOffset +cBorder + cWidth / 2;
//Kerze malen,<SUF>
Color boxColor=Color.GREEN;
int boxY2=coorFromPrice(candle.getOpening());
int boxY1=coorFromPrice(candle.getClosing());
//Annahme falsch
if (candle.getOpening()>candle.getClosing()) {
boxColor=Color.RED;
boxY2 = coorFromPrice(candle.getClosing());
boxY1 = coorFromPrice(candle.getOpening());
}
//Dochte
g.drawLine(cMid ,coorFromPrice(candle.getHigh()), cMid, boxY1);
g.drawLine(cMid ,coorFromPrice(candle.getLow()), cMid, boxY2);
//Candle und ihre Umrandung
g.setColor(boxColor);
g.fillRect(cOffset + cBorder, boxY1 , cWidth, boxY2-boxY1);
g.setColor(Color.BLACK);
g.drawRect( cOffset + cBorder, boxY1 , cWidth, boxY2-boxY1);
//Zwischenlinien
//notTODO Montagslinien rot wg. Wochenende? nein
g.setColor(Color.LIGHT_GRAY);
g.drawLine(cOffset, chartOffset, cOffset, chartOffset + locHeight);
paintScalX( g, pos, cOffset, sWidth);
}} |
1652_4 | package be.pxl.h4.exoef1;
/*Extra oefening 1
*
* Geef 2 getallen in via het toetsenbord. Maak een afdruk als volgt:
* het kleinste getal is ...
* Het kwadraat van het kleinste getal is ...*/
import java.util.Scanner;
public class H4ExOef1 {
public static void main(String[] args) {
//Scanner en variabelen aanmaken
Scanner keyboard = new Scanner(System.in);
int a, b, kleinste_getal, kwadraat_kleinste_getal;
//Input vragen van de gebruiker
System.out.println("Getal a: ");
a = keyboard.nextInt();
System.out.println("Getal b: ");
b = keyboard.nextInt();
//Bepalen welk getal het kleinste is
if (a > b) {
kleinste_getal = b;
} else {
kleinste_getal = a;
}
//Kwadraat berekenen en kleinste getal en zijn kwadraat uitrekenen
kwadraat_kleinste_getal = kleinste_getal * kleinste_getal; // Opgelost zonder de math klasse - normaal wordt die voor deze berekening gebruikt.
System.out.println("Het kleinste getal is " + kleinste_getal);
System.out.println("Het kwadraat van het kleinste getal is " + kwadraat_kleinste_getal);
keyboard.close();
}
}
| JoachimVeulemans/PXL-DIGITAL | PXL_DIGITAL_JAAR_1/Programming Basics/Oplossingen Oefeningen/H4/exoef1/H4ExOef1.java | 421 | //Kwadraat berekenen en kleinste getal en zijn kwadraat uitrekenen | line_comment | nl | package be.pxl.h4.exoef1;
/*Extra oefening 1
*
* Geef 2 getallen in via het toetsenbord. Maak een afdruk als volgt:
* het kleinste getal is ...
* Het kwadraat van het kleinste getal is ...*/
import java.util.Scanner;
public class H4ExOef1 {
public static void main(String[] args) {
//Scanner en variabelen aanmaken
Scanner keyboard = new Scanner(System.in);
int a, b, kleinste_getal, kwadraat_kleinste_getal;
//Input vragen van de gebruiker
System.out.println("Getal a: ");
a = keyboard.nextInt();
System.out.println("Getal b: ");
b = keyboard.nextInt();
//Bepalen welk getal het kleinste is
if (a > b) {
kleinste_getal = b;
} else {
kleinste_getal = a;
}
//Kwadraat berekenen<SUF>
kwadraat_kleinste_getal = kleinste_getal * kleinste_getal; // Opgelost zonder de math klasse - normaal wordt die voor deze berekening gebruikt.
System.out.println("Het kleinste getal is " + kleinste_getal);
System.out.println("Het kwadraat van het kleinste getal is " + kwadraat_kleinste_getal);
keyboard.close();
}
}
|
150998_3 | // Importeer de Scanner klasse
import java.util.Scanner;
public class DayOfWeek {
/**
* @param args
*/
public static void main(String[] args) {
// Instantieer een nieuw Scanner object
Scanner input = new Scanner(System.in);
// Vraag gebruiker het jaar, de maand en de dag van de maand in te voeren: jaar, maand en dag.
System.out.print("Voer het jaartal in, bijvoorbeeld '1978': ");
int jaar = input.nextInt();
System.out.print("Voer de maand in, 1 voor januari, 4 voor april, etc.: ");
int maand = input.nextInt();
System.out.print("Voer de dag van de maand in (1-31): ");
int dag = input.nextInt();
// Bereken q: = dag
int q = dag;
// Bereken m: = maand als de maand niet januari of februari is, anders m = maand+12 en jaar = jaar-1
int m = maand;
if (m < 3) {
m = m + 12;
jaar = jaar - 1;
}
// bereken j, de eeuw = jaar / 100
int j = jaar / 100;
// bereken k, het jaar van de eeuw: = jaar % 100
int k = jaar % 100;
// bereken h, de numerieke waarde van de dag van de week: h = (q + (26*(m + 1))/10 + k + k/4 + j/4 + 5*j)%7
int h = (q + (26 * (m + 1)) / 10 + k + (k / 4) + (j / 4) + (5 * j)) % 7;
// Geef de naam van de dag met een switch statement
switch (h) {
case 0: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een zaterdag."); break;
case 1: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een zondag."); break;
case 2: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een maandag."); break;
case 3: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een dinsdag."); break;
case 4: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een woensdag."); break;
case 5: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een donderdag."); break;
case 6: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een vrijdag."); break;
}
}
}
| JobSarneel/java | h1-3/DayOfWeek.java | 794 | // Vraag gebruiker het jaar, de maand en de dag van de maand in te voeren: jaar, maand en dag. | line_comment | nl | // Importeer de Scanner klasse
import java.util.Scanner;
public class DayOfWeek {
/**
* @param args
*/
public static void main(String[] args) {
// Instantieer een nieuw Scanner object
Scanner input = new Scanner(System.in);
// Vraag gebruiker<SUF>
System.out.print("Voer het jaartal in, bijvoorbeeld '1978': ");
int jaar = input.nextInt();
System.out.print("Voer de maand in, 1 voor januari, 4 voor april, etc.: ");
int maand = input.nextInt();
System.out.print("Voer de dag van de maand in (1-31): ");
int dag = input.nextInt();
// Bereken q: = dag
int q = dag;
// Bereken m: = maand als de maand niet januari of februari is, anders m = maand+12 en jaar = jaar-1
int m = maand;
if (m < 3) {
m = m + 12;
jaar = jaar - 1;
}
// bereken j, de eeuw = jaar / 100
int j = jaar / 100;
// bereken k, het jaar van de eeuw: = jaar % 100
int k = jaar % 100;
// bereken h, de numerieke waarde van de dag van de week: h = (q + (26*(m + 1))/10 + k + k/4 + j/4 + 5*j)%7
int h = (q + (26 * (m + 1)) / 10 + k + (k / 4) + (j / 4) + (5 * j)) % 7;
// Geef de naam van de dag met een switch statement
switch (h) {
case 0: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een zaterdag."); break;
case 1: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een zondag."); break;
case 2: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een maandag."); break;
case 3: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een dinsdag."); break;
case 4: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een woensdag."); break;
case 5: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een donderdag."); break;
case 6: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een vrijdag."); break;
}
}
}
|
18986_3 | package com.ictm2n2.resources;
public class Backtracking {
private Configuratie config = new Configuratie();
private double kosten = 0;
private Componenten componenten = new Componenten();
public Configuratie maakConfiguratie(double percentage) {
/*
* Kijken of er al componenten in de huidige configuratie zitten. Als er niks in
* zit worden er 1 van elke soort in gezet.
*/
if (config.getComponenten().isEmpty()) {
config.voegToeComponent(componenten.firewalls.get(0));
config.voegToeComponent(componenten.webServers.get(0));
config.voegToeComponent(componenten.dbServers.get(0));
} else {
if (berekenComponent(Webserver.class, config) < berekenComponent(DatabaseServer.class, config)) {
voegVolgendeToe(Webserver.class);
} else {
voegVolgendeToe(DatabaseServer.class);
}
}
if (!isVoldaan(percentage, config)) {
maakConfiguratie(percentage);
} else {
kosten = berekenTotalePrijs(config);
config.setComponenten(maakGoedkoper(percentage, config).getComponenten());
}
config.print();
return this.config;
}
public double berekenTotaleBeschikbaarheid(Configuratie configuratie) {
/* Loop over de componenten en bereken totale beschikbaarheid */
return (berekenComponent(Firewall.class, configuratie) / 100)
* (berekenComponent(Webserver.class, configuratie) / 100)
* (berekenComponent(Loadbalancer.class, configuratie) / 100)
* berekenComponent(DatabaseServer.class, configuratie);
}
// public Configuratie maakConfiguratie(double percentage) {
// /*
// * Kijken of er al componenten in de huidige configuratie zitten. Als er niks
// in
// * zit worden er 1 van elke soort in gezet.
// */
// if (c.getComponenten().isEmpty()) {
// c.voegToeComponent(componenten.firewalls.get(0));
// c.voegToeComponent(componenten.loadbalancers.get(0));
// c.voegToeComponent(componenten.webServers.get(0));
// c.voegToeComponent(componenten.dbServers.get(0));
// } else {
// if (berekenComponent(Webserver.class, c) <
// berekenComponent(DatabaseServer.class, c)) {
// voegVolgendeToe(Webserver.class);
// } else {
// voegVolgendeToe(DatabaseServer.class);
// }
// }
// if (isVoldaan(percentage, c)) {
// kosten = berekenTotalePrijs(c);
// c.setComponenten(maakGoedkoper(percentage, c).getComponenten());
// // System.out.println("Voldaan" + c.berekenTotalePrijsDouble());
// } else if (!isVoldaan(percentage, c)) {
// return maakConfiguratie(percentage);
// }
// System.out.println("Returned: " + c.berekenTotalePrijsDouble() + " - " +
// kosten);
// return c;
// }
private Configuratie maakGoedkoper(double percentage, Configuratie configuratie) {
boolean wsDoorlopen = false;
boolean dbDoorlopen = false;
while (!wsDoorlopen && !dbDoorlopen) {
for (int i = 0; i < componenten.webServers.size() - 1; i++) {
Webserver goedkoopsteWs = componenten.webServers.get(0);
Webserver duurdereWs = componenten.webServers.get(componenten.webServers.indexOf(goedkoopsteWs) + 1);
for (int j = 0; j < hoeveelVan(goedkoopsteWs, configuratie); j++) {
configuratie.vervangComponent(configuratie.getComponenten().lastIndexOf(goedkoopsteWs), duurdereWs);
}
// kijken of het goedkoper is en of het nog wel voldaan is aan het percentage
// als dit niet zo is dan gaan we eerst weer een goedkope webserver toevoegen
// als dat nog niet werkt gaan we helemaal terug naar de vorige stap en eindigt
// de loop
for (int j = 0; j < hoeveelVan(duurdereWs, configuratie); j++) {
if (kosten < berekenTotalePrijs(configuratie)) {
configuratie.verwijderComponent(goedkoopsteWs);
} else if (isVoldaan(percentage, configuratie)) {
kosten = berekenTotalePrijsDouble(configuratie);
}
if (!isVoldaan(percentage, configuratie)) {
configuratie.voegToeComponent(goedkoopsteWs);
} else {
break;
}
}
}
wsDoorlopen = true;
for (int i = 0; i < componenten.dbServers.size() - 1; i++) {
DatabaseServer goedkoopsteDb = componenten.dbServers.get(0);
DatabaseServer duurdereDb = componenten.dbServers.get(componenten.dbServers.indexOf(goedkoopsteDb) + 1);
for (int j = 0; j < hoeveelVan(goedkoopsteDb, configuratie); j++) {
configuratie.vervangComponent(configuratie.getComponenten().lastIndexOf(goedkoopsteDb), duurdereDb);
}
for (int j = 0; j < hoeveelVan(duurdereDb, configuratie); j++) {
if (kosten < berekenTotalePrijsDouble(configuratie)) {
configuratie.verwijderComponent(duurdereDb);
} else {
kosten = berekenTotalePrijsDouble(configuratie);
}
if (!isVoldaan(percentage, configuratie)) {
configuratie.voegToeComponent(goedkoopsteDb);
} else {
break;
}
}
}
dbDoorlopen = true;
}
return configuratie;
}
private boolean isVoldaan(double percentage, Configuratie configuratie) {
double b = (berekenComponent(Firewall.class, configuratie) / 100)
* (berekenComponent(Loadbalancer.class, configuratie) / 100)
* (berekenComponent(Webserver.class, configuratie) / 100)
* berekenComponent(DatabaseServer.class, configuratie);
System.out.println(String.format("%s >= %s ---- %s", b, percentage, b >= percentage));
// Om te kijken of de percentage al behaald is in de configuratie.
// System.out.println("1");
// System.out.println(berekenComponent(Firewall.class, configuratie));
// System.out.println("2");
// System.out.println(berekenComponent(Webserver.class, configuratie));
// System.out.println("3");
// System.out.println(berekenComponent(DatabaseServer.class, configuratie));
// System.out.println((berekenComponent(Firewall.class, configuratie)/100) *
// (berekenComponent(Webserver.class, configuratie)/100) *
// (berekenComponent(DatabaseServer.class, configuratie)));
// System.out.println(((berekenComponent(Firewall.class, configuratie) / 100) *
// (berekenComponent(Webserver.class, configuratie) / 100) *
// (berekenComponent(DatabaseServer.class, configuratie) / 100) * 100));
return ((berekenComponent(Firewall.class, configuratie) / 100)
* (berekenComponent(Webserver.class, configuratie) / 100)
* (berekenComponent(DatabaseServer.class, configuratie) / 100) * 100) >= percentage;
}
private void voegVolgendeToe(Class<?> type) {
// Switchen tussen Webserver en Database server.
if (type.isAssignableFrom(Webserver.class)) {
config.voegToeComponent(componenten.webServers.get(0));
} else if (type.isAssignableFrom(DatabaseServer.class)) {
config.voegToeComponent(componenten.dbServers.get(0));
}
}
public int hoeveelVan(Component component, Configuratie configuratie) {
// Bereken hoeveel er van een component al in de configuratie zitten.
int counter = 0;
for (Component c : configuratie.getComponenten()) {
if (c.equals(component)) {
counter++;
}
}
return counter;
}
public double berekenComponent(Class<?> type, Configuratie configuratie) {
double beschikbaarheid = 1;
// Voor elk component wordt gekeken wat voor component het is. Daarna wordt de
// beschikbaarheid berekend.
for (Component c : configuratie.getComponenten()) {
if (type.isAssignableFrom(c.getClass())) {
beschikbaarheid *= (1 - (c.getBeschikbaarheid() / 100));
}
}
return (1 - beschikbaarheid) * 100;
}
private int berekenTotalePrijs(Configuratie configuratie) {
int totalePrijs = 0;
try {
for (Component component : configuratie.getComponenten()) {
totalePrijs += component.getPrijs();
}
} catch (NullPointerException npe) {
System.out.println(npe);
}
return totalePrijs;
}
public double berekenTotalePrijsDouble(Configuratie configuratie) {
double totalePrijs = 0;
try {
for (Component component : configuratie.getComponenten()) {
totalePrijs += component.getPrijs();
}
} catch (NullPointerException npe) {
System.out.println(npe);
}
return totalePrijs;
}
}
| Joehoel/kbs | src/com/ictm2n2/resources/Backtracking.java | 2,756 | // * Kijken of er al componenten in de huidige configuratie zitten. Als er niks | line_comment | nl | package com.ictm2n2.resources;
public class Backtracking {
private Configuratie config = new Configuratie();
private double kosten = 0;
private Componenten componenten = new Componenten();
public Configuratie maakConfiguratie(double percentage) {
/*
* Kijken of er al componenten in de huidige configuratie zitten. Als er niks in
* zit worden er 1 van elke soort in gezet.
*/
if (config.getComponenten().isEmpty()) {
config.voegToeComponent(componenten.firewalls.get(0));
config.voegToeComponent(componenten.webServers.get(0));
config.voegToeComponent(componenten.dbServers.get(0));
} else {
if (berekenComponent(Webserver.class, config) < berekenComponent(DatabaseServer.class, config)) {
voegVolgendeToe(Webserver.class);
} else {
voegVolgendeToe(DatabaseServer.class);
}
}
if (!isVoldaan(percentage, config)) {
maakConfiguratie(percentage);
} else {
kosten = berekenTotalePrijs(config);
config.setComponenten(maakGoedkoper(percentage, config).getComponenten());
}
config.print();
return this.config;
}
public double berekenTotaleBeschikbaarheid(Configuratie configuratie) {
/* Loop over de componenten en bereken totale beschikbaarheid */
return (berekenComponent(Firewall.class, configuratie) / 100)
* (berekenComponent(Webserver.class, configuratie) / 100)
* (berekenComponent(Loadbalancer.class, configuratie) / 100)
* berekenComponent(DatabaseServer.class, configuratie);
}
// public Configuratie maakConfiguratie(double percentage) {
// /*
// * Kijken of<SUF>
// in
// * zit worden er 1 van elke soort in gezet.
// */
// if (c.getComponenten().isEmpty()) {
// c.voegToeComponent(componenten.firewalls.get(0));
// c.voegToeComponent(componenten.loadbalancers.get(0));
// c.voegToeComponent(componenten.webServers.get(0));
// c.voegToeComponent(componenten.dbServers.get(0));
// } else {
// if (berekenComponent(Webserver.class, c) <
// berekenComponent(DatabaseServer.class, c)) {
// voegVolgendeToe(Webserver.class);
// } else {
// voegVolgendeToe(DatabaseServer.class);
// }
// }
// if (isVoldaan(percentage, c)) {
// kosten = berekenTotalePrijs(c);
// c.setComponenten(maakGoedkoper(percentage, c).getComponenten());
// // System.out.println("Voldaan" + c.berekenTotalePrijsDouble());
// } else if (!isVoldaan(percentage, c)) {
// return maakConfiguratie(percentage);
// }
// System.out.println("Returned: " + c.berekenTotalePrijsDouble() + " - " +
// kosten);
// return c;
// }
private Configuratie maakGoedkoper(double percentage, Configuratie configuratie) {
boolean wsDoorlopen = false;
boolean dbDoorlopen = false;
while (!wsDoorlopen && !dbDoorlopen) {
for (int i = 0; i < componenten.webServers.size() - 1; i++) {
Webserver goedkoopsteWs = componenten.webServers.get(0);
Webserver duurdereWs = componenten.webServers.get(componenten.webServers.indexOf(goedkoopsteWs) + 1);
for (int j = 0; j < hoeveelVan(goedkoopsteWs, configuratie); j++) {
configuratie.vervangComponent(configuratie.getComponenten().lastIndexOf(goedkoopsteWs), duurdereWs);
}
// kijken of het goedkoper is en of het nog wel voldaan is aan het percentage
// als dit niet zo is dan gaan we eerst weer een goedkope webserver toevoegen
// als dat nog niet werkt gaan we helemaal terug naar de vorige stap en eindigt
// de loop
for (int j = 0; j < hoeveelVan(duurdereWs, configuratie); j++) {
if (kosten < berekenTotalePrijs(configuratie)) {
configuratie.verwijderComponent(goedkoopsteWs);
} else if (isVoldaan(percentage, configuratie)) {
kosten = berekenTotalePrijsDouble(configuratie);
}
if (!isVoldaan(percentage, configuratie)) {
configuratie.voegToeComponent(goedkoopsteWs);
} else {
break;
}
}
}
wsDoorlopen = true;
for (int i = 0; i < componenten.dbServers.size() - 1; i++) {
DatabaseServer goedkoopsteDb = componenten.dbServers.get(0);
DatabaseServer duurdereDb = componenten.dbServers.get(componenten.dbServers.indexOf(goedkoopsteDb) + 1);
for (int j = 0; j < hoeveelVan(goedkoopsteDb, configuratie); j++) {
configuratie.vervangComponent(configuratie.getComponenten().lastIndexOf(goedkoopsteDb), duurdereDb);
}
for (int j = 0; j < hoeveelVan(duurdereDb, configuratie); j++) {
if (kosten < berekenTotalePrijsDouble(configuratie)) {
configuratie.verwijderComponent(duurdereDb);
} else {
kosten = berekenTotalePrijsDouble(configuratie);
}
if (!isVoldaan(percentage, configuratie)) {
configuratie.voegToeComponent(goedkoopsteDb);
} else {
break;
}
}
}
dbDoorlopen = true;
}
return configuratie;
}
private boolean isVoldaan(double percentage, Configuratie configuratie) {
double b = (berekenComponent(Firewall.class, configuratie) / 100)
* (berekenComponent(Loadbalancer.class, configuratie) / 100)
* (berekenComponent(Webserver.class, configuratie) / 100)
* berekenComponent(DatabaseServer.class, configuratie);
System.out.println(String.format("%s >= %s ---- %s", b, percentage, b >= percentage));
// Om te kijken of de percentage al behaald is in de configuratie.
// System.out.println("1");
// System.out.println(berekenComponent(Firewall.class, configuratie));
// System.out.println("2");
// System.out.println(berekenComponent(Webserver.class, configuratie));
// System.out.println("3");
// System.out.println(berekenComponent(DatabaseServer.class, configuratie));
// System.out.println((berekenComponent(Firewall.class, configuratie)/100) *
// (berekenComponent(Webserver.class, configuratie)/100) *
// (berekenComponent(DatabaseServer.class, configuratie)));
// System.out.println(((berekenComponent(Firewall.class, configuratie) / 100) *
// (berekenComponent(Webserver.class, configuratie) / 100) *
// (berekenComponent(DatabaseServer.class, configuratie) / 100) * 100));
return ((berekenComponent(Firewall.class, configuratie) / 100)
* (berekenComponent(Webserver.class, configuratie) / 100)
* (berekenComponent(DatabaseServer.class, configuratie) / 100) * 100) >= percentage;
}
private void voegVolgendeToe(Class<?> type) {
// Switchen tussen Webserver en Database server.
if (type.isAssignableFrom(Webserver.class)) {
config.voegToeComponent(componenten.webServers.get(0));
} else if (type.isAssignableFrom(DatabaseServer.class)) {
config.voegToeComponent(componenten.dbServers.get(0));
}
}
public int hoeveelVan(Component component, Configuratie configuratie) {
// Bereken hoeveel er van een component al in de configuratie zitten.
int counter = 0;
for (Component c : configuratie.getComponenten()) {
if (c.equals(component)) {
counter++;
}
}
return counter;
}
public double berekenComponent(Class<?> type, Configuratie configuratie) {
double beschikbaarheid = 1;
// Voor elk component wordt gekeken wat voor component het is. Daarna wordt de
// beschikbaarheid berekend.
for (Component c : configuratie.getComponenten()) {
if (type.isAssignableFrom(c.getClass())) {
beschikbaarheid *= (1 - (c.getBeschikbaarheid() / 100));
}
}
return (1 - beschikbaarheid) * 100;
}
private int berekenTotalePrijs(Configuratie configuratie) {
int totalePrijs = 0;
try {
for (Component component : configuratie.getComponenten()) {
totalePrijs += component.getPrijs();
}
} catch (NullPointerException npe) {
System.out.println(npe);
}
return totalePrijs;
}
public double berekenTotalePrijsDouble(Configuratie configuratie) {
double totalePrijs = 0;
try {
for (Component component : configuratie.getComponenten()) {
totalePrijs += component.getPrijs();
}
} catch (NullPointerException npe) {
System.out.println(npe);
}
return totalePrijs;
}
}
|
199982_1 | package com.mygdx.game.GameLayer.Levels;
import com.mygdx.game.EngineLayer.EngineLevels.EngineLevel;
import java.util.List;
// Levels class containing the assets for each level object (will be deserialized from our levels.json)
public class Levels extends EngineLevel {
// Declare attributes
private String levelTitle;
private String levelMusic;
private String levelBackground;
private String[] dialogue;
private int numberOfFries;
private int numberOfBurgers;
private int numberOfRocks;
private int numberOfApples;
private int numberOfBananas;
private int numberOfCherries;
private int numberOfVegetables;
private String scoreNeeded;
private List<String> respawnables;
private float playerSpeed;
private float enemySpeed;
private List<String> playerTexture;
private List<String> enemyTexture;
private List<String> propTexture;
// Default Constructor
protected Levels() {};
// Get Level Title
public String getLevelTitle() {
return levelTitle;
}
// Get Level Music
public String getLevelMusic() {
return levelMusic;
}
// Get Level Background
public String getLevelBackground() {
return levelBackground;
}
// Get dialogue
public String[] getDialogue() {
return dialogue;
}
// Get Number of Fries
public int getNumberOfFries() {
return numberOfFries;
}
// Get Number of Burgers
public int getNumberOfBurgers() {
return numberOfBurgers;
}
// Get Number of Rocks
public int getNumberOfRocks() {
return numberOfRocks;
}
// Get Number of Apples
public int getNumberOfApples() {
return numberOfApples;
}
// Get Number of Bananas
public int getNumberOfBananas() {
return numberOfBananas;
}
// Get Number of Cherries
public int getNumberOfCherries() {
return numberOfCherries;
}
// Get Number of Vegetables
public int getNumberOfVegetables() {
return numberOfVegetables;
}
// Get the score needed to win
public String getScoreNeeded() {
return scoreNeeded;
}
// Get Respawnables
public List<String> getRespawnables() {
return respawnables;
}
// Get Enemy Speed
public float getEnemySpeed() {
return enemySpeed;
}
// Get Player Texture
public List<String> getPlayerTexture() {
return playerTexture;
}
// Get Enemy Texture
public List<String> getEnemyTexture() {
return enemyTexture;
}
// Get Player speed
public float getPlayerSpeed() {
return playerSpeed;
}
// Get Prop Texture
public List<String> getPropTexture() {
return propTexture;
}
} | JoelKong/NutriSprint-OOP | desktop/src/com/mygdx/game/GameLayer/Levels/Levels.java | 779 | // Get Level Title | line_comment | nl | package com.mygdx.game.GameLayer.Levels;
import com.mygdx.game.EngineLayer.EngineLevels.EngineLevel;
import java.util.List;
// Levels class containing the assets for each level object (will be deserialized from our levels.json)
public class Levels extends EngineLevel {
// Declare attributes
private String levelTitle;
private String levelMusic;
private String levelBackground;
private String[] dialogue;
private int numberOfFries;
private int numberOfBurgers;
private int numberOfRocks;
private int numberOfApples;
private int numberOfBananas;
private int numberOfCherries;
private int numberOfVegetables;
private String scoreNeeded;
private List<String> respawnables;
private float playerSpeed;
private float enemySpeed;
private List<String> playerTexture;
private List<String> enemyTexture;
private List<String> propTexture;
// Default Constructor
protected Levels() {};
// Get Level<SUF>
public String getLevelTitle() {
return levelTitle;
}
// Get Level Music
public String getLevelMusic() {
return levelMusic;
}
// Get Level Background
public String getLevelBackground() {
return levelBackground;
}
// Get dialogue
public String[] getDialogue() {
return dialogue;
}
// Get Number of Fries
public int getNumberOfFries() {
return numberOfFries;
}
// Get Number of Burgers
public int getNumberOfBurgers() {
return numberOfBurgers;
}
// Get Number of Rocks
public int getNumberOfRocks() {
return numberOfRocks;
}
// Get Number of Apples
public int getNumberOfApples() {
return numberOfApples;
}
// Get Number of Bananas
public int getNumberOfBananas() {
return numberOfBananas;
}
// Get Number of Cherries
public int getNumberOfCherries() {
return numberOfCherries;
}
// Get Number of Vegetables
public int getNumberOfVegetables() {
return numberOfVegetables;
}
// Get the score needed to win
public String getScoreNeeded() {
return scoreNeeded;
}
// Get Respawnables
public List<String> getRespawnables() {
return respawnables;
}
// Get Enemy Speed
public float getEnemySpeed() {
return enemySpeed;
}
// Get Player Texture
public List<String> getPlayerTexture() {
return playerTexture;
}
// Get Enemy Texture
public List<String> getEnemyTexture() {
return enemyTexture;
}
// Get Player speed
public float getPlayerSpeed() {
return playerSpeed;
}
// Get Prop Texture
public List<String> getPropTexture() {
return propTexture;
}
} |
73341_0 | package be.kuleuven.dbproject;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import be.kuleuven.dbproject.jdbi.JDBIManager;
/**
* DB Taak 2022-2023: De Vrolijke Zweters
* Zie https://kuleuven-diepenbeek.github.io/db-course/extra/project/ voor opgave details
*
* Deze code is slechts een quick-start om je op weg te helpen met de integratie van JavaFX tabellen en data!
* Zie README.md voor meer informatie.
*/
public class ProjectMain extends Application {
private static Stage rootStage;
public static Stage getRootStage() {
return rootStage;
}
@Override
public void start(Stage stage) throws Exception {
rootStage = stage;
Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("login.fxml"));
Scene scene = new Scene(root);
stage.setTitle("Administratie hoofdscherm");
stage.setScene(scene);
stage.setResizable(false);
stage.show();
}
public static void main(String[] args) {
JDBIManager.getJdbi();
launch();
}
}
| JohannesChopov/VGHFdb | project-template/src/main/java/be/kuleuven/dbproject/ProjectMain.java | 388 | /**
* DB Taak 2022-2023: De Vrolijke Zweters
* Zie https://kuleuven-diepenbeek.github.io/db-course/extra/project/ voor opgave details
*
* Deze code is slechts een quick-start om je op weg te helpen met de integratie van JavaFX tabellen en data!
* Zie README.md voor meer informatie.
*/ | block_comment | nl | package be.kuleuven.dbproject;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import be.kuleuven.dbproject.jdbi.JDBIManager;
/**
* DB Taak 2022-2023:<SUF>*/
public class ProjectMain extends Application {
private static Stage rootStage;
public static Stage getRootStage() {
return rootStage;
}
@Override
public void start(Stage stage) throws Exception {
rootStage = stage;
Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("login.fxml"));
Scene scene = new Scene(root);
stage.setTitle("Administratie hoofdscherm");
stage.setScene(scene);
stage.setResizable(false);
stage.show();
}
public static void main(String[] args) {
JDBIManager.getJdbi();
launch();
}
}
|
36825_1 | package app;
import java.util.Scanner;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class App {
static ChatClient client;
static boolean shouldLog = false;
static String[] kamers = {"Zolder", "Woonkamer", "WC"};
public static void main(String[] args) throws Exception {
System.out.println("Welkom bij deze chatapp, we hebben uw naam nodig om te kunnen chatten..");
String username = getUserInput("Wat is uw naam?");
// start de chatclient
client = new ChatClient();
client.start(username, new IWantNewMessages(){
@Override public void processNewMessage(String message) {
while (message.contains("room ")) {
char roomnumber = message.charAt(message.indexOf("room ") + 5);
if (roomnumber != 'u') {
int roomno = Integer.parseInt(roomnumber + "");
String kamer = kamers[roomno-1];
message = message.replace("room " + roomno,kamer);
} else {
message = message.replace("room undefined", "onbekend");
}
}
System.out.println(Log("SERVER SENDS: " + message));
}
});
client.sendMessage(Log("USER:" + username));
// zolang de gebruiker iets wil, doen we dat
String command = getUserInput("client :>");
while (!command.equals("q")){
processCommand(command);
command = getUserInput("client :>");
}
System.out.println("Ok, bye!");
}
public static void processCommand(String command){
switch (command) {
case "h": {
System.out.println("De beschikbare commando's zijn: ");
System.out.println("\th: toont deze hulp functie");
System.out.println("\tq: eindigt dit programma");
System.out.println("\tr: verander van kamer");
System.out.println("\ts: stuur een bericht");
System.out.println("\tx: voer een ban uit (admin only)");
System.out.println("\tb: vraag om een ban");
System.out.println("\t?: vraag om status informatie");
break;
}
case "r": {
System.out.println("De beschikbare kamers zijn: ");
for (int i = 0; i < kamers.length; i++) {
System.out.println("\th: " + (i + 1) + ". " + kamers[i]);
}
String kamer = getUserInput("Welke kamer wilt u in?");
client.sendMessage(Log("ROOM:" + kamer));
break;
}
case "s": {
String datatosend = getUserInput("Wat wilt u versturen?");
client.sendMessage(Log("MESSAGE:" + datatosend ));
break;
}
case "log": {
shouldLog = !shouldLog;
System.out.println(Log("Logging is set to " + shouldLog));
break;
}
case "x": {
String user = getUserInput("execute ban on user?");
client.sendMessage(Log("EXECUTEBAN:" + user ));
break;
}
case "xx": {
String user = getUserInput("execute superban on?");
client.sendMessage(Log("EXECUTEBAN2:" + user ));
break;
}
case "b": {
String user = getUserInput("Wie wilt u bannen?");
client.sendMessage(Log("BAN:" + user ));
break;
}
case "?": {
client.sendMessage(Log("STATUS"));
break;
}
default: {
System.out.println(Log("onbekend commando!"));
break;
}
}
}
public static String Log(String line) {
if (shouldLog) {
try {
FileWriter logFile = new FileWriter("./log.txt", true);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
logFile.append(dtf.format(now) + " " + line + "\r\n");
logFile.close();
} catch (IOException io){
System.out.println("error: " + io.getMessage());
}
}
return line;
}
public static String getUserInput(String prompt){
System.out.println(prompt);
Scanner s = new Scanner(System.in);
String data = s.nextLine();
return data;
}
} | JohnGorter/JavaChatDemo | src/app/App.java | 1,250 | // zolang de gebruiker iets wil, doen we dat | line_comment | nl | package app;
import java.util.Scanner;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class App {
static ChatClient client;
static boolean shouldLog = false;
static String[] kamers = {"Zolder", "Woonkamer", "WC"};
public static void main(String[] args) throws Exception {
System.out.println("Welkom bij deze chatapp, we hebben uw naam nodig om te kunnen chatten..");
String username = getUserInput("Wat is uw naam?");
// start de chatclient
client = new ChatClient();
client.start(username, new IWantNewMessages(){
@Override public void processNewMessage(String message) {
while (message.contains("room ")) {
char roomnumber = message.charAt(message.indexOf("room ") + 5);
if (roomnumber != 'u') {
int roomno = Integer.parseInt(roomnumber + "");
String kamer = kamers[roomno-1];
message = message.replace("room " + roomno,kamer);
} else {
message = message.replace("room undefined", "onbekend");
}
}
System.out.println(Log("SERVER SENDS: " + message));
}
});
client.sendMessage(Log("USER:" + username));
// zolang de<SUF>
String command = getUserInput("client :>");
while (!command.equals("q")){
processCommand(command);
command = getUserInput("client :>");
}
System.out.println("Ok, bye!");
}
public static void processCommand(String command){
switch (command) {
case "h": {
System.out.println("De beschikbare commando's zijn: ");
System.out.println("\th: toont deze hulp functie");
System.out.println("\tq: eindigt dit programma");
System.out.println("\tr: verander van kamer");
System.out.println("\ts: stuur een bericht");
System.out.println("\tx: voer een ban uit (admin only)");
System.out.println("\tb: vraag om een ban");
System.out.println("\t?: vraag om status informatie");
break;
}
case "r": {
System.out.println("De beschikbare kamers zijn: ");
for (int i = 0; i < kamers.length; i++) {
System.out.println("\th: " + (i + 1) + ". " + kamers[i]);
}
String kamer = getUserInput("Welke kamer wilt u in?");
client.sendMessage(Log("ROOM:" + kamer));
break;
}
case "s": {
String datatosend = getUserInput("Wat wilt u versturen?");
client.sendMessage(Log("MESSAGE:" + datatosend ));
break;
}
case "log": {
shouldLog = !shouldLog;
System.out.println(Log("Logging is set to " + shouldLog));
break;
}
case "x": {
String user = getUserInput("execute ban on user?");
client.sendMessage(Log("EXECUTEBAN:" + user ));
break;
}
case "xx": {
String user = getUserInput("execute superban on?");
client.sendMessage(Log("EXECUTEBAN2:" + user ));
break;
}
case "b": {
String user = getUserInput("Wie wilt u bannen?");
client.sendMessage(Log("BAN:" + user ));
break;
}
case "?": {
client.sendMessage(Log("STATUS"));
break;
}
default: {
System.out.println(Log("onbekend commando!"));
break;
}
}
}
public static String Log(String line) {
if (shouldLog) {
try {
FileWriter logFile = new FileWriter("./log.txt", true);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
logFile.append(dtf.format(now) + " " + line + "\r\n");
logFile.close();
} catch (IOException io){
System.out.println("error: " + io.getMessage());
}
}
return line;
}
public static String getUserInput(String prompt){
System.out.println(prompt);
Scanner s = new Scanner(System.in);
String data = s.nextLine();
return data;
}
} |
68114_1 | public class Schaakbord {
private char[][] bord;
public Schaakbord() {
bord = new char[8][8];
initializeBoard();
}
private void initializeBoard() {
// Vul het schaakbord met beginopstelling
// Hieronder staat een eenvoudige opstelling, je kunt deze aanpassen als je wilt
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (i == 1 || i == 6) {
bord[i][j] = 'P'; // Pion
} else if ((i == 0 || i == 7) && (j == 0 || j == 7)) {
bord[i][j] = 'R'; // Toren
} else if ((i == 0 || i == 7) && (j == 1 || j == 6)) {
bord[i][j] = 'N'; // Paard
} else if ((i == 0 || i == 7) && (j == 2 || j == 5)) {
bord[i][j] = 'B'; // Loper
} else if (i == 0 && j == 3) {
bord[i][j] = 'Q'; // Koningin
} else if (i == 0 && j == 4) {
bord[i][j] = 'K'; // Koning
} else {
bord[i][j] = ' '; // Leeg veld
}
}
}
}
public void printBoard() {
// Toon het schaakbord
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
System.out.print(bord[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
Schaakbord schaakbord = new Schaakbord();
schaakbord.printBoard();
}
}
| Johnnyvandebuurt/Project3 | src/Schaakbord.java | 565 | // Hieronder staat een eenvoudige opstelling, je kunt deze aanpassen als je wilt | line_comment | nl | public class Schaakbord {
private char[][] bord;
public Schaakbord() {
bord = new char[8][8];
initializeBoard();
}
private void initializeBoard() {
// Vul het schaakbord met beginopstelling
// Hieronder staat<SUF>
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (i == 1 || i == 6) {
bord[i][j] = 'P'; // Pion
} else if ((i == 0 || i == 7) && (j == 0 || j == 7)) {
bord[i][j] = 'R'; // Toren
} else if ((i == 0 || i == 7) && (j == 1 || j == 6)) {
bord[i][j] = 'N'; // Paard
} else if ((i == 0 || i == 7) && (j == 2 || j == 5)) {
bord[i][j] = 'B'; // Loper
} else if (i == 0 && j == 3) {
bord[i][j] = 'Q'; // Koningin
} else if (i == 0 && j == 4) {
bord[i][j] = 'K'; // Koning
} else {
bord[i][j] = ' '; // Leeg veld
}
}
}
}
public void printBoard() {
// Toon het schaakbord
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
System.out.print(bord[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
Schaakbord schaakbord = new Schaakbord();
schaakbord.printBoard();
}
}
|
30148_1 | package Allocator;
import java.lang.Math;
import java.util.concurrent.ConcurrentHashMap;
public class SingleThreadedAllocator implements Allocator {
private final ConcurrentHashMap<Integer, Arena> arenas = new ConcurrentHashMap<>();
private static final double LOG_2 = Math.log(2); // niet nodig om telkens opnieuw te berekenen
// bit shifts zouden sneller moeten zijn ipv Math.pow(2, exp)
private static int pow2(int exp) {
return 1 << exp; // -> 2^exp
}
// De best passende grootte zoeken (bv. 3015 -> 4096, 17 -> 32, 8522 -> 16384...)
public static int bestFitted(int size){
return pow2((int) Math.ceil(Math.log(size) / LOG_2));
}
public Long allocate(int size) {
int bestFittedSize = bestFitted(size);
Arena arena;
if (arenas.containsKey(bestFittedSize)) arena = arenas.get(bestFittedSize);
else {
if (size > 4096) arena = new Arena(bestFittedSize);
else arena = new Arena(4096, bestFittedSize);
arenas.put(bestFittedSize, arena);
}
return arena.allocate();
}
public void free(Long address) {
for (Arena arena : arenas.values()) {
if (arena.isAccessible(address)) {
arena.free(address);
return;
}
}
}
public Long reAllocate(Long oldAddress, int newSize) {
for (Arena arena : arenas.values()) {
if (arena.isAccessible(oldAddress)) {
int oldSize = arena.getPageSize();
if (oldSize >= newSize)
return oldAddress;
free(oldAddress);
return allocate(newSize);
}
}
return -1L;
}
public boolean isAccessible(Long address) {
return isAccessible(address, 1);
}
public boolean isAccessible(Long address, int size) {
for (Arena arena : arenas.values()) {
if (arena.isAccessible(address, size)) {
return true;
}
}
return false;
}
} | Jonas-VN/Besturingssystemen-2-Labo-3 | Allocator/SingleThreadedAllocator.java | 605 | // bit shifts zouden sneller moeten zijn ipv Math.pow(2, exp) | line_comment | nl | package Allocator;
import java.lang.Math;
import java.util.concurrent.ConcurrentHashMap;
public class SingleThreadedAllocator implements Allocator {
private final ConcurrentHashMap<Integer, Arena> arenas = new ConcurrentHashMap<>();
private static final double LOG_2 = Math.log(2); // niet nodig om telkens opnieuw te berekenen
// bit shifts<SUF>
private static int pow2(int exp) {
return 1 << exp; // -> 2^exp
}
// De best passende grootte zoeken (bv. 3015 -> 4096, 17 -> 32, 8522 -> 16384...)
public static int bestFitted(int size){
return pow2((int) Math.ceil(Math.log(size) / LOG_2));
}
public Long allocate(int size) {
int bestFittedSize = bestFitted(size);
Arena arena;
if (arenas.containsKey(bestFittedSize)) arena = arenas.get(bestFittedSize);
else {
if (size > 4096) arena = new Arena(bestFittedSize);
else arena = new Arena(4096, bestFittedSize);
arenas.put(bestFittedSize, arena);
}
return arena.allocate();
}
public void free(Long address) {
for (Arena arena : arenas.values()) {
if (arena.isAccessible(address)) {
arena.free(address);
return;
}
}
}
public Long reAllocate(Long oldAddress, int newSize) {
for (Arena arena : arenas.values()) {
if (arena.isAccessible(oldAddress)) {
int oldSize = arena.getPageSize();
if (oldSize >= newSize)
return oldAddress;
free(oldAddress);
return allocate(newSize);
}
}
return -1L;
}
public boolean isAccessible(Long address) {
return isAccessible(address, 1);
}
public boolean isAccessible(Long address, int size) {
for (Arena arena : arenas.values()) {
if (arena.isAccessible(address, size)) {
return true;
}
}
return false;
}
} |
96577_9 | package tup;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class BranchAndBound {
private Problem problem;
private int bestDistance = Integer.MAX_VALUE;
public int[][] bestSolution;
private int[] numberOfUniqueVenuesVisited;
private boolean[][] visited;
private LowerBound lowerBound;
private long nNodes = 0;
private long startTime = System.currentTimeMillis();
private int m = 0;
public BranchAndBound(Problem problem) throws InterruptedException {
this.problem = problem;
bestSolution = new int[problem.nUmpires][problem.nRounds];
numberOfUniqueVenuesVisited = new int[problem.nUmpires];
visited = new boolean[problem.nUmpires][problem.nTeams];
// init arrays
for (int i = 0; i < problem.nUmpires; i++) {
numberOfUniqueVenuesVisited[i] = 0;
for (int j = 0; j < problem.nTeams; j++) {
visited[i][j] = false;
}
}
// Start lower bound calculation in a separate thread
lowerBound = new LowerBound(problem);
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
long StartTime = System.currentTimeMillis();
try {
lowerBound.solve();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("Lower bound calculation time: " + (System.currentTimeMillis() - StartTime) / 1000.0 + "s");
});
executor.shutdown();
}
public void solve() throws InterruptedException {
startTime = System.currentTimeMillis();
int[][] path = new int[problem.nUmpires][problem.nRounds];
// Wijs in de eerste ronde elke scheidsrechter willekeurig toe aan een wedstrijd
int umpire = 0;
for (int team = 0; team < problem.nTeams; team++) {
if (problem.opponents[0][team] < 0) {
path[umpire][0] = -problem.opponents[0][team];
numberOfUniqueVenuesVisited[umpire]++;
visited[umpire++][-problem.opponents[0][team] - 1] = true;
}
}
// Voer het branch-and-bound algoritme uit vanaf de tweede ronde
this.branchAndBound(path, 0, 1, 0);
this.lowerBound.shutdown = true;
System.out.println("Best solution: ");
printPath(bestSolution);
System.out.println("Distance: " + bestDistance);
System.out.println("Number of nodes: " + nNodes);
System.out.println("Time: " + (System.currentTimeMillis() - startTime) / 1_000.0 + "s");
}
private void branchAndBound(int[][] path, int umpire, int round, int currentCost) throws InterruptedException {
if (round == this.problem.nRounds) {
// Constructed a full feasible path
if (currentCost < bestDistance) {
// The constructed path is better than the current best path! :)
System.out.println("New BEST solution found in " + (System.currentTimeMillis() - startTime) / 60_000.0 + " min with cost " + currentCost + "! :)");
//printPath(path);
// Copy solution
bestDistance = currentCost;
for (int _umpire = 0; _umpire < this.problem.nUmpires; _umpire++) {
System.arraycopy(path[_umpire], 0, bestSolution[_umpire], 0, this.problem.nRounds);
}
}
return;
}
List<Integer> feasibleAllocations = problem.getValidAllocations(path, umpire, round);
if (!feasibleAllocations.isEmpty()) {
for (Integer allocation : feasibleAllocations) {
// int[][] subgraph = generateSubgraph(path, round, allocation);
// if (subgraph != null) {
// int m = solveMatchingProblem(subgraph);
// }
path[umpire][round] = allocation;
boolean firstVisit = !visited[umpire][allocation - 1];
if (firstVisit) {
visited[umpire][allocation - 1] = true;
numberOfUniqueVenuesVisited[umpire]++;
}
int prevHomeTeam = path[umpire][round - 1];
int extraCost = this.problem.dist[prevHomeTeam - 1][allocation - 1];
//if (problem.nTeams - numberOfUniqueVenuesVisited[umpire] < problem.nRounds - round && currentCost + extraCost + lowerBound.getLowerBound(round) < bestDistance) {
if (!canPrune(path, umpire, round, allocation, currentCost + extraCost)) {
nNodes++;
if (umpire == this.problem.nUmpires - 1) {
this.branchAndBound(path, 0, round + 1, currentCost + extraCost);
}
else this.branchAndBound(path, umpire + 1, round, currentCost + extraCost);
}
// Backtrack
path[umpire][round] = 0;
if (firstVisit) {
visited[umpire][allocation - 1] = false;
numberOfUniqueVenuesVisited[umpire]--;
}
}
}
}
private int solveMatchingProblem(int[][] subgraph){
Hungarian hungarian = new Hungarian();
hungarian.assignmentProblem(subgraph);
int[] solution = hungarian.xy;
int cost = 0;
for (int i = 0; i < solution.length; i++) {
cost += subgraph[i][solution[i]];
}
return cost;
}
private int[][] generateSubgraph(int[][] assignments, int round, int allocation) {
List<Integer> visitedTeams = new ArrayList<>();//aantal teams gevisited in deze ronde
List<Integer> previousTeams = new ArrayList<>();//teams visited in de vorige ronde
List<Integer> currentRoundTeams = new ArrayList<>();//overige nog te bezoeken teams in deze ronde
for (int i = 0; i < problem.nUmpires; i++) {
if (assignments[i][round] == 0) {
} else {
visitedTeams.add(assignments[i][round]);
}
}
// System.out.println("Generating subgraph for round " + round +1);
if (visitedTeams.isEmpty()) {
return null;
}
for (int i = visitedTeams.size(); i < problem.nUmpires; i++) {
previousTeams.add(assignments[i][round-1]);
}
for (int i = 0; i < problem.nTeams; i++) {
if (problem.opponents[round][i] < 0) {
int homeTeam = -problem.opponents[round][i];
int awayTeam = i + 1;
if (!visitedTeams.contains(homeTeam) && !visitedTeams.contains(awayTeam) && homeTeam != allocation) {
currentRoundTeams.add(homeTeam);
}
}
}
int size = Math.max(previousTeams.size(), currentRoundTeams.size());
int[][] subgraph = new int[size][size];
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (i < previousTeams.size() && j < currentRoundTeams.size()) {
// Vul de kosten in voor de werkelijke teams
subgraph[i][j] = problem.dist[previousTeams.get(i)-1][currentRoundTeams.get(j)-1];
} else {
// Vul de kosten in voor de dummy-knopen
subgraph[i][j] = Integer.MAX_VALUE;
}
}
}
return subgraph;
}
private boolean canPrune(int[][] path, int umpire, int round, int allocation, int currentCost) throws InterruptedException {
// Controleer of het team al is toegewezen in deze ronde
// for (int i = 0; i < umpire; i++) {
// if (path[i][round] == allocation) {
// return true;
// }
// }
if (problem.nTeams - numberOfUniqueVenuesVisited[umpire] >= problem.nRounds - round) return true;
double lb = this.lowerBound.getLowerBound(round);
if (currentCost + lb >= bestDistance) {
//System.out.println("Pruned op LB");
return true;
}
int[][] subgraph = generateSubgraph(path, round, allocation);
if (subgraph != null && currentCost + lb + lowerBound.getLowerBound(round, round+1) >= bestDistance) {
m = solveMatchingProblem(subgraph);
//System.out.println("Matching cost: " + m);
if (currentCost + lowerBound.getLowerBound(round) + m >= bestDistance) {
//System.out.println("Pruned op matching");
return true;
}
}
return false;
}
private void printPath(int[][] path) {
System.out.println("-------------------------------------------------------------------------------------");
System.out.println(Arrays.deepToString(path));
}
} | Jonas-VN/TUP | src/tup/BranchAndBound.java | 2,599 | //aantal teams gevisited in deze ronde | line_comment | nl | package tup;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class BranchAndBound {
private Problem problem;
private int bestDistance = Integer.MAX_VALUE;
public int[][] bestSolution;
private int[] numberOfUniqueVenuesVisited;
private boolean[][] visited;
private LowerBound lowerBound;
private long nNodes = 0;
private long startTime = System.currentTimeMillis();
private int m = 0;
public BranchAndBound(Problem problem) throws InterruptedException {
this.problem = problem;
bestSolution = new int[problem.nUmpires][problem.nRounds];
numberOfUniqueVenuesVisited = new int[problem.nUmpires];
visited = new boolean[problem.nUmpires][problem.nTeams];
// init arrays
for (int i = 0; i < problem.nUmpires; i++) {
numberOfUniqueVenuesVisited[i] = 0;
for (int j = 0; j < problem.nTeams; j++) {
visited[i][j] = false;
}
}
// Start lower bound calculation in a separate thread
lowerBound = new LowerBound(problem);
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
long StartTime = System.currentTimeMillis();
try {
lowerBound.solve();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("Lower bound calculation time: " + (System.currentTimeMillis() - StartTime) / 1000.0 + "s");
});
executor.shutdown();
}
public void solve() throws InterruptedException {
startTime = System.currentTimeMillis();
int[][] path = new int[problem.nUmpires][problem.nRounds];
// Wijs in de eerste ronde elke scheidsrechter willekeurig toe aan een wedstrijd
int umpire = 0;
for (int team = 0; team < problem.nTeams; team++) {
if (problem.opponents[0][team] < 0) {
path[umpire][0] = -problem.opponents[0][team];
numberOfUniqueVenuesVisited[umpire]++;
visited[umpire++][-problem.opponents[0][team] - 1] = true;
}
}
// Voer het branch-and-bound algoritme uit vanaf de tweede ronde
this.branchAndBound(path, 0, 1, 0);
this.lowerBound.shutdown = true;
System.out.println("Best solution: ");
printPath(bestSolution);
System.out.println("Distance: " + bestDistance);
System.out.println("Number of nodes: " + nNodes);
System.out.println("Time: " + (System.currentTimeMillis() - startTime) / 1_000.0 + "s");
}
private void branchAndBound(int[][] path, int umpire, int round, int currentCost) throws InterruptedException {
if (round == this.problem.nRounds) {
// Constructed a full feasible path
if (currentCost < bestDistance) {
// The constructed path is better than the current best path! :)
System.out.println("New BEST solution found in " + (System.currentTimeMillis() - startTime) / 60_000.0 + " min with cost " + currentCost + "! :)");
//printPath(path);
// Copy solution
bestDistance = currentCost;
for (int _umpire = 0; _umpire < this.problem.nUmpires; _umpire++) {
System.arraycopy(path[_umpire], 0, bestSolution[_umpire], 0, this.problem.nRounds);
}
}
return;
}
List<Integer> feasibleAllocations = problem.getValidAllocations(path, umpire, round);
if (!feasibleAllocations.isEmpty()) {
for (Integer allocation : feasibleAllocations) {
// int[][] subgraph = generateSubgraph(path, round, allocation);
// if (subgraph != null) {
// int m = solveMatchingProblem(subgraph);
// }
path[umpire][round] = allocation;
boolean firstVisit = !visited[umpire][allocation - 1];
if (firstVisit) {
visited[umpire][allocation - 1] = true;
numberOfUniqueVenuesVisited[umpire]++;
}
int prevHomeTeam = path[umpire][round - 1];
int extraCost = this.problem.dist[prevHomeTeam - 1][allocation - 1];
//if (problem.nTeams - numberOfUniqueVenuesVisited[umpire] < problem.nRounds - round && currentCost + extraCost + lowerBound.getLowerBound(round) < bestDistance) {
if (!canPrune(path, umpire, round, allocation, currentCost + extraCost)) {
nNodes++;
if (umpire == this.problem.nUmpires - 1) {
this.branchAndBound(path, 0, round + 1, currentCost + extraCost);
}
else this.branchAndBound(path, umpire + 1, round, currentCost + extraCost);
}
// Backtrack
path[umpire][round] = 0;
if (firstVisit) {
visited[umpire][allocation - 1] = false;
numberOfUniqueVenuesVisited[umpire]--;
}
}
}
}
private int solveMatchingProblem(int[][] subgraph){
Hungarian hungarian = new Hungarian();
hungarian.assignmentProblem(subgraph);
int[] solution = hungarian.xy;
int cost = 0;
for (int i = 0; i < solution.length; i++) {
cost += subgraph[i][solution[i]];
}
return cost;
}
private int[][] generateSubgraph(int[][] assignments, int round, int allocation) {
List<Integer> visitedTeams = new ArrayList<>();//aantal teams<SUF>
List<Integer> previousTeams = new ArrayList<>();//teams visited in de vorige ronde
List<Integer> currentRoundTeams = new ArrayList<>();//overige nog te bezoeken teams in deze ronde
for (int i = 0; i < problem.nUmpires; i++) {
if (assignments[i][round] == 0) {
} else {
visitedTeams.add(assignments[i][round]);
}
}
// System.out.println("Generating subgraph for round " + round +1);
if (visitedTeams.isEmpty()) {
return null;
}
for (int i = visitedTeams.size(); i < problem.nUmpires; i++) {
previousTeams.add(assignments[i][round-1]);
}
for (int i = 0; i < problem.nTeams; i++) {
if (problem.opponents[round][i] < 0) {
int homeTeam = -problem.opponents[round][i];
int awayTeam = i + 1;
if (!visitedTeams.contains(homeTeam) && !visitedTeams.contains(awayTeam) && homeTeam != allocation) {
currentRoundTeams.add(homeTeam);
}
}
}
int size = Math.max(previousTeams.size(), currentRoundTeams.size());
int[][] subgraph = new int[size][size];
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (i < previousTeams.size() && j < currentRoundTeams.size()) {
// Vul de kosten in voor de werkelijke teams
subgraph[i][j] = problem.dist[previousTeams.get(i)-1][currentRoundTeams.get(j)-1];
} else {
// Vul de kosten in voor de dummy-knopen
subgraph[i][j] = Integer.MAX_VALUE;
}
}
}
return subgraph;
}
private boolean canPrune(int[][] path, int umpire, int round, int allocation, int currentCost) throws InterruptedException {
// Controleer of het team al is toegewezen in deze ronde
// for (int i = 0; i < umpire; i++) {
// if (path[i][round] == allocation) {
// return true;
// }
// }
if (problem.nTeams - numberOfUniqueVenuesVisited[umpire] >= problem.nRounds - round) return true;
double lb = this.lowerBound.getLowerBound(round);
if (currentCost + lb >= bestDistance) {
//System.out.println("Pruned op LB");
return true;
}
int[][] subgraph = generateSubgraph(path, round, allocation);
if (subgraph != null && currentCost + lb + lowerBound.getLowerBound(round, round+1) >= bestDistance) {
m = solveMatchingProblem(subgraph);
//System.out.println("Matching cost: " + m);
if (currentCost + lowerBound.getLowerBound(round) + m >= bestDistance) {
//System.out.println("Pruned op matching");
return true;
}
}
return false;
}
private void printPath(int[][] path) {
System.out.println("-------------------------------------------------------------------------------------");
System.out.println(Arrays.deepToString(path));
}
} |
22443_1 | package model;
import model.article.Article;
import model.basket.Basket;
import model.log.Log;
import model.observer.Observer;
import model.shop.Shop;
import db.ArticleDbContext;
import java.io.IOException;
import java.util.*;
/**
* @author the team
*/
public class DomainFacade {
private final Shop shop;
private final Log log;
public DomainFacade() throws IOException {
Prop.load();
this.log = new Log();
this.shop = new Shop(log);
}
public Log getLog() {
return log;
}
public List<String> getLogItems() {
return log.getItems();
}
public void addLogObserver(Observer observer) {
log.addObserver(observer);
}
public Shop getShop() {
return shop;
}
public ArticleDbContext getArticleDb() {
return shop.getArticleDb();
}
public void putSaleOnHold() {
shop.putSaleOnHold();
}
public void continueHeldSale() {
shop.resumeSale();
}
public boolean saleIsOnHold() {
return shop.saleIsOnHold();
}
public void addShopObserver(Observer observer) { shop.addObserver(observer); }
public void removeShopObserver(Observer observer) { shop.removeObserver(observer); }
//region Basket
public Basket getBasket() {
return shop.getBasket();
}
public void updateDiscountContext() {
getBasket().updateDiscountContext();
}
public void addBasketObserver(Observer observer) {
getBasket().addObserver(observer);
}
public void removeBasketObserver(Observer observer) {
getBasket().removeObserver(observer);
}
public void closeBasket() {
getBasket().close();
}
public void payBasket() {
getBasket().pay();
}
public void cancelBasket() {
getBasket().cancel();
}
public void addBasketArticle(Article article) {
getBasket().add(article);
}
public Collection<Article> getAllUniqueBasketArticles() {
return getBasket().getAllUniqueArticles();
}
public Map<Article, Integer> getBasketArticleStacks() {
return getBasket().getArticleStacks();
}
public void removeBasketArticle(Article article) {
getBasket().remove(article);
}
public void removeBasketArticles(Map<Article, Integer> articleAmountsToRemove) {
getBasket().removeAll(articleAmountsToRemove);
}
public void removeBasketArticles(Collection<Article> articles) {
getBasket().removeAll(articles);
}
public void clearBasketArticles() {
getBasket().clear();
}
//Geeft prijs ZONDER toegepaste korting
public double getBasketTotalPrice() {
return getBasket().getTotalPrice();
}
//Geeft totale prijs MET korting toegepast
public double getBasketDiscountedPrice() {
return getBasket().getTotalDiscountedPrice();
}
//endregion
}
| JonasBerx/3_Berx_Draelants_Fiers_KassaApp_2019 | src/model/DomainFacade.java | 872 | //Geeft prijs ZONDER toegepaste korting | line_comment | nl | package model;
import model.article.Article;
import model.basket.Basket;
import model.log.Log;
import model.observer.Observer;
import model.shop.Shop;
import db.ArticleDbContext;
import java.io.IOException;
import java.util.*;
/**
* @author the team
*/
public class DomainFacade {
private final Shop shop;
private final Log log;
public DomainFacade() throws IOException {
Prop.load();
this.log = new Log();
this.shop = new Shop(log);
}
public Log getLog() {
return log;
}
public List<String> getLogItems() {
return log.getItems();
}
public void addLogObserver(Observer observer) {
log.addObserver(observer);
}
public Shop getShop() {
return shop;
}
public ArticleDbContext getArticleDb() {
return shop.getArticleDb();
}
public void putSaleOnHold() {
shop.putSaleOnHold();
}
public void continueHeldSale() {
shop.resumeSale();
}
public boolean saleIsOnHold() {
return shop.saleIsOnHold();
}
public void addShopObserver(Observer observer) { shop.addObserver(observer); }
public void removeShopObserver(Observer observer) { shop.removeObserver(observer); }
//region Basket
public Basket getBasket() {
return shop.getBasket();
}
public void updateDiscountContext() {
getBasket().updateDiscountContext();
}
public void addBasketObserver(Observer observer) {
getBasket().addObserver(observer);
}
public void removeBasketObserver(Observer observer) {
getBasket().removeObserver(observer);
}
public void closeBasket() {
getBasket().close();
}
public void payBasket() {
getBasket().pay();
}
public void cancelBasket() {
getBasket().cancel();
}
public void addBasketArticle(Article article) {
getBasket().add(article);
}
public Collection<Article> getAllUniqueBasketArticles() {
return getBasket().getAllUniqueArticles();
}
public Map<Article, Integer> getBasketArticleStacks() {
return getBasket().getArticleStacks();
}
public void removeBasketArticle(Article article) {
getBasket().remove(article);
}
public void removeBasketArticles(Map<Article, Integer> articleAmountsToRemove) {
getBasket().removeAll(articleAmountsToRemove);
}
public void removeBasketArticles(Collection<Article> articles) {
getBasket().removeAll(articles);
}
public void clearBasketArticles() {
getBasket().clear();
}
//Geeft prijs<SUF>
public double getBasketTotalPrice() {
return getBasket().getTotalPrice();
}
//Geeft totale prijs MET korting toegepast
public double getBasketDiscountedPrice() {
return getBasket().getTotalDiscountedPrice();
}
//endregion
}
|
107080_5 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package be.ehb.database.model;
/**
*
* @author ruben_000
*/
public class Experiment {
private int id;
private int nummer;
private int actief;
private int zone;
public String[][] teksten = new String[3][4];
//Rij 1 zijn de Nederlandse teksten
//Rij 2 zijn de Franse teksten
//Rij 3 zijn de Engelse teksten
//De teksten in volgorde: Naam, Instructies, Verklaring, Benodigdheden.
public void setId(int Id) {
this.id = Id;
}
public void setNummer(int nummer) {
this.nummer = nummer;
}
public void setActief(int actief) {
this.actief = actief;
}
public void setZone(int zone) {
this.zone = zone;
}
public int getId() {
return id;
}
public int getNummer() {
return nummer;
}
public int getActief() {
return actief;
}
public int getZone() {
return zone;
}
public Experiment(int Id, int nummer, int actief, int zone) {
this.id = Id;
this.nummer = nummer;
this.actief = actief;
this.zone = zone;
}
public Experiment() {
this.actief = 1;
this.zone = 0;
}
}
| JonasPardon/Technopolis | TechnopolisSwing/src/be/ehb/database/model/Experiment.java | 456 | //De teksten in volgorde: Naam, Instructies, Verklaring, Benodigdheden. | line_comment | nl | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package be.ehb.database.model;
/**
*
* @author ruben_000
*/
public class Experiment {
private int id;
private int nummer;
private int actief;
private int zone;
public String[][] teksten = new String[3][4];
//Rij 1 zijn de Nederlandse teksten
//Rij 2 zijn de Franse teksten
//Rij 3 zijn de Engelse teksten
//De teksten<SUF>
public void setId(int Id) {
this.id = Id;
}
public void setNummer(int nummer) {
this.nummer = nummer;
}
public void setActief(int actief) {
this.actief = actief;
}
public void setZone(int zone) {
this.zone = zone;
}
public int getId() {
return id;
}
public int getNummer() {
return nummer;
}
public int getActief() {
return actief;
}
public int getZone() {
return zone;
}
public Experiment(int Id, int nummer, int actief, int zone) {
this.id = Id;
this.nummer = nummer;
this.actief = actief;
this.zone = zone;
}
public Experiment() {
this.actief = 1;
this.zone = 0;
}
}
|
159134_16 | /*
* This file is part of UltimateCore, licensed under the MIT License (MIT).
*
* Copyright (c) Bammerbom
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package bammerbom.ultimatecore.sponge.api.module;
import bammerbom.ultimatecore.sponge.UltimateCore;
import java.util.Optional;
/**
* This is a enum containing all official modules of UltimateCore
*/
public class Modules {
private static ModuleService service = UltimateCore.get().getModuleService();
//TODO create javadocs for a description of every module
public static Optional<Module> AFK = service.getModule("afk");
public static Optional<Module> AUTOMESSAGE = service.getModule("automessage");
public static Optional<Module> BACK = service.getModule("back");
public static Optional<Module> BACKUP = service.getModule("backup");
public static Optional<Module> BAN = service.getModule("ban");
public static Optional<Module> BLACKLIST = service.getModule("blacklist");
public static Optional<Module> BLOCKPROTECTION = service.getModule("blockprotection");
public static Optional<Module> BLOOD = service.getModule("blood");
public static Optional<Module> BROADCAST = service.getModule("broadcast");
public static Optional<Module> BURN = service.getModule("burn");
public static Optional<Module> CHAT = service.getModule("chat");
//Allows for warmup & cooldown for commands
public static Optional<Module> COMMANDTIMER = service.getModule("commandtimer");
//Logs all commands to the console, should be filterable
public static Optional<Module> COMMANDLOG = service.getModule("commandlog");
public static Optional<Module> COMMANDSIGN = service.getModule("commandsigns");
//Custom join & leave messages
//First join commands
public static Optional<Module> CONNECTIONMESSAGES = service.getModule("connectionmessages");
public static Optional<Module> CORE = service.getModule("core");
//Create custom commands which print specific text or execute other commands
public static Optional<Module> CUSTOMCOMMANDS = service.getModule("customcommands");
public static Optional<Module> DEAF = service.getModule("deaf");
public static Optional<Module> DEATHMESSAGE = service.getModule("deathmessage");
public static Optional<Module> DEFAULT = service.getModule("default");
public static Optional<Module> ECONOMY = service.getModule("economy");
public static Optional<Module> EXPERIENCE = service.getModule("experience");
public static Optional<Module> EXPLOSION = service.getModule("explosion");
public static Optional<Module> FOOD = service.getModule("food");
public static Optional<Module> FLY = service.getModule("fly");
public static Optional<Module> FREEZE = service.getModule("freeze");
public static Optional<Module> GAMEMODE = service.getModule("gamemode");
public static Optional<Module> GEOIP = service.getModule("geoip");
public static Optional<Module> GOD = service.getModule("god");
public static Optional<Module> HOLOGRAM = service.getModule("holograms");
public static Optional<Module> HOME = service.getModule("home");
public static Optional<Module> HEAL = service.getModule("heal");
//Exempt perm
public static Optional<Module> IGNORE = service.getModule("ignore");
public static Optional<Module> INSTANTRESPAWN = service.getModule("instantrespawn");
public static Optional<Module> INVSEE = service.getModule("invsee");
public static Optional<Module> ITEM = service.getModule("item");
public static Optional<Module> JAIL = service.getModule("jail");
public static Optional<Module> KICK = service.getModule("kick");
public static Optional<Module> KIT = service.getModule("kit");
public static Optional<Module> MAIL = service.getModule("mail");
public static Optional<Module> MOBTP = service.getModule("mobtp");
//Commands like /accountstatus, /mcservers, etc
public static Optional<Module> MOJANGSERVICE = service.getModule("mojangservice");
public static Optional<Module> MUTE = service.getModule("mute");
//Change player's nametag
public static Optional<Module> NAMETAG = service.getModule("nametag");
public static Optional<Module> NICK = service.getModule("nick");
public static Optional<Module> NOCLIP = service.getModule("noclip");
public static Optional<Module> PARTICLE = service.getModule("particle");
public static Optional<Module> PERFORMANCE = service.getModule("performance");
//The /playerinfo command which displays a lot of info of a player, clickable to change
public static Optional<Module> PLAYERINFO = service.getModule("playerinfo");
public static Optional<Module> PLUGIN = service.getModule("plugin");
public static Optional<Module> PERSONALMESSAGE = service.getModule("personalmessage");
public static Optional<Module> POKE = service.getModule("poke");
//Create portals
public static Optional<Module> PORTAL = service.getModule("portal");
//Global and per person
public static Optional<Module> POWERTOOL = service.getModule("powertool");
public static Optional<Module> PREGENERATOR = service.getModule("pregenerator");
//Protect stuff like chests, itemframes, etc (Customizable, obviously)
public static Optional<Module> PROTECT = service.getModule("protect");
//Generate random numbers, booleans, strings, etc
public static Optional<Module> RANDOM = service.getModule("random");
public static Optional<Module> REPORT = service.getModule("report");
//Schedule commands at specific times of a day
public static Optional<Module> SCHEDULER = service.getModule("scheduler");
public static Optional<Module> SCOREBOARD = service.getModule("scoreboard");
public static Optional<Module> SERVERLIST = service.getModule("serverlist");
public static Optional<Module> SIGN = service.getModule("sign");
public static Optional<Module> SOUND = service.getModule("sound");
//Seperate /firstspawn & /setfirstspawn
public static Optional<Module> SPAWN = service.getModule("spawn");
public static Optional<Module> SPAWNMOB = service.getModule("spawnmob");
public static Optional<Module> SPY = service.getModule("spy");
//Mogelijkheid om meerdere commands te maken
public static Optional<Module> STAFFCHAT = service.getModule("staffchat");
//Better /stop and /restart commands (Time?)
public static Optional<Module> STOPRESTART = service.getModule("stoprestart");
public static Optional<Module> SUDO = service.getModule("sudo");
//Animated, refresh every x seconds
public static Optional<Module> TABLIST = service.getModule("tablist");
//Split the /teleport command better
public static Optional<Module> TELEPORT = service.getModule("teleport");
//Teleport to a random location, include /biometp
public static Optional<Module> TELEPORTRANDOM = service.getModule("teleportrandom");
public static Optional<Module> TIME = service.getModule("time");
//Timber
public static Optional<Module> TREE = service.getModule("tree");
//Change the unknown command message
public static Optional<Module> UNKNOWNCOMMAND = service.getModule("unknowncommand");
public static Optional<Module> UPDATE = service.getModule("update");
public static Optional<Module> VANISH = service.getModule("vanish");
public static Optional<Module> VILLAGER = service.getModule("villager");
//Votifier module
public static Optional<Module> VOTIFIER = service.getModule("votifier");
public static Optional<Module> WARP = service.getModule("warp");
public static Optional<Module> WEATHER = service.getModule("weather");
//Stop using flags, use seperate commands & clickable chat interface
public static Optional<Module> WORLD = service.getModule("world");
public static Optional<Module> WORLDBORDER = service.getModule("worldborder");
public static Optional<Module> WORLDINVENTORIES = service.getModule("worldinventories");
//TODO /smelt command?
public static Optional<Module> get(String id) {
return service.getModule(id);
}
}
| JonathanBrouwer/UltimateCore | src/main/java/bammerbom/ultimatecore/sponge/api/module/Modules.java | 2,482 | //Mogelijkheid om meerdere commands te maken | line_comment | nl | /*
* This file is part of UltimateCore, licensed under the MIT License (MIT).
*
* Copyright (c) Bammerbom
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package bammerbom.ultimatecore.sponge.api.module;
import bammerbom.ultimatecore.sponge.UltimateCore;
import java.util.Optional;
/**
* This is a enum containing all official modules of UltimateCore
*/
public class Modules {
private static ModuleService service = UltimateCore.get().getModuleService();
//TODO create javadocs for a description of every module
public static Optional<Module> AFK = service.getModule("afk");
public static Optional<Module> AUTOMESSAGE = service.getModule("automessage");
public static Optional<Module> BACK = service.getModule("back");
public static Optional<Module> BACKUP = service.getModule("backup");
public static Optional<Module> BAN = service.getModule("ban");
public static Optional<Module> BLACKLIST = service.getModule("blacklist");
public static Optional<Module> BLOCKPROTECTION = service.getModule("blockprotection");
public static Optional<Module> BLOOD = service.getModule("blood");
public static Optional<Module> BROADCAST = service.getModule("broadcast");
public static Optional<Module> BURN = service.getModule("burn");
public static Optional<Module> CHAT = service.getModule("chat");
//Allows for warmup & cooldown for commands
public static Optional<Module> COMMANDTIMER = service.getModule("commandtimer");
//Logs all commands to the console, should be filterable
public static Optional<Module> COMMANDLOG = service.getModule("commandlog");
public static Optional<Module> COMMANDSIGN = service.getModule("commandsigns");
//Custom join & leave messages
//First join commands
public static Optional<Module> CONNECTIONMESSAGES = service.getModule("connectionmessages");
public static Optional<Module> CORE = service.getModule("core");
//Create custom commands which print specific text or execute other commands
public static Optional<Module> CUSTOMCOMMANDS = service.getModule("customcommands");
public static Optional<Module> DEAF = service.getModule("deaf");
public static Optional<Module> DEATHMESSAGE = service.getModule("deathmessage");
public static Optional<Module> DEFAULT = service.getModule("default");
public static Optional<Module> ECONOMY = service.getModule("economy");
public static Optional<Module> EXPERIENCE = service.getModule("experience");
public static Optional<Module> EXPLOSION = service.getModule("explosion");
public static Optional<Module> FOOD = service.getModule("food");
public static Optional<Module> FLY = service.getModule("fly");
public static Optional<Module> FREEZE = service.getModule("freeze");
public static Optional<Module> GAMEMODE = service.getModule("gamemode");
public static Optional<Module> GEOIP = service.getModule("geoip");
public static Optional<Module> GOD = service.getModule("god");
public static Optional<Module> HOLOGRAM = service.getModule("holograms");
public static Optional<Module> HOME = service.getModule("home");
public static Optional<Module> HEAL = service.getModule("heal");
//Exempt perm
public static Optional<Module> IGNORE = service.getModule("ignore");
public static Optional<Module> INSTANTRESPAWN = service.getModule("instantrespawn");
public static Optional<Module> INVSEE = service.getModule("invsee");
public static Optional<Module> ITEM = service.getModule("item");
public static Optional<Module> JAIL = service.getModule("jail");
public static Optional<Module> KICK = service.getModule("kick");
public static Optional<Module> KIT = service.getModule("kit");
public static Optional<Module> MAIL = service.getModule("mail");
public static Optional<Module> MOBTP = service.getModule("mobtp");
//Commands like /accountstatus, /mcservers, etc
public static Optional<Module> MOJANGSERVICE = service.getModule("mojangservice");
public static Optional<Module> MUTE = service.getModule("mute");
//Change player's nametag
public static Optional<Module> NAMETAG = service.getModule("nametag");
public static Optional<Module> NICK = service.getModule("nick");
public static Optional<Module> NOCLIP = service.getModule("noclip");
public static Optional<Module> PARTICLE = service.getModule("particle");
public static Optional<Module> PERFORMANCE = service.getModule("performance");
//The /playerinfo command which displays a lot of info of a player, clickable to change
public static Optional<Module> PLAYERINFO = service.getModule("playerinfo");
public static Optional<Module> PLUGIN = service.getModule("plugin");
public static Optional<Module> PERSONALMESSAGE = service.getModule("personalmessage");
public static Optional<Module> POKE = service.getModule("poke");
//Create portals
public static Optional<Module> PORTAL = service.getModule("portal");
//Global and per person
public static Optional<Module> POWERTOOL = service.getModule("powertool");
public static Optional<Module> PREGENERATOR = service.getModule("pregenerator");
//Protect stuff like chests, itemframes, etc (Customizable, obviously)
public static Optional<Module> PROTECT = service.getModule("protect");
//Generate random numbers, booleans, strings, etc
public static Optional<Module> RANDOM = service.getModule("random");
public static Optional<Module> REPORT = service.getModule("report");
//Schedule commands at specific times of a day
public static Optional<Module> SCHEDULER = service.getModule("scheduler");
public static Optional<Module> SCOREBOARD = service.getModule("scoreboard");
public static Optional<Module> SERVERLIST = service.getModule("serverlist");
public static Optional<Module> SIGN = service.getModule("sign");
public static Optional<Module> SOUND = service.getModule("sound");
//Seperate /firstspawn & /setfirstspawn
public static Optional<Module> SPAWN = service.getModule("spawn");
public static Optional<Module> SPAWNMOB = service.getModule("spawnmob");
public static Optional<Module> SPY = service.getModule("spy");
//Mogelijkheid om<SUF>
public static Optional<Module> STAFFCHAT = service.getModule("staffchat");
//Better /stop and /restart commands (Time?)
public static Optional<Module> STOPRESTART = service.getModule("stoprestart");
public static Optional<Module> SUDO = service.getModule("sudo");
//Animated, refresh every x seconds
public static Optional<Module> TABLIST = service.getModule("tablist");
//Split the /teleport command better
public static Optional<Module> TELEPORT = service.getModule("teleport");
//Teleport to a random location, include /biometp
public static Optional<Module> TELEPORTRANDOM = service.getModule("teleportrandom");
public static Optional<Module> TIME = service.getModule("time");
//Timber
public static Optional<Module> TREE = service.getModule("tree");
//Change the unknown command message
public static Optional<Module> UNKNOWNCOMMAND = service.getModule("unknowncommand");
public static Optional<Module> UPDATE = service.getModule("update");
public static Optional<Module> VANISH = service.getModule("vanish");
public static Optional<Module> VILLAGER = service.getModule("villager");
//Votifier module
public static Optional<Module> VOTIFIER = service.getModule("votifier");
public static Optional<Module> WARP = service.getModule("warp");
public static Optional<Module> WEATHER = service.getModule("weather");
//Stop using flags, use seperate commands & clickable chat interface
public static Optional<Module> WORLD = service.getModule("world");
public static Optional<Module> WORLDBORDER = service.getModule("worldborder");
public static Optional<Module> WORLDINVENTORIES = service.getModule("worldinventories");
//TODO /smelt command?
public static Optional<Module> get(String id) {
return service.getModule(id);
}
}
|
145197_3 | package jonathan.jaron.boodschappenVergelijkerBackend.service;
import com.beust.ah.A;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import jonathan.jaron.boodschappenVergelijkerBackend.model.ProductDto;
import jonathan.jaron.boodschappenVergelijkerBackend.model.SupermarktDto;
import jonathan.jaron.boodschappenVergelijkerBackend.repository.ProductRepository;
import jonathan.jaron.boodschappenVergelijkerBackend.repository.SupermarktRepository;
import jonathan.jaron.boodschappenVergelijkerBackend.tools.ConsoleColors;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.w3c.dom.NodeList;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
@Service
public class ImageGetterService {
double time_now = System.currentTimeMillis();
double last_ah = time_now;
double last_jumbo= time_now;
double last_aldi= time_now;
double last_coop= time_now;
double last_vomar= time_now;
double last_spar= time_now;
double last_dirk= time_now;
int last_coop_id = 30505;
double progressAmount = 0.0;
@Autowired
private HtmlService htmlService;
private final SupermarktRepository supermarktRepository;
private final ProductRepository productRepository;
@Autowired
public ImageGetterService(SupermarktRepository supermarktRepository, ProductRepository productRepository) {
this.supermarktRepository = supermarktRepository;
this.productRepository = productRepository;
}
public int getRandomNumber(int min, int max) {
return (int) ((Math.random() * (max - min)) + min);
}
public void getImages() throws InterruptedException, IOException {
List<SupermarktDto> supermarktList = supermarktRepository.findAll();
Thread progress = new Thread(){
public void run(){
while(true) {
int amountOfProducts = 0;
int amountOfProductsWithUrl = 0;
for (SupermarktDto supermarkt : supermarktList) {
List<ProductDto> productList = supermarkt.getProducten();
for (ProductDto selpro : productList) {
amountOfProducts++;
if (selpro.getImageUrl() != null) {
amountOfProductsWithUrl++;
}
}
}
progressAmount = ((double) amountOfProductsWithUrl /amountOfProducts) * 100;
try {
Thread.sleep(30000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
};
Thread last = new Thread(){
public void run(){
while (true){
double last_ah_local = System.currentTimeMillis() - last_ah;
System.out.println("Laatste AH: \t\t" + last_ah_local);
double last_jumbo_local = System.currentTimeMillis() - last_jumbo;
System.out.println("Laatste Jumbo: \t\t" + last_jumbo_local);
double last_aldi_local = System.currentTimeMillis() - last_aldi;
System.out.println("Laatste Aldi: \t\t" + last_aldi_local);
double last_coop_local = System.currentTimeMillis() - last_coop;
System.out.println("Laatste Coop: \t\t" + last_coop_local);
double last_vomar_local = System.currentTimeMillis() - last_vomar;
System.out.println("Laatste Vomar: \t\t" + last_vomar_local);
double last_spar_local = System.currentTimeMillis() - last_spar;
System.out.println("Laatste Spar: \t\t" + last_spar_local);
double last_dirk_local = System.currentTimeMillis() - last_dirk;
System.out.println("Laatste Dirk: \t\t" + last_dirk_local);
System.out.println(ConsoleColors.ANSI_GREEN + "Progressie: " + progressAmount +"%" + ConsoleColors.ANSI_RESET);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
};
Thread ah1 = new Thread() {
public void run() {
for (SupermarktDto supermarkt : supermarktList) {
String rootUrl = supermarkt.getUrl().strip();
List<ProductDto> productList = supermarkt.getProducten();
int productListSize = productList.size();
int count = 0;
for (ProductDto product : productList) {
if (supermarkt.getNaam().equals("ah")) {
if (product.getImageUrl() == null) {
try {
Thread.sleep(getRandomNumber(1500, 2500));
} catch (InterruptedException e) {
continue;
}
String productUrl = product.getUrl().strip();
String imagePageUrl = rootUrl + productUrl;
URL url = null;
try {
url = new URL(imagePageUrl);
} catch (MalformedURLException e) {
continue;
}
InputStream is = null;
try {
is = url.openStream();
} catch (IOException e) {
continue;
}
int ptr = 0;
StringBuffer buffer = new StringBuffer();
while (true) {
try {
if (!((ptr = is.read()) != -1)) break;
} catch (IOException e) {
continue;
}
buffer.append((char) ptr);
}
String bufferStr = buffer.toString();
BufferedReader bufReader = new BufferedReader(new StringReader(bufferStr));
String line = null;
String imageUrl = "";
int index = 0;
ArrayList<String> stringList = new ArrayList<>();
while (true) {
try {
if (!((line = bufReader.readLine()) != null)) break;
} catch (IOException e) {
continue;
}
line = line.replace("\\u002F", "/");
String[] lines = line.split(",");
for (String selLine : lines) {
if (selLine.contains("800x800")) {
stringList.add(selLine.split("\"")[3]);
break;
}
}
}
//System.out.println("\nProduct gezocht voor " + product.getNaam() + "supermarkt: " + supermarkt.getNaam());
try {
String productImgUrl = stringList.get(0);
//System.out.println("Gevonden IMG Url: \t" + ConsoleColors.ANSI_GREEN + productImgUrl + ConsoleColors.ANSI_RESET);
product.setImageUrl(productImgUrl);
productRepository.save(product);
//System.out.println(ConsoleColors.ANSI_GREEN + "Progressie: " + progressAmount +"%" + ConsoleColors.ANSI_RESET);
last_ah = System.currentTimeMillis();
} catch (Exception e) {
System.out.println(ConsoleColors.ANSI_RED + "URL NIET GEVONDEN" + ConsoleColors.ANSI_RESET);
continue;
}
}
}
}
}
}
};
Thread aldi = new Thread() {
public void run() {
for (SupermarktDto supermarkt : supermarktList) {
String rootUrl = supermarkt.getUrl().strip();
List<ProductDto> productList = supermarkt.getProducten();
int productListSize = productList.size();
int count = 0;
for (ProductDto product : productList) {
if (supermarkt.getNaam().equals("aldi")) {
if (product.getImageUrl() == null) {
try {
Thread.sleep(getRandomNumber(1500, 2500));
} catch (InterruptedException e) {
continue;
}
String productUrl = product.getUrl().strip();
String imagePageUrl = productUrl;
URL url = null;
try {
url = new URL(imagePageUrl);
} catch (MalformedURLException e) {
continue;
}
InputStream is = null;
try {
is = url.openStream();
} catch (IOException e) {
continue;
}
int ptr = 0;
StringBuffer buffer = new StringBuffer();
while (true) {
try {
if ((ptr = is.read()) == -1) break;
} catch (IOException e) {
continue;
}
buffer.append((char) ptr);
}
String bufferStr = buffer.toString();
//System.out.println(bufferStr);
BufferedReader bufReader = new BufferedReader(new StringReader(bufferStr));
String line = null;
int index = 0;
ArrayList<String> stringList = new ArrayList<>();
while (true) {
try {
if (!((line = bufReader.readLine()) != null)) break;
} catch (IOException e) {
continue;
}
if (line.contains("png")) {
index++;
line = line.strip();
stringList.add(line);
//Index 1
}
}
//System.out.println("\nProduct gezocht voor " + product.getNaam() + "supermarkt: " + supermarkt.getNaam());
try {
String productImgUrl = stringList.get(0).split("\"")[3];
//System.out.println("Gevonden IMG Url: \t" + ConsoleColors.ANSI_GREEN + productImgUrl + ConsoleColors.ANSI_RESET);
product.setImageUrl(productImgUrl);
productRepository.save(product);
//System.out.println(ConsoleColors.ANSI_GREEN + "Progressie: " + progressAmount +"%" + ConsoleColors.ANSI_RESET);
last_aldi = System.currentTimeMillis();
} catch (Exception e) {
System.out.println(ConsoleColors.ANSI_RED + "URL NIET GEVONDEN" + ConsoleColors.ANSI_RESET);
continue;
}
}
}
}
}
}
};
Thread dirk = new Thread() {
public void run() {
for (SupermarktDto supermarkt : supermarktList) {
String rootUrl = supermarkt.getUrl().strip();
List<ProductDto> productList = supermarkt.getProducten();
int productListSize = productList.size();
int count = 0;
for (ProductDto product : productList) {
if (supermarkt.getNaam().equals("dirk")) {
if (product.getImageUrl() == null) {
try {
Thread.sleep(getRandomNumber(1500, 2500));
} catch (InterruptedException e) {
continue;
}
String productUrl = product.getUrl().strip();
String imagePageUrl = rootUrl + productUrl;
URL url = null;
try {
url = new URL(imagePageUrl);
} catch (MalformedURLException e) {
continue;
}
InputStream is = null;
try {
is = url.openStream();
} catch (IOException e) {
continue;
}
int ptr = 0;
StringBuffer buffer = new StringBuffer();
while (true) {
try {
if (!((ptr = is.read()) != -1)) break;
} catch (IOException e) {
continue;
}
buffer.append((char) ptr);
}
String bufferStr = buffer.toString();
bufferStr = bufferStr.replace(" ", "\n");
BufferedReader bufReader = new BufferedReader(new StringReader(bufferStr));
String line = null;
int index = 0;
ArrayList<String> stringList = new ArrayList<>();
while (true) {
try {
if (!((line = bufReader.readLine()) != null)) break;
} catch (IOException e) {
continue;
}
if (line.contains("&")) {
index++;
line = line.strip();
stringList.add(line);
}
}
//System.out.println("\nProduct gezocht voor " + product.getNaam() + "supermarkt: " + supermarkt.getNaam());
try {
String productImgUrl = stringList.get(0).split("\"")[1];
//System.out.println("Gevonden IMG Url: \t" + ConsoleColors.ANSI_GREEN + productImgUrl + ConsoleColors.ANSI_RESET);
product.setImageUrl(productImgUrl);
productRepository.save(product);
//System.out.println(ConsoleColors.ANSI_GREEN + "Progressie: " + progressAmount +"%" + ConsoleColors.ANSI_RESET);
last_dirk = System.currentTimeMillis();
} catch (Exception e) {
System.out.println(ConsoleColors.ANSI_RED + "URL NIET GEVONDEN" + ConsoleColors.ANSI_RESET);
continue;
}
}
}
}
}
}
};
Thread jumbo = new Thread() {
public void run() {
for (SupermarktDto supermarkt : supermarktList) {
String rootUrl = supermarkt.getUrl().strip();
List<ProductDto> productList = supermarkt.getProducten();
int productListSize = productList.size();
int count = 0;
for (ProductDto product : productList) {
if (supermarkt.getNaam().equals("jumbo")) {
if (product.getImageUrl() == null) {
try {
Thread.sleep(getRandomNumber(1500, 2500));
} catch (InterruptedException e) {
continue;
}
String productUrl = product.getUrl().strip();
String imagePageUrl = rootUrl + productUrl;
URL url = null;
try {
url = new URL(imagePageUrl);
} catch (MalformedURLException e) {
continue;
}
InputStream is = null;
try {
is = url.openStream();
} catch (IOException e) {
continue;
}
int ptr = 0;
StringBuffer buffer = new StringBuffer();
while (true) {
try {
if (!((ptr = is.read()) != -1)) break;
} catch (IOException e) {
continue;
}
buffer.append((char) ptr);
}
String bufferStr = buffer.toString();
bufferStr = bufferStr.replace(" ", "\n");
BufferedReader bufReader = new BufferedReader(new StringReader(bufferStr));
String line = null;
int index = 0;
ArrayList<String> stringList = new ArrayList<>();
while (true) {
try {
if (!((line = bufReader.readLine()) != null)) break;
} catch (IOException e) {
continue;
}
if (line.contains(".png")) {
line = line.strip();
index++;
stringList.add(line);
}
}
//System.out.println("\nProduct gezocht voor " + product.getNaam() + "supermarkt: " + supermarkt.getNaam());
try {
String productImgUrl = stringList.get(3).split("\"")[1];
//System.out.println("Gevonden IMG Url: \t" + ConsoleColors.ANSI_GREEN + productImgUrl + ConsoleColors.ANSI_RESET);
product.setImageUrl(productImgUrl);
productRepository.save(product);
//System.out.println(ConsoleColors.ANSI_GREEN + "Progressie: " + progressAmount +"%" + ConsoleColors.ANSI_RESET);
last_jumbo = System.currentTimeMillis();
} catch (Exception e) {
System.out.println(ConsoleColors.ANSI_RED + "URL NIET GEVONDEN" + ConsoleColors.ANSI_RESET);
continue;
}
}
}
}
}
}
};
Thread spar = new Thread() {
public void run() {
for (SupermarktDto supermarkt : supermarktList) {
String rootUrl = supermarkt.getUrl().strip();
List<ProductDto> productList = supermarkt.getProducten();
int productListSize = productList.size();
int count = 0;
for (ProductDto product : productList) {
if (supermarkt.getNaam().equals("spar")) {
if(product.getImageUrl() == null){
try {
Thread.sleep(getRandomNumber(1500, 2500));
} catch (InterruptedException e) {
continue;
}
String productUrl = product.getUrl().strip();
String imagePageUrl = rootUrl + productUrl;
URL url = null;
try {
url = new URL(imagePageUrl);
} catch (MalformedURLException e) {
continue;
}
InputStream is = null;
try {
is = url.openStream();
} catch (IOException e) {
continue;
}
int ptr = 0;
StringBuffer buffer = new StringBuffer();
while (true) {
try {
if (!((ptr = is.read()) != -1)) break;
} catch (IOException e) {
continue;
}
buffer.append((char) ptr);
}
String bufferStr = buffer.toString();
bufferStr = bufferStr.replace(" ", "\n");
BufferedReader bufReader = new BufferedReader(new StringReader(bufferStr));
String line = null;
int index = 0;
ArrayList<String> stringList = new ArrayList<>();
while (true) {
try {
if (!((line = bufReader.readLine()) != null)) break;
} catch (IOException e) {
continue;
}
if (line.contains("jpg")) {
line = line.strip();
index++;
stringList.add(line);
}
}
//System.out.println("\nProduct gezocht voor " + product.getNaam() + "supermarkt: " + supermarkt.getNaam());
try {
String productImgUrl = stringList.get(0).split("\"")[1];
//System.out.println("Gevonden IMG Url: \t" + ConsoleColors.ANSI_GREEN + productImgUrl + ConsoleColors.ANSI_RESET);
product.setImageUrl(productImgUrl);
productRepository.save(product);
//System.out.println(ConsoleColors.ANSI_GREEN + "Progressie: " + progressAmount +"%" + ConsoleColors.ANSI_RESET);
last_spar = System.currentTimeMillis();
} catch (Exception e) {
System.out.println(ConsoleColors.ANSI_RED + "URL NIET GEVONDEN" + ConsoleColors.ANSI_RESET);
continue;
}
}
}
}
}
}
};
Thread coop = new Thread() {
public void run() {
for (SupermarktDto supermarkt : supermarktList) {
String rootUrl = supermarkt.getUrl().strip();
List<ProductDto> productList = supermarkt.getProducten();
int productListSize = productList.size();
int count = 0;
for (ProductDto product : productList) {
if (supermarkt.getNaam().equals("coop")) {
if (product.getImageUrl() == null && product.getId() > last_coop_id) {
try {
Thread.sleep(getRandomNumber(1500, 2500));
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
String productUrl = product.getUrl().strip();
String imagePageUrl = rootUrl + productUrl;
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get(imagePageUrl);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
String content = driver.getPageSource();
content = content.replace(" ", "\n");
driver.quit();
//System.out.println(content);
BufferedReader bufReader = new BufferedReader(new StringReader(content));
String line = null;
int index = 0;
ArrayList<String> stringList = new ArrayList<>();
while (true) {
try {
if (!((line = bufReader.readLine()) != null)) break;
} catch (Exception e) {
continue;
}
if (line.contains("syndy")) {
index++;
line = line.strip();
//System.out.println(index + ": " + line);
stringList.add(line);
//1
}
}
//System.out.println("\nProduct gezocht voor " + product.getNaam() + "supermarkt: " + supermarkt.getNaam());
try {
String productImgUrl = stringList.get(0).split("\"")[1];
//System.out.println("Gevonden IMG Url: \t" + ConsoleColors.ANSI_GREEN + productImgUrl + ConsoleColors.ANSI_RESET);
product.setImageUrl(productImgUrl);
productRepository.save(product);
//System.out.println(ConsoleColors.ANSI_GREEN + "Progressie: " + progressAmount +"%" + ConsoleColors.ANSI_RESET);
last_coop = System.currentTimeMillis();
} catch (Exception e) {
System.out.println(ConsoleColors.ANSI_RED + "URL NIET GEVONDEN" + ConsoleColors.ANSI_RESET);
continue;
}
}
}
}
}
}
};
Thread vomar = new Thread() {
public void run() {
for (SupermarktDto supermarkt : supermarktList) {
String rootUrl = supermarkt.getUrl().strip();
List<ProductDto> productList = supermarkt.getProducten();
int productListSize = productList.size();
int count = 0;
for (ProductDto product : productList) {
if (supermarkt.getNaam().equals("vomar")) {
if(product.getImageUrl() == null){
try {
Thread.sleep(getRandomNumber(1500, 2500));
} catch (InterruptedException e) {
continue;
}
String productUrl = product.getUrl().strip();
String imagePageUrl = rootUrl + productUrl;
URL url = null;
try {
url = new URL(imagePageUrl);
} catch (MalformedURLException e) {
continue;
}
InputStream is = null;
try {
is = url.openStream();
} catch (IOException e) {
continue;
}
int ptr = 0;
StringBuffer buffer = new StringBuffer();
while (true) {
try {
if (!((ptr = is.read()) != -1)) break;
} catch (IOException e) {
continue;
}
buffer.append((char) ptr);
}
String bufferStr = buffer.toString();
bufferStr = bufferStr.replace(" ", "\n");
BufferedReader bufReader = new BufferedReader(new StringReader(bufferStr));
String line = null;
int index = 0;
ArrayList<String> stringList = new ArrayList<>();
while (true) {
try {
if (!((line = bufReader.readLine()) != null)) break;
} catch (IOException e) {
continue;
}
if (line.contains("png")) {
line = line.strip();
index++;
stringList.add(line);
}
}
//System.out.println("\nProduct gezocht voor " + product.getNaam() + "supermarkt: " + supermarkt.getNaam());
try {
String productImgUrl = stringList.get(0).split("\"")[1];
//System.out.println("Gevonden IMG Url: \t" + ConsoleColors.ANSI_GREEN + productImgUrl + ConsoleColors.ANSI_RESET);
product.setImageUrl(productImgUrl);
productRepository.save(product);
//System.out.println(ConsoleColors.ANSI_GREEN + "Progressie: " + progressAmount +"%" + ConsoleColors.ANSI_RESET);
last_vomar = System.currentTimeMillis();
} catch (Exception e) {
System.out.println(ConsoleColors.ANSI_RED + "URL NIET GEVONDEN" + ConsoleColors.ANSI_RESET);
continue;
}
}
}
}
}
}
};
System.out.println("running ah1");
//ah1.start();
System.out.println("running aldi");
//aldi.start();
System.out.println("running dirk");
//dirk.start();
System.out.println("running jumbo");
//jumbo.start();
System.out.println("running vomar");
//vomar.start();
System.out.println("running spar");
//spar.start();
System.out.println("running coop");
coop.start();
progress.start();
last.start();
}
}
| JonathanKlimp/boodschappen_vergelijker | boodschappenVergelijkerBackend/src/main/java/jonathan/jaron/boodschappenVergelijkerBackend/service/ImageGetterService.java | 8,127 | //System.out.println("\nProduct gezocht voor " + product.getNaam() + "supermarkt: " + supermarkt.getNaam()); | line_comment | nl | package jonathan.jaron.boodschappenVergelijkerBackend.service;
import com.beust.ah.A;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import jonathan.jaron.boodschappenVergelijkerBackend.model.ProductDto;
import jonathan.jaron.boodschappenVergelijkerBackend.model.SupermarktDto;
import jonathan.jaron.boodschappenVergelijkerBackend.repository.ProductRepository;
import jonathan.jaron.boodschappenVergelijkerBackend.repository.SupermarktRepository;
import jonathan.jaron.boodschappenVergelijkerBackend.tools.ConsoleColors;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.w3c.dom.NodeList;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
@Service
public class ImageGetterService {
double time_now = System.currentTimeMillis();
double last_ah = time_now;
double last_jumbo= time_now;
double last_aldi= time_now;
double last_coop= time_now;
double last_vomar= time_now;
double last_spar= time_now;
double last_dirk= time_now;
int last_coop_id = 30505;
double progressAmount = 0.0;
@Autowired
private HtmlService htmlService;
private final SupermarktRepository supermarktRepository;
private final ProductRepository productRepository;
@Autowired
public ImageGetterService(SupermarktRepository supermarktRepository, ProductRepository productRepository) {
this.supermarktRepository = supermarktRepository;
this.productRepository = productRepository;
}
public int getRandomNumber(int min, int max) {
return (int) ((Math.random() * (max - min)) + min);
}
public void getImages() throws InterruptedException, IOException {
List<SupermarktDto> supermarktList = supermarktRepository.findAll();
Thread progress = new Thread(){
public void run(){
while(true) {
int amountOfProducts = 0;
int amountOfProductsWithUrl = 0;
for (SupermarktDto supermarkt : supermarktList) {
List<ProductDto> productList = supermarkt.getProducten();
for (ProductDto selpro : productList) {
amountOfProducts++;
if (selpro.getImageUrl() != null) {
amountOfProductsWithUrl++;
}
}
}
progressAmount = ((double) amountOfProductsWithUrl /amountOfProducts) * 100;
try {
Thread.sleep(30000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
};
Thread last = new Thread(){
public void run(){
while (true){
double last_ah_local = System.currentTimeMillis() - last_ah;
System.out.println("Laatste AH: \t\t" + last_ah_local);
double last_jumbo_local = System.currentTimeMillis() - last_jumbo;
System.out.println("Laatste Jumbo: \t\t" + last_jumbo_local);
double last_aldi_local = System.currentTimeMillis() - last_aldi;
System.out.println("Laatste Aldi: \t\t" + last_aldi_local);
double last_coop_local = System.currentTimeMillis() - last_coop;
System.out.println("Laatste Coop: \t\t" + last_coop_local);
double last_vomar_local = System.currentTimeMillis() - last_vomar;
System.out.println("Laatste Vomar: \t\t" + last_vomar_local);
double last_spar_local = System.currentTimeMillis() - last_spar;
System.out.println("Laatste Spar: \t\t" + last_spar_local);
double last_dirk_local = System.currentTimeMillis() - last_dirk;
System.out.println("Laatste Dirk: \t\t" + last_dirk_local);
System.out.println(ConsoleColors.ANSI_GREEN + "Progressie: " + progressAmount +"%" + ConsoleColors.ANSI_RESET);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
};
Thread ah1 = new Thread() {
public void run() {
for (SupermarktDto supermarkt : supermarktList) {
String rootUrl = supermarkt.getUrl().strip();
List<ProductDto> productList = supermarkt.getProducten();
int productListSize = productList.size();
int count = 0;
for (ProductDto product : productList) {
if (supermarkt.getNaam().equals("ah")) {
if (product.getImageUrl() == null) {
try {
Thread.sleep(getRandomNumber(1500, 2500));
} catch (InterruptedException e) {
continue;
}
String productUrl = product.getUrl().strip();
String imagePageUrl = rootUrl + productUrl;
URL url = null;
try {
url = new URL(imagePageUrl);
} catch (MalformedURLException e) {
continue;
}
InputStream is = null;
try {
is = url.openStream();
} catch (IOException e) {
continue;
}
int ptr = 0;
StringBuffer buffer = new StringBuffer();
while (true) {
try {
if (!((ptr = is.read()) != -1)) break;
} catch (IOException e) {
continue;
}
buffer.append((char) ptr);
}
String bufferStr = buffer.toString();
BufferedReader bufReader = new BufferedReader(new StringReader(bufferStr));
String line = null;
String imageUrl = "";
int index = 0;
ArrayList<String> stringList = new ArrayList<>();
while (true) {
try {
if (!((line = bufReader.readLine()) != null)) break;
} catch (IOException e) {
continue;
}
line = line.replace("\\u002F", "/");
String[] lines = line.split(",");
for (String selLine : lines) {
if (selLine.contains("800x800")) {
stringList.add(selLine.split("\"")[3]);
break;
}
}
}
//System.out.println("\nProduct gezocht voor " + product.getNaam() + "supermarkt: " + supermarkt.getNaam());
try {
String productImgUrl = stringList.get(0);
//System.out.println("Gevonden IMG Url: \t" + ConsoleColors.ANSI_GREEN + productImgUrl + ConsoleColors.ANSI_RESET);
product.setImageUrl(productImgUrl);
productRepository.save(product);
//System.out.println(ConsoleColors.ANSI_GREEN + "Progressie: " + progressAmount +"%" + ConsoleColors.ANSI_RESET);
last_ah = System.currentTimeMillis();
} catch (Exception e) {
System.out.println(ConsoleColors.ANSI_RED + "URL NIET GEVONDEN" + ConsoleColors.ANSI_RESET);
continue;
}
}
}
}
}
}
};
Thread aldi = new Thread() {
public void run() {
for (SupermarktDto supermarkt : supermarktList) {
String rootUrl = supermarkt.getUrl().strip();
List<ProductDto> productList = supermarkt.getProducten();
int productListSize = productList.size();
int count = 0;
for (ProductDto product : productList) {
if (supermarkt.getNaam().equals("aldi")) {
if (product.getImageUrl() == null) {
try {
Thread.sleep(getRandomNumber(1500, 2500));
} catch (InterruptedException e) {
continue;
}
String productUrl = product.getUrl().strip();
String imagePageUrl = productUrl;
URL url = null;
try {
url = new URL(imagePageUrl);
} catch (MalformedURLException e) {
continue;
}
InputStream is = null;
try {
is = url.openStream();
} catch (IOException e) {
continue;
}
int ptr = 0;
StringBuffer buffer = new StringBuffer();
while (true) {
try {
if ((ptr = is.read()) == -1) break;
} catch (IOException e) {
continue;
}
buffer.append((char) ptr);
}
String bufferStr = buffer.toString();
//System.out.println(bufferStr);
BufferedReader bufReader = new BufferedReader(new StringReader(bufferStr));
String line = null;
int index = 0;
ArrayList<String> stringList = new ArrayList<>();
while (true) {
try {
if (!((line = bufReader.readLine()) != null)) break;
} catch (IOException e) {
continue;
}
if (line.contains("png")) {
index++;
line = line.strip();
stringList.add(line);
//Index 1
}
}
//System.out.println("\nProduct gezocht<SUF>
try {
String productImgUrl = stringList.get(0).split("\"")[3];
//System.out.println("Gevonden IMG Url: \t" + ConsoleColors.ANSI_GREEN + productImgUrl + ConsoleColors.ANSI_RESET);
product.setImageUrl(productImgUrl);
productRepository.save(product);
//System.out.println(ConsoleColors.ANSI_GREEN + "Progressie: " + progressAmount +"%" + ConsoleColors.ANSI_RESET);
last_aldi = System.currentTimeMillis();
} catch (Exception e) {
System.out.println(ConsoleColors.ANSI_RED + "URL NIET GEVONDEN" + ConsoleColors.ANSI_RESET);
continue;
}
}
}
}
}
}
};
Thread dirk = new Thread() {
public void run() {
for (SupermarktDto supermarkt : supermarktList) {
String rootUrl = supermarkt.getUrl().strip();
List<ProductDto> productList = supermarkt.getProducten();
int productListSize = productList.size();
int count = 0;
for (ProductDto product : productList) {
if (supermarkt.getNaam().equals("dirk")) {
if (product.getImageUrl() == null) {
try {
Thread.sleep(getRandomNumber(1500, 2500));
} catch (InterruptedException e) {
continue;
}
String productUrl = product.getUrl().strip();
String imagePageUrl = rootUrl + productUrl;
URL url = null;
try {
url = new URL(imagePageUrl);
} catch (MalformedURLException e) {
continue;
}
InputStream is = null;
try {
is = url.openStream();
} catch (IOException e) {
continue;
}
int ptr = 0;
StringBuffer buffer = new StringBuffer();
while (true) {
try {
if (!((ptr = is.read()) != -1)) break;
} catch (IOException e) {
continue;
}
buffer.append((char) ptr);
}
String bufferStr = buffer.toString();
bufferStr = bufferStr.replace(" ", "\n");
BufferedReader bufReader = new BufferedReader(new StringReader(bufferStr));
String line = null;
int index = 0;
ArrayList<String> stringList = new ArrayList<>();
while (true) {
try {
if (!((line = bufReader.readLine()) != null)) break;
} catch (IOException e) {
continue;
}
if (line.contains("&")) {
index++;
line = line.strip();
stringList.add(line);
}
}
//System.out.println("\nProduct gezocht voor " + product.getNaam() + "supermarkt: " + supermarkt.getNaam());
try {
String productImgUrl = stringList.get(0).split("\"")[1];
//System.out.println("Gevonden IMG Url: \t" + ConsoleColors.ANSI_GREEN + productImgUrl + ConsoleColors.ANSI_RESET);
product.setImageUrl(productImgUrl);
productRepository.save(product);
//System.out.println(ConsoleColors.ANSI_GREEN + "Progressie: " + progressAmount +"%" + ConsoleColors.ANSI_RESET);
last_dirk = System.currentTimeMillis();
} catch (Exception e) {
System.out.println(ConsoleColors.ANSI_RED + "URL NIET GEVONDEN" + ConsoleColors.ANSI_RESET);
continue;
}
}
}
}
}
}
};
Thread jumbo = new Thread() {
public void run() {
for (SupermarktDto supermarkt : supermarktList) {
String rootUrl = supermarkt.getUrl().strip();
List<ProductDto> productList = supermarkt.getProducten();
int productListSize = productList.size();
int count = 0;
for (ProductDto product : productList) {
if (supermarkt.getNaam().equals("jumbo")) {
if (product.getImageUrl() == null) {
try {
Thread.sleep(getRandomNumber(1500, 2500));
} catch (InterruptedException e) {
continue;
}
String productUrl = product.getUrl().strip();
String imagePageUrl = rootUrl + productUrl;
URL url = null;
try {
url = new URL(imagePageUrl);
} catch (MalformedURLException e) {
continue;
}
InputStream is = null;
try {
is = url.openStream();
} catch (IOException e) {
continue;
}
int ptr = 0;
StringBuffer buffer = new StringBuffer();
while (true) {
try {
if (!((ptr = is.read()) != -1)) break;
} catch (IOException e) {
continue;
}
buffer.append((char) ptr);
}
String bufferStr = buffer.toString();
bufferStr = bufferStr.replace(" ", "\n");
BufferedReader bufReader = new BufferedReader(new StringReader(bufferStr));
String line = null;
int index = 0;
ArrayList<String> stringList = new ArrayList<>();
while (true) {
try {
if (!((line = bufReader.readLine()) != null)) break;
} catch (IOException e) {
continue;
}
if (line.contains(".png")) {
line = line.strip();
index++;
stringList.add(line);
}
}
//System.out.println("\nProduct gezocht voor " + product.getNaam() + "supermarkt: " + supermarkt.getNaam());
try {
String productImgUrl = stringList.get(3).split("\"")[1];
//System.out.println("Gevonden IMG Url: \t" + ConsoleColors.ANSI_GREEN + productImgUrl + ConsoleColors.ANSI_RESET);
product.setImageUrl(productImgUrl);
productRepository.save(product);
//System.out.println(ConsoleColors.ANSI_GREEN + "Progressie: " + progressAmount +"%" + ConsoleColors.ANSI_RESET);
last_jumbo = System.currentTimeMillis();
} catch (Exception e) {
System.out.println(ConsoleColors.ANSI_RED + "URL NIET GEVONDEN" + ConsoleColors.ANSI_RESET);
continue;
}
}
}
}
}
}
};
Thread spar = new Thread() {
public void run() {
for (SupermarktDto supermarkt : supermarktList) {
String rootUrl = supermarkt.getUrl().strip();
List<ProductDto> productList = supermarkt.getProducten();
int productListSize = productList.size();
int count = 0;
for (ProductDto product : productList) {
if (supermarkt.getNaam().equals("spar")) {
if(product.getImageUrl() == null){
try {
Thread.sleep(getRandomNumber(1500, 2500));
} catch (InterruptedException e) {
continue;
}
String productUrl = product.getUrl().strip();
String imagePageUrl = rootUrl + productUrl;
URL url = null;
try {
url = new URL(imagePageUrl);
} catch (MalformedURLException e) {
continue;
}
InputStream is = null;
try {
is = url.openStream();
} catch (IOException e) {
continue;
}
int ptr = 0;
StringBuffer buffer = new StringBuffer();
while (true) {
try {
if (!((ptr = is.read()) != -1)) break;
} catch (IOException e) {
continue;
}
buffer.append((char) ptr);
}
String bufferStr = buffer.toString();
bufferStr = bufferStr.replace(" ", "\n");
BufferedReader bufReader = new BufferedReader(new StringReader(bufferStr));
String line = null;
int index = 0;
ArrayList<String> stringList = new ArrayList<>();
while (true) {
try {
if (!((line = bufReader.readLine()) != null)) break;
} catch (IOException e) {
continue;
}
if (line.contains("jpg")) {
line = line.strip();
index++;
stringList.add(line);
}
}
//System.out.println("\nProduct gezocht voor " + product.getNaam() + "supermarkt: " + supermarkt.getNaam());
try {
String productImgUrl = stringList.get(0).split("\"")[1];
//System.out.println("Gevonden IMG Url: \t" + ConsoleColors.ANSI_GREEN + productImgUrl + ConsoleColors.ANSI_RESET);
product.setImageUrl(productImgUrl);
productRepository.save(product);
//System.out.println(ConsoleColors.ANSI_GREEN + "Progressie: " + progressAmount +"%" + ConsoleColors.ANSI_RESET);
last_spar = System.currentTimeMillis();
} catch (Exception e) {
System.out.println(ConsoleColors.ANSI_RED + "URL NIET GEVONDEN" + ConsoleColors.ANSI_RESET);
continue;
}
}
}
}
}
}
};
Thread coop = new Thread() {
public void run() {
for (SupermarktDto supermarkt : supermarktList) {
String rootUrl = supermarkt.getUrl().strip();
List<ProductDto> productList = supermarkt.getProducten();
int productListSize = productList.size();
int count = 0;
for (ProductDto product : productList) {
if (supermarkt.getNaam().equals("coop")) {
if (product.getImageUrl() == null && product.getId() > last_coop_id) {
try {
Thread.sleep(getRandomNumber(1500, 2500));
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
String productUrl = product.getUrl().strip();
String imagePageUrl = rootUrl + productUrl;
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get(imagePageUrl);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
String content = driver.getPageSource();
content = content.replace(" ", "\n");
driver.quit();
//System.out.println(content);
BufferedReader bufReader = new BufferedReader(new StringReader(content));
String line = null;
int index = 0;
ArrayList<String> stringList = new ArrayList<>();
while (true) {
try {
if (!((line = bufReader.readLine()) != null)) break;
} catch (Exception e) {
continue;
}
if (line.contains("syndy")) {
index++;
line = line.strip();
//System.out.println(index + ": " + line);
stringList.add(line);
//1
}
}
//System.out.println("\nProduct gezocht voor " + product.getNaam() + "supermarkt: " + supermarkt.getNaam());
try {
String productImgUrl = stringList.get(0).split("\"")[1];
//System.out.println("Gevonden IMG Url: \t" + ConsoleColors.ANSI_GREEN + productImgUrl + ConsoleColors.ANSI_RESET);
product.setImageUrl(productImgUrl);
productRepository.save(product);
//System.out.println(ConsoleColors.ANSI_GREEN + "Progressie: " + progressAmount +"%" + ConsoleColors.ANSI_RESET);
last_coop = System.currentTimeMillis();
} catch (Exception e) {
System.out.println(ConsoleColors.ANSI_RED + "URL NIET GEVONDEN" + ConsoleColors.ANSI_RESET);
continue;
}
}
}
}
}
}
};
Thread vomar = new Thread() {
public void run() {
for (SupermarktDto supermarkt : supermarktList) {
String rootUrl = supermarkt.getUrl().strip();
List<ProductDto> productList = supermarkt.getProducten();
int productListSize = productList.size();
int count = 0;
for (ProductDto product : productList) {
if (supermarkt.getNaam().equals("vomar")) {
if(product.getImageUrl() == null){
try {
Thread.sleep(getRandomNumber(1500, 2500));
} catch (InterruptedException e) {
continue;
}
String productUrl = product.getUrl().strip();
String imagePageUrl = rootUrl + productUrl;
URL url = null;
try {
url = new URL(imagePageUrl);
} catch (MalformedURLException e) {
continue;
}
InputStream is = null;
try {
is = url.openStream();
} catch (IOException e) {
continue;
}
int ptr = 0;
StringBuffer buffer = new StringBuffer();
while (true) {
try {
if (!((ptr = is.read()) != -1)) break;
} catch (IOException e) {
continue;
}
buffer.append((char) ptr);
}
String bufferStr = buffer.toString();
bufferStr = bufferStr.replace(" ", "\n");
BufferedReader bufReader = new BufferedReader(new StringReader(bufferStr));
String line = null;
int index = 0;
ArrayList<String> stringList = new ArrayList<>();
while (true) {
try {
if (!((line = bufReader.readLine()) != null)) break;
} catch (IOException e) {
continue;
}
if (line.contains("png")) {
line = line.strip();
index++;
stringList.add(line);
}
}
//System.out.println("\nProduct gezocht voor " + product.getNaam() + "supermarkt: " + supermarkt.getNaam());
try {
String productImgUrl = stringList.get(0).split("\"")[1];
//System.out.println("Gevonden IMG Url: \t" + ConsoleColors.ANSI_GREEN + productImgUrl + ConsoleColors.ANSI_RESET);
product.setImageUrl(productImgUrl);
productRepository.save(product);
//System.out.println(ConsoleColors.ANSI_GREEN + "Progressie: " + progressAmount +"%" + ConsoleColors.ANSI_RESET);
last_vomar = System.currentTimeMillis();
} catch (Exception e) {
System.out.println(ConsoleColors.ANSI_RED + "URL NIET GEVONDEN" + ConsoleColors.ANSI_RESET);
continue;
}
}
}
}
}
}
};
System.out.println("running ah1");
//ah1.start();
System.out.println("running aldi");
//aldi.start();
System.out.println("running dirk");
//dirk.start();
System.out.println("running jumbo");
//jumbo.start();
System.out.println("running vomar");
//vomar.start();
System.out.println("running spar");
//spar.start();
System.out.println("running coop");
coop.start();
progress.start();
last.start();
}
}
|
35787_0 | package be.leerstad.collections.map;
import java.util.SortedMap;
import java.util.TreeMap;
/**
* @author Peter Hardeel
*/
public class SortedMapDemo {
public static void main(String[] args) {
SortedMap<Integer, String> map = new TreeMap<>();
map.put(new Integer(1), "een");
map.put(new Integer(2), "twee");
map.put(new Integer(3), "drie");
map.put(new Integer(4), "vier");
map.put(new Integer(5), "vijf");
map.put(new Integer(6), "zes");
System.out.println(map.entrySet());
System.out.println(map.values());
System.out.println(map.keySet());
System.out.println(map.firstKey());
System.out.println(map.lastKey());
//submap
System.out.println(map.subMap(new Integer(2), new Integer(5)));
//headMap
System.out.println(map.headMap(new Integer(3)));
//tailmap
System.out.println(map.tailMap(new Integer(3)));
}
}
| Jonathandlm/B1-Programmeren-3 | Code/collections/map/SortedMapDemo.java | 314 | /**
* @author Peter Hardeel
*/ | block_comment | nl | package be.leerstad.collections.map;
import java.util.SortedMap;
import java.util.TreeMap;
/**
* @author Peter Hardeel<SUF>*/
public class SortedMapDemo {
public static void main(String[] args) {
SortedMap<Integer, String> map = new TreeMap<>();
map.put(new Integer(1), "een");
map.put(new Integer(2), "twee");
map.put(new Integer(3), "drie");
map.put(new Integer(4), "vier");
map.put(new Integer(5), "vijf");
map.put(new Integer(6), "zes");
System.out.println(map.entrySet());
System.out.println(map.values());
System.out.println(map.keySet());
System.out.println(map.firstKey());
System.out.println(map.lastKey());
//submap
System.out.println(map.subMap(new Integer(2), new Integer(5)));
//headMap
System.out.println(map.headMap(new Integer(3)));
//tailmap
System.out.println(map.tailMap(new Integer(3)));
}
}
|
158727_1 | package com.joran.test;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.command.TabCompleter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class joranCommand implements CommandExecutor, TabCompleter {
public static boolean isLoggerOn = false;
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (sender instanceof Player) {
Player speler = (Player) sender;
if (args.length == 1) {
if (args[0].equalsIgnoreCase("heal")) {
if (speler.hasPermission("joranPlugin.heal")) {
speler.setHealth(20);
speler.setFoodLevel(40);
} else {
speler.sendMessage(ChatColor.DARK_RED + "Sorry, Je hebt geen perms om deze command uit te voeren");
}
} else if (args[0].equalsIgnoreCase("fly")) {
if (speler.hasPermission("joranPlugin.fly")) {
if (speler.getAllowFlight()) {
speler.sendMessage("je kan niet meer vliegen");
speler.setAllowFlight(false);
speler.setFlying(false);
} else {
speler.sendMessage("Je kan nu vliegen");
speler.setAllowFlight(true);
speler.setFlying(true);
}
} else {
speler.sendMessage(ChatColor.DARK_RED + "Sorry, Je hebt geen perms om deze command uit te voeren");
}
} else if (args[0].equalsIgnoreCase("gmc")) {
if (speler.hasPermission("joranPlugin.gmc")) {
speler.setGameMode(GameMode.CREATIVE);
speler.sendMessage(ChatColor.GOLD + "Je gamemode is veranderd naar " + speler.getGameMode());
}
} else if (args[0].equalsIgnoreCase("gma")) {
if (speler.hasPermission("joranPlugin.gma")) {
speler.setGameMode(GameMode.ADVENTURE);
speler.sendMessage(ChatColor.GOLD + "Je gamemode is veranderd naar " + speler.getGameMode());
}
} else if (args[0].equalsIgnoreCase("gmsp")) {
if (speler.hasPermission("joranPlugin.gmsp")) {
speler.setGameMode(GameMode.SPECTATOR);
speler.sendMessage(ChatColor.GOLD + "Je gamemode is veranderd naar " + speler.getGameMode());
}
} else if (args[0].equalsIgnoreCase("gms")) {
if (speler.hasPermission("joranPlugin.gms")) {
speler.setGameMode(GameMode.SURVIVAL);
speler.sendMessage(ChatColor.GOLD + "Je gamemode is veranderd naar " + speler.getGameMode());
}
} else if (args[0].equalsIgnoreCase("logger")) {
if (speler.hasPermission("joranPlugin.logger")){
if (isLoggerOn == true){
isLoggerOn = false;
speler.sendMessage(ChatColor.DARK_RED.BOLD + "Je hebt de console logger uitgezet!");
} else if (isLoggerOn == false) {
isLoggerOn = true;
speler.sendMessage(ChatColor.DARK_RED.BOLD + "Je hebt de console logger aangezet!");
}
}
} else if (args[0].equalsIgnoreCase("vanish")) {
if (speler.hasPermission("joranPlugin.vanish")){
}
}
}
} else {
System.out.println("Helaas je bent geen speler dus dit gaat niet lukken.");
}
return false;
}
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
List<String> completions = new ArrayList<>();
// Voor het eerste argument, voeg "heal" toe als mogelijkheid
if (args.length == 1) {
completions.add("heal");
completions.add("fly");
completions.add("gmc");
completions.add("gms");
completions.add("gmsp");
completions.add("gma");
completions.add("vanish");
completions.add("logger");
// Je kunt hier meer argumenten toevoegen
}
return completions;
}
}
| JoranDW/minecraft-Plugin | src/main/java/com/joran/test/joranCommand.java | 1,318 | // Je kunt hier meer argumenten toevoegen | line_comment | nl | package com.joran.test;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.command.TabCompleter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class joranCommand implements CommandExecutor, TabCompleter {
public static boolean isLoggerOn = false;
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (sender instanceof Player) {
Player speler = (Player) sender;
if (args.length == 1) {
if (args[0].equalsIgnoreCase("heal")) {
if (speler.hasPermission("joranPlugin.heal")) {
speler.setHealth(20);
speler.setFoodLevel(40);
} else {
speler.sendMessage(ChatColor.DARK_RED + "Sorry, Je hebt geen perms om deze command uit te voeren");
}
} else if (args[0].equalsIgnoreCase("fly")) {
if (speler.hasPermission("joranPlugin.fly")) {
if (speler.getAllowFlight()) {
speler.sendMessage("je kan niet meer vliegen");
speler.setAllowFlight(false);
speler.setFlying(false);
} else {
speler.sendMessage("Je kan nu vliegen");
speler.setAllowFlight(true);
speler.setFlying(true);
}
} else {
speler.sendMessage(ChatColor.DARK_RED + "Sorry, Je hebt geen perms om deze command uit te voeren");
}
} else if (args[0].equalsIgnoreCase("gmc")) {
if (speler.hasPermission("joranPlugin.gmc")) {
speler.setGameMode(GameMode.CREATIVE);
speler.sendMessage(ChatColor.GOLD + "Je gamemode is veranderd naar " + speler.getGameMode());
}
} else if (args[0].equalsIgnoreCase("gma")) {
if (speler.hasPermission("joranPlugin.gma")) {
speler.setGameMode(GameMode.ADVENTURE);
speler.sendMessage(ChatColor.GOLD + "Je gamemode is veranderd naar " + speler.getGameMode());
}
} else if (args[0].equalsIgnoreCase("gmsp")) {
if (speler.hasPermission("joranPlugin.gmsp")) {
speler.setGameMode(GameMode.SPECTATOR);
speler.sendMessage(ChatColor.GOLD + "Je gamemode is veranderd naar " + speler.getGameMode());
}
} else if (args[0].equalsIgnoreCase("gms")) {
if (speler.hasPermission("joranPlugin.gms")) {
speler.setGameMode(GameMode.SURVIVAL);
speler.sendMessage(ChatColor.GOLD + "Je gamemode is veranderd naar " + speler.getGameMode());
}
} else if (args[0].equalsIgnoreCase("logger")) {
if (speler.hasPermission("joranPlugin.logger")){
if (isLoggerOn == true){
isLoggerOn = false;
speler.sendMessage(ChatColor.DARK_RED.BOLD + "Je hebt de console logger uitgezet!");
} else if (isLoggerOn == false) {
isLoggerOn = true;
speler.sendMessage(ChatColor.DARK_RED.BOLD + "Je hebt de console logger aangezet!");
}
}
} else if (args[0].equalsIgnoreCase("vanish")) {
if (speler.hasPermission("joranPlugin.vanish")){
}
}
}
} else {
System.out.println("Helaas je bent geen speler dus dit gaat niet lukken.");
}
return false;
}
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
List<String> completions = new ArrayList<>();
// Voor het eerste argument, voeg "heal" toe als mogelijkheid
if (args.length == 1) {
completions.add("heal");
completions.add("fly");
completions.add("gmc");
completions.add("gms");
completions.add("gmsp");
completions.add("gma");
completions.add("vanish");
completions.add("logger");
// Je kunt<SUF>
}
return completions;
}
}
|
203445_0 | package com.example.rentathing.product;
import com.example.rentathing.Medewerker;
import com.example.rentathing.Observer;
import java.util.ArrayList;
public abstract class Product {
private String naam;
private boolean verhuurd;
// private double huurprijs;
private String categorie;
private ArrayList<Observer> observers;
private String klantVoornaam;
private String klantAchternaam;
private boolean verzekerd;
//door welke medewerker is het verhuurd?
private String medewerker;
public Product(String naam, String categorie, ArrayList<Observer> observers) {
this.naam = naam;
this.verhuurd = false;
this.categorie = categorie;
this.observers = observers;
this.klantVoornaam = null;
this.klantAchternaam = null;
this.verzekerd = false;
this.medewerker = null;
}
// public double getHuurprijs() {
// return huurprijs;
// }
public String getCategorie() {
return categorie;
}
public ArrayList<Observer> getObservers() {
return observers;
}
public String getKlantVoornaam() {
return klantVoornaam;
}
public String getKlantAchternaam() {
return klantAchternaam;
}
public void setKlantVoornaam(String klantVoornaam) {
this.klantVoornaam = klantVoornaam;
}
public void setKlantAchternaam(String klantAchternaam) {
this.klantAchternaam = klantAchternaam;
}
public void setVerzekerd(boolean verzekerd) {
this.verzekerd = verzekerd;
}
public void setMedewerker(String medewerker) {
this.medewerker = medewerker;
}
public boolean isVerzekerd() {
return verzekerd;
}
public String getMedewerker() {
return medewerker;
}
public String getNaam() {
return naam;
}
public void setNaam(String naam) {
this.naam = naam;
}
public boolean isVerhuurt() {
return verhuurd;
}
public void setVerhuurd(boolean verhuurd) {
this.verhuurd = verhuurd;
}
//berekent per dag kosten
public double prijsBerekening() {
double huur = berekenHuurprijs();
double verzekering = berekenVerzekering();
return huur + verzekering;
}
public abstract double berekenHuurprijs();
public abstract double berekenVerzekering();
public void meldingGeven(String melding) {
for (Observer o : observers) {
o.update(melding);
}
}
public void voegObserverToe(Medewerker medewerker) {
observers.add(medewerker);
}
}
| JordiPan/rentathing | src/main/java/com/example/rentathing/product/Product.java | 811 | // private double huurprijs; | line_comment | nl | package com.example.rentathing.product;
import com.example.rentathing.Medewerker;
import com.example.rentathing.Observer;
import java.util.ArrayList;
public abstract class Product {
private String naam;
private boolean verhuurd;
// private double<SUF>
private String categorie;
private ArrayList<Observer> observers;
private String klantVoornaam;
private String klantAchternaam;
private boolean verzekerd;
//door welke medewerker is het verhuurd?
private String medewerker;
public Product(String naam, String categorie, ArrayList<Observer> observers) {
this.naam = naam;
this.verhuurd = false;
this.categorie = categorie;
this.observers = observers;
this.klantVoornaam = null;
this.klantAchternaam = null;
this.verzekerd = false;
this.medewerker = null;
}
// public double getHuurprijs() {
// return huurprijs;
// }
public String getCategorie() {
return categorie;
}
public ArrayList<Observer> getObservers() {
return observers;
}
public String getKlantVoornaam() {
return klantVoornaam;
}
public String getKlantAchternaam() {
return klantAchternaam;
}
public void setKlantVoornaam(String klantVoornaam) {
this.klantVoornaam = klantVoornaam;
}
public void setKlantAchternaam(String klantAchternaam) {
this.klantAchternaam = klantAchternaam;
}
public void setVerzekerd(boolean verzekerd) {
this.verzekerd = verzekerd;
}
public void setMedewerker(String medewerker) {
this.medewerker = medewerker;
}
public boolean isVerzekerd() {
return verzekerd;
}
public String getMedewerker() {
return medewerker;
}
public String getNaam() {
return naam;
}
public void setNaam(String naam) {
this.naam = naam;
}
public boolean isVerhuurt() {
return verhuurd;
}
public void setVerhuurd(boolean verhuurd) {
this.verhuurd = verhuurd;
}
//berekent per dag kosten
public double prijsBerekening() {
double huur = berekenHuurprijs();
double verzekering = berekenVerzekering();
return huur + verzekering;
}
public abstract double berekenHuurprijs();
public abstract double berekenVerzekering();
public void meldingGeven(String melding) {
for (Observer o : observers) {
o.update(melding);
}
}
public void voegObserverToe(Medewerker medewerker) {
observers.add(medewerker);
}
}
|
22362_0 | import java.util.Random;
import java.util.Scanner;
public class Oefendag1 {
public static void main(String[] args) {
/* int a;
a = 4;
a = 9;
System.out.println(a);
String test = "stukje tekst";
System.out.println(test);
boolean eersteboolean = true;
int i = 0b111; // 0b verteld dat het binair is
int y = 077; // 0 verteld dat het getal octaal is
int q = 0x5A; // 0x verteld dat het getal hexadicimaal is
System.out.println(q);
System.out.println(y);
System.out.println(i);
int hallo = 0x4_5_2;
long voorbeeld = 63647485859323223L; //L moet er achter bij een long getal
float defloat = 66.5F; //F moet erachter bij een float
char karakter = 'e'; //enkele character tussen enkele quotes
String zin = "h"; //meerdere characters tussen dubbele quotes
char karakter = '\uFFFF';
char a = 97;
System.out.println(karakter);
for(int x = 0; x<26; x++) {
System.out.println(a++);
}
System.out.println(karakter);
*/
Scanner scanner = new Scanner(System.in);
Random random = new Random ();
Vulpen vulpen = new Vulpen ();
System.out.println(vulpen.kleur); // de punt staat voor het vertellen van de waarde van een eigenschap
vulpen.kleur = "oranje";
System.out.println(vulpen.kleur);
}
}
class Vulpen {
String kleur = "blauw";
boolean leeg;
int prijs;
} | Jorimvdw/Schoenmaat | Oefendag1.java | 523 | /* int a;
a = 4;
a = 9;
System.out.println(a);
String test = "stukje tekst";
System.out.println(test);
boolean eersteboolean = true;
int i = 0b111; // 0b verteld dat het binair is
int y = 077; // 0 verteld dat het getal octaal is
int q = 0x5A; // 0x verteld dat het getal hexadicimaal is
System.out.println(q);
System.out.println(y);
System.out.println(i);
int hallo = 0x4_5_2;
long voorbeeld = 63647485859323223L; //L moet er achter bij een long getal
float defloat = 66.5F; //F moet erachter bij een float
char karakter = 'e'; //enkele character tussen enkele quotes
String zin = "h"; //meerdere characters tussen dubbele quotes
char karakter = '\uFFFF';
char a = 97;
System.out.println(karakter);
for(int x = 0; x<26; x++) {
System.out.println(a++);
}
System.out.println(karakter);
*/ | block_comment | nl | import java.util.Random;
import java.util.Scanner;
public class Oefendag1 {
public static void main(String[] args) {
/* int a;
<SUF>*/
Scanner scanner = new Scanner(System.in);
Random random = new Random ();
Vulpen vulpen = new Vulpen ();
System.out.println(vulpen.kleur); // de punt staat voor het vertellen van de waarde van een eigenschap
vulpen.kleur = "oranje";
System.out.println(vulpen.kleur);
}
}
class Vulpen {
String kleur = "blauw";
boolean leeg;
int prijs;
} |
150664_1 | package Dinsdag;
public class oefen {
public static void main(String[] args) {
/* public static void main(String[] args) {
int qq = optellen(14, 15);
System.out.println(qq);
}
static int optellen (int a, int b) {
int antwoord = a + b;
return antwoord;
}
*/
Fiets fiets = new Fiets();
fiets.merk = "Gazelle";
// fiets.aantalWielen = 2;
Klant klant = new Klant();
klant.checken(fiets);
fiets.kenmerken();
klant.doodvallen();
klant.doodvallen();
}
}
class Fiets {
String merk;
AantalWielen banden = new AantalWielen();
void kenmerken () {
System.out.println("De fiets is van het merk " + merk);
System.out.println("De fiets heeft " + banden.wielen + " wielen.");
}
}
class Klant {
boolean levend = true;
void checken(Fiets a) {
System.out.println(a.merk);
}
void doodvallen() {
levend =! levend;
if (levend == false) {
System.out.println("De klant is dood!");
} else {
System.out.println("Een wonder is geschied, de klant leeft weer!");
}
}
}
class AantalWielen {
int wielen = 2;
}
| Jorimvdw/Weekopdracht1 | oefen.java | 437 | // fiets.aantalWielen = 2; | line_comment | nl | package Dinsdag;
public class oefen {
public static void main(String[] args) {
/* public static void main(String[] args) {
int qq = optellen(14, 15);
System.out.println(qq);
}
static int optellen (int a, int b) {
int antwoord = a + b;
return antwoord;
}
*/
Fiets fiets = new Fiets();
fiets.merk = "Gazelle";
// fiets.aantalWielen =<SUF>
Klant klant = new Klant();
klant.checken(fiets);
fiets.kenmerken();
klant.doodvallen();
klant.doodvallen();
}
}
class Fiets {
String merk;
AantalWielen banden = new AantalWielen();
void kenmerken () {
System.out.println("De fiets is van het merk " + merk);
System.out.println("De fiets heeft " + banden.wielen + " wielen.");
}
}
class Klant {
boolean levend = true;
void checken(Fiets a) {
System.out.println(a.merk);
}
void doodvallen() {
levend =! levend;
if (levend == false) {
System.out.println("De klant is dood!");
} else {
System.out.println("Een wonder is geschied, de klant leeft weer!");
}
}
}
class AantalWielen {
int wielen = 2;
}
|
121928_0 | package com.fantasticfive.shared;
import com.fantasticfive.shared.enums.GroundType;
import com.fantasticfive.shared.enums.ObjectType;
import java.io.Serializable;
import java.util.*;
public class Map implements Serializable {
private List<Hexagon> hexagons;
private int id;
private int width;
private int height;
public Map(int width, int height) {
this.width = width;
this.height = height;
hexagons = new ArrayList<>();
Generate();
}
public boolean hexHasOwner(Point location) {
//TODO Daadwerkelijk checken of de tile een owner heeft
for (Hexagon h : hexagons) {
if (h.getLocation() == location) {
return h.hasOwner();
}
}
return false;
}
public void setTextures() {
for (Hexagon hex : hexagons) {
hex.setTextures();
}
}
public Point randomPoint() {
Random rnd = new Random();
int i;
do {
i = rnd.nextInt(hexagons.size());
} while (hexagons.get(i).getGroundType() != GroundType.GRASS);
return hexagons.get(i).getLocation();
}
public boolean canMoveTo(Unit u, Point location, List<Hexagon> movableHexes) {
for (Hexagon hex : movableHexes) {
if (hex.getLocation().sameAs(location)) {
return true;
}
}
return false;
}
public int pathDistance(HashMap pathMap, Hexagon currentHex, Hexagon beginHex) {
Hexagon current = currentHex;
int i = 0;
while (current != beginHex) {
current = (Hexagon) pathMap.get(current);
i++;
}
return i;
}
public boolean isWithinAttackRange(Unit u, Point location) {
List<Hexagon> movableHexes = getHexesInRadius(u.getLocation(), u.getAttackRangeLeft());
for (Hexagon hex : movableHexes) {
if (hex.getLocation().sameAs(location)) {
return true;
}
}
return false;
}
public List<Hexagon> getHexesInRadius(Point location, int radius) {
List<Hexagon> results = new ArrayList<>();
for (Hexagon hex : hexagons) {
int distance = distance(location, hex.getLocation());
if (distance >= -radius &&
distance <= radius) {
results.add(hex);
}
}
return results;
}
public int distance(Point a, Point b) {
return (Math.abs(a.getY() - b.getY()) + Math.abs(a.getX() + a.getY() - b.getX() - b.getY()) + Math.abs(a.getX() - b.getX())) / 2;
}
private void Generate() {
List<Integer> seeds = new ArrayList<>();
seeds.add(-2096365904);
seeds.add(-1982397011);
seeds.add(-1766646759);
seeds.add(-1742594191);
seeds.add(-1102120703);
seeds.add(-970991336);
seeds.add(-862200254);
seeds.add(-777100558);
seeds.add(-516396776);
seeds.add(-217823742);
seeds.add(110098218);
seeds.add(347414893);
seeds.add(406130710);
seeds.add(940360477);
seeds.add(1081319097);
seeds.add(1138543949);
seeds.add(1290340836);
seeds.add(1504742640);
seeds.add(1551778228);
seeds.add(1842268213);
seeds.add(1994802313);
seeds.add(2004522193);
Random r = new Random();
int seed = seeds.get(r.nextInt(seeds.size()));
Noise.setSeed(seed); //This value is used to calculate the map
System.out.println(seed);
float scale = 0.10f; //To determine the density
float[][] noiseValues = Noise.Calc2DNoise(height, width, scale);
int maxNoise1 = 60;
int maxNoise2 = 90;
int maxNoise3 = 120;
int maxNoise4 = 200;
int maxNoise5 = 220;
int maxNoise6 = 250;
for (int column = 0; column < width; column++) {
for (int row = 0; row < height; row++) {
GroundType gt = GroundType.GRASS;
ObjectType ot = null;
if (noiseValues[row][column] >= 0 && noiseValues[row][column] < maxNoise1) {
gt = GroundType.WATER;
}
if (noiseValues[row][column] >= maxNoise1 && noiseValues[row][column] < maxNoise2) {
gt = GroundType.SAND;
}
if (noiseValues[row][column] >= maxNoise2 && noiseValues[row][column] < maxNoise3) {
gt = GroundType.DIRT;
}
if (noiseValues[row][column] >= maxNoise3 && noiseValues[row][column] < maxNoise4) {
gt = GroundType.GRASS;
}
if (noiseValues[row][column] >= maxNoise4 && noiseValues[row][column] < maxNoise5) {
gt = GroundType.FOREST;
}
if (noiseValues[row][column] >= maxNoise5 && noiseValues[row][column] < maxNoise6) {
gt = GroundType.GRASS;
ot = ObjectType.MOUNTAIN;
}
if (ot == null) {
hexagons.add(new Hexagon(gt, new Point(row, column), 62));
} else {
hexagons.add(new Hexagon(gt, ot, new Point(row, column), 62));
}
}
}
}
public List<Hexagon> getHexagons() {
return hexagons;
}
public boolean bordersOwnLand(Point location, Player currentPlayer) {
for (Hexagon h : getHexesInRadius(location, 1)) {
if (h.getOwner() == currentPlayer) {
return true;
}
}
return false;
}
public List<Hexagon> getPath(Hexagon startHex, Hexagon destination) {
//TODO Maak gebruik van accessible boolean in Hexagon om te bepalen of je er op kan lopen.
List<Hexagon> path = new ArrayList<>();
List<Hexagon> frontier = new ArrayList<>();
HashMap pathMap = new HashMap();
boolean found = false;
Hexagon current;
int i = 0;
frontier.add(startHex);
while (!found) {
current = frontier.get(i);
if (current == destination) {
found = true;
}
for (Hexagon h : getHexesInRadius(current.getLocation(), 1)) {
if (!pathMap.containsKey(h) && h.getObjectType() != ObjectType.MOUNTAIN && h.getGroundType() != GroundType.WATER) {
frontier.add(h);
pathMap.put(h, current);
}
}
i++;
}
path.add(destination);
current = destination;
while (current != startHex) {
current = (Hexagon) pathMap.get(current);
path.add(current);
}
Collections.reverse(path);
return path;
}
//Returns hexagon at a specific location
public Hexagon getHexAtLocation(Point loc) {
for (Hexagon hex : hexagons) {
if (hex.getLocation().getX() == loc.getX() && hex.getLocation().getY() == loc.getY()) {
return hex;
}
}
return null;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
}
| JorinTielen/ProjectHex | core/src/com/fantasticfive/shared/Map.java | 2,244 | //TODO Daadwerkelijk checken of de tile een owner heeft | line_comment | nl | package com.fantasticfive.shared;
import com.fantasticfive.shared.enums.GroundType;
import com.fantasticfive.shared.enums.ObjectType;
import java.io.Serializable;
import java.util.*;
public class Map implements Serializable {
private List<Hexagon> hexagons;
private int id;
private int width;
private int height;
public Map(int width, int height) {
this.width = width;
this.height = height;
hexagons = new ArrayList<>();
Generate();
}
public boolean hexHasOwner(Point location) {
//TODO Daadwerkelijk<SUF>
for (Hexagon h : hexagons) {
if (h.getLocation() == location) {
return h.hasOwner();
}
}
return false;
}
public void setTextures() {
for (Hexagon hex : hexagons) {
hex.setTextures();
}
}
public Point randomPoint() {
Random rnd = new Random();
int i;
do {
i = rnd.nextInt(hexagons.size());
} while (hexagons.get(i).getGroundType() != GroundType.GRASS);
return hexagons.get(i).getLocation();
}
public boolean canMoveTo(Unit u, Point location, List<Hexagon> movableHexes) {
for (Hexagon hex : movableHexes) {
if (hex.getLocation().sameAs(location)) {
return true;
}
}
return false;
}
public int pathDistance(HashMap pathMap, Hexagon currentHex, Hexagon beginHex) {
Hexagon current = currentHex;
int i = 0;
while (current != beginHex) {
current = (Hexagon) pathMap.get(current);
i++;
}
return i;
}
public boolean isWithinAttackRange(Unit u, Point location) {
List<Hexagon> movableHexes = getHexesInRadius(u.getLocation(), u.getAttackRangeLeft());
for (Hexagon hex : movableHexes) {
if (hex.getLocation().sameAs(location)) {
return true;
}
}
return false;
}
public List<Hexagon> getHexesInRadius(Point location, int radius) {
List<Hexagon> results = new ArrayList<>();
for (Hexagon hex : hexagons) {
int distance = distance(location, hex.getLocation());
if (distance >= -radius &&
distance <= radius) {
results.add(hex);
}
}
return results;
}
public int distance(Point a, Point b) {
return (Math.abs(a.getY() - b.getY()) + Math.abs(a.getX() + a.getY() - b.getX() - b.getY()) + Math.abs(a.getX() - b.getX())) / 2;
}
private void Generate() {
List<Integer> seeds = new ArrayList<>();
seeds.add(-2096365904);
seeds.add(-1982397011);
seeds.add(-1766646759);
seeds.add(-1742594191);
seeds.add(-1102120703);
seeds.add(-970991336);
seeds.add(-862200254);
seeds.add(-777100558);
seeds.add(-516396776);
seeds.add(-217823742);
seeds.add(110098218);
seeds.add(347414893);
seeds.add(406130710);
seeds.add(940360477);
seeds.add(1081319097);
seeds.add(1138543949);
seeds.add(1290340836);
seeds.add(1504742640);
seeds.add(1551778228);
seeds.add(1842268213);
seeds.add(1994802313);
seeds.add(2004522193);
Random r = new Random();
int seed = seeds.get(r.nextInt(seeds.size()));
Noise.setSeed(seed); //This value is used to calculate the map
System.out.println(seed);
float scale = 0.10f; //To determine the density
float[][] noiseValues = Noise.Calc2DNoise(height, width, scale);
int maxNoise1 = 60;
int maxNoise2 = 90;
int maxNoise3 = 120;
int maxNoise4 = 200;
int maxNoise5 = 220;
int maxNoise6 = 250;
for (int column = 0; column < width; column++) {
for (int row = 0; row < height; row++) {
GroundType gt = GroundType.GRASS;
ObjectType ot = null;
if (noiseValues[row][column] >= 0 && noiseValues[row][column] < maxNoise1) {
gt = GroundType.WATER;
}
if (noiseValues[row][column] >= maxNoise1 && noiseValues[row][column] < maxNoise2) {
gt = GroundType.SAND;
}
if (noiseValues[row][column] >= maxNoise2 && noiseValues[row][column] < maxNoise3) {
gt = GroundType.DIRT;
}
if (noiseValues[row][column] >= maxNoise3 && noiseValues[row][column] < maxNoise4) {
gt = GroundType.GRASS;
}
if (noiseValues[row][column] >= maxNoise4 && noiseValues[row][column] < maxNoise5) {
gt = GroundType.FOREST;
}
if (noiseValues[row][column] >= maxNoise5 && noiseValues[row][column] < maxNoise6) {
gt = GroundType.GRASS;
ot = ObjectType.MOUNTAIN;
}
if (ot == null) {
hexagons.add(new Hexagon(gt, new Point(row, column), 62));
} else {
hexagons.add(new Hexagon(gt, ot, new Point(row, column), 62));
}
}
}
}
public List<Hexagon> getHexagons() {
return hexagons;
}
public boolean bordersOwnLand(Point location, Player currentPlayer) {
for (Hexagon h : getHexesInRadius(location, 1)) {
if (h.getOwner() == currentPlayer) {
return true;
}
}
return false;
}
public List<Hexagon> getPath(Hexagon startHex, Hexagon destination) {
//TODO Maak gebruik van accessible boolean in Hexagon om te bepalen of je er op kan lopen.
List<Hexagon> path = new ArrayList<>();
List<Hexagon> frontier = new ArrayList<>();
HashMap pathMap = new HashMap();
boolean found = false;
Hexagon current;
int i = 0;
frontier.add(startHex);
while (!found) {
current = frontier.get(i);
if (current == destination) {
found = true;
}
for (Hexagon h : getHexesInRadius(current.getLocation(), 1)) {
if (!pathMap.containsKey(h) && h.getObjectType() != ObjectType.MOUNTAIN && h.getGroundType() != GroundType.WATER) {
frontier.add(h);
pathMap.put(h, current);
}
}
i++;
}
path.add(destination);
current = destination;
while (current != startHex) {
current = (Hexagon) pathMap.get(current);
path.add(current);
}
Collections.reverse(path);
return path;
}
//Returns hexagon at a specific location
public Hexagon getHexAtLocation(Point loc) {
for (Hexagon hex : hexagons) {
if (hex.getLocation().getX() == loc.getX() && hex.getLocation().getY() == loc.getY()) {
return hex;
}
}
return null;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
}
|
111139_7 | package Main;
import Domeinklassen.*;
import org.postgresql.util.PSQLException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLOutput;
import java.util.List;
public class Main {
private static Connection connection;
public static void getConnection() throws SQLException {
String url = "jdbc:postgresql://localhost:5432/ovchip";
String user = "postgres";
String password = "Joris999!";
connection = DriverManager.getConnection(url, user, password);
}
public static void closeConnection() throws SQLException {
connection.close();
}
private static void testReizigerDAO(ReizigerDAO rdao) throws SQLException {
System.out.println("\n---------- Test ReizigerDAO -------------");
// Haal alle reizigers op uit de database
List<Reiziger> reizigers = rdao.findAll();
System.out.println("[Test] ReizigerDAO.findAll() geeft de volgende reizigers:");
for (Reiziger r : reizigers) {
System.out.println(r);
}
System.out.println();
// Maak een nieuwe reiziger aan en persisteer deze in de database
String gbdatum = "1981-03-14";
Reiziger sietske = new Reiziger(77, "S", "", "Boers", java.sql.Date.valueOf(gbdatum));
System.out.print("[Test] Eerst " + reizigers.size() + " reizigers, na ReizigerDAO.save() ");
rdao.save(sietske);
reizigers = rdao.findAll();
System.out.println(reizigers.size() + " reizigers\n");
// Maak nieuw reiziger, persisteer die en wijzig die vervolgens met een andere reiziger
System.out.print("[Test] Eerst word er een nieuwe reiziger aangemaakt, op dit moment zijn er " + reizigers.size() + " reizigers");
Reiziger wopke = new Reiziger(55, "W", "", "Hoekstra", java.sql.Date.valueOf("1976-04-20"));
rdao.save(wopke);
System.out.print("\nNu zijn er: " + reizigers.size() + " reizigers, na ReizigerDAO.save() , deze reiziger wordt gewijzigd: " + rdao.findById(55));
Reiziger wopkeVervanger = new Reiziger(55, "S", "", "Kaag", java.sql.Date.valueOf("1966-03-19"));
rdao.update(wopkeVervanger);
System.out.print("\nNa ReizigerDAO.update() is de reiziger met id 55 geupdate naar: " + rdao.findById(55));
Reiziger mark = new Reiziger(99, "M", "", "Rutte", java.sql.Date.valueOf("1967-02-10"));
rdao.save(mark);
reizigers = rdao.findAll();
System.out.println("\n\n[Test] Eerst " + reizigers.size() + " reizigers, na ReizigerDAO.delete() ");
rdao.delete(mark);
reizigers = rdao.findAll();
System.out.println(reizigers.size() + " reizigers\n");
System.out.println("[TEST] Zoek reiziger(s) o.b.v geboortedatum: " + (rdao.findByGbdatum("2002-12-03")));
}
private static void testAdres(AdresDAO adao) throws SQLException {
System.out.println("\n---------- Test AdresDAO -------------");
// Voorbeeld reiziger om het adres aan te koppelen
Reiziger wopke = new Reiziger(88, "W", "", "Hoekstra", java.sql.Date.valueOf("1976-04-20"));
adao.getRdao().save(wopke);
//Maak een adres aan en save deze in de database
Adres adr1 = new Adres(6, "8834IK", "34", "Hogeweg", "Hoevelaken", 88);
System.out.println("[Test] Eerst " + adao.findAll().size() + " adressen");
adao.save(adr1);
System.out.println("na adao.save: " + adao.findAll().size() + " adressen\n");
//Test updaten van adres en test methode findByReiziger()
Adres adr2 = new Adres(6, "2315IK", "32", "huhuhu", "Rotterdeam", 88);
System.out.println("[TEST] update, adres: " + adao.findByReiziger(wopke));
adao.update(adr2);
System.out.println("na update: " + adao.findByReiziger(wopke));
//Test delete van adres
System.out.println("\n[TEST] delete, eerst " + adao.findAll().size() + " adressen" );
adao.delete(adr1);
//Delete ook de reiziger die is aangemaakt voor het adres
adao.getRdao().delete(wopke);
System.out.println("Na adao.delete: " + adao.findAll().size() + " adressen\n");
//Tot slot een overzicht van alle reizigers met de adressen.
System.out.println("overzicht van alle reizigers met adressen na de tests:");
for (Adres adres : adao.findAll()) {
System.out.println(adao.getRdao().findById(adres.getReizigerid()));
}
}
private static void testOVChipkaarten(OVChipkaartDAO odao) throws SQLException {
System.out.println("\n---------- Test OVChipkaartDAO -------------");
// Voorbeeld reiziger om de ovchipkaarten aan te koppelen
Reiziger reiziger1 = new Reiziger(10, "P", "", "Lopemdam", java.sql.Date.valueOf("1986-03-14"));
odao.getRdao().save(reiziger1);
OVChipkaart ov1 = new OVChipkaart(12345, java.sql.Date.valueOf("2021-01-01"), 1, 25.00, 10);
OVChipkaart ov2 = new OVChipkaart(48945, java.sql.Date.valueOf("2022-01-01"), 1, 30.00, 10);
// Test save van ovchipkaart
System.out.println("[TEST] eerst " + odao.findAll().size() + " ovchipkaarten");
odao.save(ov1);
System.out.println("na odao.save: " + odao.findAll().size() + " ovchipkaarten\n");
// Koppel de ovchipkaarten aan de reiziger in java
List<OVChipkaart> listOV = List.of(ov1, ov2);
reiziger1.setOvChipkaarten(listOV);
// Test update van ovchipkaart
System.out.println("[TEST] update, ovchipkaart:\n " + odao.findbyKaartNummer(12345));
OVChipkaart ov3 = new OVChipkaart(12345, java.sql.Date.valueOf("2022-01-01"), 2, 50, 10);
odao.update(ov3);
System.out.println("na update: " + odao.findbyKaartNummer(12345));
// Test findAll van ovchipkaart
System.out.println("\n[TEST] findAll() geeft de volgende OVChipkaarten:\n");
for (OVChipkaart ov : odao.findAll()) {
System.out.println(ov.toString());
}
System.out.println();
// Test findByReiziger van ovchipkaart
System.out.println("[TEST] findByReiziger() geeft de volgende OVChipkaarten:");
for (OVChipkaart ov : odao.findByReiziger(reiziger1)) {
System.out.println(ov.toString());
}
// Test delete van ovchipkaart
System.out.println("\n[TEST] delete, eerst " + odao.findAll().size() + " ovchipkaarten" );
odao.getRdao().findById(ov1.getReizigerid()).getOvChipkaarten().remove(ov1);
odao.delete(ov1);
System.out.println("Na odao.delete: " + odao.findAll().size() + " ovchipkaarten\n");
// delete de aangemaakte reiziger
odao.getRdao().delete(reiziger1);
}
private static void testProductDAO(ProductDAO pdao) throws SQLException {
System.out.println("\n---------- Test ProductDAO -------------");
// Slaat een ovchipkaart aan om mee te testen
OVChipkaart ov7 = new OVChipkaart(77777, java.sql.Date.valueOf("2021-01-01"), 1, 50.00, 5);
pdao.getOdao().save(ov7);
// Slaat een nieuw product op in de database en koppelt deze aan de ovchipkaart
Product product1 = new Product(7, "Weekend Vrij", "Gratis reizen in het weekend", 0.00);
Product product2 = new Product(8, "Alleen staan", "Alleen staan in het ov", 0.00);
ov7.addProduct(product1);
ov7.addProduct(product2);
System.out.println("[TEST] eerst " + pdao.findAll().size() + " producten");
pdao.save(product1);
pdao.save(product2);
System.out.println("na twee keer pdao.save: " + pdao.findAll().size() + " producten\n");
// Test findByOVChipkaart van product
System.out.println("[TEST] findByOVChipkaart() geeft de volgende producten:");
for (Product product : pdao.findByOVChipkaart(ov7)) {
System.out.println(product.toString());
}
// Test update van product
System.out.println("[TEST] update, product:\n " + product1);
Product product3 = new Product(7, "Doordeweeks vrij", "Gratis reizen doordeweeks", 199.00);
pdao.update(product3);
System.out.println("na update: " + pdao.findByOVChipkaart(ov7).get(1));
// Test findAll van product
System.out.println("\n[TEST] findAll() geeft de volgende producten:\n");
for (Product product : pdao.findAll()) {
System.out.println(product.toString());
}
// Test delete van product
System.out.println("\n[TEST] delete, eerst " + pdao.findAll().size() + " producten" );
pdao.delete(product1);
pdao.delete(product2);
System.out.println("Na 2 keer pdao.delete: " + pdao.findAll().size() + " producten\n");
// delete de aangemaakte ovchipkaart
pdao.getOdao().delete(ov7);
}
public static void main(String[] args) {
try {
getConnection();
} catch(SQLException noCon) {
System.out.println("Something went wrong establishing the connection with the database: " + noCon);
}
ReizigerDAOPsql rdao = new ReizigerDAOPsql(connection);
AdresDAOPsql adao = new AdresDAOPsql(connection);
OVChipkaartDAOPsql odao = new OVChipkaartDAOPsql(connection);
ProductDAOsql pdao = new ProductDAOsql(connection);
rdao.setAdao(adao);
adao.setRdao(rdao);
odao.setRdao(rdao);
rdao.setOdao(odao);
odao.setPdao(pdao);
pdao.setOdao(odao);
try {
testReizigerDAO(rdao);
testAdres(adao);
testOVChipkaarten(odao);
testProductDAO(pdao);
}
catch(NullPointerException | SQLException e) {
System.out.println("Something went wrong: " + e);
}
}
}
| Jorisgeinig/DP_P_Opdrachten | src/nl.hu.dp/Main/Main.java | 3,405 | //Delete ook de reiziger die is aangemaakt voor het adres | line_comment | nl | package Main;
import Domeinklassen.*;
import org.postgresql.util.PSQLException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLOutput;
import java.util.List;
public class Main {
private static Connection connection;
public static void getConnection() throws SQLException {
String url = "jdbc:postgresql://localhost:5432/ovchip";
String user = "postgres";
String password = "Joris999!";
connection = DriverManager.getConnection(url, user, password);
}
public static void closeConnection() throws SQLException {
connection.close();
}
private static void testReizigerDAO(ReizigerDAO rdao) throws SQLException {
System.out.println("\n---------- Test ReizigerDAO -------------");
// Haal alle reizigers op uit de database
List<Reiziger> reizigers = rdao.findAll();
System.out.println("[Test] ReizigerDAO.findAll() geeft de volgende reizigers:");
for (Reiziger r : reizigers) {
System.out.println(r);
}
System.out.println();
// Maak een nieuwe reiziger aan en persisteer deze in de database
String gbdatum = "1981-03-14";
Reiziger sietske = new Reiziger(77, "S", "", "Boers", java.sql.Date.valueOf(gbdatum));
System.out.print("[Test] Eerst " + reizigers.size() + " reizigers, na ReizigerDAO.save() ");
rdao.save(sietske);
reizigers = rdao.findAll();
System.out.println(reizigers.size() + " reizigers\n");
// Maak nieuw reiziger, persisteer die en wijzig die vervolgens met een andere reiziger
System.out.print("[Test] Eerst word er een nieuwe reiziger aangemaakt, op dit moment zijn er " + reizigers.size() + " reizigers");
Reiziger wopke = new Reiziger(55, "W", "", "Hoekstra", java.sql.Date.valueOf("1976-04-20"));
rdao.save(wopke);
System.out.print("\nNu zijn er: " + reizigers.size() + " reizigers, na ReizigerDAO.save() , deze reiziger wordt gewijzigd: " + rdao.findById(55));
Reiziger wopkeVervanger = new Reiziger(55, "S", "", "Kaag", java.sql.Date.valueOf("1966-03-19"));
rdao.update(wopkeVervanger);
System.out.print("\nNa ReizigerDAO.update() is de reiziger met id 55 geupdate naar: " + rdao.findById(55));
Reiziger mark = new Reiziger(99, "M", "", "Rutte", java.sql.Date.valueOf("1967-02-10"));
rdao.save(mark);
reizigers = rdao.findAll();
System.out.println("\n\n[Test] Eerst " + reizigers.size() + " reizigers, na ReizigerDAO.delete() ");
rdao.delete(mark);
reizigers = rdao.findAll();
System.out.println(reizigers.size() + " reizigers\n");
System.out.println("[TEST] Zoek reiziger(s) o.b.v geboortedatum: " + (rdao.findByGbdatum("2002-12-03")));
}
private static void testAdres(AdresDAO adao) throws SQLException {
System.out.println("\n---------- Test AdresDAO -------------");
// Voorbeeld reiziger om het adres aan te koppelen
Reiziger wopke = new Reiziger(88, "W", "", "Hoekstra", java.sql.Date.valueOf("1976-04-20"));
adao.getRdao().save(wopke);
//Maak een adres aan en save deze in de database
Adres adr1 = new Adres(6, "8834IK", "34", "Hogeweg", "Hoevelaken", 88);
System.out.println("[Test] Eerst " + adao.findAll().size() + " adressen");
adao.save(adr1);
System.out.println("na adao.save: " + adao.findAll().size() + " adressen\n");
//Test updaten van adres en test methode findByReiziger()
Adres adr2 = new Adres(6, "2315IK", "32", "huhuhu", "Rotterdeam", 88);
System.out.println("[TEST] update, adres: " + adao.findByReiziger(wopke));
adao.update(adr2);
System.out.println("na update: " + adao.findByReiziger(wopke));
//Test delete van adres
System.out.println("\n[TEST] delete, eerst " + adao.findAll().size() + " adressen" );
adao.delete(adr1);
//Delete ook<SUF>
adao.getRdao().delete(wopke);
System.out.println("Na adao.delete: " + adao.findAll().size() + " adressen\n");
//Tot slot een overzicht van alle reizigers met de adressen.
System.out.println("overzicht van alle reizigers met adressen na de tests:");
for (Adres adres : adao.findAll()) {
System.out.println(adao.getRdao().findById(adres.getReizigerid()));
}
}
private static void testOVChipkaarten(OVChipkaartDAO odao) throws SQLException {
System.out.println("\n---------- Test OVChipkaartDAO -------------");
// Voorbeeld reiziger om de ovchipkaarten aan te koppelen
Reiziger reiziger1 = new Reiziger(10, "P", "", "Lopemdam", java.sql.Date.valueOf("1986-03-14"));
odao.getRdao().save(reiziger1);
OVChipkaart ov1 = new OVChipkaart(12345, java.sql.Date.valueOf("2021-01-01"), 1, 25.00, 10);
OVChipkaart ov2 = new OVChipkaart(48945, java.sql.Date.valueOf("2022-01-01"), 1, 30.00, 10);
// Test save van ovchipkaart
System.out.println("[TEST] eerst " + odao.findAll().size() + " ovchipkaarten");
odao.save(ov1);
System.out.println("na odao.save: " + odao.findAll().size() + " ovchipkaarten\n");
// Koppel de ovchipkaarten aan de reiziger in java
List<OVChipkaart> listOV = List.of(ov1, ov2);
reiziger1.setOvChipkaarten(listOV);
// Test update van ovchipkaart
System.out.println("[TEST] update, ovchipkaart:\n " + odao.findbyKaartNummer(12345));
OVChipkaart ov3 = new OVChipkaart(12345, java.sql.Date.valueOf("2022-01-01"), 2, 50, 10);
odao.update(ov3);
System.out.println("na update: " + odao.findbyKaartNummer(12345));
// Test findAll van ovchipkaart
System.out.println("\n[TEST] findAll() geeft de volgende OVChipkaarten:\n");
for (OVChipkaart ov : odao.findAll()) {
System.out.println(ov.toString());
}
System.out.println();
// Test findByReiziger van ovchipkaart
System.out.println("[TEST] findByReiziger() geeft de volgende OVChipkaarten:");
for (OVChipkaart ov : odao.findByReiziger(reiziger1)) {
System.out.println(ov.toString());
}
// Test delete van ovchipkaart
System.out.println("\n[TEST] delete, eerst " + odao.findAll().size() + " ovchipkaarten" );
odao.getRdao().findById(ov1.getReizigerid()).getOvChipkaarten().remove(ov1);
odao.delete(ov1);
System.out.println("Na odao.delete: " + odao.findAll().size() + " ovchipkaarten\n");
// delete de aangemaakte reiziger
odao.getRdao().delete(reiziger1);
}
private static void testProductDAO(ProductDAO pdao) throws SQLException {
System.out.println("\n---------- Test ProductDAO -------------");
// Slaat een ovchipkaart aan om mee te testen
OVChipkaart ov7 = new OVChipkaart(77777, java.sql.Date.valueOf("2021-01-01"), 1, 50.00, 5);
pdao.getOdao().save(ov7);
// Slaat een nieuw product op in de database en koppelt deze aan de ovchipkaart
Product product1 = new Product(7, "Weekend Vrij", "Gratis reizen in het weekend", 0.00);
Product product2 = new Product(8, "Alleen staan", "Alleen staan in het ov", 0.00);
ov7.addProduct(product1);
ov7.addProduct(product2);
System.out.println("[TEST] eerst " + pdao.findAll().size() + " producten");
pdao.save(product1);
pdao.save(product2);
System.out.println("na twee keer pdao.save: " + pdao.findAll().size() + " producten\n");
// Test findByOVChipkaart van product
System.out.println("[TEST] findByOVChipkaart() geeft de volgende producten:");
for (Product product : pdao.findByOVChipkaart(ov7)) {
System.out.println(product.toString());
}
// Test update van product
System.out.println("[TEST] update, product:\n " + product1);
Product product3 = new Product(7, "Doordeweeks vrij", "Gratis reizen doordeweeks", 199.00);
pdao.update(product3);
System.out.println("na update: " + pdao.findByOVChipkaart(ov7).get(1));
// Test findAll van product
System.out.println("\n[TEST] findAll() geeft de volgende producten:\n");
for (Product product : pdao.findAll()) {
System.out.println(product.toString());
}
// Test delete van product
System.out.println("\n[TEST] delete, eerst " + pdao.findAll().size() + " producten" );
pdao.delete(product1);
pdao.delete(product2);
System.out.println("Na 2 keer pdao.delete: " + pdao.findAll().size() + " producten\n");
// delete de aangemaakte ovchipkaart
pdao.getOdao().delete(ov7);
}
public static void main(String[] args) {
try {
getConnection();
} catch(SQLException noCon) {
System.out.println("Something went wrong establishing the connection with the database: " + noCon);
}
ReizigerDAOPsql rdao = new ReizigerDAOPsql(connection);
AdresDAOPsql adao = new AdresDAOPsql(connection);
OVChipkaartDAOPsql odao = new OVChipkaartDAOPsql(connection);
ProductDAOsql pdao = new ProductDAOsql(connection);
rdao.setAdao(adao);
adao.setRdao(rdao);
odao.setRdao(rdao);
rdao.setOdao(odao);
odao.setPdao(pdao);
pdao.setOdao(odao);
try {
testReizigerDAO(rdao);
testAdres(adao);
testOVChipkaarten(odao);
testProductDAO(pdao);
}
catch(NullPointerException | SQLException e) {
System.out.println("Something went wrong: " + e);
}
}
}
|
57602_0 | import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList<station> stations = new Utils().csvReader("resources/stations.csv");
ArrayList<track> tracks = new Utils().csvReader("resources/tracks.csv");
HashMap<String, station> stationMap = new HashMap<>(10);
for (station s : stations) {
if (s.getCountry().equals("NL")) {
stationMap.put(s.getCode(), s);
}
}
Graph<station> graph = new Graph<>() {
@Override
public String toWebGraphViz() {
StringBuilder sb = new StringBuilder();
sb.append("digraph {\n");
for (station node : getNodes()) {
sb.append(" ").append(node.getCode()).append(";\n");
}
for (station fromNode : getNodes()) {
for (station destinationNode : getNeighbors(fromNode)) {
sb.append(" ").append(fromNode.getCode()).append(" -> ").append(destinationNode.getCode()).append(" [label=\"").append(getWeight(fromNode, destinationNode)).append("\"];\n");
}
}
sb.append("}");
return sb.toString();
}
};
for (station s : stations) {
if (s.getCountry().equals("NL")) {
graph.addNode(s);
}
}
for (track t : tracks) {
station departure = stationMap.get(t.getDeparture().toUpperCase());
station arrival = stationMap.get(t.getArrival().toUpperCase());
if (departure == null || arrival == null) {
System.err.println("track " + t + " could not be added to the graph");
} else {
int duration = t.getDuration();
graph.addEdge(departure, arrival, duration);
}
}
int choice = 0;
// keuze opties voor programma 1-5
while (choice != 5) {
Scanner scanner = new Scanner(System.in);
System.out.println("1. kijk de route van een station naar een ander station");
System.out.println("2. sorteer de lijst van stations");
System.out.println("3. print de informatie van een station");
System.out.println("4. print de graphviz representatie van de graaf naar een file");
System.out.println("5. exit");
choice = scanner.nextInt();
switch (choice) {
case 1: {
LookUpRoute(scanner, graph, stationMap);
break;
}
case 2: {
SortList(scanner, stations);
break;
}
case 3: {
ZoekAlgoritmes(scanner, stationMap, stations);
break;
}
case 4: {
String webGraphvizRepresentation = graph.toWebGraphViz();
writeWebGraphvizToFile(webGraphvizRepresentation, "graphviz.dot");
break;
}
}
}
}
private static void ZoekAlgoritmes(Scanner scanner, HashMap<String, station> stationMap, ArrayList<station> stations) {
System.out.println("geef aan hou je de informatie wil zoeken");
System.out.println("gebruik Lineair of Binary");
String searchChoice = scanner.next();
System.out.println("Geef het station aan waar je informatie over wilt");
String station = scanner.next();
System.out.println("De informatie over " + station + " is:");
station stationInfo = stationMap.get(station);
System.out.println("Naam: " + stationInfo.getName_Medium());
System.out.println("Land: " + stationInfo.getCountry());
System.out.println("Latitude: " + stationInfo.getLatitude());
System.out.println("Longitude: " + stationInfo.getLongitude());
station opgezochtStation = null;
if (searchChoice.equals("Lineair")) {
opgezochtStation = BasicAlgorithms.linearSearch(stations, station);
} else if (searchChoice.equals("Binary")) {
opgezochtStation = BasicAlgorithms.binarySearch(stations, station);
}
System.out.println(opgezochtStation);
}
private static void SortList(Scanner scanner, ArrayList<station> stations) {
System.out.println("Geef aan hoe je de lijst wilt sorteren");
System.out.println("1. Sorteer op naam merge");
System.out.println("2. Sorteer op naam insertion");
int sortChoice = scanner.nextInt();
switch (sortChoice) {
case 1: {
BasicAlgorithms.mergeSort((String[]) stations.stream().map(station::getName_Medium).toArray(), 0, stations.size() - 1);
break;
}
case 2: {
BasicAlgorithms.insertionSort((String[]) stations.stream().map(station::getName_Medium).toArray());
break;
}
}
stations.forEach(station -> System.out.println(station.getName_Medium()));
}
private static void LookUpRoute(Scanner scanner, Graph<station> graph, HashMap<String, station> stationMap) {
System.out.println("geef het station waar je vandaan komt");
String departure = scanner.next();
System.out.println("geef het station waar je heen wilt");
String arrival = scanner.next();
System.out.println("Geef aan welk algoritme je wilt gebruiken");
System.out.println("1. Dijkstra");
System.out.println("2. A*");
int algoritmeChoice = scanner.nextInt();
List<station> path;
if (algoritmeChoice == 1) {
Dijkstra<station> dijkstra = new Dijkstra<>(graph);
path = dijkstra.getShortestPath(stationMap.get(departure), stationMap.get(arrival));
} else {
AStar<station> aStar = new AStar<>(graph) {
@Override
protected double heuristic(station node, station goal) {
// Assuming Node has latitude and longitude properties
double distance = calculateHaversineDistance(node.getLatitude(), node.getLongitude(), goal.getLatitude(), goal.getLongitude());
return distance;
}
private double calculateHaversineDistance(double lat1, double lon1, double lat2, double lon2) {
// Radius of the Earth in kilometers
final double R = 6371.0;
// Convert latitude and longitude from degrees to radians
double lat1Rad = Math.toRadians(lat1);
double lon1Rad = Math.toRadians(lon1);
double lat2Rad = Math.toRadians(lat2);
double lon2Rad = Math.toRadians(lon2);
// Calculate differences
double dLat = lat2Rad - lat1Rad;
double dLon = lon2Rad - lon1Rad;
// Haversine formula
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
// Distance in kilometers
double distance = R * c;
return distance;
}
};
path = aStar.findShortestPath(stationMap.get(departure), stationMap.get(arrival));
}
System.out.println("de route van " + departure + " naar " + arrival + " is:");
StringBuilder sb = new StringBuilder();
path.forEach(station -> sb.append(station.getName_Medium()).append(" -> "));
sb.delete(sb.length() - 4, sb.length());
System.out.println(sb);
}
public static void writeWebGraphvizToFile(String webGraphvizRepresentation, String fileName) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
writer.write(webGraphvizRepresentation);
System.out.println("WebGraphviz representation written to " + fileName);
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
} | Jorn01/TreinStations | src/Main.java | 2,319 | // keuze opties voor programma 1-5 | line_comment | nl | import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList<station> stations = new Utils().csvReader("resources/stations.csv");
ArrayList<track> tracks = new Utils().csvReader("resources/tracks.csv");
HashMap<String, station> stationMap = new HashMap<>(10);
for (station s : stations) {
if (s.getCountry().equals("NL")) {
stationMap.put(s.getCode(), s);
}
}
Graph<station> graph = new Graph<>() {
@Override
public String toWebGraphViz() {
StringBuilder sb = new StringBuilder();
sb.append("digraph {\n");
for (station node : getNodes()) {
sb.append(" ").append(node.getCode()).append(";\n");
}
for (station fromNode : getNodes()) {
for (station destinationNode : getNeighbors(fromNode)) {
sb.append(" ").append(fromNode.getCode()).append(" -> ").append(destinationNode.getCode()).append(" [label=\"").append(getWeight(fromNode, destinationNode)).append("\"];\n");
}
}
sb.append("}");
return sb.toString();
}
};
for (station s : stations) {
if (s.getCountry().equals("NL")) {
graph.addNode(s);
}
}
for (track t : tracks) {
station departure = stationMap.get(t.getDeparture().toUpperCase());
station arrival = stationMap.get(t.getArrival().toUpperCase());
if (departure == null || arrival == null) {
System.err.println("track " + t + " could not be added to the graph");
} else {
int duration = t.getDuration();
graph.addEdge(departure, arrival, duration);
}
}
int choice = 0;
// keuze opties<SUF>
while (choice != 5) {
Scanner scanner = new Scanner(System.in);
System.out.println("1. kijk de route van een station naar een ander station");
System.out.println("2. sorteer de lijst van stations");
System.out.println("3. print de informatie van een station");
System.out.println("4. print de graphviz representatie van de graaf naar een file");
System.out.println("5. exit");
choice = scanner.nextInt();
switch (choice) {
case 1: {
LookUpRoute(scanner, graph, stationMap);
break;
}
case 2: {
SortList(scanner, stations);
break;
}
case 3: {
ZoekAlgoritmes(scanner, stationMap, stations);
break;
}
case 4: {
String webGraphvizRepresentation = graph.toWebGraphViz();
writeWebGraphvizToFile(webGraphvizRepresentation, "graphviz.dot");
break;
}
}
}
}
private static void ZoekAlgoritmes(Scanner scanner, HashMap<String, station> stationMap, ArrayList<station> stations) {
System.out.println("geef aan hou je de informatie wil zoeken");
System.out.println("gebruik Lineair of Binary");
String searchChoice = scanner.next();
System.out.println("Geef het station aan waar je informatie over wilt");
String station = scanner.next();
System.out.println("De informatie over " + station + " is:");
station stationInfo = stationMap.get(station);
System.out.println("Naam: " + stationInfo.getName_Medium());
System.out.println("Land: " + stationInfo.getCountry());
System.out.println("Latitude: " + stationInfo.getLatitude());
System.out.println("Longitude: " + stationInfo.getLongitude());
station opgezochtStation = null;
if (searchChoice.equals("Lineair")) {
opgezochtStation = BasicAlgorithms.linearSearch(stations, station);
} else if (searchChoice.equals("Binary")) {
opgezochtStation = BasicAlgorithms.binarySearch(stations, station);
}
System.out.println(opgezochtStation);
}
private static void SortList(Scanner scanner, ArrayList<station> stations) {
System.out.println("Geef aan hoe je de lijst wilt sorteren");
System.out.println("1. Sorteer op naam merge");
System.out.println("2. Sorteer op naam insertion");
int sortChoice = scanner.nextInt();
switch (sortChoice) {
case 1: {
BasicAlgorithms.mergeSort((String[]) stations.stream().map(station::getName_Medium).toArray(), 0, stations.size() - 1);
break;
}
case 2: {
BasicAlgorithms.insertionSort((String[]) stations.stream().map(station::getName_Medium).toArray());
break;
}
}
stations.forEach(station -> System.out.println(station.getName_Medium()));
}
private static void LookUpRoute(Scanner scanner, Graph<station> graph, HashMap<String, station> stationMap) {
System.out.println("geef het station waar je vandaan komt");
String departure = scanner.next();
System.out.println("geef het station waar je heen wilt");
String arrival = scanner.next();
System.out.println("Geef aan welk algoritme je wilt gebruiken");
System.out.println("1. Dijkstra");
System.out.println("2. A*");
int algoritmeChoice = scanner.nextInt();
List<station> path;
if (algoritmeChoice == 1) {
Dijkstra<station> dijkstra = new Dijkstra<>(graph);
path = dijkstra.getShortestPath(stationMap.get(departure), stationMap.get(arrival));
} else {
AStar<station> aStar = new AStar<>(graph) {
@Override
protected double heuristic(station node, station goal) {
// Assuming Node has latitude and longitude properties
double distance = calculateHaversineDistance(node.getLatitude(), node.getLongitude(), goal.getLatitude(), goal.getLongitude());
return distance;
}
private double calculateHaversineDistance(double lat1, double lon1, double lat2, double lon2) {
// Radius of the Earth in kilometers
final double R = 6371.0;
// Convert latitude and longitude from degrees to radians
double lat1Rad = Math.toRadians(lat1);
double lon1Rad = Math.toRadians(lon1);
double lat2Rad = Math.toRadians(lat2);
double lon2Rad = Math.toRadians(lon2);
// Calculate differences
double dLat = lat2Rad - lat1Rad;
double dLon = lon2Rad - lon1Rad;
// Haversine formula
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
// Distance in kilometers
double distance = R * c;
return distance;
}
};
path = aStar.findShortestPath(stationMap.get(departure), stationMap.get(arrival));
}
System.out.println("de route van " + departure + " naar " + arrival + " is:");
StringBuilder sb = new StringBuilder();
path.forEach(station -> sb.append(station.getName_Medium()).append(" -> "));
sb.delete(sb.length() - 4, sb.length());
System.out.println(sb);
}
public static void writeWebGraphvizToFile(String webGraphvizRepresentation, String fileName) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
writer.write(webGraphvizRepresentation);
System.out.println("WebGraphviz representation written to " + fileName);
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
} |
11810_5 | package nl.joris.joris.model;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import jakarta.persistence.*;
import org.springframework.data.relational.core.sql.In;
import java.util.ArrayList;
import java.util.List;
// One to one
// many to one
// one to many
// many to many
@Entity
public class Kat {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String naam;
private Integer leeftijd;
@OneToOne
@JoinColumn(name = "chip_id")
private Chip chip;
@OneToMany
@JsonManagedReference
private List<Kitten> kittens = new ArrayList<>();
// Eigenaarskant van de relatie
@ManyToMany
@JoinTable(
name = "katten_mensen",
joinColumns = @JoinColumn(name = "kat_id"),
inverseJoinColumns = @JoinColumn(name = "mens_id")
)
private List<Mens> mensen = new ArrayList<>();
// default constructor
public Kat() {}
// constructor om alle velden behalve id te zetten
public Kat(String naam, Integer leeftijd) {
this.naam = naam;
this.leeftijd = leeftijd;
}
public Long getId() {
return id;
}
public Chip getChip() {
return chip;
}
public void setChip(Chip chip) {
this.chip = chip;
}
public String getNaam() {
return naam;
}
public void setNaam(String naam) {
this.naam = naam;
}
public Integer getLeeftijd() {
return leeftijd;
}
public void setLeeftijd(Integer leeftijd) {
this.leeftijd = leeftijd;
}
public List<Kitten> getKittens() {
return kittens;
}
public void setKittens(List<Kitten> kittens) {
this.kittens = kittens;
}
}
| Joroovb/itvitae-fase3 | dag2/joris/src/main/java/nl/joris/joris/model/Kat.java | 561 | // constructor om alle velden behalve id te zetten | line_comment | nl | package nl.joris.joris.model;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import jakarta.persistence.*;
import org.springframework.data.relational.core.sql.In;
import java.util.ArrayList;
import java.util.List;
// One to one
// many to one
// one to many
// many to many
@Entity
public class Kat {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String naam;
private Integer leeftijd;
@OneToOne
@JoinColumn(name = "chip_id")
private Chip chip;
@OneToMany
@JsonManagedReference
private List<Kitten> kittens = new ArrayList<>();
// Eigenaarskant van de relatie
@ManyToMany
@JoinTable(
name = "katten_mensen",
joinColumns = @JoinColumn(name = "kat_id"),
inverseJoinColumns = @JoinColumn(name = "mens_id")
)
private List<Mens> mensen = new ArrayList<>();
// default constructor
public Kat() {}
// constructor om<SUF>
public Kat(String naam, Integer leeftijd) {
this.naam = naam;
this.leeftijd = leeftijd;
}
public Long getId() {
return id;
}
public Chip getChip() {
return chip;
}
public void setChip(Chip chip) {
this.chip = chip;
}
public String getNaam() {
return naam;
}
public void setNaam(String naam) {
this.naam = naam;
}
public Integer getLeeftijd() {
return leeftijd;
}
public void setLeeftijd(Integer leeftijd) {
this.leeftijd = leeftijd;
}
public List<Kitten> getKittens() {
return kittens;
}
public void setKittens(List<Kitten> kittens) {
this.kittens = kittens;
}
}
|
67676_13 | // Encapsulation
// private attributes, public methods
class Hond {
String naam;
final int geboorteDatum = 1234;
static int aantalHonden;
static final String LATIJNSE_NAAM = "Canine";
}
//class Persoon {
// int leeftijd;
// final String oogKleur;
// static int aantalPersonen;
// static final String LATIJNSE_NAAM = "Homo Sapien"
//}
//
//class Melk {
// int aantalDagenHoudbaar;
// final String batch;
// static int aantalLitersMelk;
// static final String kleur;
//}
//
//class Voertuig {
// String naam;
// final int productieJaar;
// static int aantalInProductie;
// static final boolean kanRijden;
//}
class Parent {
static int leeftijd;
}
class Child extends Parent {
}
public class Vogel {
int aantalVleugels; // 0
private String naam;
String voeding;
static int MAX_LEEFTIJD = 40;
// abstract void eten();
public Vogel() {
}
public Vogel(String jojo, int jo, String jojojo) {
}
// public Vogel(int aantalVleugels, String naam, String voeding) {
// this.aantalVleugels = aantalVleugels;
// this.naam = naam;
// this.voeding = voeding;
// }
public void vliegen() {
System.out.println("Ik ga vliegen");
}
public void vliegen(String naam) {
}
public void zegNaam() {
System.out.println("Mijn naam is: " + naam);
}
public String getNaam() {
return naam;
}
public void setNaam(String naam) {
this.naam = naam;
}
}
| Joroovb/itvitae-lessen | Les 1/scratchpad-itv/src/Vogel.java | 512 | // abstract void eten(); | line_comment | nl | // Encapsulation
// private attributes, public methods
class Hond {
String naam;
final int geboorteDatum = 1234;
static int aantalHonden;
static final String LATIJNSE_NAAM = "Canine";
}
//class Persoon {
// int leeftijd;
// final String oogKleur;
// static int aantalPersonen;
// static final String LATIJNSE_NAAM = "Homo Sapien"
//}
//
//class Melk {
// int aantalDagenHoudbaar;
// final String batch;
// static int aantalLitersMelk;
// static final String kleur;
//}
//
//class Voertuig {
// String naam;
// final int productieJaar;
// static int aantalInProductie;
// static final boolean kanRijden;
//}
class Parent {
static int leeftijd;
}
class Child extends Parent {
}
public class Vogel {
int aantalVleugels; // 0
private String naam;
String voeding;
static int MAX_LEEFTIJD = 40;
// abstract void<SUF>
public Vogel() {
}
public Vogel(String jojo, int jo, String jojojo) {
}
// public Vogel(int aantalVleugels, String naam, String voeding) {
// this.aantalVleugels = aantalVleugels;
// this.naam = naam;
// this.voeding = voeding;
// }
public void vliegen() {
System.out.println("Ik ga vliegen");
}
public void vliegen(String naam) {
}
public void zegNaam() {
System.out.println("Mijn naam is: " + naam);
}
public String getNaam() {
return naam;
}
public void setNaam(String naam) {
this.naam = naam;
}
}
|
111054_26 | package clientmenu;
import com.toedter.calendar.JDateChooser;
import employeeacess.ValidateInput;
import model.TaskManagment;
import javax.swing.*;
import java.awt.*;
import java.text.SimpleDateFormat;
//No Ticket Registration o createTask deve ser assim please(a ordem das strings):
// createTask("Ticket Registration", nifNum, plate, date, reason, value, expirationDate);
public class InsertMenuForm extends JFrame implements ValidateInput {
private int nifNum;
public InsertMenuForm(int nifNum) {
this.nifNum = nifNum;
try {
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Exception e) {
e.printStackTrace();
}
initializeUI();
}
private void initializeUI() {
setTitle("Register Menu");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setExtendedState(JFrame.MAXIMIZED_BOTH);
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(10, 10, 10, 10);
JLabel headerLabel = new JLabel("Register Menu");
headerLabel.setFont(new Font("Helvetica", Font.BOLD, 36));
gbc.gridx = 0;
gbc.gridy = 0;
panel.add(headerLabel, gbc);
JButton insertVehicleButton = new JButton("Register Vehicle");
insertVehicleButton.setBackground(new Color(6, 65, 16));
insertVehicleButton.setForeground(Color.white);
insertVehicleButton.setPreferredSize(new Dimension(250, 40));
insertVehicleButton.addActionListener(e -> showInsertVehicleDialog());
gbc.gridy = 1;
panel.add(insertVehicleButton, gbc);
JButton insertInsuranceButton = new JButton("Register Insurance");
insertInsuranceButton.setBackground(new Color(6, 65, 16));
insertInsuranceButton.setForeground(Color.white);
insertInsuranceButton.setPreferredSize(new Dimension(250, 40));
insertInsuranceButton.addActionListener(e -> showInsertInsuranceDialog());
gbc.gridy = 2;
panel.add(insertInsuranceButton, gbc);
// JButton insertTicketButton = new JButton("Register Ticket");
// insertTicketButton.setBackground(new Color(6, 65, 16));
// insertTicketButton.setForeground(Color.white);
// insertTicketButton.setPreferredSize(new Dimension(250, 40));
// insertTicketButton.addActionListener(e -> showInsertTicketDialog());
// gbc.gridy = 3;
// panel.add(insertTicketButton, gbc);
JButton goBackButton = new JButton("Go Back");
goBackButton.setBackground(new Color(32, 32, 32));
goBackButton.setForeground(Color.white);
goBackButton.setPreferredSize(new Dimension(250, 40));
goBackButton.addActionListener(e -> handleGoBackButton());
gbc.gridy = 3;
panel.add(goBackButton, gbc);
add(panel);
setVisible(true);
}
private void showInsertVehicleDialog() {
JPanel panel = new JPanel(new GridLayout(0, 1));
JComboBox<String> brandField = new JComboBox<>(new String[]{" ", "Abarth", "Alfa Romeo", "Aston Martin", "Audi",
"Bentley", "BMW", "Bugatti", "Cadillac", "Chevrolet", "Chrysler", "Citroen", "Dacia", "Daewoo",
"Daihatsu", "Dodge", "Donkervoort", "DS", "Ferrari", "Fiat", "Fisker", "Ford", "Honda", "Hummer",
"Hyundai", "Infiniti", "Iveco", "Jaguar", "Jeep", "Kia", "KTM", "Lada", "Lamborghini", "Lancia",
"Land Rover", "Landwind", "Lexus", "Lotus", "Maserati", "Maybach", "Mazda", "McLaren", "Mercedes-Benz",
"MG", "Mini", "Mitsubishi", "Morgan", "Nissan", "Opel", "Peugeot", "Porsche", "Renault", "Rolls-Royce",
"Rover", "Saab", "Seat", "Skoda", "Smart", "SsangYong", "Subaru", "Suzuki", "Tesla", "Toyota",
"Volkswagen", "Volvo"});
JTextField modelField = new JTextField(15);
JTextField plateField = new JTextField(15);
JComboBox<String> colorField = new JComboBox<>(new String[]{" ", "Black", "White",
"Red", "Blue", "Green", "Yellow", "Gray", "Silver", "Brown", "Orange"});
JDateChooser registrationDateField = new JDateChooser();
registrationDateField.setDateFormatString("yyyy-MM-dd");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
JTextField vinField = new JTextField(15);
JTextField nifField = new JTextField(15);
JComboBox<String> categoryField = new JComboBox<>(new String[]{" ", "Light Commercial Vehicle",
"Light Passenger Vehicle",
"Heavy-duty Commercial Vehicle",
"Heavy-duty Passenger Vehicle",
"Motorcycle", "Moped",
"Heavy-duty Passenger Vehicle"});
panel.add(new JLabel("Brand:"));
panel.add(brandField);
panel.add(new JLabel("Model:"));
panel.add(modelField);
panel.add(new JLabel("Plate: XX-XX-XX "));
panel.add(plateField);
panel.add(new JLabel("Color:"));
panel.add(colorField);
panel.add(new JLabel("Registration Date:"));
panel.add(registrationDateField);
panel.add(new JLabel("VIN: (17 characters)"));
panel.add(vinField);
// panel.add(new JLabel("NIF: (9 digits)"));
// panel.add(nifField);
panel.add(new JLabel("Category:"));
panel.add(categoryField);
int result = JOptionPane.showConfirmDialog(this, panel, "Register New Vehicle", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
String brand = (String) brandField.getSelectedItem();
String model = modelField.getText();
String plate = plateField.getText();
String color = (String) colorField.getSelectedItem();
String registrationDate = sdf.format(registrationDateField.getDate());
String vin = vinField.getText();
String nif = nifField.getText();
String category = (String) categoryField.getSelectedItem();
TaskManagment taskManagment = new TaskManagment();
if (!brand.equals(" ") && isValidString(model) && isPlate(plate)
&& !color.equals(" ") && isDate(registrationDate) && isVIN(vin)
&& !category.equals(" ")) {
taskManagment.createTask("Vehicle Registration", nifNum, plate, vin, color, brand, model, registrationDate, category, String.valueOf(nifNum));
JOptionPane.showMessageDialog(this, "Register request has been made.");
} else {
JOptionPane.showMessageDialog(this, "Invalid input.");
}
}
}
private void showInsertInsuranceDialog() {
JPanel panel = new JPanel(new GridLayout(0, 1));
JTextField plateField = new JTextField(15);
JComboBox<String> insuranceCategoryField = new JComboBox<>(new String[]{" ", "Third Party",
"Third Party Fire and Theft", "Third Party Fire and Auto-Liabitlity", "Comprehensive"});
JTextField policyField = new JTextField(15);
JDateChooser startDateField = new JDateChooser();
startDateField.setDateFormatString("yyyy-MM-dd");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
JDateChooser endDateField = new JDateChooser();
endDateField.setDateFormatString("yyyy-MM-dd");
JComboBox<String> companyNameField2 = new JComboBox<>(new String[]{" ", "Tranquilidade",
"Generalli", "Fidelidade", "Logo", "Ok!", "AGEAS Seguros", "Cofidis", "ACP Seguuros", "UNO Seguros", "Allianz"});
panel.add(new JLabel("Plate: "));
panel.add(plateField);
panel.add(new JLabel("Insurance Category: "));
panel.add(insuranceCategoryField);
panel.add(new JLabel("Policy: (9 Numbers) "));
panel.add(policyField);
panel.add(new JLabel("Start Date: "));
panel.add(startDateField);
panel.add(new JLabel("End Date: "));
panel.add(endDateField);
panel.add(new JLabel("Company Name: "));
panel.add(companyNameField2);
int result = JOptionPane.showConfirmDialog(this, panel, "Register New Insurance", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
String plate = plateField.getText();
String insuranceCategory = (String) insuranceCategoryField.getSelectedItem();
String policy = policyField.getText();
String startDate = sdf.format(startDateField.getDate());
String endDate = sdf.format(endDateField.getDate());
String companyName = (String) companyNameField2.getSelectedItem();
TaskManagment taskManagment = new TaskManagment();
if (isPlate(plate) && !insuranceCategory.equals(" ") && isPolicy(policy) &&
isDate(startDate) && isDate(endDate) && !companyName.equals(" ")) {
taskManagment.createTask("Insurance Registration", nifNum, policy, plate, startDate, insuranceCategory, endDate, companyName);
JOptionPane.showMessageDialog(this, "Register request has been made.");
} else {
JOptionPane.showMessageDialog(this, "Invalid input.");
}
}
}
// private void showInsertTicketDialog() {
// JPanel panel = new JPanel(new GridLayout(0, 1));
// JTextField plateField = new JTextField(15);
// JDateChooser dateField = new JDateChooser();
// dateField.setDateFormatString("yyyy-MM-dd");
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
// JComboBox<String> reasonField = new JComboBox<>(new String[]{" ", "Illegal arking",
// "Speeding", "Red light", "Reckless driving", "DUI"});
// JTextField valueField = new JTextField(15);
// JTextField nifField = new JTextField(15);
// JTextField expirationDateField = new JTextField(15);
//
// panel.add(new JLabel("Plate: "));
// panel.add(plateField);
// panel.add(new JLabel("Date: "));
// panel.add(dateField);
// panel.add(new JLabel("Reason: "));
// panel.add(reasonField);
// panel.add(new JLabel("Value: "));
// panel.add(valueField);
//// panel.add(new JLabel("NIF: "));
//// panel.add(nifField);
// panel.add(new JLabel("Expiration Date: "));
// panel.add(expirationDateField);
//
// int result = JOptionPane.showConfirmDialog(this, panel, "Register New Ticket", JOptionPane.OK_CANCEL_OPTION);
// if (result == JOptionPane.OK_OPTION) {
// String plate = plateField.getText();
// String date = sdf.format(dateField.getDate());
// String reason = (String) reasonField.getSelectedItem();
// String value = valueField.getText();
//// String nif = nifField.getText();
// String expirationDate = expirationDateField.getText();
//
// TaskManagment taskManagment = new TaskManagment();
//
// if (isPlate(plate) && isDate(date) && isValidExpirationDate(expirationDate) && isDouble(value)
// && !reason.equals(" ")) {
// taskManagment.createTask("Ticket Registration", nifNum, String.valueOf(nifNum),
// plate, date, reason, value, expirationDate);
// JOptionPane.showMessageDialog(this, "Request has been made.");
// } else {
// JOptionPane.showMessageDialog(this, "Invalid input.");
// }
// }
// }
private void handleGoBackButton() {
this.dispose();
CustomerForm customerForm = new CustomerForm(nifNum);
customerForm.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
InsertMenuForm insertMenuForm = new InsertMenuForm(-1);
// insertMenuForm.setVisible(true);
});
}
} | JoseDRomano/CarSync | src/clientmenu/InsertMenuForm.java | 3,582 | // String plate = plateField.getText(); | line_comment | nl | package clientmenu;
import com.toedter.calendar.JDateChooser;
import employeeacess.ValidateInput;
import model.TaskManagment;
import javax.swing.*;
import java.awt.*;
import java.text.SimpleDateFormat;
//No Ticket Registration o createTask deve ser assim please(a ordem das strings):
// createTask("Ticket Registration", nifNum, plate, date, reason, value, expirationDate);
public class InsertMenuForm extends JFrame implements ValidateInput {
private int nifNum;
public InsertMenuForm(int nifNum) {
this.nifNum = nifNum;
try {
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Exception e) {
e.printStackTrace();
}
initializeUI();
}
private void initializeUI() {
setTitle("Register Menu");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setExtendedState(JFrame.MAXIMIZED_BOTH);
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(10, 10, 10, 10);
JLabel headerLabel = new JLabel("Register Menu");
headerLabel.setFont(new Font("Helvetica", Font.BOLD, 36));
gbc.gridx = 0;
gbc.gridy = 0;
panel.add(headerLabel, gbc);
JButton insertVehicleButton = new JButton("Register Vehicle");
insertVehicleButton.setBackground(new Color(6, 65, 16));
insertVehicleButton.setForeground(Color.white);
insertVehicleButton.setPreferredSize(new Dimension(250, 40));
insertVehicleButton.addActionListener(e -> showInsertVehicleDialog());
gbc.gridy = 1;
panel.add(insertVehicleButton, gbc);
JButton insertInsuranceButton = new JButton("Register Insurance");
insertInsuranceButton.setBackground(new Color(6, 65, 16));
insertInsuranceButton.setForeground(Color.white);
insertInsuranceButton.setPreferredSize(new Dimension(250, 40));
insertInsuranceButton.addActionListener(e -> showInsertInsuranceDialog());
gbc.gridy = 2;
panel.add(insertInsuranceButton, gbc);
// JButton insertTicketButton = new JButton("Register Ticket");
// insertTicketButton.setBackground(new Color(6, 65, 16));
// insertTicketButton.setForeground(Color.white);
// insertTicketButton.setPreferredSize(new Dimension(250, 40));
// insertTicketButton.addActionListener(e -> showInsertTicketDialog());
// gbc.gridy = 3;
// panel.add(insertTicketButton, gbc);
JButton goBackButton = new JButton("Go Back");
goBackButton.setBackground(new Color(32, 32, 32));
goBackButton.setForeground(Color.white);
goBackButton.setPreferredSize(new Dimension(250, 40));
goBackButton.addActionListener(e -> handleGoBackButton());
gbc.gridy = 3;
panel.add(goBackButton, gbc);
add(panel);
setVisible(true);
}
private void showInsertVehicleDialog() {
JPanel panel = new JPanel(new GridLayout(0, 1));
JComboBox<String> brandField = new JComboBox<>(new String[]{" ", "Abarth", "Alfa Romeo", "Aston Martin", "Audi",
"Bentley", "BMW", "Bugatti", "Cadillac", "Chevrolet", "Chrysler", "Citroen", "Dacia", "Daewoo",
"Daihatsu", "Dodge", "Donkervoort", "DS", "Ferrari", "Fiat", "Fisker", "Ford", "Honda", "Hummer",
"Hyundai", "Infiniti", "Iveco", "Jaguar", "Jeep", "Kia", "KTM", "Lada", "Lamborghini", "Lancia",
"Land Rover", "Landwind", "Lexus", "Lotus", "Maserati", "Maybach", "Mazda", "McLaren", "Mercedes-Benz",
"MG", "Mini", "Mitsubishi", "Morgan", "Nissan", "Opel", "Peugeot", "Porsche", "Renault", "Rolls-Royce",
"Rover", "Saab", "Seat", "Skoda", "Smart", "SsangYong", "Subaru", "Suzuki", "Tesla", "Toyota",
"Volkswagen", "Volvo"});
JTextField modelField = new JTextField(15);
JTextField plateField = new JTextField(15);
JComboBox<String> colorField = new JComboBox<>(new String[]{" ", "Black", "White",
"Red", "Blue", "Green", "Yellow", "Gray", "Silver", "Brown", "Orange"});
JDateChooser registrationDateField = new JDateChooser();
registrationDateField.setDateFormatString("yyyy-MM-dd");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
JTextField vinField = new JTextField(15);
JTextField nifField = new JTextField(15);
JComboBox<String> categoryField = new JComboBox<>(new String[]{" ", "Light Commercial Vehicle",
"Light Passenger Vehicle",
"Heavy-duty Commercial Vehicle",
"Heavy-duty Passenger Vehicle",
"Motorcycle", "Moped",
"Heavy-duty Passenger Vehicle"});
panel.add(new JLabel("Brand:"));
panel.add(brandField);
panel.add(new JLabel("Model:"));
panel.add(modelField);
panel.add(new JLabel("Plate: XX-XX-XX "));
panel.add(plateField);
panel.add(new JLabel("Color:"));
panel.add(colorField);
panel.add(new JLabel("Registration Date:"));
panel.add(registrationDateField);
panel.add(new JLabel("VIN: (17 characters)"));
panel.add(vinField);
// panel.add(new JLabel("NIF: (9 digits)"));
// panel.add(nifField);
panel.add(new JLabel("Category:"));
panel.add(categoryField);
int result = JOptionPane.showConfirmDialog(this, panel, "Register New Vehicle", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
String brand = (String) brandField.getSelectedItem();
String model = modelField.getText();
String plate = plateField.getText();
String color = (String) colorField.getSelectedItem();
String registrationDate = sdf.format(registrationDateField.getDate());
String vin = vinField.getText();
String nif = nifField.getText();
String category = (String) categoryField.getSelectedItem();
TaskManagment taskManagment = new TaskManagment();
if (!brand.equals(" ") && isValidString(model) && isPlate(plate)
&& !color.equals(" ") && isDate(registrationDate) && isVIN(vin)
&& !category.equals(" ")) {
taskManagment.createTask("Vehicle Registration", nifNum, plate, vin, color, brand, model, registrationDate, category, String.valueOf(nifNum));
JOptionPane.showMessageDialog(this, "Register request has been made.");
} else {
JOptionPane.showMessageDialog(this, "Invalid input.");
}
}
}
private void showInsertInsuranceDialog() {
JPanel panel = new JPanel(new GridLayout(0, 1));
JTextField plateField = new JTextField(15);
JComboBox<String> insuranceCategoryField = new JComboBox<>(new String[]{" ", "Third Party",
"Third Party Fire and Theft", "Third Party Fire and Auto-Liabitlity", "Comprehensive"});
JTextField policyField = new JTextField(15);
JDateChooser startDateField = new JDateChooser();
startDateField.setDateFormatString("yyyy-MM-dd");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
JDateChooser endDateField = new JDateChooser();
endDateField.setDateFormatString("yyyy-MM-dd");
JComboBox<String> companyNameField2 = new JComboBox<>(new String[]{" ", "Tranquilidade",
"Generalli", "Fidelidade", "Logo", "Ok!", "AGEAS Seguros", "Cofidis", "ACP Seguuros", "UNO Seguros", "Allianz"});
panel.add(new JLabel("Plate: "));
panel.add(plateField);
panel.add(new JLabel("Insurance Category: "));
panel.add(insuranceCategoryField);
panel.add(new JLabel("Policy: (9 Numbers) "));
panel.add(policyField);
panel.add(new JLabel("Start Date: "));
panel.add(startDateField);
panel.add(new JLabel("End Date: "));
panel.add(endDateField);
panel.add(new JLabel("Company Name: "));
panel.add(companyNameField2);
int result = JOptionPane.showConfirmDialog(this, panel, "Register New Insurance", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
String plate = plateField.getText();
String insuranceCategory = (String) insuranceCategoryField.getSelectedItem();
String policy = policyField.getText();
String startDate = sdf.format(startDateField.getDate());
String endDate = sdf.format(endDateField.getDate());
String companyName = (String) companyNameField2.getSelectedItem();
TaskManagment taskManagment = new TaskManagment();
if (isPlate(plate) && !insuranceCategory.equals(" ") && isPolicy(policy) &&
isDate(startDate) && isDate(endDate) && !companyName.equals(" ")) {
taskManagment.createTask("Insurance Registration", nifNum, policy, plate, startDate, insuranceCategory, endDate, companyName);
JOptionPane.showMessageDialog(this, "Register request has been made.");
} else {
JOptionPane.showMessageDialog(this, "Invalid input.");
}
}
}
// private void showInsertTicketDialog() {
// JPanel panel = new JPanel(new GridLayout(0, 1));
// JTextField plateField = new JTextField(15);
// JDateChooser dateField = new JDateChooser();
// dateField.setDateFormatString("yyyy-MM-dd");
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
// JComboBox<String> reasonField = new JComboBox<>(new String[]{" ", "Illegal arking",
// "Speeding", "Red light", "Reckless driving", "DUI"});
// JTextField valueField = new JTextField(15);
// JTextField nifField = new JTextField(15);
// JTextField expirationDateField = new JTextField(15);
//
// panel.add(new JLabel("Plate: "));
// panel.add(plateField);
// panel.add(new JLabel("Date: "));
// panel.add(dateField);
// panel.add(new JLabel("Reason: "));
// panel.add(reasonField);
// panel.add(new JLabel("Value: "));
// panel.add(valueField);
//// panel.add(new JLabel("NIF: "));
//// panel.add(nifField);
// panel.add(new JLabel("Expiration Date: "));
// panel.add(expirationDateField);
//
// int result = JOptionPane.showConfirmDialog(this, panel, "Register New Ticket", JOptionPane.OK_CANCEL_OPTION);
// if (result == JOptionPane.OK_OPTION) {
// String plate<SUF>
// String date = sdf.format(dateField.getDate());
// String reason = (String) reasonField.getSelectedItem();
// String value = valueField.getText();
//// String nif = nifField.getText();
// String expirationDate = expirationDateField.getText();
//
// TaskManagment taskManagment = new TaskManagment();
//
// if (isPlate(plate) && isDate(date) && isValidExpirationDate(expirationDate) && isDouble(value)
// && !reason.equals(" ")) {
// taskManagment.createTask("Ticket Registration", nifNum, String.valueOf(nifNum),
// plate, date, reason, value, expirationDate);
// JOptionPane.showMessageDialog(this, "Request has been made.");
// } else {
// JOptionPane.showMessageDialog(this, "Invalid input.");
// }
// }
// }
private void handleGoBackButton() {
this.dispose();
CustomerForm customerForm = new CustomerForm(nifNum);
customerForm.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
InsertMenuForm insertMenuForm = new InsertMenuForm(-1);
// insertMenuForm.setVisible(true);
});
}
} |
101693_3 | import ea.edu.*;
import ea.*;
public class Bild extends BildE
{
/**
* BILD Konstruktor
*
* @param x x-Koordinate im Fenster (Pixel)
* @param y y-Koordinate im Fenster (Pixel)
* @param name Name der Grafik-Datei (im Projekt-Ordner)
*/
public Bild(int x, int y, String name)
{
super(x, y, name);
this.setzeMittelpunkt(x, y);
}
/**
* Methode verschiebenUm
*
* @param deltaX Pixel in x-Richtung (wird bei Bedarf auf ganze Pixel
* gerundet)
* @param deltaY Pixel in y-Richtung (wird bei Bedarf auf ganze Pixel
* gerundet)
*/
public void verschiebenUm(double deltaX, double deltaY)
{
super.bewegen((int) (Math.round(deltaX)), (int) (Math.round(deltaY)));
}
/**
* Methode beinhaltetPunkt
*
* @param x x-Koordinate des Punkts (Pixel)
* @param y x-Koordinate des Punkts (Pixel)
* @return true, wenn Punkt innerhalb der Grafik
*/
public boolean beinhaltetPunkt(int x, int y)
{
return super.beinhaltet(new Punkt(x, y));
}
/**
* Methode setzeMittelpunkt
*
* @param x x-Koordinate des Mittelpunkts (Pixel)
* @param y y-Koordinate des Mittelpunkts (Pixel)
*/
public void setzeMittelpunkt(int x, int y)
{
super.mittelpunktSetzen(x, y);
}
/**
* Methode nenneMx
*
* @return x-Koordinate des Mittelpunkts (Pixel)
*/
public int nenneMx()
{
return super.zentrum().x();
}
/**
* Methode nenneMY
*
* @return y-Koordinate des Mittelpunkts (Pixel)
*/
public int nenneMy()
{
return super.zentrum().y();
}
/**
* Methode setzeSichtbar
*
* @param sichtbarNeu true, wenn die Grafik sichtbar sein soll
*/
public void setzeSichtbar(boolean sichtbarNeu)
{
super.sichtbarSetzen(sichtbarNeu);
}
/**
* Methode nenneSichtbar
*
* @return true, wenn die Grafik gerade sichbar ist
*/
public boolean nenneSichtbar()
{
return super.sichtbar();
}
/**
* Dreht die Grafik um einen Winkel
*
* @param winkelAenderung +: mathematisch positiver Drehsinn (gegen den
* Uhrzeigersinn) -: mathematisch negativer Drehsinn
* (im Uhrzeigersinn)
*/
public void drehenUm(int winkelAenderung)
{
this.drehenRelativ((double) (winkelAenderung));
}
/**
* Setzt den Drehwinkel auf eine absoluten neuen Wert
*
* @param neuerDrehwinkel der neue Drehwinkel +: mathematisch positiver
* Drehsinn (gegen den Uhrzeigersinn) -: mathematisch
* negativer Drehsinn (im Uhrzeigersinn)
*/
public void setzeDrehwinkel(int neuerDrehwinkel)
{
this.drehenAbsolut((double) (-neuerDrehwinkel));
}
/**
* Nennt den Winkel, um den die Grafik gedreht wurde
*
* @return der Winkel, um den die Grafik gedreht wurde 0: wenn nicht gedreht
* +: wenn mathematisch positiver Drehsinn (gegen den Uhrzeigersinn)
* -: wenn mathematisch negativer Drehsinn (im Uhrzeigersinn)
*/
public int nenneWinkel()
{
return (int) (-this.gibDrehung());
}
/**
* liefert den Sinus des Drehwinkels der Grafik
*
* @return Sinus des aktuellen Drehwinkels
*/
public double sin_Drehwinkel()
{
return Math.sin(-this.gibDrehung() * Math.PI / 180);
}
/**
* liefert den Cosinus des Drehwinkels der Grafik
*
* @return Cosinus des aktuellen Drehwinkels
*/
public double cos_Drehwinkel()
{
return Math.cos(this.gibDrehung() * Math.PI / 180);
}
}
| Josef-Friedrich/erzeuger-verbraucher-stapler | Bild.java | 1,325 | /**
* Methode setzeMittelpunkt
*
* @param x x-Koordinate des Mittelpunkts (Pixel)
* @param y y-Koordinate des Mittelpunkts (Pixel)
*/ | block_comment | nl | import ea.edu.*;
import ea.*;
public class Bild extends BildE
{
/**
* BILD Konstruktor
*
* @param x x-Koordinate im Fenster (Pixel)
* @param y y-Koordinate im Fenster (Pixel)
* @param name Name der Grafik-Datei (im Projekt-Ordner)
*/
public Bild(int x, int y, String name)
{
super(x, y, name);
this.setzeMittelpunkt(x, y);
}
/**
* Methode verschiebenUm
*
* @param deltaX Pixel in x-Richtung (wird bei Bedarf auf ganze Pixel
* gerundet)
* @param deltaY Pixel in y-Richtung (wird bei Bedarf auf ganze Pixel
* gerundet)
*/
public void verschiebenUm(double deltaX, double deltaY)
{
super.bewegen((int) (Math.round(deltaX)), (int) (Math.round(deltaY)));
}
/**
* Methode beinhaltetPunkt
*
* @param x x-Koordinate des Punkts (Pixel)
* @param y x-Koordinate des Punkts (Pixel)
* @return true, wenn Punkt innerhalb der Grafik
*/
public boolean beinhaltetPunkt(int x, int y)
{
return super.beinhaltet(new Punkt(x, y));
}
/**
* Methode setzeMittelpunkt
<SUF>*/
public void setzeMittelpunkt(int x, int y)
{
super.mittelpunktSetzen(x, y);
}
/**
* Methode nenneMx
*
* @return x-Koordinate des Mittelpunkts (Pixel)
*/
public int nenneMx()
{
return super.zentrum().x();
}
/**
* Methode nenneMY
*
* @return y-Koordinate des Mittelpunkts (Pixel)
*/
public int nenneMy()
{
return super.zentrum().y();
}
/**
* Methode setzeSichtbar
*
* @param sichtbarNeu true, wenn die Grafik sichtbar sein soll
*/
public void setzeSichtbar(boolean sichtbarNeu)
{
super.sichtbarSetzen(sichtbarNeu);
}
/**
* Methode nenneSichtbar
*
* @return true, wenn die Grafik gerade sichbar ist
*/
public boolean nenneSichtbar()
{
return super.sichtbar();
}
/**
* Dreht die Grafik um einen Winkel
*
* @param winkelAenderung +: mathematisch positiver Drehsinn (gegen den
* Uhrzeigersinn) -: mathematisch negativer Drehsinn
* (im Uhrzeigersinn)
*/
public void drehenUm(int winkelAenderung)
{
this.drehenRelativ((double) (winkelAenderung));
}
/**
* Setzt den Drehwinkel auf eine absoluten neuen Wert
*
* @param neuerDrehwinkel der neue Drehwinkel +: mathematisch positiver
* Drehsinn (gegen den Uhrzeigersinn) -: mathematisch
* negativer Drehsinn (im Uhrzeigersinn)
*/
public void setzeDrehwinkel(int neuerDrehwinkel)
{
this.drehenAbsolut((double) (-neuerDrehwinkel));
}
/**
* Nennt den Winkel, um den die Grafik gedreht wurde
*
* @return der Winkel, um den die Grafik gedreht wurde 0: wenn nicht gedreht
* +: wenn mathematisch positiver Drehsinn (gegen den Uhrzeigersinn)
* -: wenn mathematisch negativer Drehsinn (im Uhrzeigersinn)
*/
public int nenneWinkel()
{
return (int) (-this.gibDrehung());
}
/**
* liefert den Sinus des Drehwinkels der Grafik
*
* @return Sinus des aktuellen Drehwinkels
*/
public double sin_Drehwinkel()
{
return Math.sin(-this.gibDrehung() * Math.PI / 180);
}
/**
* liefert den Cosinus des Drehwinkels der Grafik
*
* @return Cosinus des aktuellen Drehwinkels
*/
public double cos_Drehwinkel()
{
return Math.cos(this.gibDrehung() * Math.PI / 180);
}
}
|
18925_6 | package les08.opdracht8_1;
public class Main {
public static void main(String[] args) {
/* Opgave a t/m f */
// Gebouw g;
// Huis h = new Huis(10, 7, 1);
//
// g = h; // wel
// g = new Huis(); // wel
// h = g; // niet
// h = (Huis)g; // wel
// if (g instanceof Huis) h = (Huis)g; // wel
// h.super.laatsteRenovatie = 1980; // niet
/* Opgave g t/m k */
// Gebouw g;
// Huis h = new Huis(10, 7, 2);
// g = h;
//
// g.laatsteRenovatie = 1985; // binnen = 0 buiten = 1985
// h.laatsteRenovatie = 1990; // binnen = 1990 buiten = 1985
// ((Huis)g).laatsteRenovatie = 1995; // binnen = 1995 buiten = 1985
// h.renoveer(2000, 2005); // binnen = 2000 buiten = 2005
// g.isGeisoleerd = true; // niet
/* Opgave l t/m o */
// Gebouw g;
// Huis h = new Huis(10, 7, 3);
// g = h;
//
// h.berekenHuur(); // klasse Huis
// g.berekenHuur(); // klasse Huis
// g.isoleer(); // niet
// ((Huis)g).isoleer(); // wel
}
}
| Josvanreenen/DU1OOP_werkboek | src/les08/opdracht8_1/Main.java | 488 | // h = (Huis)g; // wel | line_comment | nl | package les08.opdracht8_1;
public class Main {
public static void main(String[] args) {
/* Opgave a t/m f */
// Gebouw g;
// Huis h = new Huis(10, 7, 1);
//
// g = h; // wel
// g = new Huis(); // wel
// h = g; // niet
// h =<SUF>
// if (g instanceof Huis) h = (Huis)g; // wel
// h.super.laatsteRenovatie = 1980; // niet
/* Opgave g t/m k */
// Gebouw g;
// Huis h = new Huis(10, 7, 2);
// g = h;
//
// g.laatsteRenovatie = 1985; // binnen = 0 buiten = 1985
// h.laatsteRenovatie = 1990; // binnen = 1990 buiten = 1985
// ((Huis)g).laatsteRenovatie = 1995; // binnen = 1995 buiten = 1985
// h.renoveer(2000, 2005); // binnen = 2000 buiten = 2005
// g.isGeisoleerd = true; // niet
/* Opgave l t/m o */
// Gebouw g;
// Huis h = new Huis(10, 7, 3);
// g = h;
//
// h.berekenHuur(); // klasse Huis
// g.berekenHuur(); // klasse Huis
// g.isoleer(); // niet
// ((Huis)g).isoleer(); // wel
}
}
|
36783_6 | package model;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import model.klas.Klas;
import model.persoon.Docent;
import model.persoon.Student;
public class PrIS {
private ArrayList<Docent> deDocenten;
private ArrayList<Student> deStudenten;
private ArrayList<Klas> deKlassen;
/**
* De constructor maakt een set met standaard-data aan. Deze data moet nog
* uitgebreidt worden met rooster gegevens die uit een bestand worden ingelezen,
* maar dat is geen onderdeel van deze demo-applicatie!
*
* De klasse PrIS (PresentieInformatieSysteem) heeft nu een meervoudige
* associatie met de klassen Docent, Student, Vakken en Klassen Uiteraard kan
* dit nog veel verder uitgebreid en aangepast worden!
*
* De klasse fungeert min of meer als ingangspunt voor het domeinmodel. Op dit
* moment zijn de volgende methoden aanroepbaar:
*
* String login(String gebruikersnaam, String wachtwoord) Docent
* getDocent(String gebruikersnaam) Student getStudent(String gebruikersnaam)
* ArrayList<Student> getStudentenVanKlas(String klasCode)
*
* Methode login geeft de rol van de gebruiker die probeert in te loggen, dat
* kan 'student', 'docent' of 'undefined' zijn! Die informatie kan gebruikt
* worden om in de Polymer-GUI te bepalen wat het volgende scherm is dat getoond
* moet worden.
*
*/
public PrIS() {
deDocenten = new ArrayList<Docent>();
deStudenten = new ArrayList<Student>();
deKlassen = new ArrayList<Klas>(); // Inladen klassen
vulKlassen(deKlassen); // Inladen studenten in klassen
vulStudenten(deStudenten, deKlassen);
// Inladen docenten
vulDocenten(deDocenten);
} // Einde Pris constructor
// deze method is static onderdeel van PrIS omdat hij als hulp methode
// in veel controllers gebruikt wordt
// een standaardDatumString heeft formaat YYYY-MM-DD
public static Calendar standaardDatumStringToCal(String pStadaardDatumString) {
Calendar lCal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
lCal.setTime(sdf.parse(pStadaardDatumString));
} catch (ParseException e) {
e.printStackTrace();
lCal = null;
}
return lCal;
}
// deze method is static onderdeel van PrIS omdat hij als hulp methode
// in veel controllers gebruikt wordt
// een standaardDatumString heeft formaat YYYY-MM-DD
public static String calToStandaardDatumString(Calendar pCalendar) {
int lJaar = pCalendar.get(Calendar.YEAR);
int lMaand = pCalendar.get(Calendar.MONTH) + 1;
int lDag = pCalendar.get(Calendar.DAY_OF_MONTH);
String lMaandStr = Integer.toString(lMaand);
if (lMaandStr.length() == 1) {
lMaandStr = "0" + lMaandStr;
}
String lDagStr = Integer.toString(lDag);
if (lDagStr.length() == 1) {
lDagStr = "0" + lDagStr;
}
String lString = Integer.toString(lJaar) + "-" + lMaandStr + "-" + lDagStr;
return lString;
}
public Docent getDocent(String gebruikersnaam) {
return deDocenten.stream().filter(d -> d.getGebruikersnaam().equals(gebruikersnaam)).findFirst().orElse(null);
}
public Klas getKlasVanStudent(Student pStudent) {
return deKlassen.stream().filter(k -> k.bevatStudent(pStudent)).findFirst().orElse(null);
}
public Student getStudent(String pGebruikersnaam) {
return deStudenten.stream().filter(s -> s.getGebruikersnaam().equals(pGebruikersnaam)).findFirst().orElse(null);
}
public Student getStudent(int pStudentNummer) {
return deStudenten.stream().filter(s -> s.getStudentNummer() == pStudentNummer).findFirst().orElse(null);
}
public String login(String gebruikersnaam, String wachtwoord) {
for (Docent d : deDocenten) {
if (d.getGebruikersnaam().equals(gebruikersnaam)) {
if (d.komtWachtwoordOvereen(wachtwoord)) {
return "docent";
}
}
}
for (Student s : deStudenten) {
if (s.getGebruikersnaam().equals(gebruikersnaam)) {
if (s.komtWachtwoordOvereen(wachtwoord)) {
return "student";
}
}
}
return "undefined";
}
private void vulDocenten(ArrayList<Docent> pDocenten) {
String csvFile = "././CSV/docenten.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] element = line.split(cvsSplitBy);
String gebruikersnaam = element[0].toLowerCase();
String voornaam = element[1];
String tussenvoegsel = element[2];
String achternaam = element[3];
pDocenten.add(new Docent(voornaam, tussenvoegsel, achternaam, "geheim", gebruikersnaam, 1));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// close the bufferedReader if opened.
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// verify content of arraylist, if empty add Jos
if (pDocenten.isEmpty())
pDocenten.add(new Docent("Jos", "van", "Reenen", "supergeheim", "[email protected]", 1));
}
}
private void vulKlassen(ArrayList<Klas> pKlassen) {
// TICT-SIE-VIA is de klascode die ook in de rooster file voorkomt
// V1A is de naam van de klas die ook als file naam voor de studenten van die
// klas wordt gebruikt
Klas k1 = new Klas("TICT-SIE-V1A", "V1A");
Klas k2 = new Klas("TICT-SIE-V1B", "V1B");
Klas k3 = new Klas("TICT-SIE-V1C", "V1C");
Klas k4 = new Klas("TICT-SIE-V1D", "V1D");
Klas k5 = new Klas("TICT-SIE-V1E", "V1E");
pKlassen.add(k1);
pKlassen.add(k2);
pKlassen.add(k3);
pKlassen.add(k4);
pKlassen.add(k5);
}
private void vulStudenten(ArrayList<Student> pStudenten, ArrayList<Klas> pKlassen) {
Student lStudent;
Student dummyStudent = new Student("Stu", "de", "Student", "geheim", "[email protected]", 0);
for (Klas k : pKlassen) {
// per klas
String csvFile = "././CSV/" + k.getNaam() + ".csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// line = line.replace(",,", ", ,");
// use comma as separator
String[] element = line.split(cvsSplitBy);
String gebruikersnaam = (element[3] + "." + element[2] + element[1] + "@student.hu.nl")
.toLowerCase();
// verwijder spaties tussen dubbele voornamen en tussen bv van der
gebruikersnaam = gebruikersnaam.replace(" ", "");
String lStudentNrString = element[0];
int lStudentNr = Integer.parseInt(lStudentNrString);
// Volgorde 3-2-1 = voornaam, tussenvoegsel en achternaam
lStudent = new Student(element[3], element[2], element[1], "geheim", gebruikersnaam, lStudentNr);
pStudenten.add(lStudent);
k.voegStudentToe(lStudent);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// mocht deze klas geen studenten bevatten omdat de csv niet heeft gewerkt:
if (k.getStudenten().isEmpty()) {
k.voegStudentToe(dummyStudent);
System.out.println("Had to add Stu de Student to class: " + k.getKlasCode());
}
}
}
// mocht de lijst met studenten nu nog leeg zijn
if (pStudenten.isEmpty())
pStudenten.add(dummyStudent);
}
}
| Josvanreenen/GroupProject2019 | src/model/PrIS.java | 2,825 | // deze method is static onderdeel van PrIS omdat hij als hulp methode | line_comment | nl | package model;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import model.klas.Klas;
import model.persoon.Docent;
import model.persoon.Student;
public class PrIS {
private ArrayList<Docent> deDocenten;
private ArrayList<Student> deStudenten;
private ArrayList<Klas> deKlassen;
/**
* De constructor maakt een set met standaard-data aan. Deze data moet nog
* uitgebreidt worden met rooster gegevens die uit een bestand worden ingelezen,
* maar dat is geen onderdeel van deze demo-applicatie!
*
* De klasse PrIS (PresentieInformatieSysteem) heeft nu een meervoudige
* associatie met de klassen Docent, Student, Vakken en Klassen Uiteraard kan
* dit nog veel verder uitgebreid en aangepast worden!
*
* De klasse fungeert min of meer als ingangspunt voor het domeinmodel. Op dit
* moment zijn de volgende methoden aanroepbaar:
*
* String login(String gebruikersnaam, String wachtwoord) Docent
* getDocent(String gebruikersnaam) Student getStudent(String gebruikersnaam)
* ArrayList<Student> getStudentenVanKlas(String klasCode)
*
* Methode login geeft de rol van de gebruiker die probeert in te loggen, dat
* kan 'student', 'docent' of 'undefined' zijn! Die informatie kan gebruikt
* worden om in de Polymer-GUI te bepalen wat het volgende scherm is dat getoond
* moet worden.
*
*/
public PrIS() {
deDocenten = new ArrayList<Docent>();
deStudenten = new ArrayList<Student>();
deKlassen = new ArrayList<Klas>(); // Inladen klassen
vulKlassen(deKlassen); // Inladen studenten in klassen
vulStudenten(deStudenten, deKlassen);
// Inladen docenten
vulDocenten(deDocenten);
} // Einde Pris constructor
// deze method is static onderdeel van PrIS omdat hij als hulp methode
// in veel controllers gebruikt wordt
// een standaardDatumString heeft formaat YYYY-MM-DD
public static Calendar standaardDatumStringToCal(String pStadaardDatumString) {
Calendar lCal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
lCal.setTime(sdf.parse(pStadaardDatumString));
} catch (ParseException e) {
e.printStackTrace();
lCal = null;
}
return lCal;
}
// deze method<SUF>
// in veel controllers gebruikt wordt
// een standaardDatumString heeft formaat YYYY-MM-DD
public static String calToStandaardDatumString(Calendar pCalendar) {
int lJaar = pCalendar.get(Calendar.YEAR);
int lMaand = pCalendar.get(Calendar.MONTH) + 1;
int lDag = pCalendar.get(Calendar.DAY_OF_MONTH);
String lMaandStr = Integer.toString(lMaand);
if (lMaandStr.length() == 1) {
lMaandStr = "0" + lMaandStr;
}
String lDagStr = Integer.toString(lDag);
if (lDagStr.length() == 1) {
lDagStr = "0" + lDagStr;
}
String lString = Integer.toString(lJaar) + "-" + lMaandStr + "-" + lDagStr;
return lString;
}
public Docent getDocent(String gebruikersnaam) {
return deDocenten.stream().filter(d -> d.getGebruikersnaam().equals(gebruikersnaam)).findFirst().orElse(null);
}
public Klas getKlasVanStudent(Student pStudent) {
return deKlassen.stream().filter(k -> k.bevatStudent(pStudent)).findFirst().orElse(null);
}
public Student getStudent(String pGebruikersnaam) {
return deStudenten.stream().filter(s -> s.getGebruikersnaam().equals(pGebruikersnaam)).findFirst().orElse(null);
}
public Student getStudent(int pStudentNummer) {
return deStudenten.stream().filter(s -> s.getStudentNummer() == pStudentNummer).findFirst().orElse(null);
}
public String login(String gebruikersnaam, String wachtwoord) {
for (Docent d : deDocenten) {
if (d.getGebruikersnaam().equals(gebruikersnaam)) {
if (d.komtWachtwoordOvereen(wachtwoord)) {
return "docent";
}
}
}
for (Student s : deStudenten) {
if (s.getGebruikersnaam().equals(gebruikersnaam)) {
if (s.komtWachtwoordOvereen(wachtwoord)) {
return "student";
}
}
}
return "undefined";
}
private void vulDocenten(ArrayList<Docent> pDocenten) {
String csvFile = "././CSV/docenten.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] element = line.split(cvsSplitBy);
String gebruikersnaam = element[0].toLowerCase();
String voornaam = element[1];
String tussenvoegsel = element[2];
String achternaam = element[3];
pDocenten.add(new Docent(voornaam, tussenvoegsel, achternaam, "geheim", gebruikersnaam, 1));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// close the bufferedReader if opened.
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// verify content of arraylist, if empty add Jos
if (pDocenten.isEmpty())
pDocenten.add(new Docent("Jos", "van", "Reenen", "supergeheim", "[email protected]", 1));
}
}
private void vulKlassen(ArrayList<Klas> pKlassen) {
// TICT-SIE-VIA is de klascode die ook in de rooster file voorkomt
// V1A is de naam van de klas die ook als file naam voor de studenten van die
// klas wordt gebruikt
Klas k1 = new Klas("TICT-SIE-V1A", "V1A");
Klas k2 = new Klas("TICT-SIE-V1B", "V1B");
Klas k3 = new Klas("TICT-SIE-V1C", "V1C");
Klas k4 = new Klas("TICT-SIE-V1D", "V1D");
Klas k5 = new Klas("TICT-SIE-V1E", "V1E");
pKlassen.add(k1);
pKlassen.add(k2);
pKlassen.add(k3);
pKlassen.add(k4);
pKlassen.add(k5);
}
private void vulStudenten(ArrayList<Student> pStudenten, ArrayList<Klas> pKlassen) {
Student lStudent;
Student dummyStudent = new Student("Stu", "de", "Student", "geheim", "[email protected]", 0);
for (Klas k : pKlassen) {
// per klas
String csvFile = "././CSV/" + k.getNaam() + ".csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// line = line.replace(",,", ", ,");
// use comma as separator
String[] element = line.split(cvsSplitBy);
String gebruikersnaam = (element[3] + "." + element[2] + element[1] + "@student.hu.nl")
.toLowerCase();
// verwijder spaties tussen dubbele voornamen en tussen bv van der
gebruikersnaam = gebruikersnaam.replace(" ", "");
String lStudentNrString = element[0];
int lStudentNr = Integer.parseInt(lStudentNrString);
// Volgorde 3-2-1 = voornaam, tussenvoegsel en achternaam
lStudent = new Student(element[3], element[2], element[1], "geheim", gebruikersnaam, lStudentNr);
pStudenten.add(lStudent);
k.voegStudentToe(lStudent);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// mocht deze klas geen studenten bevatten omdat de csv niet heeft gewerkt:
if (k.getStudenten().isEmpty()) {
k.voegStudentToe(dummyStudent);
System.out.println("Had to add Stu de Student to class: " + k.getKlasCode());
}
}
}
// mocht de lijst met studenten nu nog leeg zijn
if (pStudenten.isEmpty())
pStudenten.add(dummyStudent);
}
}
|
32035_0 | package demos.nehe.lesson08;
import demos.common.GLDisplay;
import demos.common.LessonNativeLoader;
/**
* @author Pepijn Van Eeckhoudt
*/
public class Lesson08 extends LessonNativeLoader {
public static void main(String[] args) {
GLDisplay neheGLDisplay = GLDisplay
.createGLDisplay("Lesson 08: Blending");
Renderer renderer = new Renderer();
InputHandler inputHandler = new InputHandler(renderer, neheGLDisplay);
neheGLDisplay.addGLEventListener(renderer);
neheGLDisplay.addKeyListener(inputHandler);
neheGLDisplay.start();
}
}
| Jotschi/jogl2-example | src/main/java/demos/nehe/lesson08/Lesson08.java | 189 | /**
* @author Pepijn Van Eeckhoudt
*/ | block_comment | nl | package demos.nehe.lesson08;
import demos.common.GLDisplay;
import demos.common.LessonNativeLoader;
/**
* @author Pepijn Van<SUF>*/
public class Lesson08 extends LessonNativeLoader {
public static void main(String[] args) {
GLDisplay neheGLDisplay = GLDisplay
.createGLDisplay("Lesson 08: Blending");
Renderer renderer = new Renderer();
InputHandler inputHandler = new InputHandler(renderer, neheGLDisplay);
neheGLDisplay.addGLEventListener(renderer);
neheGLDisplay.addKeyListener(inputHandler);
neheGLDisplay.start();
}
}
|
163102_38 | /*
* Copyright 2013 Thom Castermans [email protected]
* Copyright 2013 Willem Sonke [email protected]
*
* 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 2 of
* the License or (at your option) version 3 or any later version
* accepted by the membership of KDE e.V. (or its successor approved
* by the membership of KDE e.V.), which shall act as a proxy
* defined in Section 14 of version 3 of the license.
*
* 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 joxy.ui;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.util.Hashtable;
import javax.swing.*;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicRootPaneUI;
import joxy.color.ColorUtils;
import joxy.color.ColorUtils.ShadeRoles;
import joxy.utils.*;
/**
* Joxy's UI delegate for the JRootPaneUI.
*
* <p>This class is responsible for drawing the radial background of windows.
* Several ways of caching are used, since this is done very often. See {@link #backgroundCache},
* {@link #radialGradient600px} and {@link #currentCache}.</p>
*
* @author Thom Castermans
* @author Willem Sonke
*/
public class JoxyRootPaneUI extends BasicRootPaneUI {
/**
* In this hash table we store cached images of the <b>linear</b> part of the
* background to improve performance. Because these images are just stretchable
* in the <i>x</i> direction, they are 1 pixel wide.
*/
private static Hashtable<Integer, BufferedImage> backgroundCache = new Hashtable<Integer, BufferedImage>();
/**
* In this image we cache the radial gradient that is 600 pixels wide. It is
* too memory-wasting to store every radial gradient, but because 600 pixels is the
* maximum width for these gradient, this width will be used for every window with
* width greater or equal than 600 pixels. So it is worth caching this gradient.
*/
private static BufferedImage radialGradient600px = null;
/**
* In this image we cache the entire current radial background. That is useful since
* when the window size hasn't changed, the radial background will be entirely the same
* and thus, it can be completely taken from the cache.
*/
private static BufferedImage currentCache = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
/**
* Whether we still have to use {@link XUtils#setOxygenGradientHint(Frame, boolean)}
* to tell Oxygen that it should draw the radial background.
*/
private boolean shouldTellOxygenAboutRadialBackground = true;
/**
* Initialize the {@link #radialGradient600px}.
*/
static {
radialGradient600px = new BufferedImage(600, 64, BufferedImage.TYPE_INT_ARGB);
Color color = UIManager.getColor("Window.background");
Color backgroundRadialColor = getBackgroundRadialColor(color);
Color radial1 = new Color(backgroundRadialColor.getRed(), backgroundRadialColor.getGreen(),backgroundRadialColor.getBlue(), 0);
Color radial2 = new Color(backgroundRadialColor.getRed(), backgroundRadialColor.getGreen(),backgroundRadialColor.getBlue(), 37);
Color radial3 = new Color(backgroundRadialColor.getRed(), backgroundRadialColor.getGreen(),backgroundRadialColor.getBlue(), 105);
Color radial4 = new Color(backgroundRadialColor.getRed(), backgroundRadialColor.getGreen(),backgroundRadialColor.getBlue(), 255);
Graphics2D imgg2 = (Graphics2D) (radialGradient600px.getGraphics());
imgg2.setPaint(new RadialGradientPaint(new Rectangle2D.Double(0, -64 - 23, 600, 2 * 64),
new float[] {0.0f, 0.5f, 0.75f, 1.0f}, // Distribution of colors over gradient
new Color[] {radial4, radial3, radial2, radial1},
RadialGradientPaint.CycleMethod.NO_CYCLE));
imgg2.fillRect(0, 0, 600, 64); // last one is gradientHeight
}
public static ComponentUI createUI(JComponent c) {
JoxyRootPaneUI rootPaneUI = new JoxyRootPaneUI();
return rootPaneUI;
}
@Override
protected void installDefaults(JRootPane c) {
super.installDefaults(c);
// this is a fix for bug 15; see the description there
c.setOpaque(true);
}
@Override
protected void uninstallDefaults(JRootPane c) {
super.uninstallDefaults(c);
// tell Oxygen that we are not drawing the radial background anymore
Window w = SwingUtilities.getWindowAncestor(c);
XUtils.setOxygenGradientHint(w, false);
}
/**
* {@inheritDoc}
*
* <p>The logic for this method is taken from the actual Oxygen rendering code,
* but with a different caching scheme.</p>
*/
@Override
public void paint(Graphics g, JComponent c) {
Graphics2D g2 = (Graphics2D) g;
// Bug 12: some applications (breaking the API) create a JFrame and apply the LAF thereafter.
// That means that JoxyRootPaneUI will be applied already, coinciding with other LAF components,
// for example Metal. Most worrying, all kinds of stuff can happen to the defaults. Therefore
// we check if the LAF is Joxy, and if not, we update the component tree ourselves.
if (!Utils.isJoxyActive()) {
Output.warning("Application created the JRootPane after setting the LAF, but without using \n" +
"SwingUtilities.updateComponentTreeUI(frame). Joxy will do that now.");
SwingUtilities.updateComponentTreeUI(c);
return;
}
// Bug 23: let Oxygen know that we are drawing the radial background, so that
// Oxygen starts drawing it in the window decoration too.
if (shouldTellOxygenAboutRadialBackground) {
Window w = SwingUtilities.getWindowAncestor(c);
XUtils.setOxygenGradientHint(w, true);
shouldTellOxygenAboutRadialBackground = false;
}
// if the currentCache is not up-to-date, draw a new one
if (c.getWidth() != currentCache.getWidth() || c.getHeight() != currentCache.getHeight()) {
paintBackgroundToCache(c.getWidth(), c.getHeight());
}
// actually draw the background
g2.drawImage(currentCache, 0, 0, null);
}
/**
* Actually draws the background onto the {@link #currentCache}.
* @param width The desired width.
* @param height The desired height.
*/
protected void paintBackgroundToCache(int width, int height) {
currentCache = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = (Graphics2D) currentCache.getGraphics();
// speed is important here
g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
int splitY = (int) Math.min(300 - 23, .75 * (height + 23));
// determine colors to use
Color color = UIManager.getColor("Window.background");
// draw linear gradient
BufferedImage gradient = backgroundCache.get(height);
if (gradient == null) {
// Output.debug("Linear background: created new image for height " + height);
BufferedImage newGradient = new BufferedImage(1, height, BufferedImage.TYPE_INT_RGB);
Graphics2D imgg2 = (Graphics2D) (newGradient.getGraphics());
Color backgroundTopColor = getBackgroundTopColor(color);
Color backgroundBottomColor = getBackgroundBottomColor(color);
imgg2.setPaint(new GradientPaint(0, -23, backgroundTopColor, 0, splitY, backgroundBottomColor));
imgg2.fillRect(0, 0, 1, height);
backgroundCache.put(height, newGradient);
g2.drawImage(newGradient, AffineTransform.getScaleInstance(width, 1), null);
} else {
// Output.debug("Linear background: used cached image for height " + height);
g2.drawImage(gradient, AffineTransform.getScaleInstance(width, 1), null);
}
// draw upper radial gradient
Color backgroundRadialColor = getBackgroundRadialColor(color);
int radialWidth = Math.min(600, width);
if (width >= 600) {
// Output.debug("Radial background: used the cached 600px image");
g2.drawImage(radialGradient600px, (width-600)/2, 0, null);
} else {
// Output.debug("Radial background: created a new image");
Color radial1 = new Color(backgroundRadialColor.getRed(), backgroundRadialColor.getGreen(),backgroundRadialColor.getBlue(), 0);
Color radial2 = new Color(backgroundRadialColor.getRed(), backgroundRadialColor.getGreen(),backgroundRadialColor.getBlue(), 37);
Color radial3 = new Color(backgroundRadialColor.getRed(), backgroundRadialColor.getGreen(),backgroundRadialColor.getBlue(), 105);
Color radial4 = new Color(backgroundRadialColor.getRed(), backgroundRadialColor.getGreen(),backgroundRadialColor.getBlue(), 255);
g2.setPaint(new RadialGradientPaint(new Rectangle2D.Double(0, -23 - 64, radialWidth, 2 * 64),
new float[] {0.0f, 0.5f, 0.75f, 1.0f}, // Distribution of colors over gradient
new Color[] {radial4, radial3, radial2, radial1},
RadialGradientPaint.CycleMethod.NO_CYCLE));
g2.fillRect(0, 0, width, 64); // last one is gradientHeight
}
}
/**
* Returns the color to use for the upper part of the pane.
* @param baseColor The color that is given in the defaults.
* @return The generated color.
*/
public static Color getBackgroundTopColor(Color baseColor) {
Color out = new Color(0, 0, 0);
//if (ColorUtils.lowThreshold(baseColor)) {
// out = ColorUtils.shadeScheme(baseColor, ShadeRoles.MidlightShade, 0.0f);
//} else {
float my = ColorUtils.luma(ColorUtils.shadeScheme(baseColor, ShadeRoles.LightShade, 0.0f));
float by = ColorUtils.luma(baseColor);
int contrast = UIManager.getInt("General.contrast");
// Remark: in the original code, it stated "0.9 * contrast / 0.7". But this turns out to refer
// to contrastF, that divides the contrast by 10.
double backgroundContrast = Math.min(1, 0.9 * contrast / 7);
out = ColorUtils.shade(baseColor, (float) ((my-by) * backgroundContrast));
//}
return out;
}
public static Color getBackgroundBottomColor(Color baseColor) {
Color out = new Color(0, 0, 0);
Color midColor = ColorUtils.shadeScheme(baseColor, ShadeRoles.MidShade, 0.0f);
//if( lowThreshold( color ) ) out = new QColor( midColor );
// else {
//if (ColorUtils.lowThreshold(baseColor)) { // [ws] FIXME volgens mij zit er een ernstige bug in lowThreshold.
// out = midColor;
//} else {
float by = ColorUtils.luma(baseColor);
float my = ColorUtils.luma(midColor);
int contrast = UIManager.getInt("General.contrast");
// Remark: in the original code, it stated "0.9 * contrast / 0.7". But this turns out to refer
// to contrastF, that divides the contrast by 10.
double backgroundContrast = Math.min(1, 0.9 * contrast / 7);
out = ColorUtils.shade(baseColor, (float) ((my-by) * backgroundContrast));
//}
return out;
}
public static Color getBackgroundRadialColor(Color baseColor) {
assert baseColor != null;
Color out = new Color(0, 0, 0);
//if (ColorUtils.lowThreshold(baseColor)) {
// out = ColorUtils.shadeScheme(baseColor, ShadeRoles.LightShade, 0.0f);
//} //else if ((ColorUtils.highThreshold(baseColor)) { // TODO zolang we highThreshold nog niet hebben
//}
int contrast = UIManager.getInt("General.contrast");
// Remark: in the original code, it stated "0.9 * contrast / 0.7". But this turns out to refer
// to contrastF, that divides the contrast by 10.
double backgroundContrast = Math.min(1, 0.9 * contrast / 7);
out = ColorUtils.shadeScheme(baseColor, ShadeRoles.LightShade, (float) backgroundContrast);
//}
return out;
}
@Override
public void update(Graphics g, JComponent c) {
if (c.isOpaque()) {
paint(g, c);
}
}
}
| Joxy-LAF/joxy-oxygen | joxy/src/main/java/joxy/ui/JoxyRootPaneUI.java | 3,861 | //if (ColorUtils.lowThreshold(baseColor)) { // [ws] FIXME volgens mij zit er een ernstige bug in lowThreshold. | line_comment | nl | /*
* Copyright 2013 Thom Castermans [email protected]
* Copyright 2013 Willem Sonke [email protected]
*
* 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 2 of
* the License or (at your option) version 3 or any later version
* accepted by the membership of KDE e.V. (or its successor approved
* by the membership of KDE e.V.), which shall act as a proxy
* defined in Section 14 of version 3 of the license.
*
* 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 joxy.ui;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.util.Hashtable;
import javax.swing.*;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicRootPaneUI;
import joxy.color.ColorUtils;
import joxy.color.ColorUtils.ShadeRoles;
import joxy.utils.*;
/**
* Joxy's UI delegate for the JRootPaneUI.
*
* <p>This class is responsible for drawing the radial background of windows.
* Several ways of caching are used, since this is done very often. See {@link #backgroundCache},
* {@link #radialGradient600px} and {@link #currentCache}.</p>
*
* @author Thom Castermans
* @author Willem Sonke
*/
public class JoxyRootPaneUI extends BasicRootPaneUI {
/**
* In this hash table we store cached images of the <b>linear</b> part of the
* background to improve performance. Because these images are just stretchable
* in the <i>x</i> direction, they are 1 pixel wide.
*/
private static Hashtable<Integer, BufferedImage> backgroundCache = new Hashtable<Integer, BufferedImage>();
/**
* In this image we cache the radial gradient that is 600 pixels wide. It is
* too memory-wasting to store every radial gradient, but because 600 pixels is the
* maximum width for these gradient, this width will be used for every window with
* width greater or equal than 600 pixels. So it is worth caching this gradient.
*/
private static BufferedImage radialGradient600px = null;
/**
* In this image we cache the entire current radial background. That is useful since
* when the window size hasn't changed, the radial background will be entirely the same
* and thus, it can be completely taken from the cache.
*/
private static BufferedImage currentCache = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
/**
* Whether we still have to use {@link XUtils#setOxygenGradientHint(Frame, boolean)}
* to tell Oxygen that it should draw the radial background.
*/
private boolean shouldTellOxygenAboutRadialBackground = true;
/**
* Initialize the {@link #radialGradient600px}.
*/
static {
radialGradient600px = new BufferedImage(600, 64, BufferedImage.TYPE_INT_ARGB);
Color color = UIManager.getColor("Window.background");
Color backgroundRadialColor = getBackgroundRadialColor(color);
Color radial1 = new Color(backgroundRadialColor.getRed(), backgroundRadialColor.getGreen(),backgroundRadialColor.getBlue(), 0);
Color radial2 = new Color(backgroundRadialColor.getRed(), backgroundRadialColor.getGreen(),backgroundRadialColor.getBlue(), 37);
Color radial3 = new Color(backgroundRadialColor.getRed(), backgroundRadialColor.getGreen(),backgroundRadialColor.getBlue(), 105);
Color radial4 = new Color(backgroundRadialColor.getRed(), backgroundRadialColor.getGreen(),backgroundRadialColor.getBlue(), 255);
Graphics2D imgg2 = (Graphics2D) (radialGradient600px.getGraphics());
imgg2.setPaint(new RadialGradientPaint(new Rectangle2D.Double(0, -64 - 23, 600, 2 * 64),
new float[] {0.0f, 0.5f, 0.75f, 1.0f}, // Distribution of colors over gradient
new Color[] {radial4, radial3, radial2, radial1},
RadialGradientPaint.CycleMethod.NO_CYCLE));
imgg2.fillRect(0, 0, 600, 64); // last one is gradientHeight
}
public static ComponentUI createUI(JComponent c) {
JoxyRootPaneUI rootPaneUI = new JoxyRootPaneUI();
return rootPaneUI;
}
@Override
protected void installDefaults(JRootPane c) {
super.installDefaults(c);
// this is a fix for bug 15; see the description there
c.setOpaque(true);
}
@Override
protected void uninstallDefaults(JRootPane c) {
super.uninstallDefaults(c);
// tell Oxygen that we are not drawing the radial background anymore
Window w = SwingUtilities.getWindowAncestor(c);
XUtils.setOxygenGradientHint(w, false);
}
/**
* {@inheritDoc}
*
* <p>The logic for this method is taken from the actual Oxygen rendering code,
* but with a different caching scheme.</p>
*/
@Override
public void paint(Graphics g, JComponent c) {
Graphics2D g2 = (Graphics2D) g;
// Bug 12: some applications (breaking the API) create a JFrame and apply the LAF thereafter.
// That means that JoxyRootPaneUI will be applied already, coinciding with other LAF components,
// for example Metal. Most worrying, all kinds of stuff can happen to the defaults. Therefore
// we check if the LAF is Joxy, and if not, we update the component tree ourselves.
if (!Utils.isJoxyActive()) {
Output.warning("Application created the JRootPane after setting the LAF, but without using \n" +
"SwingUtilities.updateComponentTreeUI(frame). Joxy will do that now.");
SwingUtilities.updateComponentTreeUI(c);
return;
}
// Bug 23: let Oxygen know that we are drawing the radial background, so that
// Oxygen starts drawing it in the window decoration too.
if (shouldTellOxygenAboutRadialBackground) {
Window w = SwingUtilities.getWindowAncestor(c);
XUtils.setOxygenGradientHint(w, true);
shouldTellOxygenAboutRadialBackground = false;
}
// if the currentCache is not up-to-date, draw a new one
if (c.getWidth() != currentCache.getWidth() || c.getHeight() != currentCache.getHeight()) {
paintBackgroundToCache(c.getWidth(), c.getHeight());
}
// actually draw the background
g2.drawImage(currentCache, 0, 0, null);
}
/**
* Actually draws the background onto the {@link #currentCache}.
* @param width The desired width.
* @param height The desired height.
*/
protected void paintBackgroundToCache(int width, int height) {
currentCache = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = (Graphics2D) currentCache.getGraphics();
// speed is important here
g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
int splitY = (int) Math.min(300 - 23, .75 * (height + 23));
// determine colors to use
Color color = UIManager.getColor("Window.background");
// draw linear gradient
BufferedImage gradient = backgroundCache.get(height);
if (gradient == null) {
// Output.debug("Linear background: created new image for height " + height);
BufferedImage newGradient = new BufferedImage(1, height, BufferedImage.TYPE_INT_RGB);
Graphics2D imgg2 = (Graphics2D) (newGradient.getGraphics());
Color backgroundTopColor = getBackgroundTopColor(color);
Color backgroundBottomColor = getBackgroundBottomColor(color);
imgg2.setPaint(new GradientPaint(0, -23, backgroundTopColor, 0, splitY, backgroundBottomColor));
imgg2.fillRect(0, 0, 1, height);
backgroundCache.put(height, newGradient);
g2.drawImage(newGradient, AffineTransform.getScaleInstance(width, 1), null);
} else {
// Output.debug("Linear background: used cached image for height " + height);
g2.drawImage(gradient, AffineTransform.getScaleInstance(width, 1), null);
}
// draw upper radial gradient
Color backgroundRadialColor = getBackgroundRadialColor(color);
int radialWidth = Math.min(600, width);
if (width >= 600) {
// Output.debug("Radial background: used the cached 600px image");
g2.drawImage(radialGradient600px, (width-600)/2, 0, null);
} else {
// Output.debug("Radial background: created a new image");
Color radial1 = new Color(backgroundRadialColor.getRed(), backgroundRadialColor.getGreen(),backgroundRadialColor.getBlue(), 0);
Color radial2 = new Color(backgroundRadialColor.getRed(), backgroundRadialColor.getGreen(),backgroundRadialColor.getBlue(), 37);
Color radial3 = new Color(backgroundRadialColor.getRed(), backgroundRadialColor.getGreen(),backgroundRadialColor.getBlue(), 105);
Color radial4 = new Color(backgroundRadialColor.getRed(), backgroundRadialColor.getGreen(),backgroundRadialColor.getBlue(), 255);
g2.setPaint(new RadialGradientPaint(new Rectangle2D.Double(0, -23 - 64, radialWidth, 2 * 64),
new float[] {0.0f, 0.5f, 0.75f, 1.0f}, // Distribution of colors over gradient
new Color[] {radial4, radial3, radial2, radial1},
RadialGradientPaint.CycleMethod.NO_CYCLE));
g2.fillRect(0, 0, width, 64); // last one is gradientHeight
}
}
/**
* Returns the color to use for the upper part of the pane.
* @param baseColor The color that is given in the defaults.
* @return The generated color.
*/
public static Color getBackgroundTopColor(Color baseColor) {
Color out = new Color(0, 0, 0);
//if (ColorUtils.lowThreshold(baseColor)) {
// out = ColorUtils.shadeScheme(baseColor, ShadeRoles.MidlightShade, 0.0f);
//} else {
float my = ColorUtils.luma(ColorUtils.shadeScheme(baseColor, ShadeRoles.LightShade, 0.0f));
float by = ColorUtils.luma(baseColor);
int contrast = UIManager.getInt("General.contrast");
// Remark: in the original code, it stated "0.9 * contrast / 0.7". But this turns out to refer
// to contrastF, that divides the contrast by 10.
double backgroundContrast = Math.min(1, 0.9 * contrast / 7);
out = ColorUtils.shade(baseColor, (float) ((my-by) * backgroundContrast));
//}
return out;
}
public static Color getBackgroundBottomColor(Color baseColor) {
Color out = new Color(0, 0, 0);
Color midColor = ColorUtils.shadeScheme(baseColor, ShadeRoles.MidShade, 0.0f);
//if( lowThreshold( color ) ) out = new QColor( midColor );
// else {
//if (ColorUtils.lowThreshold(baseColor))<SUF>
// out = midColor;
//} else {
float by = ColorUtils.luma(baseColor);
float my = ColorUtils.luma(midColor);
int contrast = UIManager.getInt("General.contrast");
// Remark: in the original code, it stated "0.9 * contrast / 0.7". But this turns out to refer
// to contrastF, that divides the contrast by 10.
double backgroundContrast = Math.min(1, 0.9 * contrast / 7);
out = ColorUtils.shade(baseColor, (float) ((my-by) * backgroundContrast));
//}
return out;
}
public static Color getBackgroundRadialColor(Color baseColor) {
assert baseColor != null;
Color out = new Color(0, 0, 0);
//if (ColorUtils.lowThreshold(baseColor)) {
// out = ColorUtils.shadeScheme(baseColor, ShadeRoles.LightShade, 0.0f);
//} //else if ((ColorUtils.highThreshold(baseColor)) { // TODO zolang we highThreshold nog niet hebben
//}
int contrast = UIManager.getInt("General.contrast");
// Remark: in the original code, it stated "0.9 * contrast / 0.7". But this turns out to refer
// to contrastF, that divides the contrast by 10.
double backgroundContrast = Math.min(1, 0.9 * contrast / 7);
out = ColorUtils.shadeScheme(baseColor, ShadeRoles.LightShade, (float) backgroundContrast);
//}
return out;
}
@Override
public void update(Graphics g, JComponent c) {
if (c.isOpaque()) {
paint(g, c);
}
}
}
|
76402_1 | /********************************************************************************
* Copyright (c) 2015-2018 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
********************************************************************************/
package org.eclipse.mdm.mdfsorter.mdf3;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.zip.DataFormatException;
import org.eclipse.mdm.mdfsorter.MDFAbstractProcessWriter;
public class MDF3BlocksSplittMerger {
/**
* Parent Object.
*/
private MDF3ProcessWriter ps;
/**
* Pointer to block in which the data is written.
*/
private DTBLOCK curr;
/**
* Pointer to block that is currently written. If curr is an DZBlock, write
* out data is buffered here, and zipped and written out, once all data for
* this block is read.
*/
private final MDF3GenBlock parentnode;
/**
* Total length of the new Data section. Needs to be calculated in advance
* before processing blocks.
*/
private final long totdatalength;
/**
* Amount of bytes of data written behind the output block
*/
private long datawritten = 0;
/**
* An offset in the global data section, only used, if the block that is
* read from is not known (towrite == null)
*/
private long globalReadPtr = 0;
/**
* Data Provider for reading blocks. This Object manages unzipping of
* blocks.
*/
private MDF3DataProvider prov;
/**
* Create a new Datasection with the given options, to write data without
* concern about the underlying block structure. Totaldatalength and prov
* can be passed manually. Therfore oldsection is not needed.
*
* @param ps
* The parent ProcessWriter
* @param parentnode
* Node that is parent of this datasection.
* @param totdatalength
* The length of data that will be written.
* @param prov
* The DataProvider to read from.
*/
public MDF3BlocksSplittMerger(MDF3ProcessWriter ps, MDF3GenBlock parentnode, long totdatalength,
MDF3DataProvider prov) {
this.ps = ps;
this.parentnode = parentnode;
this.totdatalength = totdatalength;
this.prov = prov;
}
public DTBLOCK getStructuralRoot() {
return curr;
}
/**
* Append the datasection beginning at <code>startaddress</code> until
* length to the output.
*
* @param startaddress
* Beginning of the section.
* @param length
* Length of the section.
* @throws IOException
* If an input error occurs.
* @throws DataFormatException
* If zipped data is in an invalid format.
*/
public void splitmerge(long startaddress, long length) throws IOException, DataFormatException {
globalReadPtr = startaddress;
appendDataFromPos(length);
}
/**
* Reads leftbytes from the current position and appends them to the output
* section.
*
* @param leftbytes
* The number of bytes to append.
* @throws IOException
* If an I/O-Error occurs.
* @throws DataFormatException
* If zipped data is in an invalid format.
*/
public void appendDataFromPos(long leftbytes) throws IOException, DataFormatException {
// check if space in curr-Block is available, and fill with first data,
// or attach all data if it fits
if (curr == null) {
curr = abstractcreate(totdatalength);
}
if (datawritten + leftbytes <= totdatalength) { // Space available
abstractcopy(leftbytes);
datawritten += leftbytes;
} else {
throw new RuntimeException("MDF3Merger got more data than space was reserved.");
}
}
/**
* Read data was read from the stream or Cache.
*
* @param length
* Number of Bytes to get.
* @return A Bytebuffer where <code>length</code> Bytes can be read from.
* @throws IOException
* If an I/O-Error occurs.
* @throws DataFormatException
* If zipped data is in an invalid format.
*/
public ByteBuffer abstractread(int length) throws IOException, DataFormatException {
return prov.cachedRead(globalReadPtr, length);
}
public void abstractput(ByteBuffer buf, int length) {
ps.performPut(buf, length, true);
}
/**
* This Method creats a new data block.
*
* @param newblocklength
* Datalength of the new block
* @return The newly created block.
* @throws IOException
* If an I/O-Error occurs.
*/
public DTBLOCK abstractcreate(long newblocklength) throws IOException {
DTBLOCK ret;
ret = ps.create(newblocklength);
return ret;
}
/**
* Reads length bytes with <code>reader</code> and writes them out. This
* happens in smaller blocks.
*
* @param length
* The number of bytes to copy.
* @throws IOException
* If an I/O-Error occurs.
* @throws DataFormatException
* If zipped data is in an invalid format.
*/
public void abstractcopy(long length) throws IOException, DataFormatException {
long written = 0L;
do {
int bytesread = 0;
if (written + MDFAbstractProcessWriter.MAX_OUTPUTBLOCKSIZE > length) {
bytesread = (int) (length - written);
ByteBuffer custombuffer = abstractread(bytesread);
abstractput(custombuffer, bytesread);
} else {
ByteBuffer buffer = abstractread(MDFAbstractProcessWriter.MAX_OUTPUTBLOCKSIZE);
bytesread = MDFAbstractProcessWriter.MAX_OUTPUTBLOCKSIZE;
abstractput(buffer, bytesread);
}
written += bytesread;
} while (written < length);
if (length != written) {
throw new IOException(new StringBuilder().append("written length not equal to blocklength: ").append(length).append("/").append(written).toString());
}
}
public void setLinks() {
if (parentnode instanceof DGBLOCK) {
parentnode.setLink(3, curr);
} else {
System.err.println("Unable to set link to data block. Parent block not recognized.");
}
}
/**
* ONLY FOR TESTING! Used in MDFUnsorter, replaces this splitmerger's
* provider.
*
* @param prov
* The new data provider.
*/
public void setProv(MDF3DataProvider prov) {
this.prov = prov;
}
}
| Jsparrow/org.eclipse.mdm.mdfsorter | src/main/java/org/eclipse/mdm/mdfsorter/mdf3/MDF3BlocksSplittMerger.java | 1,908 | /**
* Parent Object.
*/ | block_comment | nl | /********************************************************************************
* Copyright (c) 2015-2018 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
********************************************************************************/
package org.eclipse.mdm.mdfsorter.mdf3;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.zip.DataFormatException;
import org.eclipse.mdm.mdfsorter.MDFAbstractProcessWriter;
public class MDF3BlocksSplittMerger {
/**
* Parent Object.
<SUF>*/
private MDF3ProcessWriter ps;
/**
* Pointer to block in which the data is written.
*/
private DTBLOCK curr;
/**
* Pointer to block that is currently written. If curr is an DZBlock, write
* out data is buffered here, and zipped and written out, once all data for
* this block is read.
*/
private final MDF3GenBlock parentnode;
/**
* Total length of the new Data section. Needs to be calculated in advance
* before processing blocks.
*/
private final long totdatalength;
/**
* Amount of bytes of data written behind the output block
*/
private long datawritten = 0;
/**
* An offset in the global data section, only used, if the block that is
* read from is not known (towrite == null)
*/
private long globalReadPtr = 0;
/**
* Data Provider for reading blocks. This Object manages unzipping of
* blocks.
*/
private MDF3DataProvider prov;
/**
* Create a new Datasection with the given options, to write data without
* concern about the underlying block structure. Totaldatalength and prov
* can be passed manually. Therfore oldsection is not needed.
*
* @param ps
* The parent ProcessWriter
* @param parentnode
* Node that is parent of this datasection.
* @param totdatalength
* The length of data that will be written.
* @param prov
* The DataProvider to read from.
*/
public MDF3BlocksSplittMerger(MDF3ProcessWriter ps, MDF3GenBlock parentnode, long totdatalength,
MDF3DataProvider prov) {
this.ps = ps;
this.parentnode = parentnode;
this.totdatalength = totdatalength;
this.prov = prov;
}
public DTBLOCK getStructuralRoot() {
return curr;
}
/**
* Append the datasection beginning at <code>startaddress</code> until
* length to the output.
*
* @param startaddress
* Beginning of the section.
* @param length
* Length of the section.
* @throws IOException
* If an input error occurs.
* @throws DataFormatException
* If zipped data is in an invalid format.
*/
public void splitmerge(long startaddress, long length) throws IOException, DataFormatException {
globalReadPtr = startaddress;
appendDataFromPos(length);
}
/**
* Reads leftbytes from the current position and appends them to the output
* section.
*
* @param leftbytes
* The number of bytes to append.
* @throws IOException
* If an I/O-Error occurs.
* @throws DataFormatException
* If zipped data is in an invalid format.
*/
public void appendDataFromPos(long leftbytes) throws IOException, DataFormatException {
// check if space in curr-Block is available, and fill with first data,
// or attach all data if it fits
if (curr == null) {
curr = abstractcreate(totdatalength);
}
if (datawritten + leftbytes <= totdatalength) { // Space available
abstractcopy(leftbytes);
datawritten += leftbytes;
} else {
throw new RuntimeException("MDF3Merger got more data than space was reserved.");
}
}
/**
* Read data was read from the stream or Cache.
*
* @param length
* Number of Bytes to get.
* @return A Bytebuffer where <code>length</code> Bytes can be read from.
* @throws IOException
* If an I/O-Error occurs.
* @throws DataFormatException
* If zipped data is in an invalid format.
*/
public ByteBuffer abstractread(int length) throws IOException, DataFormatException {
return prov.cachedRead(globalReadPtr, length);
}
public void abstractput(ByteBuffer buf, int length) {
ps.performPut(buf, length, true);
}
/**
* This Method creats a new data block.
*
* @param newblocklength
* Datalength of the new block
* @return The newly created block.
* @throws IOException
* If an I/O-Error occurs.
*/
public DTBLOCK abstractcreate(long newblocklength) throws IOException {
DTBLOCK ret;
ret = ps.create(newblocklength);
return ret;
}
/**
* Reads length bytes with <code>reader</code> and writes them out. This
* happens in smaller blocks.
*
* @param length
* The number of bytes to copy.
* @throws IOException
* If an I/O-Error occurs.
* @throws DataFormatException
* If zipped data is in an invalid format.
*/
public void abstractcopy(long length) throws IOException, DataFormatException {
long written = 0L;
do {
int bytesread = 0;
if (written + MDFAbstractProcessWriter.MAX_OUTPUTBLOCKSIZE > length) {
bytesread = (int) (length - written);
ByteBuffer custombuffer = abstractread(bytesread);
abstractput(custombuffer, bytesread);
} else {
ByteBuffer buffer = abstractread(MDFAbstractProcessWriter.MAX_OUTPUTBLOCKSIZE);
bytesread = MDFAbstractProcessWriter.MAX_OUTPUTBLOCKSIZE;
abstractput(buffer, bytesread);
}
written += bytesread;
} while (written < length);
if (length != written) {
throw new IOException(new StringBuilder().append("written length not equal to blocklength: ").append(length).append("/").append(written).toString());
}
}
public void setLinks() {
if (parentnode instanceof DGBLOCK) {
parentnode.setLink(3, curr);
} else {
System.err.println("Unable to set link to data block. Parent block not recognized.");
}
}
/**
* ONLY FOR TESTING! Used in MDFUnsorter, replaces this splitmerger's
* provider.
*
* @param prov
* The new data provider.
*/
public void setProv(MDF3DataProvider prov) {
this.prov = prov;
}
}
|
86358_0 | package org.example.missies;
import java.util.Scanner;
public class NullPointerMissie extends Missie {
final int TE_BEHALEN_PUNTEN = 3;
int behaaldePunten = 0;
@Override
int voerUit(boolean sloper) {
GebruikerInteractie.toonBericht("een NullPointerException.", sloper);
String tekst = GebruikerInteractie.leesInput(); // Simuleert een situatie waar een variabele null kan zijn.
try {
if (tekst.isEmpty()) throw new NullPointerException("tekst is null");
GebruikerInteractie.toonBericht("De lengte van de tekst is: " + tekst.length());
setPunten(!sloper);
} catch (NullPointerException e) {
e.printStackTrace();
setPunten(sloper);
GebruikerInteractie.toonBericht("Gevangen NullPointerException: " + e.getMessage());
return behaaldePunten;
// Bied de gebruiker uitleg en tips om deze situatie te voorkomen.
} catch (Exception e){
behaaldePunten = DEVELOPER_STRAFPUNTEN;
} finally {
System.out.printf("Behaalde punten %d\n", behaaldePunten);
}
return behaaldePunten;
}
} | Jules95Game/JavaOpdrachtenSlides | h7_exceptions/org/example/missies/NullPointerMissie.java | 372 | // Simuleert een situatie waar een variabele null kan zijn. | line_comment | nl | package org.example.missies;
import java.util.Scanner;
public class NullPointerMissie extends Missie {
final int TE_BEHALEN_PUNTEN = 3;
int behaaldePunten = 0;
@Override
int voerUit(boolean sloper) {
GebruikerInteractie.toonBericht("een NullPointerException.", sloper);
String tekst = GebruikerInteractie.leesInput(); // Simuleert een<SUF>
try {
if (tekst.isEmpty()) throw new NullPointerException("tekst is null");
GebruikerInteractie.toonBericht("De lengte van de tekst is: " + tekst.length());
setPunten(!sloper);
} catch (NullPointerException e) {
e.printStackTrace();
setPunten(sloper);
GebruikerInteractie.toonBericht("Gevangen NullPointerException: " + e.getMessage());
return behaaldePunten;
// Bied de gebruiker uitleg en tips om deze situatie te voorkomen.
} catch (Exception e){
behaaldePunten = DEVELOPER_STRAFPUNTEN;
} finally {
System.out.printf("Behaalde punten %d\n", behaaldePunten);
}
return behaaldePunten;
}
} |
12223_34 | package domein;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import utils.Kleur;
public class Spel {
private FicheRepository ficheRepo;
private OntwikkelingskaartRepository niveau1;
private OntwikkelingskaartRepository niveau2;
private OntwikkelingskaartRepository niveau3;
private EdeleRepository edeleRepo;
private List<Speler> spelers;
private Speler huidigeSpeler;
public static final int MIN_AANTAL_SPELERS = 2;
private static final int AANTAL_PRESTIGEPUNTEN_WIN = 15;
// Beurtteller
private int beurt;
public Spel(List<Speler> spelers) {
int aantalSpelers = spelers.size();
setSpelers(spelers);
setFicheRepository(aantalSpelers);
setEdeleRepository(aantalSpelers);
huidigeSpeler = spelers.get(0);
niveau1 = new OntwikkelingskaartRepository(1);
niveau2 = new OntwikkelingskaartRepository(2);
niveau3 = new OntwikkelingskaartRepository(3);
this.beurt = 0;
}
public List<Speler> getSpelers() {
return spelers;
}
private void setSpelers(List<Speler> spelers) {
if (spelers == null) {
throw new IllegalArgumentException("geenSpelers");
}
if (spelers.size() < MIN_AANTAL_SPELERS) {
throw new IllegalArgumentException("minAantalSpelers");
}
this.spelers = spelers;
}
public int[] getFiches() {
return ficheRepo.getFiches();
}
private void setFicheRepository(int aantalSpelers) {
// aantal fiches voor elke edelsteen bepalen a.d.h.v. het aantal spelers
int aantalFiches = switch (aantalSpelers) {
case 2 -> 4;
case 3 -> 5;
case 4 -> 7;
default -> throw new IllegalArgumentException("aantalSpelersError");
};
int lengte = Kleur.values().length;
int[] edelstenen = new int[lengte];
// het aantal fiches voor elke edelsteen gelijkstellen aan het eerder bepaalde
// aantal
for (int i = 0; i < lengte; i++) {
edelstenen[i] = aantalFiches;
}
ficheRepo = new FicheRepository(edelstenen);
}
public List<Edele> getEdelen() {
return edeleRepo.getEdelen();
}
public void setEdeleRepository(int aantalSpelers) {
// aantal edelen van het spel bepalen a.d.h.v. het aantal spelers
int aantalEdelen = switch (aantalSpelers) {
case 2 -> 3;
case 3 -> 4;
case 4 -> 5;
default -> 3;
};
this.edeleRepo = new EdeleRepository(aantalEdelen);
}
public List<Ontwikkelingskaart> getNiveau1() {
return niveau1.getOntwikkelingskaarten();
}
public List<Ontwikkelingskaart> getNiveau2() {
return niveau2.getOntwikkelingskaarten();
}
public List<Ontwikkelingskaart> getNiveau3() {
return niveau3.getOntwikkelingskaarten();
}
public boolean isEindeSpel() {
// als de huidige speler geen startspeler is wilt dat zeggen dat er nog een
// ronde bezig is en kan er nog geen winnaar zijn
if (!huidigeSpeler.isStartSpeler()) {
return false;
}
// spelers overlopen en checken of één van de spelers 15 of meer prestigepunten
// heeft
for (Speler s : spelers) {
if (s.getPrestigePunten() >= AANTAL_PRESTIGEPUNTEN_WIN) {
return true;
}
}
return false;
}
private int geefIndexSpelerAanDeBeurt() {
return beurt % spelers.size();
}
public Speler geefSpeler(Speler speler) {
for (Speler s : spelers) {
if (s.equals(speler)) {
return s;
}
}
return null;
}
/**
* @return een lijst met de winnaars van het spel
* dit kan er maar 1 zijn maar het kunnen ook meerdere spelers zijn
*/
public List<Speler> geefWinnaars() {
// als het spel nog niet gedaan is kunnen er nog geen winnaars zijn
if (!isEindeSpel()) {
return null;
}
// copy maken van de spelers list
List<Speler> spelersCopy = new ArrayList<>(spelers);
// copy sorteren aan de hand van WinnaarComparator, deze sorteert op
// prestigepunten van groot naar klein en aantal ontwikkelingskaarten van klein
// naar groot
Collections.sort(spelersCopy, new WinnaarComparator());
// eerste speler in de gesorteerde copu eruit halen en gelijkstellen aan de
// mogelijkeWinaar variabele
Speler winnaar = spelersCopy.remove(0);
List<Speler> winnaars = new ArrayList<>();
winnaars.add(winnaar);
int aantalOntwikkelingskaartenWinnaar = winnaar.getOntwikkelingskaarten().size();
int index = 0;
Speler volgendeSpeler = spelersCopy.get(index);
// kijken of er nog winnaars zijn door de overige speler af te lopen en te
// kijken of ze even veel prestigepunten en even weinig ontwikkelingskaarten
// hebben
while (volgendeSpeler.getPrestigePunten() == winnaar.getPrestigePunten()
&& volgendeSpeler.getOntwikkelingskaarten().size() == aantalOntwikkelingskaartenWinnaar) {
winnaars.add(volgendeSpeler);
if (index + 1 < spelersCopy.size()) {
volgendeSpeler = spelersCopy.get(++index);
} else {
volgendeSpeler = new Speler("test", 2002);
}
}
return winnaars;
}
/**
* Voegt 2 fiches van dezelfde kleur toe aan de fiches van de speler
* en neem 2 fiches van die kleur weg bij het spel.
* @param kleur geeft aan welke kleur de 2 fiches zijn die de speler moet krijgen en weggenomen moeten worden bij het spel
*/
public void neemTweeDezelfdeFiches(int kleur) {
// als er minder dan 4 fiches van de opgegeven kleur in het spel zitten dan
// mogen er geen 2 dezelfde fiches van die kleur genomen worden
if (ficheRepo.geefAantal(kleur) < 4) {
throw new IllegalArgumentException("teweinigEdfiches");
}
// contoleren of de speler niet meer dan 10 fiches heeft als hij er 2 bijneemt
controleerAantalFichesSpeler(huidigeSpeler.geefTotaalAantalFiches() + 2);
// fiches wegnemen van het spel
ficheRepo.neemFichesWeg(kleur, 2);
// fiches toevoegen bij de speler
huidigeSpeler.voegFichesToe(kleur, 2);
beurt++;
}
public void neemVerschillendeFiches(List<Integer> kleuren) {
// het aantal genomen fiches mag maximaal 3 zijn
if (kleuren.size() > 3) {
throw new IllegalArgumentException("teveelEdfiches");
}
// er mogen geen duplicate fiches bijzitten
if (kleuren.size() > new HashSet<>(kleuren).size()) {
throw new IllegalArgumentException("dubbeleFiches");
}
// controleren of de speler niet meer dan 10 fiches heeft als hij het aantal
// geselecteerde fiches neemt
controleerAantalFichesSpeler(huidigeSpeler.geefTotaalAantalFiches() + kleuren.size());
// elk geselecteerd fiche toevoegen bij de speler en wegnemen bij het spel
for (int kleur : kleuren) {
ficheRepo.neemFichesWeg(kleur, 1);
huidigeSpeler.voegFichesToe(kleur, 1);
}
beurt++;
}
private void controleerAantalFichesSpeler(int aantal) {
// een speler mag niet meer dan 10 fiches in bezit hebben
if (aantal > 10) {
throw new IllegalArgumentException("maxEdelfiches");
}
}
private Ontwikkelingskaart geefOntwikkelingskaart(int id, int niveau) {
List<Ontwikkelingskaart> kaarten = geefNiveau(niveau);
for (Ontwikkelingskaart o : kaarten) {
if (o.getId() == id) {
return o;
}
}
return null;
}
public List<Integer> koopOntwikkelingskaart(int id, int niveau) {
Ontwikkelingskaart o = geefOntwikkelingskaart(id, niveau);
List<Ontwikkelingskaart> ontwikkelingskaartenSpeler = huidigeSpeler.getOntwikkelingskaarten();
int[] fichesSpeler = huidigeSpeler.getFiches();
int[] fichesEnBonussenSpeler = Arrays.copyOf(fichesSpeler, fichesSpeler.length);
int[] vereisteFiches = o.getVereisteFiches();
int[] wegTeHalen = Arrays.copyOf(vereisteFiches, vereisteFiches.length);
// bonussen toevoegen aan fiches en aftrekken van de weg te halen fiches
for (Ontwikkelingskaart kaart : ontwikkelingskaartenSpeler) {
int bonus = Kleur.valueOf(kaart.getBonus().toUpperCase()).ordinal();
fichesEnBonussenSpeler[bonus]++;
if (wegTeHalen[bonus] > 0) {
wegTeHalen[bonus]--;
}
}
// kijken of speler genoeg fiches heeft om kaart te kopen
for (int i = 0; i < fichesEnBonussenSpeler.length; i++) {
if (fichesEnBonussenSpeler[i] < vereisteFiches[i]) {
throw new IllegalArgumentException("teWeinigFichesError");
}
}
// fiches weghalen bij speler en toevoegen aan spel
for (int i = 0; i < wegTeHalen.length; i++) {
int aantal = wegTeHalen[i];
huidigeSpeler.neemFichesWeg(i, aantal);
ficheRepo.voegFichesToe(i, aantal);
}
geefNiveau(niveau).remove(o);
huidigeSpeler.voegOntwikkelingskaartToe(o);
// bepaal of er koopbare edelen zijn na een ontwikkelingskaart kopen
return geefIDsKoopbareEdelen(); // TODO Opgelet: zorg ervoor dat de beurtteller na deze methode verhoogt.
}
private List<Integer> geefIDsKoopbareEdelen() {
List<Integer> idsKoopbareEdelen = new ArrayList<>();
for (Edele e : edeleRepo.getEdelen()) {
if (controleerEdeleIsKoopbaar(e)) {
idsKoopbareEdelen.add(e.getId());
}
}
return idsKoopbareEdelen;
}
public void koopEdele(int id) {
Edele e = geefEdele(id);
// controlleren of de speler genoeg bonussen heeft om de edele te kopen
if (!controleerEdeleIsKoopbaar(e)) {
throw new IllegalArgumentException("teWeinigBonussenError");
}
// edele verwijderen bij spel en toevoegen bij de huidige speler
edeleRepo.verwijderEdele(e);
huidigeSpeler.voegEdeleToe(e);
}
private Edele geefEdele(int id) {
for (Edele e : edeleRepo.getEdelen()) {
if (e.getId() == id) {
return e;
}
}
return null;
}
private boolean controleerEdeleIsKoopbaar(Edele e) {
int[] bonussenSpeler = huidigeSpeler.berekenBonussen();
int[] vereisteBonussenEdele = e.getVereisteBonussen();
// kijken of de huidige speler de edele kan kopen
for (int i = 0; i < bonussenSpeler.length; i++) {
if (bonussenSpeler[i] < vereisteBonussenEdele[i]) {
return false;
}
}
return true;
}
private List<Ontwikkelingskaart> geefNiveau(int niveau) {
return switch (niveau) {
case 1 -> niveau1.getOntwikkelingskaarten();
case 2 -> niveau2.getOntwikkelingskaarten();
case 3 -> niveau3.getOntwikkelingskaarten();
default -> null;
};
}
public void verhoogBeurtTeller() {
beurt++;
}
public void setHuidigeSpeler() {
huidigeSpeler = spelers.get(geefIndexSpelerAanDeBeurt());
}
public Speler getHuidigeSpeler() {
return huidigeSpeler;
}
public boolean isAanDeBeurt(String gebruikersnaam, int geboortedatum) {
Speler s = geefSpeler(new Speler(gebruikersnaam, geboortedatum));
return huidigeSpeler.equals(s);
}
// methode om de spelers aan het begin van het spel al ontwikkelingskaarten te
// geven
public void preload() {
for (Speler s : spelers) {
neemKaarten(s, niveau1, 5);
neemKaarten(s, niveau2, 3);
// neemKaarten(s, niveau3, 1);
}
}
private void neemKaarten(Speler s, OntwikkelingskaartRepository ontwikklingskaartRepo, int aantal) {
for (int i = 0; i < aantal; i++) {
Ontwikkelingskaart kaart = ontwikklingskaartRepo.geefOntwikkelingskaart(i);
ontwikklingskaartRepo.verwijderOntwikkelingskaart(kaart);
s.voegOntwikkelingskaartToe(kaart);
}
}
// methode die alle ontwikkelingskaarten uit het spel retourneert
public List<Ontwikkelingskaart> geefAlleOntwikkelingskaarten() {
List<Ontwikkelingskaart> alleOntwikkelingskaarten = geefNiveau2En3();
for (Ontwikkelingskaart o : niveau1.getOntwikkelingskaarten()) {
alleOntwikkelingskaarten.add(o);
}
return alleOntwikkelingskaarten;
}
public List<Ontwikkelingskaart> geefNiveau2En3() {
List<Ontwikkelingskaart> kaarten = new ArrayList<>();
for (Ontwikkelingskaart o : niveau2.getOntwikkelingskaarten()) {
kaarten.add(o);
}
for (Ontwikkelingskaart o : niveau3.getOntwikkelingskaarten()) {
kaarten.add(o);
}
return kaarten;
}
// methode om het nemen van een Edele te testen
public void geefGenoegKaartenOmEdelenTeKopen() {
Speler s = spelers.get(0);
int[] aantallen = new int[5];
List<Ontwikkelingskaart> kaarten = geefAlleOntwikkelingskaarten();
Collections.shuffle(kaarten);
int i = 0;
while (s.getOntwikkelingskaarten().size() < 20) {
Ontwikkelingskaart o = kaarten.get(i++);
int bonus = Kleur.valueOf(o.getBonus().toUpperCase()).ordinal();
if (aantallen[bonus] < 4) {
s.voegOntwikkelingskaartToe(o);
}
aantallen[bonus]++;
}
}
private void geef15Prestigepunten(int index) {
Speler s = spelers.get(index);
int i = 0;
List<Ontwikkelingskaart> kaarten = geefNiveau2En3();
while (s.getPrestigePunten() != 15) {
Ontwikkelingskaart o = kaarten.get(i++);
if (s.getPrestigePunten() + o.getPrestigepunten() <= 15) {
s.voegOntwikkelingskaartToe(o);
}
}
}
public void maakWinnaars() {
geef15Prestigepunten(0);
geef15Prestigepunten(1);
}
}
| JulesGoubert/splendor | src/domein/Spel.java | 4,955 | // methode om de spelers aan het begin van het spel al ontwikkelingskaarten te | line_comment | nl | package domein;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import utils.Kleur;
public class Spel {
private FicheRepository ficheRepo;
private OntwikkelingskaartRepository niveau1;
private OntwikkelingskaartRepository niveau2;
private OntwikkelingskaartRepository niveau3;
private EdeleRepository edeleRepo;
private List<Speler> spelers;
private Speler huidigeSpeler;
public static final int MIN_AANTAL_SPELERS = 2;
private static final int AANTAL_PRESTIGEPUNTEN_WIN = 15;
// Beurtteller
private int beurt;
public Spel(List<Speler> spelers) {
int aantalSpelers = spelers.size();
setSpelers(spelers);
setFicheRepository(aantalSpelers);
setEdeleRepository(aantalSpelers);
huidigeSpeler = spelers.get(0);
niveau1 = new OntwikkelingskaartRepository(1);
niveau2 = new OntwikkelingskaartRepository(2);
niveau3 = new OntwikkelingskaartRepository(3);
this.beurt = 0;
}
public List<Speler> getSpelers() {
return spelers;
}
private void setSpelers(List<Speler> spelers) {
if (spelers == null) {
throw new IllegalArgumentException("geenSpelers");
}
if (spelers.size() < MIN_AANTAL_SPELERS) {
throw new IllegalArgumentException("minAantalSpelers");
}
this.spelers = spelers;
}
public int[] getFiches() {
return ficheRepo.getFiches();
}
private void setFicheRepository(int aantalSpelers) {
// aantal fiches voor elke edelsteen bepalen a.d.h.v. het aantal spelers
int aantalFiches = switch (aantalSpelers) {
case 2 -> 4;
case 3 -> 5;
case 4 -> 7;
default -> throw new IllegalArgumentException("aantalSpelersError");
};
int lengte = Kleur.values().length;
int[] edelstenen = new int[lengte];
// het aantal fiches voor elke edelsteen gelijkstellen aan het eerder bepaalde
// aantal
for (int i = 0; i < lengte; i++) {
edelstenen[i] = aantalFiches;
}
ficheRepo = new FicheRepository(edelstenen);
}
public List<Edele> getEdelen() {
return edeleRepo.getEdelen();
}
public void setEdeleRepository(int aantalSpelers) {
// aantal edelen van het spel bepalen a.d.h.v. het aantal spelers
int aantalEdelen = switch (aantalSpelers) {
case 2 -> 3;
case 3 -> 4;
case 4 -> 5;
default -> 3;
};
this.edeleRepo = new EdeleRepository(aantalEdelen);
}
public List<Ontwikkelingskaart> getNiveau1() {
return niveau1.getOntwikkelingskaarten();
}
public List<Ontwikkelingskaart> getNiveau2() {
return niveau2.getOntwikkelingskaarten();
}
public List<Ontwikkelingskaart> getNiveau3() {
return niveau3.getOntwikkelingskaarten();
}
public boolean isEindeSpel() {
// als de huidige speler geen startspeler is wilt dat zeggen dat er nog een
// ronde bezig is en kan er nog geen winnaar zijn
if (!huidigeSpeler.isStartSpeler()) {
return false;
}
// spelers overlopen en checken of één van de spelers 15 of meer prestigepunten
// heeft
for (Speler s : spelers) {
if (s.getPrestigePunten() >= AANTAL_PRESTIGEPUNTEN_WIN) {
return true;
}
}
return false;
}
private int geefIndexSpelerAanDeBeurt() {
return beurt % spelers.size();
}
public Speler geefSpeler(Speler speler) {
for (Speler s : spelers) {
if (s.equals(speler)) {
return s;
}
}
return null;
}
/**
* @return een lijst met de winnaars van het spel
* dit kan er maar 1 zijn maar het kunnen ook meerdere spelers zijn
*/
public List<Speler> geefWinnaars() {
// als het spel nog niet gedaan is kunnen er nog geen winnaars zijn
if (!isEindeSpel()) {
return null;
}
// copy maken van de spelers list
List<Speler> spelersCopy = new ArrayList<>(spelers);
// copy sorteren aan de hand van WinnaarComparator, deze sorteert op
// prestigepunten van groot naar klein en aantal ontwikkelingskaarten van klein
// naar groot
Collections.sort(spelersCopy, new WinnaarComparator());
// eerste speler in de gesorteerde copu eruit halen en gelijkstellen aan de
// mogelijkeWinaar variabele
Speler winnaar = spelersCopy.remove(0);
List<Speler> winnaars = new ArrayList<>();
winnaars.add(winnaar);
int aantalOntwikkelingskaartenWinnaar = winnaar.getOntwikkelingskaarten().size();
int index = 0;
Speler volgendeSpeler = spelersCopy.get(index);
// kijken of er nog winnaars zijn door de overige speler af te lopen en te
// kijken of ze even veel prestigepunten en even weinig ontwikkelingskaarten
// hebben
while (volgendeSpeler.getPrestigePunten() == winnaar.getPrestigePunten()
&& volgendeSpeler.getOntwikkelingskaarten().size() == aantalOntwikkelingskaartenWinnaar) {
winnaars.add(volgendeSpeler);
if (index + 1 < spelersCopy.size()) {
volgendeSpeler = spelersCopy.get(++index);
} else {
volgendeSpeler = new Speler("test", 2002);
}
}
return winnaars;
}
/**
* Voegt 2 fiches van dezelfde kleur toe aan de fiches van de speler
* en neem 2 fiches van die kleur weg bij het spel.
* @param kleur geeft aan welke kleur de 2 fiches zijn die de speler moet krijgen en weggenomen moeten worden bij het spel
*/
public void neemTweeDezelfdeFiches(int kleur) {
// als er minder dan 4 fiches van de opgegeven kleur in het spel zitten dan
// mogen er geen 2 dezelfde fiches van die kleur genomen worden
if (ficheRepo.geefAantal(kleur) < 4) {
throw new IllegalArgumentException("teweinigEdfiches");
}
// contoleren of de speler niet meer dan 10 fiches heeft als hij er 2 bijneemt
controleerAantalFichesSpeler(huidigeSpeler.geefTotaalAantalFiches() + 2);
// fiches wegnemen van het spel
ficheRepo.neemFichesWeg(kleur, 2);
// fiches toevoegen bij de speler
huidigeSpeler.voegFichesToe(kleur, 2);
beurt++;
}
public void neemVerschillendeFiches(List<Integer> kleuren) {
// het aantal genomen fiches mag maximaal 3 zijn
if (kleuren.size() > 3) {
throw new IllegalArgumentException("teveelEdfiches");
}
// er mogen geen duplicate fiches bijzitten
if (kleuren.size() > new HashSet<>(kleuren).size()) {
throw new IllegalArgumentException("dubbeleFiches");
}
// controleren of de speler niet meer dan 10 fiches heeft als hij het aantal
// geselecteerde fiches neemt
controleerAantalFichesSpeler(huidigeSpeler.geefTotaalAantalFiches() + kleuren.size());
// elk geselecteerd fiche toevoegen bij de speler en wegnemen bij het spel
for (int kleur : kleuren) {
ficheRepo.neemFichesWeg(kleur, 1);
huidigeSpeler.voegFichesToe(kleur, 1);
}
beurt++;
}
private void controleerAantalFichesSpeler(int aantal) {
// een speler mag niet meer dan 10 fiches in bezit hebben
if (aantal > 10) {
throw new IllegalArgumentException("maxEdelfiches");
}
}
private Ontwikkelingskaart geefOntwikkelingskaart(int id, int niveau) {
List<Ontwikkelingskaart> kaarten = geefNiveau(niveau);
for (Ontwikkelingskaart o : kaarten) {
if (o.getId() == id) {
return o;
}
}
return null;
}
public List<Integer> koopOntwikkelingskaart(int id, int niveau) {
Ontwikkelingskaart o = geefOntwikkelingskaart(id, niveau);
List<Ontwikkelingskaart> ontwikkelingskaartenSpeler = huidigeSpeler.getOntwikkelingskaarten();
int[] fichesSpeler = huidigeSpeler.getFiches();
int[] fichesEnBonussenSpeler = Arrays.copyOf(fichesSpeler, fichesSpeler.length);
int[] vereisteFiches = o.getVereisteFiches();
int[] wegTeHalen = Arrays.copyOf(vereisteFiches, vereisteFiches.length);
// bonussen toevoegen aan fiches en aftrekken van de weg te halen fiches
for (Ontwikkelingskaart kaart : ontwikkelingskaartenSpeler) {
int bonus = Kleur.valueOf(kaart.getBonus().toUpperCase()).ordinal();
fichesEnBonussenSpeler[bonus]++;
if (wegTeHalen[bonus] > 0) {
wegTeHalen[bonus]--;
}
}
// kijken of speler genoeg fiches heeft om kaart te kopen
for (int i = 0; i < fichesEnBonussenSpeler.length; i++) {
if (fichesEnBonussenSpeler[i] < vereisteFiches[i]) {
throw new IllegalArgumentException("teWeinigFichesError");
}
}
// fiches weghalen bij speler en toevoegen aan spel
for (int i = 0; i < wegTeHalen.length; i++) {
int aantal = wegTeHalen[i];
huidigeSpeler.neemFichesWeg(i, aantal);
ficheRepo.voegFichesToe(i, aantal);
}
geefNiveau(niveau).remove(o);
huidigeSpeler.voegOntwikkelingskaartToe(o);
// bepaal of er koopbare edelen zijn na een ontwikkelingskaart kopen
return geefIDsKoopbareEdelen(); // TODO Opgelet: zorg ervoor dat de beurtteller na deze methode verhoogt.
}
private List<Integer> geefIDsKoopbareEdelen() {
List<Integer> idsKoopbareEdelen = new ArrayList<>();
for (Edele e : edeleRepo.getEdelen()) {
if (controleerEdeleIsKoopbaar(e)) {
idsKoopbareEdelen.add(e.getId());
}
}
return idsKoopbareEdelen;
}
public void koopEdele(int id) {
Edele e = geefEdele(id);
// controlleren of de speler genoeg bonussen heeft om de edele te kopen
if (!controleerEdeleIsKoopbaar(e)) {
throw new IllegalArgumentException("teWeinigBonussenError");
}
// edele verwijderen bij spel en toevoegen bij de huidige speler
edeleRepo.verwijderEdele(e);
huidigeSpeler.voegEdeleToe(e);
}
private Edele geefEdele(int id) {
for (Edele e : edeleRepo.getEdelen()) {
if (e.getId() == id) {
return e;
}
}
return null;
}
private boolean controleerEdeleIsKoopbaar(Edele e) {
int[] bonussenSpeler = huidigeSpeler.berekenBonussen();
int[] vereisteBonussenEdele = e.getVereisteBonussen();
// kijken of de huidige speler de edele kan kopen
for (int i = 0; i < bonussenSpeler.length; i++) {
if (bonussenSpeler[i] < vereisteBonussenEdele[i]) {
return false;
}
}
return true;
}
private List<Ontwikkelingskaart> geefNiveau(int niveau) {
return switch (niveau) {
case 1 -> niveau1.getOntwikkelingskaarten();
case 2 -> niveau2.getOntwikkelingskaarten();
case 3 -> niveau3.getOntwikkelingskaarten();
default -> null;
};
}
public void verhoogBeurtTeller() {
beurt++;
}
public void setHuidigeSpeler() {
huidigeSpeler = spelers.get(geefIndexSpelerAanDeBeurt());
}
public Speler getHuidigeSpeler() {
return huidigeSpeler;
}
public boolean isAanDeBeurt(String gebruikersnaam, int geboortedatum) {
Speler s = geefSpeler(new Speler(gebruikersnaam, geboortedatum));
return huidigeSpeler.equals(s);
}
// methode om<SUF>
// geven
public void preload() {
for (Speler s : spelers) {
neemKaarten(s, niveau1, 5);
neemKaarten(s, niveau2, 3);
// neemKaarten(s, niveau3, 1);
}
}
private void neemKaarten(Speler s, OntwikkelingskaartRepository ontwikklingskaartRepo, int aantal) {
for (int i = 0; i < aantal; i++) {
Ontwikkelingskaart kaart = ontwikklingskaartRepo.geefOntwikkelingskaart(i);
ontwikklingskaartRepo.verwijderOntwikkelingskaart(kaart);
s.voegOntwikkelingskaartToe(kaart);
}
}
// methode die alle ontwikkelingskaarten uit het spel retourneert
public List<Ontwikkelingskaart> geefAlleOntwikkelingskaarten() {
List<Ontwikkelingskaart> alleOntwikkelingskaarten = geefNiveau2En3();
for (Ontwikkelingskaart o : niveau1.getOntwikkelingskaarten()) {
alleOntwikkelingskaarten.add(o);
}
return alleOntwikkelingskaarten;
}
public List<Ontwikkelingskaart> geefNiveau2En3() {
List<Ontwikkelingskaart> kaarten = new ArrayList<>();
for (Ontwikkelingskaart o : niveau2.getOntwikkelingskaarten()) {
kaarten.add(o);
}
for (Ontwikkelingskaart o : niveau3.getOntwikkelingskaarten()) {
kaarten.add(o);
}
return kaarten;
}
// methode om het nemen van een Edele te testen
public void geefGenoegKaartenOmEdelenTeKopen() {
Speler s = spelers.get(0);
int[] aantallen = new int[5];
List<Ontwikkelingskaart> kaarten = geefAlleOntwikkelingskaarten();
Collections.shuffle(kaarten);
int i = 0;
while (s.getOntwikkelingskaarten().size() < 20) {
Ontwikkelingskaart o = kaarten.get(i++);
int bonus = Kleur.valueOf(o.getBonus().toUpperCase()).ordinal();
if (aantallen[bonus] < 4) {
s.voegOntwikkelingskaartToe(o);
}
aantallen[bonus]++;
}
}
private void geef15Prestigepunten(int index) {
Speler s = spelers.get(index);
int i = 0;
List<Ontwikkelingskaart> kaarten = geefNiveau2En3();
while (s.getPrestigePunten() != 15) {
Ontwikkelingskaart o = kaarten.get(i++);
if (s.getPrestigePunten() + o.getPrestigepunten() <= 15) {
s.voegOntwikkelingskaartToe(o);
}
}
}
public void maakWinnaars() {
geef15Prestigepunten(0);
geef15Prestigepunten(1);
}
}
|
72329_12 | /*******************************************************************************
* GenPlay, Einstein Genome Analyzer
* Copyright (C) 2009, 2014 Albert Einstein College of Medicine
*
* 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/>.
* Authors: Julien Lajugie <[email protected]>
* Nicolas Fourel <[email protected]>
* Eric Bouhassira <[email protected]>
*
* Website: <http://genplay.einstein.yu.edu>
******************************************************************************/
package edu.yu.einstein.genplay.core.multiGenome.operation;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import edu.yu.einstein.genplay.core.multiGenome.VCF.VCFFile.VCFFile;
import edu.yu.einstein.genplay.core.multiGenome.operation.VCF.MGOApplyVCFGenotype;
import edu.yu.einstein.genplay.core.multiGenome.utils.FormattedMultiGenomeName;
import edu.yu.einstein.genplay.exception.ExceptionManager;
/**
* The update engine is made to create a new VCF file based on a file to update, using data from a current VCF track.
* The first example in GenPlay is the {@link MGOApplyVCFGenotype}.
*
* @author Nicolas Fourel
* @version 0.1
*/
public abstract class UpdateEngine extends BasicEngine {
// Input parameters: file to update
protected VCFFile fileToUpdate; // The file to update.
protected Map<String, String> genomeNameMap; // The map between names from the track and the file to update.
// Output file
protected String path; // Path of the new VCF file.
/**
* Checks every parameter and create an full error message if any of them is not valid.
* @return the error message, null if no error.
*/
@Override
protected String getParameterErrors () {
String errors = super.getParameterErrors();
if (fileToUpdate == null) {
errors = addErrorMessage(errors, "The VCF file to update has not been declared.");
}
if (path == null) {
errors = addErrorMessage(errors, "The path of the new VCF file has not been declared.");
} else {
File file = new File(path);
try {
file.createNewFile();
} catch (IOException e) {
errors = addErrorMessage(errors, "The file could not created, the path may not be valid: " + path + ".");
ExceptionManager.getInstance().caughtException(e);
}
if (!file.isFile()) {
errors = addErrorMessage(errors, "The path of the new VCF file is not a valid file: " + path + ".");
}
file.delete();
}
return errors;
}
/**
* @return the path
*/
public String getPath() {
return path;
}
/**
* @param path the path to set
*/
public void setPath(String path) {
this.path = path;
}
/**
* @return the fileToPhase
*/
public VCFFile getFileToPhase() {
return fileToUpdate;
}
/**
* @param fileToPhase the fileToPhase to set
*/
public void setFileToPhase(VCFFile fileToPhase) {
this.fileToUpdate = fileToPhase;
}
/**
* @return the genomeNameMap
*/
public Map<String, String> getGenomeNameMap() {
return genomeNameMap;
}
/**
* @param genomeNameMap the genomeNameMap to set
*/
public void setGenomeNameMap(Map<String, String> genomeNameMap) {
this.genomeNameMap = new HashMap<String, String>();
for (String rawDestName: genomeNameMap.keySet()) {
String valueRawName = FormattedMultiGenomeName.getRawName(genomeNameMap.get(rawDestName));
this.genomeNameMap.put(rawDestName, valueRawName);
}
}
}
| JulienLajugie/GenPlay | trunk/GenPlay/src/edu/yu/einstein/genplay/core/multiGenome/operation/UpdateEngine.java | 1,285 | /**
* @param genomeNameMap the genomeNameMap to set
*/ | block_comment | nl | /*******************************************************************************
* GenPlay, Einstein Genome Analyzer
* Copyright (C) 2009, 2014 Albert Einstein College of Medicine
*
* 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/>.
* Authors: Julien Lajugie <[email protected]>
* Nicolas Fourel <[email protected]>
* Eric Bouhassira <[email protected]>
*
* Website: <http://genplay.einstein.yu.edu>
******************************************************************************/
package edu.yu.einstein.genplay.core.multiGenome.operation;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import edu.yu.einstein.genplay.core.multiGenome.VCF.VCFFile.VCFFile;
import edu.yu.einstein.genplay.core.multiGenome.operation.VCF.MGOApplyVCFGenotype;
import edu.yu.einstein.genplay.core.multiGenome.utils.FormattedMultiGenomeName;
import edu.yu.einstein.genplay.exception.ExceptionManager;
/**
* The update engine is made to create a new VCF file based on a file to update, using data from a current VCF track.
* The first example in GenPlay is the {@link MGOApplyVCFGenotype}.
*
* @author Nicolas Fourel
* @version 0.1
*/
public abstract class UpdateEngine extends BasicEngine {
// Input parameters: file to update
protected VCFFile fileToUpdate; // The file to update.
protected Map<String, String> genomeNameMap; // The map between names from the track and the file to update.
// Output file
protected String path; // Path of the new VCF file.
/**
* Checks every parameter and create an full error message if any of them is not valid.
* @return the error message, null if no error.
*/
@Override
protected String getParameterErrors () {
String errors = super.getParameterErrors();
if (fileToUpdate == null) {
errors = addErrorMessage(errors, "The VCF file to update has not been declared.");
}
if (path == null) {
errors = addErrorMessage(errors, "The path of the new VCF file has not been declared.");
} else {
File file = new File(path);
try {
file.createNewFile();
} catch (IOException e) {
errors = addErrorMessage(errors, "The file could not created, the path may not be valid: " + path + ".");
ExceptionManager.getInstance().caughtException(e);
}
if (!file.isFile()) {
errors = addErrorMessage(errors, "The path of the new VCF file is not a valid file: " + path + ".");
}
file.delete();
}
return errors;
}
/**
* @return the path
*/
public String getPath() {
return path;
}
/**
* @param path the path to set
*/
public void setPath(String path) {
this.path = path;
}
/**
* @return the fileToPhase
*/
public VCFFile getFileToPhase() {
return fileToUpdate;
}
/**
* @param fileToPhase the fileToPhase to set
*/
public void setFileToPhase(VCFFile fileToPhase) {
this.fileToUpdate = fileToPhase;
}
/**
* @return the genomeNameMap
*/
public Map<String, String> getGenomeNameMap() {
return genomeNameMap;
}
/**
* @param genomeNameMap the<SUF>*/
public void setGenomeNameMap(Map<String, String> genomeNameMap) {
this.genomeNameMap = new HashMap<String, String>();
for (String rawDestName: genomeNameMap.keySet()) {
String valueRawName = FormattedMultiGenomeName.getRawName(genomeNameMap.get(rawDestName));
this.genomeNameMap.put(rawDestName, valueRawName);
}
}
}
|
140629_32 | /*
* Copyright 2013-2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.s3.internal.crypto.v2;
import static com.amazonaws.services.s3.model.CryptoMode.AuthenticatedEncryption;
import static com.amazonaws.services.s3.model.CryptoMode.StrictAuthenticatedEncryption;
import static com.amazonaws.services.s3.model.ExtraMaterialsDescription.NONE;
import static com.amazonaws.util.IOUtils.closeQuietly;
import com.amazonaws.services.s3.model.CryptoRangeGetMode;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collections;
import java.util.Map;
import com.amazonaws.SdkClientException;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import com.amazonaws.internal.SdkFilterInputStream;
import com.amazonaws.services.kms.AWSKMS;
import com.amazonaws.services.s3.internal.S3Direct;
import com.amazonaws.services.s3.internal.crypto.AdjustedRangeInputStream;
import com.amazonaws.services.s3.internal.crypto.CipherLite;
import com.amazonaws.services.s3.internal.crypto.CipherLiteInputStream;
import com.amazonaws.services.s3.internal.crypto.ContentCryptoScheme;
import com.amazonaws.services.s3.internal.crypto.CryptoRuntime;
import com.amazonaws.services.s3.model.CryptoConfigurationV2;
import com.amazonaws.services.s3.model.CryptoMode;
import com.amazonaws.services.s3.model.EncryptedGetObjectRequest;
import com.amazonaws.services.s3.model.EncryptionMaterialsProvider;
import com.amazonaws.services.s3.model.ExtraMaterialsDescription;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.InitiateMultipartUploadRequest;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectId;
import com.amazonaws.services.s3.model.S3ObjectInputStream;
import com.amazonaws.services.s3.model.UploadPartRequest;
import com.amazonaws.util.json.Jackson;
/**
* Authenticated encryption (AE) cryptographic module for the S3 encryption client.
*/
public class S3CryptoModuleAE extends S3CryptoModuleBase<MultipartUploadCryptoContext> {
static {
// Enable bouncy castle if available
CryptoRuntime.enableBouncyCastle();
}
/**
* @param cryptoConfig a read-only copy of the crypto configuration.
*/
public S3CryptoModuleAE(AWSKMS kms, S3Direct s3,
AWSCredentialsProvider credentialsProvider,
EncryptionMaterialsProvider encryptionMaterialsProvider,
CryptoConfigurationV2 cryptoConfig) {
super(kms, s3, encryptionMaterialsProvider, cryptoConfig);
CryptoMode mode = cryptoConfig.getCryptoMode();
if (mode != StrictAuthenticatedEncryption
&& mode != AuthenticatedEncryption) {
throw new IllegalArgumentException();
}
}
/**
* Used for testing purposes only.
*/
S3CryptoModuleAE(S3Direct s3,
EncryptionMaterialsProvider encryptionMaterialsProvider,
CryptoConfigurationV2 cryptoConfig) {
this(null, s3, new DefaultAWSCredentialsProviderChain(),
encryptionMaterialsProvider, cryptoConfig);
}
/**
* Used for testing purposes only.
*/
S3CryptoModuleAE(AWSKMS kms, S3Direct s3,
EncryptionMaterialsProvider encryptionMaterialsProvider,
CryptoConfigurationV2 cryptoConfig) {
this(kms, s3, new DefaultAWSCredentialsProviderChain(),
encryptionMaterialsProvider, cryptoConfig);
}
/**
* Returns true if a strict encryption mode is in use in the current crypto
* module; false otherwise.
*/
protected boolean isStrict() {
return false;
}
@Override
public S3Object getObjectSecurely(GetObjectRequest req) {
// Adjust the crypto range to retrieve all of the cipher blocks needed to contain the user's desired
// range of bytes.
long[] desiredRange = req.getRange();
boolean isPartialObject = desiredRange != null || req.getPartNumber() != null;
if (isPartialObject) {
assertCanGetPartialObject();
}
long[] adjustedCryptoRange = getAdjustedCryptoRange(desiredRange);
if (adjustedCryptoRange != null)
req.setRange(adjustedCryptoRange[0], adjustedCryptoRange[1]);
// Get the object from S3
S3Object retrieved = s3.getObject(req);
// If the caller has specified constraints, it's possible that super.getObject(...)
// would return null, so we simply return null as well.
if (retrieved == null)
return null;
String suffix = null;
if (req instanceof EncryptedGetObjectRequest) {
EncryptedGetObjectRequest ereq = (EncryptedGetObjectRequest)req;
suffix = ereq.getInstructionFileSuffix();
}
try {
return suffix == null || suffix.trim().isEmpty()
? decipher(req, desiredRange, adjustedCryptoRange, retrieved)
: decipherWithInstFileSuffix(req,
desiredRange, adjustedCryptoRange, retrieved,
suffix)
;
} catch (RuntimeException ex) {
// If we're unable to set up the decryption, make sure we close the
// HTTP connection
closeQuietly(retrieved, log);
throw ex;
} catch (Error error) {
closeQuietly(retrieved, log);
throw error;
}
}
private S3Object decipher(GetObjectRequest req,
long[] desiredRange, long[] cryptoRange,
S3Object retrieved) {
S3ObjectWrapper wrapped = new S3ObjectWrapper(retrieved, req.getS3ObjectId());
// Check if encryption info is in object metadata
if (wrapped.hasEncryptionInfo())
return decipherWithMetadata(req, desiredRange, cryptoRange, wrapped);
// Check if encrypted info is in an instruction file
S3ObjectWrapper ifile = fetchInstructionFile(req.getS3ObjectId(), null);
if (ifile != null) {
try {
return decipherWithInstructionFile(req, desiredRange,
cryptoRange, wrapped, ifile);
} finally {
closeQuietly(ifile, log);
}
}
if (isStrict()) {
closeQuietly(wrapped, log);
throw new SecurityException("Unencrypted object found, cannot be decrypted in mode "
+ StrictAuthenticatedEncryption + "; bucket name: "
+ retrieved.getBucketName() + ", key: "
+ retrieved.getKey());
}
if (cryptoConfig.isUnsafeUndecryptableObjectPassthrough()) {
log.warn(String.format(
"Unable to detect encryption information for object '%s' in bucket '%s'. "
+ "Returning object without decryption.",
retrieved.getKey(),
retrieved.getBucketName()));
// Adjust the output to the desired range of bytes.
S3ObjectWrapper adjusted = adjustToDesiredRange(wrapped, desiredRange, null);
return adjusted.getS3Object();
} else {
closeQuietly(wrapped, log);
throw new SecurityException("Instruction file not found for S3 object with bucket name: "
+ retrieved.getBucketName() + ", key: "
+ retrieved.getKey());
}
}
/**
* Same as {@link #decipher(GetObjectRequest, long[], long[], S3Object)}
* but makes use of an instruction file with the specified suffix.
* @param instFileSuffix never null or empty (which is assumed to have been
* sanitized upstream.)
*/
private S3Object decipherWithInstFileSuffix(GetObjectRequest req,
long[] desiredRange, long[] cryptoRange, S3Object retrieved,
String instFileSuffix) {
final S3ObjectId id = req.getS3ObjectId();
// Check if encrypted info is in an instruction file
final S3ObjectWrapper ifile = fetchInstructionFile(id, instFileSuffix);
if (ifile == null) {
throw new SdkClientException("Instruction file with suffix "
+ instFileSuffix + " is not found for " + retrieved);
}
try {
return decipherWithInstructionFile(req, desiredRange,
cryptoRange, new S3ObjectWrapper(retrieved, id), ifile);
} finally {
closeQuietly(ifile, log);
}
}
private S3Object decipherWithInstructionFile(GetObjectRequest req,
long[] desiredRange, long[] cryptoRange, S3ObjectWrapper retrieved,
S3ObjectWrapper instructionFile) {
ExtraMaterialsDescription extraMatDesc = NONE;
boolean keyWrapExpected = isStrict();
if (req instanceof EncryptedGetObjectRequest) {
EncryptedGetObjectRequest ereq = (EncryptedGetObjectRequest)req;
extraMatDesc = ereq.getExtraMaterialDescription();
if (!keyWrapExpected)
keyWrapExpected = ereq.isKeyWrapExpected();
}
String json = instructionFile.toJsonString();
Map<String, String> matdesc =
Collections.unmodifiableMap(Jackson.stringMapFromJsonString(json));
ContentCryptoMaterial cekMaterial =
ContentCryptoMaterial.fromInstructionFile(
matdesc,
kekMaterialsProvider,
cryptoConfig,
cryptoRange, // range is sometimes necessary to compute the adjusted IV
extraMatDesc,
keyWrapExpected,
kms
);
boolean isRangeGet = desiredRange != null;
securityCheck(cekMaterial, retrieved.getS3ObjectId(), isRangeGet);
S3ObjectWrapper decrypted = decrypt(retrieved, cekMaterial, cryptoRange);
// Adjust the output to the desired range of bytes.
S3ObjectWrapper adjusted = adjustToDesiredRange(
decrypted, desiredRange, matdesc);
return adjusted.getS3Object();
}
private S3Object decipherWithMetadata(GetObjectRequest req,
long[] desiredRange,
long[] cryptoRange, S3ObjectWrapper retrieved) {
ExtraMaterialsDescription extraMatDesc = NONE;
boolean keyWrapExpected = isStrict();
if (req instanceof EncryptedGetObjectRequest) {
EncryptedGetObjectRequest ereq = (EncryptedGetObjectRequest)req;
extraMatDesc = ereq.getExtraMaterialDescription();
if (!keyWrapExpected)
keyWrapExpected = ereq.isKeyWrapExpected();
}
ContentCryptoMaterial cekMaterial = ContentCryptoMaterial
.fromObjectMetadata(retrieved.getObjectMetadata().getUserMetadata(),
kekMaterialsProvider,
cryptoConfig,
// range is sometimes necessary to compute the adjusted IV
cryptoRange,
extraMatDesc,
keyWrapExpected,
kms
);
boolean isRangeGet = desiredRange != null;
securityCheck(cekMaterial, retrieved.getS3ObjectId(), isRangeGet);
S3ObjectWrapper decrypted = decrypt(retrieved, cekMaterial, cryptoRange);
// Adjust the output to the desired range of bytes.
S3ObjectWrapper adjusted = adjustToDesiredRange(
decrypted, desiredRange, null);
return adjusted.getS3Object();
}
/**
* Adjusts the retrieved S3Object so that the object contents contain only the range of bytes
* desired by the user. Since encrypted contents can only be retrieved in CIPHER_BLOCK_SIZE
* (16 bytes) chunks, the S3Object potentially contains more bytes than desired, so this method
* adjusts the contents range.
*
* @param s3object
* The S3Object retrieved from S3 that could possibly contain more bytes than desired
* by the user.
* @param range
* A two-element array of longs corresponding to the start and finish (inclusive) of a desired
* range of bytes.
* @param instruction
* Instruction file in JSON or null if no instruction file is involved
* @return
* The S3Object with adjusted object contents containing only the range desired by the user.
* If the range specified is invalid, then the S3Object is returned without any modifications.
*/
protected final S3ObjectWrapper adjustToDesiredRange(S3ObjectWrapper s3object,
long[] range, Map<String,String> instruction) {
if (range == null)
return s3object;
// Figure out the original encryption scheme used, which can be
// different from the crypto scheme used for decryption.
ContentCryptoScheme encryptionScheme = s3object.encryptionSchemeOf(instruction);
// range get on data encrypted using AES_GCM
final long instanceLen = s3object.getObjectMetadata().getInstanceLength();
final long maxOffset = instanceLen - encryptionScheme.getTagLengthInBits() / 8 - 1;
if (range[1] > maxOffset) {
range[1] = maxOffset;
if (range[0] > range[1]) {
// Return empty content
// First let's close the existing input stream to avoid resource
// leakage
closeQuietly(s3object.getObjectContent(), log);
s3object.setObjectContent(new ByteArrayInputStream(new byte[0]));
return s3object;
}
}
if (range[0] > range[1]) {
// Make no modifications if range is invalid.
return s3object;
}
try {
S3ObjectInputStream objectContent = s3object.getObjectContent();
InputStream adjustedRangeContents = new AdjustedRangeInputStream(objectContent, range[0], range[1]);
s3object.setObjectContent(new S3ObjectInputStream(adjustedRangeContents, objectContent.getHttpRequest()));
return s3object;
} catch (IOException e) {
throw new SdkClientException("Error adjusting output to desired byte range: " + e.getMessage());
}
}
@Override
public ObjectMetadata getObjectSecurely(GetObjectRequest getObjectRequest,
File destinationFile) {
assertParameterNotNull(destinationFile,
"The destination file parameter must be specified when downloading an object directly to a file");
S3Object s3Object = getObjectSecurely(getObjectRequest);
// getObject can return null if constraints were specified but not met
if (s3Object == null) return null;
OutputStream outputStream = null;
try {
outputStream = new BufferedOutputStream(new FileOutputStream(destinationFile));
byte[] buffer = new byte[1024*10];
int bytesRead;
while ((bytesRead = s3Object.getObjectContent().read(buffer)) > -1) {
outputStream.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
throw new SdkClientException(
"Unable to store object contents to disk: " + e.getMessage(), e);
} finally {
closeQuietly(outputStream, log);
closeQuietly(s3Object.getObjectContent(), log);
}
/*
* Unlike the standard Amazon S3 Client, the Amazon S3 Encryption Client does not do an MD5 check
* here because the contents stored in S3 and the contents we just retrieved are different. In
* S3, the stored contents are encrypted, and locally, the retrieved contents are decrypted.
*/
return s3Object.getObjectMetadata();
}
@Override
final MultipartUploadCryptoContext newUploadContext(
InitiateMultipartUploadRequest req, ContentCryptoMaterial cekMaterial) {
return new MultipartUploadCryptoContext(
req.getBucketName(), req.getKey(), cekMaterial);
}
//// specific overrides for uploading parts.
@Override
final CipherLite cipherLiteForNextPart(
MultipartUploadCryptoContext uploadContext) {
return uploadContext.getCipherLite();
}
@Override
final SdkFilterInputStream wrapForMultipart(
CipherLiteInputStream is, long partSize) {
return is;
}
@Override
final long computeLastPartSize(UploadPartRequest req) {
return req.getPartSize()
+ (contentCryptoScheme.getTagLengthInBits() / 8);
}
@Override
final void updateUploadContext(MultipartUploadCryptoContext uploadContext,
SdkFilterInputStream is) {
}
/*
* Private helper methods
*/
/**
* Returns an updated object where the object content input stream contains the decrypted contents.
*
* @param wrapper
* The object whose contents are to be decrypted.
* @param cekMaterial
* The instruction that will be used to decrypt the object data.
* @return
* The updated object where the object content input stream contains the decrypted contents.
*/
private S3ObjectWrapper decrypt(S3ObjectWrapper wrapper,
ContentCryptoMaterial cekMaterial, long[] range) {
S3ObjectInputStream objectContent = wrapper.getObjectContent();
wrapper.setObjectContent(new S3ObjectInputStream(
new CipherLiteInputStream(objectContent,
cekMaterial.getCipherLite(),
DEFAULT_BUFFER_SIZE),
objectContent.getHttpRequest()));
return wrapper;
}
/**
* Asserts that the specified parameter value is not null and if it is,
* throws an IllegalArgumentException with the specified error message.
*
* @param parameterValue
* The parameter value being checked.
* @param errorMessage
* The error message to include in the IllegalArgumentException
* if the specified parameter is null.
*/
private void assertParameterNotNull(Object parameterValue, String errorMessage) {
if (parameterValue == null) throw new IllegalArgumentException(errorMessage);
}
@Override
protected final long ciphertextLength(long originalContentLength) {
// Add 16 bytes for the 128-bit tag length using AES/GCM
return originalContentLength + contentCryptoScheme.getTagLengthInBits()/8;
}
private void assertCanGetPartialObject() {
if (!isRangeGetEnabled()) {
String msg = "Unable to perform range get request: Range get support has been disabled. " +
"See https://docs.aws.amazon.com/general/latest/gr/aws_sdk_cryptography.html";
throw new SecurityException(msg);
}
}
protected boolean isRangeGetEnabled() {
CryptoRangeGetMode rangeGetMode = cryptoConfig.getRangeGetMode();
switch (rangeGetMode) {
case ALL:
return true;
case DISABLED:
default:
return false;
}
}
}
| JulienZe/alldata | fs/aws-s3/src/main/java/com/amazonaws/services/s3/internal/crypto/v2/S3CryptoModuleAE.java | 5,150 | /*
* Private helper methods
*/ | block_comment | nl | /*
* Copyright 2013-2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.s3.internal.crypto.v2;
import static com.amazonaws.services.s3.model.CryptoMode.AuthenticatedEncryption;
import static com.amazonaws.services.s3.model.CryptoMode.StrictAuthenticatedEncryption;
import static com.amazonaws.services.s3.model.ExtraMaterialsDescription.NONE;
import static com.amazonaws.util.IOUtils.closeQuietly;
import com.amazonaws.services.s3.model.CryptoRangeGetMode;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collections;
import java.util.Map;
import com.amazonaws.SdkClientException;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import com.amazonaws.internal.SdkFilterInputStream;
import com.amazonaws.services.kms.AWSKMS;
import com.amazonaws.services.s3.internal.S3Direct;
import com.amazonaws.services.s3.internal.crypto.AdjustedRangeInputStream;
import com.amazonaws.services.s3.internal.crypto.CipherLite;
import com.amazonaws.services.s3.internal.crypto.CipherLiteInputStream;
import com.amazonaws.services.s3.internal.crypto.ContentCryptoScheme;
import com.amazonaws.services.s3.internal.crypto.CryptoRuntime;
import com.amazonaws.services.s3.model.CryptoConfigurationV2;
import com.amazonaws.services.s3.model.CryptoMode;
import com.amazonaws.services.s3.model.EncryptedGetObjectRequest;
import com.amazonaws.services.s3.model.EncryptionMaterialsProvider;
import com.amazonaws.services.s3.model.ExtraMaterialsDescription;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.InitiateMultipartUploadRequest;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectId;
import com.amazonaws.services.s3.model.S3ObjectInputStream;
import com.amazonaws.services.s3.model.UploadPartRequest;
import com.amazonaws.util.json.Jackson;
/**
* Authenticated encryption (AE) cryptographic module for the S3 encryption client.
*/
public class S3CryptoModuleAE extends S3CryptoModuleBase<MultipartUploadCryptoContext> {
static {
// Enable bouncy castle if available
CryptoRuntime.enableBouncyCastle();
}
/**
* @param cryptoConfig a read-only copy of the crypto configuration.
*/
public S3CryptoModuleAE(AWSKMS kms, S3Direct s3,
AWSCredentialsProvider credentialsProvider,
EncryptionMaterialsProvider encryptionMaterialsProvider,
CryptoConfigurationV2 cryptoConfig) {
super(kms, s3, encryptionMaterialsProvider, cryptoConfig);
CryptoMode mode = cryptoConfig.getCryptoMode();
if (mode != StrictAuthenticatedEncryption
&& mode != AuthenticatedEncryption) {
throw new IllegalArgumentException();
}
}
/**
* Used for testing purposes only.
*/
S3CryptoModuleAE(S3Direct s3,
EncryptionMaterialsProvider encryptionMaterialsProvider,
CryptoConfigurationV2 cryptoConfig) {
this(null, s3, new DefaultAWSCredentialsProviderChain(),
encryptionMaterialsProvider, cryptoConfig);
}
/**
* Used for testing purposes only.
*/
S3CryptoModuleAE(AWSKMS kms, S3Direct s3,
EncryptionMaterialsProvider encryptionMaterialsProvider,
CryptoConfigurationV2 cryptoConfig) {
this(kms, s3, new DefaultAWSCredentialsProviderChain(),
encryptionMaterialsProvider, cryptoConfig);
}
/**
* Returns true if a strict encryption mode is in use in the current crypto
* module; false otherwise.
*/
protected boolean isStrict() {
return false;
}
@Override
public S3Object getObjectSecurely(GetObjectRequest req) {
// Adjust the crypto range to retrieve all of the cipher blocks needed to contain the user's desired
// range of bytes.
long[] desiredRange = req.getRange();
boolean isPartialObject = desiredRange != null || req.getPartNumber() != null;
if (isPartialObject) {
assertCanGetPartialObject();
}
long[] adjustedCryptoRange = getAdjustedCryptoRange(desiredRange);
if (adjustedCryptoRange != null)
req.setRange(adjustedCryptoRange[0], adjustedCryptoRange[1]);
// Get the object from S3
S3Object retrieved = s3.getObject(req);
// If the caller has specified constraints, it's possible that super.getObject(...)
// would return null, so we simply return null as well.
if (retrieved == null)
return null;
String suffix = null;
if (req instanceof EncryptedGetObjectRequest) {
EncryptedGetObjectRequest ereq = (EncryptedGetObjectRequest)req;
suffix = ereq.getInstructionFileSuffix();
}
try {
return suffix == null || suffix.trim().isEmpty()
? decipher(req, desiredRange, adjustedCryptoRange, retrieved)
: decipherWithInstFileSuffix(req,
desiredRange, adjustedCryptoRange, retrieved,
suffix)
;
} catch (RuntimeException ex) {
// If we're unable to set up the decryption, make sure we close the
// HTTP connection
closeQuietly(retrieved, log);
throw ex;
} catch (Error error) {
closeQuietly(retrieved, log);
throw error;
}
}
private S3Object decipher(GetObjectRequest req,
long[] desiredRange, long[] cryptoRange,
S3Object retrieved) {
S3ObjectWrapper wrapped = new S3ObjectWrapper(retrieved, req.getS3ObjectId());
// Check if encryption info is in object metadata
if (wrapped.hasEncryptionInfo())
return decipherWithMetadata(req, desiredRange, cryptoRange, wrapped);
// Check if encrypted info is in an instruction file
S3ObjectWrapper ifile = fetchInstructionFile(req.getS3ObjectId(), null);
if (ifile != null) {
try {
return decipherWithInstructionFile(req, desiredRange,
cryptoRange, wrapped, ifile);
} finally {
closeQuietly(ifile, log);
}
}
if (isStrict()) {
closeQuietly(wrapped, log);
throw new SecurityException("Unencrypted object found, cannot be decrypted in mode "
+ StrictAuthenticatedEncryption + "; bucket name: "
+ retrieved.getBucketName() + ", key: "
+ retrieved.getKey());
}
if (cryptoConfig.isUnsafeUndecryptableObjectPassthrough()) {
log.warn(String.format(
"Unable to detect encryption information for object '%s' in bucket '%s'. "
+ "Returning object without decryption.",
retrieved.getKey(),
retrieved.getBucketName()));
// Adjust the output to the desired range of bytes.
S3ObjectWrapper adjusted = adjustToDesiredRange(wrapped, desiredRange, null);
return adjusted.getS3Object();
} else {
closeQuietly(wrapped, log);
throw new SecurityException("Instruction file not found for S3 object with bucket name: "
+ retrieved.getBucketName() + ", key: "
+ retrieved.getKey());
}
}
/**
* Same as {@link #decipher(GetObjectRequest, long[], long[], S3Object)}
* but makes use of an instruction file with the specified suffix.
* @param instFileSuffix never null or empty (which is assumed to have been
* sanitized upstream.)
*/
private S3Object decipherWithInstFileSuffix(GetObjectRequest req,
long[] desiredRange, long[] cryptoRange, S3Object retrieved,
String instFileSuffix) {
final S3ObjectId id = req.getS3ObjectId();
// Check if encrypted info is in an instruction file
final S3ObjectWrapper ifile = fetchInstructionFile(id, instFileSuffix);
if (ifile == null) {
throw new SdkClientException("Instruction file with suffix "
+ instFileSuffix + " is not found for " + retrieved);
}
try {
return decipherWithInstructionFile(req, desiredRange,
cryptoRange, new S3ObjectWrapper(retrieved, id), ifile);
} finally {
closeQuietly(ifile, log);
}
}
private S3Object decipherWithInstructionFile(GetObjectRequest req,
long[] desiredRange, long[] cryptoRange, S3ObjectWrapper retrieved,
S3ObjectWrapper instructionFile) {
ExtraMaterialsDescription extraMatDesc = NONE;
boolean keyWrapExpected = isStrict();
if (req instanceof EncryptedGetObjectRequest) {
EncryptedGetObjectRequest ereq = (EncryptedGetObjectRequest)req;
extraMatDesc = ereq.getExtraMaterialDescription();
if (!keyWrapExpected)
keyWrapExpected = ereq.isKeyWrapExpected();
}
String json = instructionFile.toJsonString();
Map<String, String> matdesc =
Collections.unmodifiableMap(Jackson.stringMapFromJsonString(json));
ContentCryptoMaterial cekMaterial =
ContentCryptoMaterial.fromInstructionFile(
matdesc,
kekMaterialsProvider,
cryptoConfig,
cryptoRange, // range is sometimes necessary to compute the adjusted IV
extraMatDesc,
keyWrapExpected,
kms
);
boolean isRangeGet = desiredRange != null;
securityCheck(cekMaterial, retrieved.getS3ObjectId(), isRangeGet);
S3ObjectWrapper decrypted = decrypt(retrieved, cekMaterial, cryptoRange);
// Adjust the output to the desired range of bytes.
S3ObjectWrapper adjusted = adjustToDesiredRange(
decrypted, desiredRange, matdesc);
return adjusted.getS3Object();
}
private S3Object decipherWithMetadata(GetObjectRequest req,
long[] desiredRange,
long[] cryptoRange, S3ObjectWrapper retrieved) {
ExtraMaterialsDescription extraMatDesc = NONE;
boolean keyWrapExpected = isStrict();
if (req instanceof EncryptedGetObjectRequest) {
EncryptedGetObjectRequest ereq = (EncryptedGetObjectRequest)req;
extraMatDesc = ereq.getExtraMaterialDescription();
if (!keyWrapExpected)
keyWrapExpected = ereq.isKeyWrapExpected();
}
ContentCryptoMaterial cekMaterial = ContentCryptoMaterial
.fromObjectMetadata(retrieved.getObjectMetadata().getUserMetadata(),
kekMaterialsProvider,
cryptoConfig,
// range is sometimes necessary to compute the adjusted IV
cryptoRange,
extraMatDesc,
keyWrapExpected,
kms
);
boolean isRangeGet = desiredRange != null;
securityCheck(cekMaterial, retrieved.getS3ObjectId(), isRangeGet);
S3ObjectWrapper decrypted = decrypt(retrieved, cekMaterial, cryptoRange);
// Adjust the output to the desired range of bytes.
S3ObjectWrapper adjusted = adjustToDesiredRange(
decrypted, desiredRange, null);
return adjusted.getS3Object();
}
/**
* Adjusts the retrieved S3Object so that the object contents contain only the range of bytes
* desired by the user. Since encrypted contents can only be retrieved in CIPHER_BLOCK_SIZE
* (16 bytes) chunks, the S3Object potentially contains more bytes than desired, so this method
* adjusts the contents range.
*
* @param s3object
* The S3Object retrieved from S3 that could possibly contain more bytes than desired
* by the user.
* @param range
* A two-element array of longs corresponding to the start and finish (inclusive) of a desired
* range of bytes.
* @param instruction
* Instruction file in JSON or null if no instruction file is involved
* @return
* The S3Object with adjusted object contents containing only the range desired by the user.
* If the range specified is invalid, then the S3Object is returned without any modifications.
*/
protected final S3ObjectWrapper adjustToDesiredRange(S3ObjectWrapper s3object,
long[] range, Map<String,String> instruction) {
if (range == null)
return s3object;
// Figure out the original encryption scheme used, which can be
// different from the crypto scheme used for decryption.
ContentCryptoScheme encryptionScheme = s3object.encryptionSchemeOf(instruction);
// range get on data encrypted using AES_GCM
final long instanceLen = s3object.getObjectMetadata().getInstanceLength();
final long maxOffset = instanceLen - encryptionScheme.getTagLengthInBits() / 8 - 1;
if (range[1] > maxOffset) {
range[1] = maxOffset;
if (range[0] > range[1]) {
// Return empty content
// First let's close the existing input stream to avoid resource
// leakage
closeQuietly(s3object.getObjectContent(), log);
s3object.setObjectContent(new ByteArrayInputStream(new byte[0]));
return s3object;
}
}
if (range[0] > range[1]) {
// Make no modifications if range is invalid.
return s3object;
}
try {
S3ObjectInputStream objectContent = s3object.getObjectContent();
InputStream adjustedRangeContents = new AdjustedRangeInputStream(objectContent, range[0], range[1]);
s3object.setObjectContent(new S3ObjectInputStream(adjustedRangeContents, objectContent.getHttpRequest()));
return s3object;
} catch (IOException e) {
throw new SdkClientException("Error adjusting output to desired byte range: " + e.getMessage());
}
}
@Override
public ObjectMetadata getObjectSecurely(GetObjectRequest getObjectRequest,
File destinationFile) {
assertParameterNotNull(destinationFile,
"The destination file parameter must be specified when downloading an object directly to a file");
S3Object s3Object = getObjectSecurely(getObjectRequest);
// getObject can return null if constraints were specified but not met
if (s3Object == null) return null;
OutputStream outputStream = null;
try {
outputStream = new BufferedOutputStream(new FileOutputStream(destinationFile));
byte[] buffer = new byte[1024*10];
int bytesRead;
while ((bytesRead = s3Object.getObjectContent().read(buffer)) > -1) {
outputStream.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
throw new SdkClientException(
"Unable to store object contents to disk: " + e.getMessage(), e);
} finally {
closeQuietly(outputStream, log);
closeQuietly(s3Object.getObjectContent(), log);
}
/*
* Unlike the standard Amazon S3 Client, the Amazon S3 Encryption Client does not do an MD5 check
* here because the contents stored in S3 and the contents we just retrieved are different. In
* S3, the stored contents are encrypted, and locally, the retrieved contents are decrypted.
*/
return s3Object.getObjectMetadata();
}
@Override
final MultipartUploadCryptoContext newUploadContext(
InitiateMultipartUploadRequest req, ContentCryptoMaterial cekMaterial) {
return new MultipartUploadCryptoContext(
req.getBucketName(), req.getKey(), cekMaterial);
}
//// specific overrides for uploading parts.
@Override
final CipherLite cipherLiteForNextPart(
MultipartUploadCryptoContext uploadContext) {
return uploadContext.getCipherLite();
}
@Override
final SdkFilterInputStream wrapForMultipart(
CipherLiteInputStream is, long partSize) {
return is;
}
@Override
final long computeLastPartSize(UploadPartRequest req) {
return req.getPartSize()
+ (contentCryptoScheme.getTagLengthInBits() / 8);
}
@Override
final void updateUploadContext(MultipartUploadCryptoContext uploadContext,
SdkFilterInputStream is) {
}
/*
* Private helper methods<SUF>*/
/**
* Returns an updated object where the object content input stream contains the decrypted contents.
*
* @param wrapper
* The object whose contents are to be decrypted.
* @param cekMaterial
* The instruction that will be used to decrypt the object data.
* @return
* The updated object where the object content input stream contains the decrypted contents.
*/
private S3ObjectWrapper decrypt(S3ObjectWrapper wrapper,
ContentCryptoMaterial cekMaterial, long[] range) {
S3ObjectInputStream objectContent = wrapper.getObjectContent();
wrapper.setObjectContent(new S3ObjectInputStream(
new CipherLiteInputStream(objectContent,
cekMaterial.getCipherLite(),
DEFAULT_BUFFER_SIZE),
objectContent.getHttpRequest()));
return wrapper;
}
/**
* Asserts that the specified parameter value is not null and if it is,
* throws an IllegalArgumentException with the specified error message.
*
* @param parameterValue
* The parameter value being checked.
* @param errorMessage
* The error message to include in the IllegalArgumentException
* if the specified parameter is null.
*/
private void assertParameterNotNull(Object parameterValue, String errorMessage) {
if (parameterValue == null) throw new IllegalArgumentException(errorMessage);
}
@Override
protected final long ciphertextLength(long originalContentLength) {
// Add 16 bytes for the 128-bit tag length using AES/GCM
return originalContentLength + contentCryptoScheme.getTagLengthInBits()/8;
}
private void assertCanGetPartialObject() {
if (!isRangeGetEnabled()) {
String msg = "Unable to perform range get request: Range get support has been disabled. " +
"See https://docs.aws.amazon.com/general/latest/gr/aws_sdk_cryptography.html";
throw new SecurityException(msg);
}
}
protected boolean isRangeGetEnabled() {
CryptoRangeGetMode rangeGetMode = cryptoConfig.getRangeGetMode();
switch (rangeGetMode) {
case ALL:
return true;
case DISABLED:
default:
return false;
}
}
}
|
53981_33 | package juloo.keyboard2;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.KeyEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import juloo.keyboard2.prefs.CustomExtraKeysPreference;
import juloo.keyboard2.prefs.ExtraKeysPreference;
import juloo.keyboard2.prefs.LayoutsPreference;
public final class Config
{
private final SharedPreferences _prefs;
// From resources
public final float marginTop;
public final float keyPadding;
public final float labelTextSize;
public final float sublabelTextSize;
// From preferences
/** [null] represent the [system] layout. */
public List<KeyboardData> layouts;
public boolean show_numpad = false;
// From the 'numpad_layout' option, also apply to the numeric pane.
public boolean inverse_numpad = false;
public boolean number_row;
public float swipe_dist_px;
public float slide_step_px;
// Let the system handle vibration when false.
public boolean vibrate_custom;
// Control the vibration if [vibrate_custom] is true.
public long vibrate_duration;
public long longPressTimeout;
public long longPressInterval;
public float margin_bottom;
public float keyHeight;
public float horizontal_margin;
public float key_vertical_margin;
public float key_horizontal_margin;
public int labelBrightness; // 0 - 255
public int keyboardOpacity; // 0 - 255
public float customBorderRadius; // 0 - 1
public float customBorderLineWidth; // dp
public int keyOpacity; // 0 - 255
public int keyActivatedOpacity; // 0 - 255
public boolean double_tap_lock_shift;
public float characterSize; // Ratio
public int theme; // Values are R.style.*
public boolean autocapitalisation;
public boolean switch_input_immediate;
public boolean pin_entry_enabled;
public boolean borderConfig;
// Dynamically set
public boolean shouldOfferVoiceTyping;
public String actionLabel; // Might be 'null'
public int actionId; // Meaningful only when 'actionLabel' isn't 'null'
public boolean swapEnterActionKey; // Swap the "enter" and "action" keys
public ExtraKeys extra_keys_subtype;
public Map<KeyValue, KeyboardData.PreferredPos> extra_keys_param;
public Map<KeyValue, KeyboardData.PreferredPos> extra_keys_custom;
public final IKeyEventHandler handler;
public boolean orientation_landscape = false;
/** Index in 'layouts' of the currently used layout. See
[get_current_layout()] and [set_current_layout()]. */
int current_layout_portrait;
int current_layout_landscape;
private Config(SharedPreferences prefs, Resources res, IKeyEventHandler h)
{
_prefs = prefs;
// static values
marginTop = res.getDimension(R.dimen.margin_top);
keyPadding = res.getDimension(R.dimen.key_padding);
labelTextSize = 0.33f;
sublabelTextSize = 0.22f;
// from prefs
refresh(res);
// initialized later
shouldOfferVoiceTyping = false;
actionLabel = null;
actionId = 0;
swapEnterActionKey = false;
extra_keys_subtype = null;
handler = h;
}
/*
** Reload prefs
*/
public void refresh(Resources res)
{
DisplayMetrics dm = res.getDisplayMetrics();
orientation_landscape = res.getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE;
// The height of the keyboard is relative to the height of the screen.
// This is the height of the keyboard if it have 4 rows.
int keyboardHeightPercent;
float characterSizeScale = 1.f;
String show_numpad_s = _prefs.getString("show_numpad", "never");
show_numpad = "always".equals(show_numpad_s);
if (orientation_landscape)
{
if ("landscape".equals(show_numpad_s))
show_numpad = true;
keyboardHeightPercent = _prefs.getInt("keyboard_height_landscape", 50);
characterSizeScale = 1.25f;
}
else
{
keyboardHeightPercent = _prefs.getInt("keyboard_height", 35);
}
layouts = LayoutsPreference.load_from_preferences(res, _prefs);
inverse_numpad = _prefs.getString("numpad_layout", "default").equals("low_first");
number_row = _prefs.getBoolean("number_row", false);
// The baseline for the swipe distance correspond to approximately the
// width of a key in portrait mode, as most layouts have 10 columns.
// Multipled by the DPI ratio because most swipes are made in the diagonals.
// The option value uses an unnamed scale where the baseline is around 25.
float dpi_ratio = Math.max(dm.xdpi, dm.ydpi) / Math.min(dm.xdpi, dm.ydpi);
float swipe_scaling = Math.min(dm.widthPixels, dm.heightPixels) / 10.f * dpi_ratio;
float swipe_dist_value = Float.valueOf(_prefs.getString("swipe_dist", "15"));
swipe_dist_px = swipe_dist_value / 25.f * swipe_scaling;
slide_step_px = 0.2f * swipe_scaling;
vibrate_custom = _prefs.getBoolean("vibrate_custom", false);
vibrate_duration = _prefs.getInt("vibrate_duration", 20);
longPressTimeout = _prefs.getInt("longpress_timeout", 600);
longPressInterval = _prefs.getInt("longpress_interval", 65);
margin_bottom = get_dip_pref_oriented(dm, "margin_bottom", 7, 3);
key_vertical_margin = get_dip_pref(dm, "key_vertical_margin", 1.5f) / 100;
key_horizontal_margin = get_dip_pref(dm, "key_horizontal_margin", 2) / 100;
// Label brightness is used as the alpha channel
labelBrightness = _prefs.getInt("label_brightness", 100) * 255 / 100;
// Keyboard opacity
keyboardOpacity = _prefs.getInt("keyboard_opacity", 100) * 255 / 100;
keyOpacity = _prefs.getInt("key_opacity", 100) * 255 / 100;
keyActivatedOpacity = _prefs.getInt("key_activated_opacity", 100) * 255 / 100;
// keyboard border settings
borderConfig = _prefs.getBoolean("border_config", false);
customBorderRadius = _prefs.getInt("custom_border_radius", 0) / 100.f;
customBorderLineWidth = get_dip_pref(dm, "custom_border_line_width", 0);
// Do not substract key_vertical_margin from keyHeight because this is done
// during rendering.
keyHeight = dm.heightPixels * keyboardHeightPercent / 100 / 4;
horizontal_margin =
get_dip_pref_oriented(dm, "horizontal_margin", 3, 28);
double_tap_lock_shift = _prefs.getBoolean("lock_double_tap", false);
characterSize =
_prefs.getFloat("character_size", 1.f)
* characterSizeScale;
theme = getThemeId(res, _prefs.getString("theme", ""));
autocapitalisation = _prefs.getBoolean("autocapitalisation", true);
switch_input_immediate = _prefs.getBoolean("switch_input_immediate", false);
extra_keys_param = ExtraKeysPreference.get_extra_keys(_prefs);
extra_keys_custom = CustomExtraKeysPreference.get(_prefs);
pin_entry_enabled = _prefs.getBoolean("pin_entry_enabled", true);
current_layout_portrait = _prefs.getInt("current_layout_portrait", 0);
current_layout_landscape = _prefs.getInt("current_layout_landscape", 0);
}
public int get_current_layout()
{
return (orientation_landscape)
? current_layout_landscape : current_layout_portrait;
}
public void set_current_layout(int l)
{
if (orientation_landscape)
current_layout_landscape = l;
else
current_layout_portrait = l;
SharedPreferences.Editor e = _prefs.edit();
e.putInt("current_layout_portrait", current_layout_portrait);
e.putInt("current_layout_landscape", current_layout_landscape);
e.apply();
}
KeyValue action_key()
{
// Update the name to avoid caching in KeyModifier
return (actionLabel == null) ? null :
KeyValue.getKeyByName("action").withSymbol(actionLabel);
}
/** Update the layout according to the configuration.
* - Remove the switching key if it isn't needed
* - Remove "localized" keys from other locales (not in 'extra_keys')
* - Replace the action key to show the right label
* - Swap the enter and action keys
* - Add the optional numpad and number row
* - Add the extra keys
*/
public KeyboardData modify_layout(KeyboardData kw)
{
final KeyValue action_key = action_key();
// Extra keys are removed from the set as they are encountered during the
// first iteration then automatically added.
final Map<KeyValue, KeyboardData.PreferredPos> extra_keys = new HashMap<KeyValue, KeyboardData.PreferredPos>();
final Set<KeyValue> remove_keys = new HashSet<KeyValue>();
// Make sure the config key is accessible to avoid being locked in a custom
// layout.
extra_keys.put(KeyValue.getKeyByName("config"), KeyboardData.PreferredPos.ANYWHERE);
extra_keys.putAll(extra_keys_param);
extra_keys.putAll(extra_keys_custom);
if (extra_keys_subtype != null)
{
Set<KeyValue> present = new HashSet<KeyValue>();
present.addAll(kw.getKeys().keySet());
present.addAll(extra_keys_param.keySet());
present.addAll(extra_keys_custom.keySet());
extra_keys_subtype.compute(extra_keys,
new ExtraKeys.Query(kw.script, present));
}
KeyboardData.Row number_row = null;
if (this.number_row && !show_numpad)
number_row = modify_number_row(KeyboardData.number_row, kw);
if (number_row != null)
remove_keys.addAll(number_row.getKeys(0).keySet());
kw = kw.mapKeys(new KeyboardData.MapKeyValues() {
public KeyValue apply(KeyValue key, boolean localized)
{
boolean is_extra_key = extra_keys.containsKey(key);
if (is_extra_key)
extra_keys.remove(key);
if (localized && !is_extra_key)
return null;
if (remove_keys.contains(key))
return null;
switch (key.getKind())
{
case Event:
switch (key.getEvent())
{
case CHANGE_METHOD_PICKER:
if (switch_input_immediate)
return KeyValue.getKeyByName("change_method_prev");
return key;
case ACTION:
return (swapEnterActionKey && action_key != null) ?
KeyValue.getKeyByName("enter") : action_key;
case SWITCH_FORWARD:
return (layouts.size() > 1) ? key : null;
case SWITCH_BACKWARD:
return (layouts.size() > 2) ? key : null;
case SWITCH_VOICE_TYPING:
case SWITCH_VOICE_TYPING_CHOOSER:
return shouldOfferVoiceTyping ? key : null;
}
break;
case Keyevent:
switch (key.getKeyevent())
{
case KeyEvent.KEYCODE_ENTER:
return (swapEnterActionKey && action_key != null) ? action_key : key;
}
break;
case Modifier:
switch (key.getModifier())
{
case SHIFT:
if (double_tap_lock_shift)
return key.withFlags(key.getFlags() | KeyValue.FLAG_LOCK);
}
break;
}
return key;
}
});
if (show_numpad)
kw = kw.addNumPad(modify_numpad(KeyboardData.num_pad, kw));
if (number_row != null)
kw = kw.addTopRow(number_row);
if (extra_keys.size() > 0)
kw = kw.addExtraKeys(extra_keys.entrySet().iterator());
return kw;
}
/** Handle the numpad layout. The [main_kw] is used to adapt the numpad to
the main layout's script. */
public KeyboardData modify_numpad(KeyboardData kw, KeyboardData main_kw)
{
final KeyValue action_key = action_key();
final KeyModifier.Map_char map_digit = KeyModifier.modify_numpad_script(main_kw.numpad_script);
return kw.mapKeys(new KeyboardData.MapKeyValues() {
public KeyValue apply(KeyValue key, boolean localized)
{
switch (key.getKind())
{
case Event:
switch (key.getEvent())
{
case ACTION:
return (swapEnterActionKey && action_key != null) ?
KeyValue.getKeyByName("enter") : action_key;
}
break;
case Keyevent:
switch (key.getKeyevent())
{
case KeyEvent.KEYCODE_ENTER:
return (swapEnterActionKey && action_key != null) ? action_key : key;
}
break;
case Char:
char prev_c = key.getChar();
char c = prev_c;
if (inverse_numpad)
c = inverse_numpad_char(c);
String modified = map_digit.apply(c);
if (modified != null) // Was modified by script
return KeyValue.makeStringKey(modified);
if (prev_c != c) // Was inverted
return key.withChar(c);
break;
}
return key;
}
});
}
static KeyboardData.MapKeyValues numpad_script_map(String numpad_script)
{
final KeyModifier.Map_char map_digit = KeyModifier.modify_numpad_script(numpad_script);
return new KeyboardData.MapKeyValues() {
public KeyValue apply(KeyValue key, boolean localized)
{
switch (key.getKind())
{
case Char:
String modified = map_digit.apply(key.getChar());
if (modified != null)
return KeyValue.makeStringKey(modified);
break;
}
return key;
}
};
}
/** Modify the pin entry layout. [main_kw] is used to map the digits into the
same script. */
public KeyboardData modify_pinentry(KeyboardData kw, KeyboardData main_kw)
{
return kw.mapKeys(numpad_script_map(main_kw.numpad_script));
}
/** Modify the number row according to [main_kw]'s script. */
public KeyboardData.Row modify_number_row(KeyboardData.Row row,
KeyboardData main_kw)
{
return row.mapKeys(numpad_script_map(main_kw.numpad_script));
}
private float get_dip_pref(DisplayMetrics dm, String pref_name, float def)
{
float value;
try { value = _prefs.getInt(pref_name, -1); }
catch (Exception e) { value = _prefs.getFloat(pref_name, -1f); }
if (value < 0f)
value = def;
return (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, dm));
}
/** [get_dip_pref] depending on orientation. */
float get_dip_pref_oriented(DisplayMetrics dm, String pref_base_name, float def_port, float def_land)
{
String suffix = orientation_landscape ? "_landscape" : "_portrait";
float def = orientation_landscape ? def_land : def_port;
return get_dip_pref(dm, pref_base_name + suffix, def);
}
private int getThemeId(Resources res, String theme_name)
{
switch (theme_name)
{
case "light": return R.style.Light;
case "black": return R.style.Black;
case "altblack": return R.style.AltBlack;
case "dark": return R.style.Dark;
case "white": return R.style.White;
case "epaper": return R.style.ePaper;
case "desert": return R.style.Desert;
case "jungle": return R.style.Jungle;
default:
case "system":
int night_mode = res.getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
if ((night_mode & Configuration.UI_MODE_NIGHT_NO) != 0)
return R.style.Light;
return R.style.Dark;
}
}
char inverse_numpad_char(char c)
{
switch (c)
{
case '7': return '1';
case '8': return '2';
case '9': return '3';
case '1': return '7';
case '2': return '8';
case '3': return '9';
default: return c;
}
}
private static Config _globalConfig = null;
public static void initGlobalConfig(SharedPreferences prefs, Resources res,
IKeyEventHandler handler)
{
migrate(prefs);
_globalConfig = new Config(prefs, res, handler);
}
public static Config globalConfig()
{
return _globalConfig;
}
public static SharedPreferences globalPrefs()
{
return _globalConfig._prefs;
}
public static interface IKeyEventHandler
{
public void key_down(KeyValue value, boolean is_swipe);
public void key_up(KeyValue value, Pointers.Modifiers mods);
public void mods_changed(Pointers.Modifiers mods);
}
/** Config migrations. */
private static int CONFIG_VERSION = 1;
public static void migrate(SharedPreferences prefs)
{
int saved_version = prefs.getInt("version", 0);
Logs.debug_config_migration(saved_version, CONFIG_VERSION);
if (saved_version == CONFIG_VERSION)
return;
SharedPreferences.Editor e = prefs.edit();
e.putInt("version", CONFIG_VERSION);
// Migrations might run on an empty [prefs] for new installs, in this case
// they set the default values of complex options.
switch (saved_version) // Fallback switch
{
case 0:
// Primary, secondary and custom layout options are merged into the new
// Layouts option. This also sets the default value.
List<LayoutsPreference.Layout> l = new ArrayList<LayoutsPreference.Layout>();
l.add(migrate_layout(prefs.getString("layout", "system")));
String snd_layout = prefs.getString("second_layout", "none");
if (snd_layout != null && !snd_layout.equals("none"))
l.add(migrate_layout(snd_layout));
String custom_layout = prefs.getString("custom_layout", "");
if (custom_layout != null && !custom_layout.equals(""))
l.add(LayoutsPreference.CustomLayout.parse(custom_layout));
LayoutsPreference.save_to_preferences(e, l);
case 1:
default: break;
}
e.apply();
}
private static LayoutsPreference.Layout migrate_layout(String name)
{
if (name == null || name.equals("system"))
return new LayoutsPreference.SystemLayout();
return new LayoutsPreference.NamedLayout(name);
}
}
| Julow/Unexpected-Keyboard | srcs/juloo.keyboard2/Config.java | 5,725 | /** [get_dip_pref] depending on orientation. */ | block_comment | nl | package juloo.keyboard2;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.KeyEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import juloo.keyboard2.prefs.CustomExtraKeysPreference;
import juloo.keyboard2.prefs.ExtraKeysPreference;
import juloo.keyboard2.prefs.LayoutsPreference;
public final class Config
{
private final SharedPreferences _prefs;
// From resources
public final float marginTop;
public final float keyPadding;
public final float labelTextSize;
public final float sublabelTextSize;
// From preferences
/** [null] represent the [system] layout. */
public List<KeyboardData> layouts;
public boolean show_numpad = false;
// From the 'numpad_layout' option, also apply to the numeric pane.
public boolean inverse_numpad = false;
public boolean number_row;
public float swipe_dist_px;
public float slide_step_px;
// Let the system handle vibration when false.
public boolean vibrate_custom;
// Control the vibration if [vibrate_custom] is true.
public long vibrate_duration;
public long longPressTimeout;
public long longPressInterval;
public float margin_bottom;
public float keyHeight;
public float horizontal_margin;
public float key_vertical_margin;
public float key_horizontal_margin;
public int labelBrightness; // 0 - 255
public int keyboardOpacity; // 0 - 255
public float customBorderRadius; // 0 - 1
public float customBorderLineWidth; // dp
public int keyOpacity; // 0 - 255
public int keyActivatedOpacity; // 0 - 255
public boolean double_tap_lock_shift;
public float characterSize; // Ratio
public int theme; // Values are R.style.*
public boolean autocapitalisation;
public boolean switch_input_immediate;
public boolean pin_entry_enabled;
public boolean borderConfig;
// Dynamically set
public boolean shouldOfferVoiceTyping;
public String actionLabel; // Might be 'null'
public int actionId; // Meaningful only when 'actionLabel' isn't 'null'
public boolean swapEnterActionKey; // Swap the "enter" and "action" keys
public ExtraKeys extra_keys_subtype;
public Map<KeyValue, KeyboardData.PreferredPos> extra_keys_param;
public Map<KeyValue, KeyboardData.PreferredPos> extra_keys_custom;
public final IKeyEventHandler handler;
public boolean orientation_landscape = false;
/** Index in 'layouts' of the currently used layout. See
[get_current_layout()] and [set_current_layout()]. */
int current_layout_portrait;
int current_layout_landscape;
private Config(SharedPreferences prefs, Resources res, IKeyEventHandler h)
{
_prefs = prefs;
// static values
marginTop = res.getDimension(R.dimen.margin_top);
keyPadding = res.getDimension(R.dimen.key_padding);
labelTextSize = 0.33f;
sublabelTextSize = 0.22f;
// from prefs
refresh(res);
// initialized later
shouldOfferVoiceTyping = false;
actionLabel = null;
actionId = 0;
swapEnterActionKey = false;
extra_keys_subtype = null;
handler = h;
}
/*
** Reload prefs
*/
public void refresh(Resources res)
{
DisplayMetrics dm = res.getDisplayMetrics();
orientation_landscape = res.getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE;
// The height of the keyboard is relative to the height of the screen.
// This is the height of the keyboard if it have 4 rows.
int keyboardHeightPercent;
float characterSizeScale = 1.f;
String show_numpad_s = _prefs.getString("show_numpad", "never");
show_numpad = "always".equals(show_numpad_s);
if (orientation_landscape)
{
if ("landscape".equals(show_numpad_s))
show_numpad = true;
keyboardHeightPercent = _prefs.getInt("keyboard_height_landscape", 50);
characterSizeScale = 1.25f;
}
else
{
keyboardHeightPercent = _prefs.getInt("keyboard_height", 35);
}
layouts = LayoutsPreference.load_from_preferences(res, _prefs);
inverse_numpad = _prefs.getString("numpad_layout", "default").equals("low_first");
number_row = _prefs.getBoolean("number_row", false);
// The baseline for the swipe distance correspond to approximately the
// width of a key in portrait mode, as most layouts have 10 columns.
// Multipled by the DPI ratio because most swipes are made in the diagonals.
// The option value uses an unnamed scale where the baseline is around 25.
float dpi_ratio = Math.max(dm.xdpi, dm.ydpi) / Math.min(dm.xdpi, dm.ydpi);
float swipe_scaling = Math.min(dm.widthPixels, dm.heightPixels) / 10.f * dpi_ratio;
float swipe_dist_value = Float.valueOf(_prefs.getString("swipe_dist", "15"));
swipe_dist_px = swipe_dist_value / 25.f * swipe_scaling;
slide_step_px = 0.2f * swipe_scaling;
vibrate_custom = _prefs.getBoolean("vibrate_custom", false);
vibrate_duration = _prefs.getInt("vibrate_duration", 20);
longPressTimeout = _prefs.getInt("longpress_timeout", 600);
longPressInterval = _prefs.getInt("longpress_interval", 65);
margin_bottom = get_dip_pref_oriented(dm, "margin_bottom", 7, 3);
key_vertical_margin = get_dip_pref(dm, "key_vertical_margin", 1.5f) / 100;
key_horizontal_margin = get_dip_pref(dm, "key_horizontal_margin", 2) / 100;
// Label brightness is used as the alpha channel
labelBrightness = _prefs.getInt("label_brightness", 100) * 255 / 100;
// Keyboard opacity
keyboardOpacity = _prefs.getInt("keyboard_opacity", 100) * 255 / 100;
keyOpacity = _prefs.getInt("key_opacity", 100) * 255 / 100;
keyActivatedOpacity = _prefs.getInt("key_activated_opacity", 100) * 255 / 100;
// keyboard border settings
borderConfig = _prefs.getBoolean("border_config", false);
customBorderRadius = _prefs.getInt("custom_border_radius", 0) / 100.f;
customBorderLineWidth = get_dip_pref(dm, "custom_border_line_width", 0);
// Do not substract key_vertical_margin from keyHeight because this is done
// during rendering.
keyHeight = dm.heightPixels * keyboardHeightPercent / 100 / 4;
horizontal_margin =
get_dip_pref_oriented(dm, "horizontal_margin", 3, 28);
double_tap_lock_shift = _prefs.getBoolean("lock_double_tap", false);
characterSize =
_prefs.getFloat("character_size", 1.f)
* characterSizeScale;
theme = getThemeId(res, _prefs.getString("theme", ""));
autocapitalisation = _prefs.getBoolean("autocapitalisation", true);
switch_input_immediate = _prefs.getBoolean("switch_input_immediate", false);
extra_keys_param = ExtraKeysPreference.get_extra_keys(_prefs);
extra_keys_custom = CustomExtraKeysPreference.get(_prefs);
pin_entry_enabled = _prefs.getBoolean("pin_entry_enabled", true);
current_layout_portrait = _prefs.getInt("current_layout_portrait", 0);
current_layout_landscape = _prefs.getInt("current_layout_landscape", 0);
}
public int get_current_layout()
{
return (orientation_landscape)
? current_layout_landscape : current_layout_portrait;
}
public void set_current_layout(int l)
{
if (orientation_landscape)
current_layout_landscape = l;
else
current_layout_portrait = l;
SharedPreferences.Editor e = _prefs.edit();
e.putInt("current_layout_portrait", current_layout_portrait);
e.putInt("current_layout_landscape", current_layout_landscape);
e.apply();
}
KeyValue action_key()
{
// Update the name to avoid caching in KeyModifier
return (actionLabel == null) ? null :
KeyValue.getKeyByName("action").withSymbol(actionLabel);
}
/** Update the layout according to the configuration.
* - Remove the switching key if it isn't needed
* - Remove "localized" keys from other locales (not in 'extra_keys')
* - Replace the action key to show the right label
* - Swap the enter and action keys
* - Add the optional numpad and number row
* - Add the extra keys
*/
public KeyboardData modify_layout(KeyboardData kw)
{
final KeyValue action_key = action_key();
// Extra keys are removed from the set as they are encountered during the
// first iteration then automatically added.
final Map<KeyValue, KeyboardData.PreferredPos> extra_keys = new HashMap<KeyValue, KeyboardData.PreferredPos>();
final Set<KeyValue> remove_keys = new HashSet<KeyValue>();
// Make sure the config key is accessible to avoid being locked in a custom
// layout.
extra_keys.put(KeyValue.getKeyByName("config"), KeyboardData.PreferredPos.ANYWHERE);
extra_keys.putAll(extra_keys_param);
extra_keys.putAll(extra_keys_custom);
if (extra_keys_subtype != null)
{
Set<KeyValue> present = new HashSet<KeyValue>();
present.addAll(kw.getKeys().keySet());
present.addAll(extra_keys_param.keySet());
present.addAll(extra_keys_custom.keySet());
extra_keys_subtype.compute(extra_keys,
new ExtraKeys.Query(kw.script, present));
}
KeyboardData.Row number_row = null;
if (this.number_row && !show_numpad)
number_row = modify_number_row(KeyboardData.number_row, kw);
if (number_row != null)
remove_keys.addAll(number_row.getKeys(0).keySet());
kw = kw.mapKeys(new KeyboardData.MapKeyValues() {
public KeyValue apply(KeyValue key, boolean localized)
{
boolean is_extra_key = extra_keys.containsKey(key);
if (is_extra_key)
extra_keys.remove(key);
if (localized && !is_extra_key)
return null;
if (remove_keys.contains(key))
return null;
switch (key.getKind())
{
case Event:
switch (key.getEvent())
{
case CHANGE_METHOD_PICKER:
if (switch_input_immediate)
return KeyValue.getKeyByName("change_method_prev");
return key;
case ACTION:
return (swapEnterActionKey && action_key != null) ?
KeyValue.getKeyByName("enter") : action_key;
case SWITCH_FORWARD:
return (layouts.size() > 1) ? key : null;
case SWITCH_BACKWARD:
return (layouts.size() > 2) ? key : null;
case SWITCH_VOICE_TYPING:
case SWITCH_VOICE_TYPING_CHOOSER:
return shouldOfferVoiceTyping ? key : null;
}
break;
case Keyevent:
switch (key.getKeyevent())
{
case KeyEvent.KEYCODE_ENTER:
return (swapEnterActionKey && action_key != null) ? action_key : key;
}
break;
case Modifier:
switch (key.getModifier())
{
case SHIFT:
if (double_tap_lock_shift)
return key.withFlags(key.getFlags() | KeyValue.FLAG_LOCK);
}
break;
}
return key;
}
});
if (show_numpad)
kw = kw.addNumPad(modify_numpad(KeyboardData.num_pad, kw));
if (number_row != null)
kw = kw.addTopRow(number_row);
if (extra_keys.size() > 0)
kw = kw.addExtraKeys(extra_keys.entrySet().iterator());
return kw;
}
/** Handle the numpad layout. The [main_kw] is used to adapt the numpad to
the main layout's script. */
public KeyboardData modify_numpad(KeyboardData kw, KeyboardData main_kw)
{
final KeyValue action_key = action_key();
final KeyModifier.Map_char map_digit = KeyModifier.modify_numpad_script(main_kw.numpad_script);
return kw.mapKeys(new KeyboardData.MapKeyValues() {
public KeyValue apply(KeyValue key, boolean localized)
{
switch (key.getKind())
{
case Event:
switch (key.getEvent())
{
case ACTION:
return (swapEnterActionKey && action_key != null) ?
KeyValue.getKeyByName("enter") : action_key;
}
break;
case Keyevent:
switch (key.getKeyevent())
{
case KeyEvent.KEYCODE_ENTER:
return (swapEnterActionKey && action_key != null) ? action_key : key;
}
break;
case Char:
char prev_c = key.getChar();
char c = prev_c;
if (inverse_numpad)
c = inverse_numpad_char(c);
String modified = map_digit.apply(c);
if (modified != null) // Was modified by script
return KeyValue.makeStringKey(modified);
if (prev_c != c) // Was inverted
return key.withChar(c);
break;
}
return key;
}
});
}
static KeyboardData.MapKeyValues numpad_script_map(String numpad_script)
{
final KeyModifier.Map_char map_digit = KeyModifier.modify_numpad_script(numpad_script);
return new KeyboardData.MapKeyValues() {
public KeyValue apply(KeyValue key, boolean localized)
{
switch (key.getKind())
{
case Char:
String modified = map_digit.apply(key.getChar());
if (modified != null)
return KeyValue.makeStringKey(modified);
break;
}
return key;
}
};
}
/** Modify the pin entry layout. [main_kw] is used to map the digits into the
same script. */
public KeyboardData modify_pinentry(KeyboardData kw, KeyboardData main_kw)
{
return kw.mapKeys(numpad_script_map(main_kw.numpad_script));
}
/** Modify the number row according to [main_kw]'s script. */
public KeyboardData.Row modify_number_row(KeyboardData.Row row,
KeyboardData main_kw)
{
return row.mapKeys(numpad_script_map(main_kw.numpad_script));
}
private float get_dip_pref(DisplayMetrics dm, String pref_name, float def)
{
float value;
try { value = _prefs.getInt(pref_name, -1); }
catch (Exception e) { value = _prefs.getFloat(pref_name, -1f); }
if (value < 0f)
value = def;
return (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, dm));
}
/** [get_dip_pref] depending on<SUF>*/
float get_dip_pref_oriented(DisplayMetrics dm, String pref_base_name, float def_port, float def_land)
{
String suffix = orientation_landscape ? "_landscape" : "_portrait";
float def = orientation_landscape ? def_land : def_port;
return get_dip_pref(dm, pref_base_name + suffix, def);
}
private int getThemeId(Resources res, String theme_name)
{
switch (theme_name)
{
case "light": return R.style.Light;
case "black": return R.style.Black;
case "altblack": return R.style.AltBlack;
case "dark": return R.style.Dark;
case "white": return R.style.White;
case "epaper": return R.style.ePaper;
case "desert": return R.style.Desert;
case "jungle": return R.style.Jungle;
default:
case "system":
int night_mode = res.getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
if ((night_mode & Configuration.UI_MODE_NIGHT_NO) != 0)
return R.style.Light;
return R.style.Dark;
}
}
char inverse_numpad_char(char c)
{
switch (c)
{
case '7': return '1';
case '8': return '2';
case '9': return '3';
case '1': return '7';
case '2': return '8';
case '3': return '9';
default: return c;
}
}
private static Config _globalConfig = null;
public static void initGlobalConfig(SharedPreferences prefs, Resources res,
IKeyEventHandler handler)
{
migrate(prefs);
_globalConfig = new Config(prefs, res, handler);
}
public static Config globalConfig()
{
return _globalConfig;
}
public static SharedPreferences globalPrefs()
{
return _globalConfig._prefs;
}
public static interface IKeyEventHandler
{
public void key_down(KeyValue value, boolean is_swipe);
public void key_up(KeyValue value, Pointers.Modifiers mods);
public void mods_changed(Pointers.Modifiers mods);
}
/** Config migrations. */
private static int CONFIG_VERSION = 1;
public static void migrate(SharedPreferences prefs)
{
int saved_version = prefs.getInt("version", 0);
Logs.debug_config_migration(saved_version, CONFIG_VERSION);
if (saved_version == CONFIG_VERSION)
return;
SharedPreferences.Editor e = prefs.edit();
e.putInt("version", CONFIG_VERSION);
// Migrations might run on an empty [prefs] for new installs, in this case
// they set the default values of complex options.
switch (saved_version) // Fallback switch
{
case 0:
// Primary, secondary and custom layout options are merged into the new
// Layouts option. This also sets the default value.
List<LayoutsPreference.Layout> l = new ArrayList<LayoutsPreference.Layout>();
l.add(migrate_layout(prefs.getString("layout", "system")));
String snd_layout = prefs.getString("second_layout", "none");
if (snd_layout != null && !snd_layout.equals("none"))
l.add(migrate_layout(snd_layout));
String custom_layout = prefs.getString("custom_layout", "");
if (custom_layout != null && !custom_layout.equals(""))
l.add(LayoutsPreference.CustomLayout.parse(custom_layout));
LayoutsPreference.save_to_preferences(e, l);
case 1:
default: break;
}
e.apply();
}
private static LayoutsPreference.Layout migrate_layout(String name)
{
if (name == null || name.equals("system"))
return new LayoutsPreference.SystemLayout();
return new LayoutsPreference.NamedLayout(name);
}
}
|
156331_6 | /*
* Copyright (c) 2014, Netherlands Forensic Institute
* All rights reserved.
*/
package nl.minvenj.nfi.common_source_identification;
import java.awt.color.CMMException;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import nl.minvenj.nfi.common_source_identification.filter.FastNoiseFilter;
import nl.minvenj.nfi.common_source_identification.filter.ImageFilter;
import nl.minvenj.nfi.common_source_identification.filter.WienerFilter;
import nl.minvenj.nfi.common_source_identification.filter.ZeroMeanTotalFilter;
public final class CommonSourceIdentification {
static final File TESTDATA_FOLDER = new File("testdata");
static final File INPUT_FOLDER = new File(TESTDATA_FOLDER, "input");
// public static final File INPUT_FILE = new File(INPUT_FOLDER, "test.jpg");
public static final File INPUT_FILE = new File("/var/scratch/bwn200/Dresden/2748x3664/Kodak_M1063_4_12664.JPG");
static final File EXPECTED_PATTERN_FILE = new File(INPUT_FOLDER, "expected.pat");
static final File OUTPUT_FOLDER = new File(TESTDATA_FOLDER, "output");
static final File OUTPUT_FILE = new File(OUTPUT_FOLDER, "test.pat");
public static void main(final String[] args) throws IOException {
long start = System.currentTimeMillis();
long end = 0;
// Laad de input file in
final BufferedImage image = readImage(INPUT_FILE);
end = System.currentTimeMillis();
System.out.println("Load image: " + (end-start) + " ms.");
// Zet de input file om in 3 matrices (rood, groen, blauw)
start = System.currentTimeMillis();
final float[][][] rgbArrays = convertImageToFloatArrays(image);
end = System.currentTimeMillis();
System.out.println("Convert image:" + (end-start) + " ms.");
// Bereken van elke matrix het PRNU patroon (extractie stap)
start = System.currentTimeMillis();
for (int i = 0; i < 3; i++) {
extractImage(rgbArrays[i]);
}
end = System.currentTimeMillis();
System.out.println("PRNU extracted: " + (end-start) + " ms.");
// Schrijf het patroon weg als een Java object
writeJavaObject(rgbArrays, OUTPUT_FILE);
System.out.println("Pattern written");
// Controleer nu het gemaakte bestand
final float[][][] expectedPattern = (float[][][]) readJavaObject(EXPECTED_PATTERN_FILE);
final float[][][] actualPattern = (float[][][]) readJavaObject(OUTPUT_FILE);
for (int i = 0; i < 3; i++) {
// Het patroon zoals dat uit PRNU Compare komt, bevat een extra matrix voor transparantie. Deze moeten we overslaan (+1)!
compare2DArray(expectedPattern[i + 1], actualPattern[i], 0.0001f);
}
System.out.println("Validation completed");
//This exit is inserted because the program will otherwise hang for a about a minute
//most likely explanation for this is the fact that the FFT library spawns a couple
//of threads which cannot be properly destroyed
System.exit(0);
}
private static BufferedImage readImage(final File file) throws IOException {
final InputStream fileInputStream = new FileInputStream(file);
try {
final BufferedImage image = ImageIO.read(new BufferedInputStream(fileInputStream));
if ((image != null) && (image.getWidth() >= 0) && (image.getHeight() >= 0)) {
return image;
}
}
catch (final CMMException e) {
// Image file is unsupported or corrupt
}
catch (final RuntimeException e) {
// Internal error processing image file
}
catch (final IOException e) {
// Error reading image from disk
}
finally {
fileInputStream.close();
}
// Image unreadable or too smalld array
return null;
}
private static float[][][] convertImageToFloatArrays(final BufferedImage image) {
final int width = image.getWidth();
final int height = image.getHeight();
final float[][][] pixels = new float[3][height][width];
final ColorModel colorModel = ColorModel.getRGBdefault();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
final int pixel = image.getRGB(x, y); // aa bb gg rr
pixels[0][y][x] = colorModel.getRed(pixel);
pixels[1][y][x] = colorModel.getGreen(pixel);
pixels[2][y][x] = colorModel.getBlue(pixel);
}
}
return pixels;
}
private static void extractImage(final float[][] pixels) {
final int width = pixels[0].length;
final int height = pixels.length;
long start = System.currentTimeMillis();
long end = 0;
final ImageFilter fastNoiseFilter = new FastNoiseFilter(width, height);
fastNoiseFilter.apply(pixels);
end = System.currentTimeMillis();
System.out.println("Fast Noise Filter: " + (end-start) + " ms.");
start = System.currentTimeMillis();
final ImageFilter zeroMeanTotalFilter = new ZeroMeanTotalFilter(width, height);
zeroMeanTotalFilter.apply(pixels);
end = System.currentTimeMillis();
System.out.println("Zero Mean Filter: " + (end-start) + " ms.");
start = System.currentTimeMillis();
final ImageFilter wienerFilter = new WienerFilter(width, height);
wienerFilter.apply(pixels);
end = System.currentTimeMillis();
System.out.println("Wiener Filter: " + (end-start) + " ms.");
}
public static Object readJavaObject(final File inputFile) throws IOException {
final ObjectInputStream inputStream = new ObjectInputStream(new BufferedInputStream(new FileInputStream(inputFile)));
try {
return inputStream.readObject();
}
catch (final ClassNotFoundException e) {
throw new IOException("Cannot read pattern: " + inputFile.getAbsolutePath(), e);
}
finally {
inputStream.close();
}
}
private static void writeJavaObject(final Object object, final File outputFile) throws IOException {
final OutputStream outputStream = new FileOutputStream(outputFile);
try {
final ObjectOutputStream objectOutputStream = new ObjectOutputStream(new BufferedOutputStream(outputStream));
objectOutputStream.writeObject(object);
objectOutputStream.close();
}
finally {
outputStream.close();
}
}
private static boolean compare2DArray(final float[][] expected, final float[][] actual, final float delta) {
for (int i = 0; i < expected.length; i++) {
for (int j = 0; j < expected[i].length; j++) {
if (Math.abs(actual[i][j] - expected[i][j]) > delta) {
System.err.println("de waarde op " + i + "," + j + " is " + actual[i][j] + " maar had moeten zijn " + expected[i][j]);
return false;
}
}
}
return true;
}
}
| JungleComputing/common-source-identification-desktop | src/main/java/nl/minvenj/nfi/common_source_identification/CommonSourceIdentification.java | 2,232 | // Controleer nu het gemaakte bestand
| line_comment | nl | /*
* Copyright (c) 2014, Netherlands Forensic Institute
* All rights reserved.
*/
package nl.minvenj.nfi.common_source_identification;
import java.awt.color.CMMException;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import nl.minvenj.nfi.common_source_identification.filter.FastNoiseFilter;
import nl.minvenj.nfi.common_source_identification.filter.ImageFilter;
import nl.minvenj.nfi.common_source_identification.filter.WienerFilter;
import nl.minvenj.nfi.common_source_identification.filter.ZeroMeanTotalFilter;
public final class CommonSourceIdentification {
static final File TESTDATA_FOLDER = new File("testdata");
static final File INPUT_FOLDER = new File(TESTDATA_FOLDER, "input");
// public static final File INPUT_FILE = new File(INPUT_FOLDER, "test.jpg");
public static final File INPUT_FILE = new File("/var/scratch/bwn200/Dresden/2748x3664/Kodak_M1063_4_12664.JPG");
static final File EXPECTED_PATTERN_FILE = new File(INPUT_FOLDER, "expected.pat");
static final File OUTPUT_FOLDER = new File(TESTDATA_FOLDER, "output");
static final File OUTPUT_FILE = new File(OUTPUT_FOLDER, "test.pat");
public static void main(final String[] args) throws IOException {
long start = System.currentTimeMillis();
long end = 0;
// Laad de input file in
final BufferedImage image = readImage(INPUT_FILE);
end = System.currentTimeMillis();
System.out.println("Load image: " + (end-start) + " ms.");
// Zet de input file om in 3 matrices (rood, groen, blauw)
start = System.currentTimeMillis();
final float[][][] rgbArrays = convertImageToFloatArrays(image);
end = System.currentTimeMillis();
System.out.println("Convert image:" + (end-start) + " ms.");
// Bereken van elke matrix het PRNU patroon (extractie stap)
start = System.currentTimeMillis();
for (int i = 0; i < 3; i++) {
extractImage(rgbArrays[i]);
}
end = System.currentTimeMillis();
System.out.println("PRNU extracted: " + (end-start) + " ms.");
// Schrijf het patroon weg als een Java object
writeJavaObject(rgbArrays, OUTPUT_FILE);
System.out.println("Pattern written");
// Controleer nu<SUF>
final float[][][] expectedPattern = (float[][][]) readJavaObject(EXPECTED_PATTERN_FILE);
final float[][][] actualPattern = (float[][][]) readJavaObject(OUTPUT_FILE);
for (int i = 0; i < 3; i++) {
// Het patroon zoals dat uit PRNU Compare komt, bevat een extra matrix voor transparantie. Deze moeten we overslaan (+1)!
compare2DArray(expectedPattern[i + 1], actualPattern[i], 0.0001f);
}
System.out.println("Validation completed");
//This exit is inserted because the program will otherwise hang for a about a minute
//most likely explanation for this is the fact that the FFT library spawns a couple
//of threads which cannot be properly destroyed
System.exit(0);
}
private static BufferedImage readImage(final File file) throws IOException {
final InputStream fileInputStream = new FileInputStream(file);
try {
final BufferedImage image = ImageIO.read(new BufferedInputStream(fileInputStream));
if ((image != null) && (image.getWidth() >= 0) && (image.getHeight() >= 0)) {
return image;
}
}
catch (final CMMException e) {
// Image file is unsupported or corrupt
}
catch (final RuntimeException e) {
// Internal error processing image file
}
catch (final IOException e) {
// Error reading image from disk
}
finally {
fileInputStream.close();
}
// Image unreadable or too smalld array
return null;
}
private static float[][][] convertImageToFloatArrays(final BufferedImage image) {
final int width = image.getWidth();
final int height = image.getHeight();
final float[][][] pixels = new float[3][height][width];
final ColorModel colorModel = ColorModel.getRGBdefault();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
final int pixel = image.getRGB(x, y); // aa bb gg rr
pixels[0][y][x] = colorModel.getRed(pixel);
pixels[1][y][x] = colorModel.getGreen(pixel);
pixels[2][y][x] = colorModel.getBlue(pixel);
}
}
return pixels;
}
private static void extractImage(final float[][] pixels) {
final int width = pixels[0].length;
final int height = pixels.length;
long start = System.currentTimeMillis();
long end = 0;
final ImageFilter fastNoiseFilter = new FastNoiseFilter(width, height);
fastNoiseFilter.apply(pixels);
end = System.currentTimeMillis();
System.out.println("Fast Noise Filter: " + (end-start) + " ms.");
start = System.currentTimeMillis();
final ImageFilter zeroMeanTotalFilter = new ZeroMeanTotalFilter(width, height);
zeroMeanTotalFilter.apply(pixels);
end = System.currentTimeMillis();
System.out.println("Zero Mean Filter: " + (end-start) + " ms.");
start = System.currentTimeMillis();
final ImageFilter wienerFilter = new WienerFilter(width, height);
wienerFilter.apply(pixels);
end = System.currentTimeMillis();
System.out.println("Wiener Filter: " + (end-start) + " ms.");
}
public static Object readJavaObject(final File inputFile) throws IOException {
final ObjectInputStream inputStream = new ObjectInputStream(new BufferedInputStream(new FileInputStream(inputFile)));
try {
return inputStream.readObject();
}
catch (final ClassNotFoundException e) {
throw new IOException("Cannot read pattern: " + inputFile.getAbsolutePath(), e);
}
finally {
inputStream.close();
}
}
private static void writeJavaObject(final Object object, final File outputFile) throws IOException {
final OutputStream outputStream = new FileOutputStream(outputFile);
try {
final ObjectOutputStream objectOutputStream = new ObjectOutputStream(new BufferedOutputStream(outputStream));
objectOutputStream.writeObject(object);
objectOutputStream.close();
}
finally {
outputStream.close();
}
}
private static boolean compare2DArray(final float[][] expected, final float[][] actual, final float delta) {
for (int i = 0; i < expected.length; i++) {
for (int j = 0; j < expected[i].length; j++) {
if (Math.abs(actual[i][j] - expected[i][j]) > delta) {
System.err.println("de waarde op " + i + "," + j + " is " + actual[i][j] + " maar had moeten zijn " + expected[i][j]);
return false;
}
}
}
return true;
}
}
|
82291_32 | package nl.hva.ict.data.MySQL;
import nl.hva.ict.models.Accommodatie;
import nl.hva.ict.models.BoekingsOverzicht;
import nl.hva.ict.models.Reiziger;
import nl.hva.ict.models.Reservering;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
/**
* DAO voor de accommodatie
*
* @author HBO-ICT
*/
public class MySQLBoekingsOverzicht extends MySQL<BoekingsOverzicht> {
private final List<BoekingsOverzicht> boekingsOverzicht;
/**
* Constructor
*/
public MySQLBoekingsOverzicht() {
// init arraylist
boekingsOverzicht = new ArrayList<>();
// Laad bij startup
load();
}
/**
* Doe dit bij het maken van dit object
*/
private void load() {
// Vul hier je SQL code in
String sql = "";
// Als je nog geen query hebt ingevuld breek dan af om een error te voorkomen.
if (sql.equals(""))
return;
try {
// Roep de methode aan in de parent class en geen je SQL door
PreparedStatement ps = getStatement(sql);
//Voer je query uit en stop het antwoord in een result set
ResultSet rs = executeSelectPreparedStatement(ps);
// Loop net zolang als er records zijn
while (rs.next()) {
int idReservering = 0;
Date aankomstDatum = rs.getDate("aankomstDatum");
Date vertrekDatum = rs.getDate("vertrekDatum");
boolean betaald = rs.getBoolean("betaald");
String accommodatieCode = rs.getString("accommodatieCode");
String reizerCode = rs.getString("reizigerCode");
String voornaam = ""; // not in use
String achternaam = rs.getString("reiziger"); // combine voor en achternaam
String adres = ""; // not in use
String postcode = "";
String plaats = "";
String land = "";
String hoofdreiziger = "";
String accommodatieNaam = rs.getString("naam");
String accommodatieStad = rs.getString("stad");
String accommodatieLand = rs.getString("land");
// Maak models aan
Reservering reservering = new Reservering(idReservering, aankomstDatum, vertrekDatum, betaald, accommodatieCode, reizerCode);
Reiziger reiziger = new Reiziger(reizerCode, voornaam, achternaam, adres, postcode, plaats, land, hoofdreiziger);
Accommodatie accommodatie = new Accommodatie();
accommodatie.setNaam(accommodatieNaam);
accommodatie.setStad(accommodatieStad);
accommodatie.setLand(accommodatieLand);
//voeg die toe aan de arraylist
boekingsOverzicht.add(new BoekingsOverzicht(accommodatie, reiziger, reservering));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Haal de boekingen op voor 1 reiziger
*
* @param reizigerscode Welke reiziger wil je de boekingen voor?
* @return Een list van boekingen
*/
public List<BoekingsOverzicht> getBoekingVoor(String reizigerscode) {
// Maak een arraylist
List<BoekingsOverzicht> reserveringVoor = new ArrayList<>();
// Voer hier je query in
String sql = """
SELECT
r.id,
r.aankomst_datum AS aankomstDatum,
r.vertrek_datum AS vertrekDatum,
r.betaald,
r.accommodatie_code AS accommodatieCode,
r.reiziger_code AS reizigerCode,
re.voornaam,
re.achternaam,
re.plaats,
a.naam,
a.stad,
a.land
FROM
`reservering` AS r
INNER JOIN reiziger AS re ON
r.reiziger_code = re.reiziger_code
INNER JOIN `accommodatie` AS a ON
r.accommodatie_code = a.accommodatie_code
WHERE
r.reiziger_code = ?
""";
try {
// Maak je statement
PreparedStatement ps = getStatement(sql);
// Vervang het eerste vraagteken met de reizigerscode. Pas dit eventueel aan voor jou eigen query
ps.setString(1, reizigerscode);
// Voer het uit
ResultSet rs = executeSelectPreparedStatement(ps);
// Loop net zolang als er records zijn
while (rs.next()) {
int idReservering = 0;
Date aankomstDatum = rs.getDate("aankomstDatum");
Date vertrekDatum = rs.getDate("vertrekDatum");
boolean betaald = rs.getBoolean("betaald");
String accommodatieCode = rs.getString("accommodatieCode");
String reizigerVoornaam = rs.getString("voornaam");
String reizigerAchternaam = rs.getString("achternaam");
String reizigerPlaats = rs.getString("plaats");
String accommodatieNaam = rs.getString("naam");
String accommodatieStad = rs.getString("stad");
String accommodatieLand = rs.getString("land");
// Maak model objecten
Reservering reservering = new Reservering(idReservering, aankomstDatum, vertrekDatum, betaald, accommodatieCode, reizigerscode);
Accommodatie accommodatie = new Accommodatie();
accommodatie.setNaam(accommodatieNaam);
accommodatie.setStad(accommodatieStad);
accommodatie.setLand(accommodatieLand);
Reiziger reiziger = new Reiziger();
reiziger.setVoornaam(reizigerVoornaam);
reiziger.setAchternaam(reizigerAchternaam);
reiziger.setPlaats(reizigerPlaats);
// Voeg de reservering toe aan de arraylist
reserveringVoor.add(new BoekingsOverzicht(accommodatie, reiziger, reservering));
}
} catch (SQLException throwables) {
// Oeps probleem
throwables.printStackTrace();
}
// Geef de arrayList terug met de juiste reserveringen
return reserveringVoor;
}
/**
* Haal de reizigerscode op voor een bepaalde boeking per accommodate en datum
*
* @param pCode de accommodatecode
* @param pDatum de datum van verblijf
* @return De reizigerscode
*/
private String getReizigerscode(String pCode, LocalDate pDatum) {
String sql = """
SELECT GeboektOp(?, ?) AS reizigerCode;
""";
// default waarde
String reizigerCode = "";
// convert datum naar ander formaat
Date date = Date.valueOf(pDatum);
try {
// query voorbereiden
PreparedStatement ps = getStatement(sql);
// Vervang de vraagtekens met de juiste waarde. Pas eventueel aan je eigen query
ps.setString(1, pCode);
ps.setDate(2, date);
// Voer het uit
ResultSet rs = executeSelectPreparedStatement(ps);
// Loop net zolang als er records zijn
while (rs.next()) {
reizigerCode = rs.getString("reizigerCode");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
// Geef de reizigercode terug
return reizigerCode;
}
/**
* Haal een lijst met reserveringen op voor een bepaalde boeking per accommodate en datum
*
* @param pCode de accommodate code
* @param pDatum de datum van verblijf
* @return Lijst met reserveringen
*/
public List<Reiziger> GeboektOp(String pCode, LocalDate pDatum) {
// Init arraylist
List<Reiziger> geboektOp = new ArrayList<>();
//Stop null pointer error als datum nog niet is ingevuld.
if (pDatum == null)
return geboektOp;
// Spring naar de methode hierboven om de reizigerscode op te halen voor deze boeking
String reizigerscode = getReizigerscode(pCode, pDatum);
if (reizigerscode != null) {
// Haal alle reserveringen op
String sql = """
SELECT reiziger.voornaam,
reiziger.achternaam,
reiziger.adres,
reiziger.postcode,
reiziger.plaats,
reiziger.land,
CONCAT(reiziger.voornaam, ' ', reiziger.achternaam) AS hoofdreiziger
FROM `reiziger`
WHERE reiziger.reiziger_code = ?
""";
// Als je nog geen query hebt ingevuld breek dan af om een error te voorkomen.
if (sql.equals(""))
return geboektOp;
try {
// Roep de methode aan in de parent class en geef je SQL door
PreparedStatement ps = getStatement(sql);
// vervang de eerste vraagteken met de reizigerscode
ps.setString(1, reizigerscode);
// Voer je query uit
ResultSet rs = executeSelectPreparedStatement(ps);
// Loop net zolang als er records zijn
while (rs.next()) {
String voornaam = rs.getString("voornaam");
String achternaam = rs.getString("achternaam");
String adres = rs.getString("adres");
String postcode = rs.getString("postcode");
String plaats = rs.getString("plaats");
String land = rs.getString("land");
String hoofdreiziger = rs.getString("hoofdreiziger");
// Maak reserveringsobject en voeg direct toe aan arraylist
geboektOp.add(new Reiziger(reizigerscode, voornaam, achternaam, adres, postcode, plaats, land, hoofdreiziger));
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
// Geef de array terug met reserveringen
return geboektOp;
}
/**
* Haal alle boekingen op door de gehele arraylist terug te geven
*
* @return Een arraylist van accommodaties
*/
@Override
public List<BoekingsOverzicht> getAll() {
return boekingsOverzicht;
}
/**
* Haal 1 boeking op
*
* @return Een arraylist van accommodaties
*/
@Override
public BoekingsOverzicht get() {
// nog niet uitgewerkt geeft nu even null terug
return null;
}
/**
* Voeg een boeking toe
*
* @param boekingsOverzicht de boeking
*/
@Override
public void add(BoekingsOverzicht boekingsOverzicht) {
// nog niet uitgewerkt
}
/**
* Update de boeking
*
* @param boekingsOverzicht de boeking
*/
@Override
public void update(BoekingsOverzicht boekingsOverzicht) {
// nog niet uitgewerkt
}
/**
* Verwijder een boeking
*
* @param object de boeking
*/
@Override
public void remove(BoekingsOverzicht object) {
// nog niet uitgewerkt
}
}
| JuniorBrPr/DB2 | src/nl/hva/ict/data/MySQL/MySQLBoekingsOverzicht.java | 3,300 | // Spring naar de methode hierboven om de reizigerscode op te halen voor deze boeking | line_comment | nl | package nl.hva.ict.data.MySQL;
import nl.hva.ict.models.Accommodatie;
import nl.hva.ict.models.BoekingsOverzicht;
import nl.hva.ict.models.Reiziger;
import nl.hva.ict.models.Reservering;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
/**
* DAO voor de accommodatie
*
* @author HBO-ICT
*/
public class MySQLBoekingsOverzicht extends MySQL<BoekingsOverzicht> {
private final List<BoekingsOverzicht> boekingsOverzicht;
/**
* Constructor
*/
public MySQLBoekingsOverzicht() {
// init arraylist
boekingsOverzicht = new ArrayList<>();
// Laad bij startup
load();
}
/**
* Doe dit bij het maken van dit object
*/
private void load() {
// Vul hier je SQL code in
String sql = "";
// Als je nog geen query hebt ingevuld breek dan af om een error te voorkomen.
if (sql.equals(""))
return;
try {
// Roep de methode aan in de parent class en geen je SQL door
PreparedStatement ps = getStatement(sql);
//Voer je query uit en stop het antwoord in een result set
ResultSet rs = executeSelectPreparedStatement(ps);
// Loop net zolang als er records zijn
while (rs.next()) {
int idReservering = 0;
Date aankomstDatum = rs.getDate("aankomstDatum");
Date vertrekDatum = rs.getDate("vertrekDatum");
boolean betaald = rs.getBoolean("betaald");
String accommodatieCode = rs.getString("accommodatieCode");
String reizerCode = rs.getString("reizigerCode");
String voornaam = ""; // not in use
String achternaam = rs.getString("reiziger"); // combine voor en achternaam
String adres = ""; // not in use
String postcode = "";
String plaats = "";
String land = "";
String hoofdreiziger = "";
String accommodatieNaam = rs.getString("naam");
String accommodatieStad = rs.getString("stad");
String accommodatieLand = rs.getString("land");
// Maak models aan
Reservering reservering = new Reservering(idReservering, aankomstDatum, vertrekDatum, betaald, accommodatieCode, reizerCode);
Reiziger reiziger = new Reiziger(reizerCode, voornaam, achternaam, adres, postcode, plaats, land, hoofdreiziger);
Accommodatie accommodatie = new Accommodatie();
accommodatie.setNaam(accommodatieNaam);
accommodatie.setStad(accommodatieStad);
accommodatie.setLand(accommodatieLand);
//voeg die toe aan de arraylist
boekingsOverzicht.add(new BoekingsOverzicht(accommodatie, reiziger, reservering));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Haal de boekingen op voor 1 reiziger
*
* @param reizigerscode Welke reiziger wil je de boekingen voor?
* @return Een list van boekingen
*/
public List<BoekingsOverzicht> getBoekingVoor(String reizigerscode) {
// Maak een arraylist
List<BoekingsOverzicht> reserveringVoor = new ArrayList<>();
// Voer hier je query in
String sql = """
SELECT
r.id,
r.aankomst_datum AS aankomstDatum,
r.vertrek_datum AS vertrekDatum,
r.betaald,
r.accommodatie_code AS accommodatieCode,
r.reiziger_code AS reizigerCode,
re.voornaam,
re.achternaam,
re.plaats,
a.naam,
a.stad,
a.land
FROM
`reservering` AS r
INNER JOIN reiziger AS re ON
r.reiziger_code = re.reiziger_code
INNER JOIN `accommodatie` AS a ON
r.accommodatie_code = a.accommodatie_code
WHERE
r.reiziger_code = ?
""";
try {
// Maak je statement
PreparedStatement ps = getStatement(sql);
// Vervang het eerste vraagteken met de reizigerscode. Pas dit eventueel aan voor jou eigen query
ps.setString(1, reizigerscode);
// Voer het uit
ResultSet rs = executeSelectPreparedStatement(ps);
// Loop net zolang als er records zijn
while (rs.next()) {
int idReservering = 0;
Date aankomstDatum = rs.getDate("aankomstDatum");
Date vertrekDatum = rs.getDate("vertrekDatum");
boolean betaald = rs.getBoolean("betaald");
String accommodatieCode = rs.getString("accommodatieCode");
String reizigerVoornaam = rs.getString("voornaam");
String reizigerAchternaam = rs.getString("achternaam");
String reizigerPlaats = rs.getString("plaats");
String accommodatieNaam = rs.getString("naam");
String accommodatieStad = rs.getString("stad");
String accommodatieLand = rs.getString("land");
// Maak model objecten
Reservering reservering = new Reservering(idReservering, aankomstDatum, vertrekDatum, betaald, accommodatieCode, reizigerscode);
Accommodatie accommodatie = new Accommodatie();
accommodatie.setNaam(accommodatieNaam);
accommodatie.setStad(accommodatieStad);
accommodatie.setLand(accommodatieLand);
Reiziger reiziger = new Reiziger();
reiziger.setVoornaam(reizigerVoornaam);
reiziger.setAchternaam(reizigerAchternaam);
reiziger.setPlaats(reizigerPlaats);
// Voeg de reservering toe aan de arraylist
reserveringVoor.add(new BoekingsOverzicht(accommodatie, reiziger, reservering));
}
} catch (SQLException throwables) {
// Oeps probleem
throwables.printStackTrace();
}
// Geef de arrayList terug met de juiste reserveringen
return reserveringVoor;
}
/**
* Haal de reizigerscode op voor een bepaalde boeking per accommodate en datum
*
* @param pCode de accommodatecode
* @param pDatum de datum van verblijf
* @return De reizigerscode
*/
private String getReizigerscode(String pCode, LocalDate pDatum) {
String sql = """
SELECT GeboektOp(?, ?) AS reizigerCode;
""";
// default waarde
String reizigerCode = "";
// convert datum naar ander formaat
Date date = Date.valueOf(pDatum);
try {
// query voorbereiden
PreparedStatement ps = getStatement(sql);
// Vervang de vraagtekens met de juiste waarde. Pas eventueel aan je eigen query
ps.setString(1, pCode);
ps.setDate(2, date);
// Voer het uit
ResultSet rs = executeSelectPreparedStatement(ps);
// Loop net zolang als er records zijn
while (rs.next()) {
reizigerCode = rs.getString("reizigerCode");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
// Geef de reizigercode terug
return reizigerCode;
}
/**
* Haal een lijst met reserveringen op voor een bepaalde boeking per accommodate en datum
*
* @param pCode de accommodate code
* @param pDatum de datum van verblijf
* @return Lijst met reserveringen
*/
public List<Reiziger> GeboektOp(String pCode, LocalDate pDatum) {
// Init arraylist
List<Reiziger> geboektOp = new ArrayList<>();
//Stop null pointer error als datum nog niet is ingevuld.
if (pDatum == null)
return geboektOp;
// Spring naar<SUF>
String reizigerscode = getReizigerscode(pCode, pDatum);
if (reizigerscode != null) {
// Haal alle reserveringen op
String sql = """
SELECT reiziger.voornaam,
reiziger.achternaam,
reiziger.adres,
reiziger.postcode,
reiziger.plaats,
reiziger.land,
CONCAT(reiziger.voornaam, ' ', reiziger.achternaam) AS hoofdreiziger
FROM `reiziger`
WHERE reiziger.reiziger_code = ?
""";
// Als je nog geen query hebt ingevuld breek dan af om een error te voorkomen.
if (sql.equals(""))
return geboektOp;
try {
// Roep de methode aan in de parent class en geef je SQL door
PreparedStatement ps = getStatement(sql);
// vervang de eerste vraagteken met de reizigerscode
ps.setString(1, reizigerscode);
// Voer je query uit
ResultSet rs = executeSelectPreparedStatement(ps);
// Loop net zolang als er records zijn
while (rs.next()) {
String voornaam = rs.getString("voornaam");
String achternaam = rs.getString("achternaam");
String adres = rs.getString("adres");
String postcode = rs.getString("postcode");
String plaats = rs.getString("plaats");
String land = rs.getString("land");
String hoofdreiziger = rs.getString("hoofdreiziger");
// Maak reserveringsobject en voeg direct toe aan arraylist
geboektOp.add(new Reiziger(reizigerscode, voornaam, achternaam, adres, postcode, plaats, land, hoofdreiziger));
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
// Geef de array terug met reserveringen
return geboektOp;
}
/**
* Haal alle boekingen op door de gehele arraylist terug te geven
*
* @return Een arraylist van accommodaties
*/
@Override
public List<BoekingsOverzicht> getAll() {
return boekingsOverzicht;
}
/**
* Haal 1 boeking op
*
* @return Een arraylist van accommodaties
*/
@Override
public BoekingsOverzicht get() {
// nog niet uitgewerkt geeft nu even null terug
return null;
}
/**
* Voeg een boeking toe
*
* @param boekingsOverzicht de boeking
*/
@Override
public void add(BoekingsOverzicht boekingsOverzicht) {
// nog niet uitgewerkt
}
/**
* Update de boeking
*
* @param boekingsOverzicht de boeking
*/
@Override
public void update(BoekingsOverzicht boekingsOverzicht) {
// nog niet uitgewerkt
}
/**
* Verwijder een boeking
*
* @param object de boeking
*/
@Override
public void remove(BoekingsOverzicht object) {
// nog niet uitgewerkt
}
}
|
111092_3 | package nl.hva.ict.data.MongoDB;
import com.mongodb.MongoException;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import nl.hva.ict.MainApplication;
import nl.hva.ict.data.Data;
import org.bson.Document;
/**
* MongoDB class die de verbinding maakt met de Mongo server
* @author Pieter Leek
*/
public abstract class MongoDB implements Data {
protected MongoCollection<Document> collection;
private MongoClient mongoClient;
private MongoDatabase mongoDatabase;
/**
* Verbind direct met de server als dit object wordt aangemaakt
*/
public MongoDB() {
connect();
}
// connect database
private void connect() {
// Heb je geen gegevens in de MainApplication staan slaat hij het maken van de verbinding over
if (MainApplication.getNosqlHost().equals(""))
return;
// Verbind alleen als er nog geen actieve verbinding is.
if (this.mongoClient == null) {
try {
// Open pijpleiding
this.mongoClient = MongoClients.create(MainApplication.getNosqlHost());
// Selecteer de juiste database
this.mongoDatabase = mongoClient.getDatabase(MainApplication.getNosqlDatabase());
} catch (MongoException e) {
e.printStackTrace();
}
}
}
/**
* Selecteer de juiste collection
* @param collection
*/
public void selectedCollection(String collection) {
this.collection = mongoDatabase.getCollection(collection);
}
}
| JuniorBrPr/DB2V2 | src/nl/hva/ict/data/MongoDB/MongoDB.java | 477 | // Verbind alleen als er nog geen actieve verbinding is. | line_comment | nl | package nl.hva.ict.data.MongoDB;
import com.mongodb.MongoException;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import nl.hva.ict.MainApplication;
import nl.hva.ict.data.Data;
import org.bson.Document;
/**
* MongoDB class die de verbinding maakt met de Mongo server
* @author Pieter Leek
*/
public abstract class MongoDB implements Data {
protected MongoCollection<Document> collection;
private MongoClient mongoClient;
private MongoDatabase mongoDatabase;
/**
* Verbind direct met de server als dit object wordt aangemaakt
*/
public MongoDB() {
connect();
}
// connect database
private void connect() {
// Heb je geen gegevens in de MainApplication staan slaat hij het maken van de verbinding over
if (MainApplication.getNosqlHost().equals(""))
return;
// Verbind alleen<SUF>
if (this.mongoClient == null) {
try {
// Open pijpleiding
this.mongoClient = MongoClients.create(MainApplication.getNosqlHost());
// Selecteer de juiste database
this.mongoDatabase = mongoClient.getDatabase(MainApplication.getNosqlDatabase());
} catch (MongoException e) {
e.printStackTrace();
}
}
}
/**
* Selecteer de juiste collection
* @param collection
*/
public void selectedCollection(String collection) {
this.collection = mongoDatabase.getCollection(collection);
}
}
|
35107_5 | package screens;
import objects.*;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.text.DateFormatter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
public class Reisplanner extends JPanel implements ActionListener
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// De data die nodig is om een GUI te maken
private JLabel label;
private JPanel panel;
private JButton zoeken;
private JComboBox aankomstBox;
private JComboBox vertrekBox;
private JTextField text;
private JLabel routegevonden;
private JLabel vertrekLocatie;
private JLabel aankomstLocatie;
public String arrivalSearch;
public String departureSearch;
public String departureTimeSearch;
public Object chosenTime;
private JLabel reisAdvies = new JLabel();
public LocalTime stringToLocalTime;
public JSpinner timeSpinner;
private Data data = new Data();
private TrainData trainData= new TrainData();
// private BusData busData = new BusData();
// private TramData tramData = new TramData();
private JPanel tripsPanel;
JScrollPane scrollPane;
private ButtonGroup group = new ButtonGroup();
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//TODO is dit nog nodig?
@Override
public void actionPerformed(ActionEvent e) {
zoeken.setText("test");
}
private String getSelectedButton() {
for (Enumeration<AbstractButton> buttons = group.getElements(); buttons.hasMoreElements();) {
AbstractButton button = buttons.nextElement();
if (button.isSelected()) {
return button.getText();
}
}
return null;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Constructor
Reisplanner(Locale locale) {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Declarations
ResourceBundle bundle = ResourceBundle.getBundle("bundle" ,locale);
zoeken = new JButton(bundle.getString("zoeken"));
label = new JLabel();
{
// comboboxen DOOR: Niels van Gortel
JPanel comboBoxPanel = new JPanel();
comboBoxPanel.setBounds(50, 100, 394, 25);
comboBoxPanel.setLayout(new GridLayout(0, 1, 10, 0));
comboBoxPanel.setBackground(Color.white);
JPanel Transport = new JPanel();
Transport.setBounds(10, 3, 10, 25);
////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////
Date date = new Date();
SpinnerDateModel sm = new SpinnerDateModel(date, null, null, Calendar.HOUR_OF_DAY);
timeSpinner = new javax.swing.JSpinner(sm);
timeSpinner.setBounds(500, 500, 100, 25);
JSpinner.DateEditor de = new JSpinner.DateEditor(timeSpinner, "HH:mm");
timeSpinner.setEditor(de);
////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////
//TODO Waar is deze voor?
add(comboBoxPanel);
////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Zet het keuze menu van de vertreklocaties
HashMap<String, Location> locations = trainData.getLocationMap();
System.out.println(locations);
Set<String> keySet = locations.keySet();
ArrayList<String> listOfKeys = new ArrayList<String>(keySet);
// String[] startLocations
// for (Object l : locations.values()) {
// Location location = (Location) l;
// System.out.println(location.getName());
// }
vertrekBox = new JComboBox(listOfKeys.toArray());
// vertrekBox = new JComboBox(new Object[]{bundle.getString("vertrekLocatie"), "Amsterdam", "Rotterdam", "Utrecht", "Den haag", "Amersfoort", "Schiphol airport"});
aankomstBox = new JComboBox(listOfKeys.toArray());
////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////
// maakt het panel aan
panel = new JPanel();
tripsPanel = new JPanel();
scrollPane = new JScrollPane();
panel.setBorder(BorderFactory.createEmptyBorder(10, 0, 30, 30));
panel.setLayout(new GridLayout(6, 0));
setSize(400, 400);
setLayout(new FlowLayout());
////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////
//sets the choice menu of the transportation
JRadioButton train = new JRadioButton(bundle.getString("trein"));
JRadioButton Tram = new JRadioButton(bundle.getString("tram"));
JRadioButton Bus = new JRadioButton(bundle.getString("bus"));
////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////
// makes sure that one of the buttons can be selected
group.add(train);
group.add(Bus);
group.add(Tram);
////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Voegt attributen toe aan het panel.
Transport.add(train);
Transport.add(Tram);
Transport.add(Bus);
add(Transport);
add(timeSpinner);
add(vertrekBox);
add(aankomstBox);
add(zoeken);
add(label);
add(panel, BorderLayout.CENTER);
setVisible(false);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Zorgt ervoor dat er een response komt als de zoek button ingedrukt wordt.
zoeken.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent search) {
remove(scrollPane);
remove(tripsPanel);
tripsPanel = new JPanel();
tripsPanel.setLayout(new GridLayout(0,1));
String arrivalSearch = (String)aankomstBox.getSelectedItem();
String departureSearch = (String)vertrekBox.getSelectedItem();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
departureTimeSearch = sdf.format(timeSpinner.getValue());
LocalTime localTimeD = LocalTime.parse(departureTimeSearch);
if(getSelectedButton()!=null&&getSelectedButton().equals(bundle.getString("trein"))){
Trips trips = trainData.getTrips(departureSearch, arrivalSearch, localTimeD);
ArrayList<Trip> tripArrayList = trips.getTrips();
Collections.sort(tripArrayList, new Comparator<Trip>() {
public int compare(Trip t1, Trip t2) {
return t1.getDeparture().compareTo(t2.getDeparture());
}
});
for (Trip t :tripArrayList){
Duration duration = Duration.between(t.getDeparture(), t.getArrival());
var tripText = new JLabel();
tripText.setFont(new Font("Arial",Font.BOLD,14));
tripText.setText(t.getRoute().getEndPoint()+" "+t.getDeparture()+"");
var tripDuration = new JLabel();
tripDuration.setFont(new Font("Arial",Font.BOLD,9));
tripDuration.setBorder(new EmptyBorder(0, 25, 0, 10));
tripDuration.setText(bundle.getString("duration")+": "+ String.valueOf(duration.toMinutes()));
// int distance = (int) (duration.toMinutes()*2.166666666666667);
// System.out.println(distance);
// long diff = Math.abs(duration.toHoursPart());
// System.out.println(t.getDeparture());
// System.out.println(t.getArrival());
// System.out.println(duration.toMinutes());
var tripPanel = new JPanel();
Border blackline = BorderFactory.createLineBorder(Color.gray);
tripPanel.setBorder(blackline);
tripPanel.setLayout(new BorderLayout());
tripPanel.setPreferredSize(new Dimension(235,30));
var addToHistory = new JButton("+");
addToHistory.setFont(new Font("Arial",Font.BOLD,20));
// addToHistory.setPreferredSize(new Dimension(40, 15));
tripPanel.add(addToHistory, BorderLayout.EAST);
tripPanel.add(tripDuration, BorderLayout.CENTER);
tripPanel.add(tripText, BorderLayout.WEST);
tripsPanel.add(tripPanel);
tripsPanel.setVisible(true);
}
if (tripArrayList.size()==0){
var tripButton = new JButton();
tripButton.setText(bundle.getString("geenReis"));
tripButton.setPreferredSize(new Dimension(235,20));
tripsPanel.add(tripButton);
}
}
else{
JLabel selectTransport = new JLabel();
selectTransport.setText(bundle.getString("selectVervoer"));
selectTransport.setBounds(300, 300, 100, 50);
add(selectTransport);
}
// JPanel container = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
// container.add(tripsPanel);
scrollPane = new JScrollPane(tripsPanel);
scrollPane.setPreferredSize(new Dimension(650, 600));
add(scrollPane);
repaint();
revalidate();
}
});
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
} | JuniorBrPr/OV-app | src/main/java/screens/Reisplanner.java | 2,820 | //TODO Waar is deze voor? | line_comment | nl | package screens;
import objects.*;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.text.DateFormatter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
public class Reisplanner extends JPanel implements ActionListener
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// De data die nodig is om een GUI te maken
private JLabel label;
private JPanel panel;
private JButton zoeken;
private JComboBox aankomstBox;
private JComboBox vertrekBox;
private JTextField text;
private JLabel routegevonden;
private JLabel vertrekLocatie;
private JLabel aankomstLocatie;
public String arrivalSearch;
public String departureSearch;
public String departureTimeSearch;
public Object chosenTime;
private JLabel reisAdvies = new JLabel();
public LocalTime stringToLocalTime;
public JSpinner timeSpinner;
private Data data = new Data();
private TrainData trainData= new TrainData();
// private BusData busData = new BusData();
// private TramData tramData = new TramData();
private JPanel tripsPanel;
JScrollPane scrollPane;
private ButtonGroup group = new ButtonGroup();
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//TODO is dit nog nodig?
@Override
public void actionPerformed(ActionEvent e) {
zoeken.setText("test");
}
private String getSelectedButton() {
for (Enumeration<AbstractButton> buttons = group.getElements(); buttons.hasMoreElements();) {
AbstractButton button = buttons.nextElement();
if (button.isSelected()) {
return button.getText();
}
}
return null;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Constructor
Reisplanner(Locale locale) {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Declarations
ResourceBundle bundle = ResourceBundle.getBundle("bundle" ,locale);
zoeken = new JButton(bundle.getString("zoeken"));
label = new JLabel();
{
// comboboxen DOOR: Niels van Gortel
JPanel comboBoxPanel = new JPanel();
comboBoxPanel.setBounds(50, 100, 394, 25);
comboBoxPanel.setLayout(new GridLayout(0, 1, 10, 0));
comboBoxPanel.setBackground(Color.white);
JPanel Transport = new JPanel();
Transport.setBounds(10, 3, 10, 25);
////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////
Date date = new Date();
SpinnerDateModel sm = new SpinnerDateModel(date, null, null, Calendar.HOUR_OF_DAY);
timeSpinner = new javax.swing.JSpinner(sm);
timeSpinner.setBounds(500, 500, 100, 25);
JSpinner.DateEditor de = new JSpinner.DateEditor(timeSpinner, "HH:mm");
timeSpinner.setEditor(de);
////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////
//TODO Waar<SUF>
add(comboBoxPanel);
////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Zet het keuze menu van de vertreklocaties
HashMap<String, Location> locations = trainData.getLocationMap();
System.out.println(locations);
Set<String> keySet = locations.keySet();
ArrayList<String> listOfKeys = new ArrayList<String>(keySet);
// String[] startLocations
// for (Object l : locations.values()) {
// Location location = (Location) l;
// System.out.println(location.getName());
// }
vertrekBox = new JComboBox(listOfKeys.toArray());
// vertrekBox = new JComboBox(new Object[]{bundle.getString("vertrekLocatie"), "Amsterdam", "Rotterdam", "Utrecht", "Den haag", "Amersfoort", "Schiphol airport"});
aankomstBox = new JComboBox(listOfKeys.toArray());
////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////
// maakt het panel aan
panel = new JPanel();
tripsPanel = new JPanel();
scrollPane = new JScrollPane();
panel.setBorder(BorderFactory.createEmptyBorder(10, 0, 30, 30));
panel.setLayout(new GridLayout(6, 0));
setSize(400, 400);
setLayout(new FlowLayout());
////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////
//sets the choice menu of the transportation
JRadioButton train = new JRadioButton(bundle.getString("trein"));
JRadioButton Tram = new JRadioButton(bundle.getString("tram"));
JRadioButton Bus = new JRadioButton(bundle.getString("bus"));
////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////
// makes sure that one of the buttons can be selected
group.add(train);
group.add(Bus);
group.add(Tram);
////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Voegt attributen toe aan het panel.
Transport.add(train);
Transport.add(Tram);
Transport.add(Bus);
add(Transport);
add(timeSpinner);
add(vertrekBox);
add(aankomstBox);
add(zoeken);
add(label);
add(panel, BorderLayout.CENTER);
setVisible(false);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Zorgt ervoor dat er een response komt als de zoek button ingedrukt wordt.
zoeken.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent search) {
remove(scrollPane);
remove(tripsPanel);
tripsPanel = new JPanel();
tripsPanel.setLayout(new GridLayout(0,1));
String arrivalSearch = (String)aankomstBox.getSelectedItem();
String departureSearch = (String)vertrekBox.getSelectedItem();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
departureTimeSearch = sdf.format(timeSpinner.getValue());
LocalTime localTimeD = LocalTime.parse(departureTimeSearch);
if(getSelectedButton()!=null&&getSelectedButton().equals(bundle.getString("trein"))){
Trips trips = trainData.getTrips(departureSearch, arrivalSearch, localTimeD);
ArrayList<Trip> tripArrayList = trips.getTrips();
Collections.sort(tripArrayList, new Comparator<Trip>() {
public int compare(Trip t1, Trip t2) {
return t1.getDeparture().compareTo(t2.getDeparture());
}
});
for (Trip t :tripArrayList){
Duration duration = Duration.between(t.getDeparture(), t.getArrival());
var tripText = new JLabel();
tripText.setFont(new Font("Arial",Font.BOLD,14));
tripText.setText(t.getRoute().getEndPoint()+" "+t.getDeparture()+"");
var tripDuration = new JLabel();
tripDuration.setFont(new Font("Arial",Font.BOLD,9));
tripDuration.setBorder(new EmptyBorder(0, 25, 0, 10));
tripDuration.setText(bundle.getString("duration")+": "+ String.valueOf(duration.toMinutes()));
// int distance = (int) (duration.toMinutes()*2.166666666666667);
// System.out.println(distance);
// long diff = Math.abs(duration.toHoursPart());
// System.out.println(t.getDeparture());
// System.out.println(t.getArrival());
// System.out.println(duration.toMinutes());
var tripPanel = new JPanel();
Border blackline = BorderFactory.createLineBorder(Color.gray);
tripPanel.setBorder(blackline);
tripPanel.setLayout(new BorderLayout());
tripPanel.setPreferredSize(new Dimension(235,30));
var addToHistory = new JButton("+");
addToHistory.setFont(new Font("Arial",Font.BOLD,20));
// addToHistory.setPreferredSize(new Dimension(40, 15));
tripPanel.add(addToHistory, BorderLayout.EAST);
tripPanel.add(tripDuration, BorderLayout.CENTER);
tripPanel.add(tripText, BorderLayout.WEST);
tripsPanel.add(tripPanel);
tripsPanel.setVisible(true);
}
if (tripArrayList.size()==0){
var tripButton = new JButton();
tripButton.setText(bundle.getString("geenReis"));
tripButton.setPreferredSize(new Dimension(235,20));
tripsPanel.add(tripButton);
}
}
else{
JLabel selectTransport = new JLabel();
selectTransport.setText(bundle.getString("selectVervoer"));
selectTransport.setBounds(300, 300, 100, 50);
add(selectTransport);
}
// JPanel container = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
// container.add(tripsPanel);
scrollPane = new JScrollPane(tripsPanel);
scrollPane.setPreferredSize(new Dimension(650, 600));
add(scrollPane);
repaint();
revalidate();
}
});
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
} |
27596_7 | import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.time.LocalTime;
public class Reisplanner extends JFrame implements ActionListener
{
// De data die nodig is om een GUI te maken
private JLabel label;
private JFrame frame;
private JPanel panel;
private JButton button;
private JComboBox combobox;
private JComboBox combobox1;
private JTextField text;
private JLabel routegevonden;
private JLabel vertrekLocatie;
private JLabel aankomstLocatie;
private JButton Home;
@Override
public void actionPerformed(ActionEvent e) {
button.setText("test");
}
Reisplanner() {
frame = new JFrame();
button = new JButton("Zoeken");
label = new JLabel();
JButton Login;
Login = new JButton("Login");
Login.setBounds(10, 100, 80, 25);
Login.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Login l = new Login();
l.setVisible(true);
l.setBounds(400, 200, 600, 300);
}
});
{
// comboboxen DOOR: Niels van Gortel
JPanel comboBoxPanel = new JPanel();
comboBoxPanel.setBounds(50, 100, 394, 25);
comboBoxPanel.setLayout(new GridLayout(0, 1, 10, 0));
comboBoxPanel.setBackground(Color.white);
JPanel Transport = new JPanel();
Transport.setBounds(10, 3, 10, 25);
// vertrektijden combobox
LocalTime tijden[] = {
LocalTime.of(0, 00),
LocalTime.of(8, 00), LocalTime.of(8, 30), LocalTime.of(9, 00),
LocalTime.of(9, 30), LocalTime.of(10, 00), LocalTime.of(10, 30),
LocalTime.of(11, 00),
LocalTime.of(11, 30), LocalTime.of(12, 00), LocalTime.of(12, 30),
LocalTime.of(13, 00), LocalTime.of(13, 30), LocalTime.of(14, 00),
LocalTime.of(14, 30), LocalTime.of(15, 00), LocalTime.of(15, 30),
LocalTime.of(16, 00), LocalTime.of(16, 30), LocalTime.of(17, 00),
LocalTime.of(17, 30), LocalTime.of(17, 30), LocalTime.of(18, 30),
LocalTime.of(19, 00), LocalTime.of(19, 30), LocalTime.of(20, 00),
LocalTime.of(20, 30), LocalTime.of(21, 00), LocalTime.of(21, 30),
LocalTime.of(22, 30)
};
JComboBox<Object> timeBox = new JComboBox<Object>(tijden);
timeBox.setBounds(100, 200, 100, 25);
frame.add(comboBoxPanel);
// Zet het keuze menu van de vertreklocaties
combobox = new JComboBox(new Object[]{"Vertreklocatie", "Amsterdam", "Rotterdam", "Utrecht", "Den haag", "Amersfoort"});
combobox1 = new JComboBox(new Object[]{"Aankomstlocatie", "Amsterdam", "Rotterdam", "Utrecht", "Den haag", "Amersfoort"});
// maakt het panel aan
panel = new JPanel();
panel.setBorder(BorderFactory.createEmptyBorder(10, 0, 30, 30));
panel.setLayout(new GridLayout(6, 0));
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
//sets the choice menu of the transportation
JRadioButton train = new JRadioButton("Trein");
JRadioButton Tram = new JRadioButton("Tram");
JRadioButton Bus = new JRadioButton("Bus");
// makes sure that one of the buttons can be selected
ButtonGroup group = new ButtonGroup();
group.add(train);
group.add(Bus);
group.add(Tram);
// sets the button to go back to the main screen
Home = new JButton("Home");
Home.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
HomeGui l = new HomeGui();
l.setBounds(400,200,600,300);
l.setVisible(true);
dispose();
}
});
// Voegt attributen toe aan het panel.
Transport.add(train);
Transport.add(Tram);
Transport.add(Bus);
frame.add(Transport);
frame.add(timeBox);
frame.add(combobox);
frame.add(combobox1);
frame.add(button);
panel.add(Home);
panel.add(label);
frame.add(panel, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("OvApp");
frame.pack();
frame.setVisible(true);
}
// Zorgt ervoor dat er een response komt als de zoek button ingedrukt wordt.
}
}
| JuniorBrPr/OV-app-main | Src/main/java/Reisplanner.java | 1,588 | // Voegt attributen toe aan het panel. | line_comment | nl | import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.time.LocalTime;
public class Reisplanner extends JFrame implements ActionListener
{
// De data die nodig is om een GUI te maken
private JLabel label;
private JFrame frame;
private JPanel panel;
private JButton button;
private JComboBox combobox;
private JComboBox combobox1;
private JTextField text;
private JLabel routegevonden;
private JLabel vertrekLocatie;
private JLabel aankomstLocatie;
private JButton Home;
@Override
public void actionPerformed(ActionEvent e) {
button.setText("test");
}
Reisplanner() {
frame = new JFrame();
button = new JButton("Zoeken");
label = new JLabel();
JButton Login;
Login = new JButton("Login");
Login.setBounds(10, 100, 80, 25);
Login.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Login l = new Login();
l.setVisible(true);
l.setBounds(400, 200, 600, 300);
}
});
{
// comboboxen DOOR: Niels van Gortel
JPanel comboBoxPanel = new JPanel();
comboBoxPanel.setBounds(50, 100, 394, 25);
comboBoxPanel.setLayout(new GridLayout(0, 1, 10, 0));
comboBoxPanel.setBackground(Color.white);
JPanel Transport = new JPanel();
Transport.setBounds(10, 3, 10, 25);
// vertrektijden combobox
LocalTime tijden[] = {
LocalTime.of(0, 00),
LocalTime.of(8, 00), LocalTime.of(8, 30), LocalTime.of(9, 00),
LocalTime.of(9, 30), LocalTime.of(10, 00), LocalTime.of(10, 30),
LocalTime.of(11, 00),
LocalTime.of(11, 30), LocalTime.of(12, 00), LocalTime.of(12, 30),
LocalTime.of(13, 00), LocalTime.of(13, 30), LocalTime.of(14, 00),
LocalTime.of(14, 30), LocalTime.of(15, 00), LocalTime.of(15, 30),
LocalTime.of(16, 00), LocalTime.of(16, 30), LocalTime.of(17, 00),
LocalTime.of(17, 30), LocalTime.of(17, 30), LocalTime.of(18, 30),
LocalTime.of(19, 00), LocalTime.of(19, 30), LocalTime.of(20, 00),
LocalTime.of(20, 30), LocalTime.of(21, 00), LocalTime.of(21, 30),
LocalTime.of(22, 30)
};
JComboBox<Object> timeBox = new JComboBox<Object>(tijden);
timeBox.setBounds(100, 200, 100, 25);
frame.add(comboBoxPanel);
// Zet het keuze menu van de vertreklocaties
combobox = new JComboBox(new Object[]{"Vertreklocatie", "Amsterdam", "Rotterdam", "Utrecht", "Den haag", "Amersfoort"});
combobox1 = new JComboBox(new Object[]{"Aankomstlocatie", "Amsterdam", "Rotterdam", "Utrecht", "Den haag", "Amersfoort"});
// maakt het panel aan
panel = new JPanel();
panel.setBorder(BorderFactory.createEmptyBorder(10, 0, 30, 30));
panel.setLayout(new GridLayout(6, 0));
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
//sets the choice menu of the transportation
JRadioButton train = new JRadioButton("Trein");
JRadioButton Tram = new JRadioButton("Tram");
JRadioButton Bus = new JRadioButton("Bus");
// makes sure that one of the buttons can be selected
ButtonGroup group = new ButtonGroup();
group.add(train);
group.add(Bus);
group.add(Tram);
// sets the button to go back to the main screen
Home = new JButton("Home");
Home.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
HomeGui l = new HomeGui();
l.setBounds(400,200,600,300);
l.setVisible(true);
dispose();
}
});
// Voegt attributen<SUF>
Transport.add(train);
Transport.add(Tram);
Transport.add(Bus);
frame.add(Transport);
frame.add(timeBox);
frame.add(combobox);
frame.add(combobox1);
frame.add(button);
panel.add(Home);
panel.add(label);
frame.add(panel, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("OvApp");
frame.pack();
frame.setVisible(true);
}
// Zorgt ervoor dat er een response komt als de zoek button ingedrukt wordt.
}
}
|
40076_4 | package javaproject.game.Helper;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;
import javaproject.game.Enity.Anchors;
import javaproject.game.Enity.Entity;
import javaproject.game.Items.Armor;
import javaproject.game.Items.Item;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class Helper {
/**
* This class exists to provide clarity in classes, if they are not filled with repeating code.
* These classes will consist of static methods.
*/
//static long indificationNumber = generateIndificationNumber();
//static long indificationWeaponNumber = generateWeaponIndificationNumber();
/**
*
* This is the default non edited id generator.
* @return The random number generated.
*/
public static final long generateIndificationNumber() {
long indificationNumber = 0;
boolean isCorrect = false;
while(!isCorrect) {
indificationNumber = (long) (Math.random() * Long.MAX_VALUE);
//Waarom doen we dit. Omdat we een unique number hebben, moeten een random nummer maken bv 12332480707
if(indificationNumber %2 == 0) {
isCorrect = true;
//Hier stopt de while loop met een correcte id.
}
}
return indificationNumber;
}
/**
* We generate an ID that is even and dividable by 3.
* Reason here: We use it in the class Weapon & Amor.
* We generate an unique id, the reason why this isn't in item class is because in Amor it shouldn't be dividable by 3
*
* @return the random number that is generated.
*/
public static long generateWeaponIndificationNumber() {
long indificationWeaponNumber = 0;
boolean isCorrect = false;
while(!isCorrect) {
indificationWeaponNumber = (long) (Math.random() * Long.MAX_VALUE);
//Waarom doen we dit. Omdat we een unique number hebben, moeten een random nummer maken bv 12332480707
if(indificationWeaponNumber %2 == 0 && indificationWeaponNumber % 3 == 0) {
isCorrect = true;
//Hier stopt de while loop met een correcte id.
}
if(indificationWeaponNumber < 0)
throw new IllegalArgumentException("Your indification number is lower then 0");
}
return indificationWeaponNumber;
}
/**Is valid name checker */
public static boolean isValidHeroName(String name) {
/**
^ matches the start of the string
[A-Z] matches any uppercase letter
[a-z]+ matches one or more lowercase letters
(?:('[a-zA-Z]+)|\s+[A-Z][a-z]+)* matches zero or more occurrences of either an apostrophe followed by one or more letters (both uppercase and lowercase),
or one or more whitespace characters followed by an uppercase letter and one or more lowercase letters
(?:('[a-zA-Z]+)|\s+[A-Z][a-z]+)? matches zero or one occurrences of the same pattern as above
$ matches the end of the string
*/
if(name == null || name.length() == 0)
//throw new NullPointerException("Je hebt geen naam ingegeven!");
return false;
if(!(name.matches("^[A-Z][a-z]+(?:('[a-zA-Z]+)|\\s+[A-Z][a-z]+)*(?:('[a-zA-Z]+)|\\s+[A-Z][a-z]+)?$"))) {
return false;
}
//throw new IllegalArgumentException("De naam klopt niet, Kijk voor hoofdletters, dubbele tekens.");
return true;
}
public static boolean isValidMonsterName(String name) {
if(name == null || name.length() == 0)
throw new NullPointerException("Je hebt geen naam ingegeven!");
if(!(name.matches("\"[A-Z]([a-zA-Z]\\s['])\"")))
throw new IllegalArgumentException("De naam klopt niet");
return true;
}
/**
* Calculating total weight of every item.
*
* @param items All the items that the user has.
* @return total weight
*/
public static double calculateTotalWeight(HashMap<Anchors, Item> items) {
double totalWeight = 0.0;
List<Item> itemList = new ArrayList<>(items.values());
/**
* items;values() searched on google.
*
* This will return all the Item objects that are in the items HashMap.
*/
for(int i = 0; i < items.size(); i++) {
Item item = itemList.get(i);
totalWeight += item.getWeight();
}
return totalWeight;
}
/**
* We generate a random number between 1-3
* From least thickness armor to most thickness armor.
*
* @return
*/
public static final int randomProtectionGenerator() {
int randomNumber = (int) (Math.random()*3)+1;
int protection = 0;
switch (randomNumber) {
case 1:
protection = (int) (Armor.getMaximumProtection()*0.35);
break;
case 2:
protection = (int) (Armor.getMaximumProtection()*0.65);
break;
case 3:
protection = (int) (Armor.getMaximumProtection());
break;
}
return protection;
}
/**
*
* @param max The max value that the user can have
* @param min The minimum value that the user can have
*
* Example -> If the user wants a random number between 100-60 then the output should be
* (int) (Math.random() * (100 - 60 + 1)) + 60
* max min min
* @return The random number.
*/
public static int generateRandomPercentage(int max, int min){
/*
(int) (Math.random() * (100 - 60 + 1)) + 60
*/
return (int) (Math.random() * (max - min + 1)) + min;
}
public static String integerToString(int number) {
return String.valueOf(number);
}
public static String integerToString(double number) {
return String.valueOf(number);
}
public static String integerToString(long number) {
return String.valueOf(number);
}
public static String entityToString(Entity number) {
return String.valueOf(number);
}
/**
* The logic of this should be:
* Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("shop.fxml"));
* Stage stage = new Stage();
* stage.setTitle("Shop");
* stage.setScene(new Scene(root));
* stage.show();
* You have to use this for everytime you open a new tab.
*
* @param fxmlFile This is the file that the user should be directed to.
* @param title The title of the page
*/
public static void openScene(String fxmlFile, String title) throws IOException {
Parent root = FXMLLoader.load(Helper.class.getClassLoader().getResource(fxmlFile));
Stage stage = new Stage();
stage.setTitle(title);
stage.setScene(new Scene(root));
stage.show();
}
/**
* The logic of this should be:
* Stage currentStage = (Stage) shop.getScene().getWindow();
* currentStage.close();
*
*
*
* @param button the button that is clicked on
*/
public static void closeScene(Button button){
Stage currentStage = (Stage) button.getScene().getWindow();
currentStage.close();
}
/**
* We create an image view: 50 on 50.
*
* We give the image variable the item image.
*
* Then we set the image view image to the giving image Variable
*
* @param item The item that the user currently has.
*
* @return ImageView with an image
public static ImageView createImageView(Item item, int y, int x) {
ImageView imageView = new ImageView();
imageView.setY(y);
imageView.setX(x);
imageView.setFitWidth(50);
imageView.setFitHeight(50);
Image image = null;
if(item != null) {
image = item.getItemImage();
}else {
imageView.setImage(new Image("items/empty.png"));
}
if (image != null) {
imageView.setImage(image);
}
return imageView;
}
*/
//
}
| JuniorDeveloper1/Java_Project_Intel | src/javaproject/game/Helper/Helper.java | 2,502 | //Waarom doen we dit. Omdat we een unique number hebben, moeten een random nummer maken bv 12332480707 | line_comment | nl | package javaproject.game.Helper;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;
import javaproject.game.Enity.Anchors;
import javaproject.game.Enity.Entity;
import javaproject.game.Items.Armor;
import javaproject.game.Items.Item;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class Helper {
/**
* This class exists to provide clarity in classes, if they are not filled with repeating code.
* These classes will consist of static methods.
*/
//static long indificationNumber = generateIndificationNumber();
//static long indificationWeaponNumber = generateWeaponIndificationNumber();
/**
*
* This is the default non edited id generator.
* @return The random number generated.
*/
public static final long generateIndificationNumber() {
long indificationNumber = 0;
boolean isCorrect = false;
while(!isCorrect) {
indificationNumber = (long) (Math.random() * Long.MAX_VALUE);
//Waarom doen<SUF>
if(indificationNumber %2 == 0) {
isCorrect = true;
//Hier stopt de while loop met een correcte id.
}
}
return indificationNumber;
}
/**
* We generate an ID that is even and dividable by 3.
* Reason here: We use it in the class Weapon & Amor.
* We generate an unique id, the reason why this isn't in item class is because in Amor it shouldn't be dividable by 3
*
* @return the random number that is generated.
*/
public static long generateWeaponIndificationNumber() {
long indificationWeaponNumber = 0;
boolean isCorrect = false;
while(!isCorrect) {
indificationWeaponNumber = (long) (Math.random() * Long.MAX_VALUE);
//Waarom doen we dit. Omdat we een unique number hebben, moeten een random nummer maken bv 12332480707
if(indificationWeaponNumber %2 == 0 && indificationWeaponNumber % 3 == 0) {
isCorrect = true;
//Hier stopt de while loop met een correcte id.
}
if(indificationWeaponNumber < 0)
throw new IllegalArgumentException("Your indification number is lower then 0");
}
return indificationWeaponNumber;
}
/**Is valid name checker */
public static boolean isValidHeroName(String name) {
/**
^ matches the start of the string
[A-Z] matches any uppercase letter
[a-z]+ matches one or more lowercase letters
(?:('[a-zA-Z]+)|\s+[A-Z][a-z]+)* matches zero or more occurrences of either an apostrophe followed by one or more letters (both uppercase and lowercase),
or one or more whitespace characters followed by an uppercase letter and one or more lowercase letters
(?:('[a-zA-Z]+)|\s+[A-Z][a-z]+)? matches zero or one occurrences of the same pattern as above
$ matches the end of the string
*/
if(name == null || name.length() == 0)
//throw new NullPointerException("Je hebt geen naam ingegeven!");
return false;
if(!(name.matches("^[A-Z][a-z]+(?:('[a-zA-Z]+)|\\s+[A-Z][a-z]+)*(?:('[a-zA-Z]+)|\\s+[A-Z][a-z]+)?$"))) {
return false;
}
//throw new IllegalArgumentException("De naam klopt niet, Kijk voor hoofdletters, dubbele tekens.");
return true;
}
public static boolean isValidMonsterName(String name) {
if(name == null || name.length() == 0)
throw new NullPointerException("Je hebt geen naam ingegeven!");
if(!(name.matches("\"[A-Z]([a-zA-Z]\\s['])\"")))
throw new IllegalArgumentException("De naam klopt niet");
return true;
}
/**
* Calculating total weight of every item.
*
* @param items All the items that the user has.
* @return total weight
*/
public static double calculateTotalWeight(HashMap<Anchors, Item> items) {
double totalWeight = 0.0;
List<Item> itemList = new ArrayList<>(items.values());
/**
* items;values() searched on google.
*
* This will return all the Item objects that are in the items HashMap.
*/
for(int i = 0; i < items.size(); i++) {
Item item = itemList.get(i);
totalWeight += item.getWeight();
}
return totalWeight;
}
/**
* We generate a random number between 1-3
* From least thickness armor to most thickness armor.
*
* @return
*/
public static final int randomProtectionGenerator() {
int randomNumber = (int) (Math.random()*3)+1;
int protection = 0;
switch (randomNumber) {
case 1:
protection = (int) (Armor.getMaximumProtection()*0.35);
break;
case 2:
protection = (int) (Armor.getMaximumProtection()*0.65);
break;
case 3:
protection = (int) (Armor.getMaximumProtection());
break;
}
return protection;
}
/**
*
* @param max The max value that the user can have
* @param min The minimum value that the user can have
*
* Example -> If the user wants a random number between 100-60 then the output should be
* (int) (Math.random() * (100 - 60 + 1)) + 60
* max min min
* @return The random number.
*/
public static int generateRandomPercentage(int max, int min){
/*
(int) (Math.random() * (100 - 60 + 1)) + 60
*/
return (int) (Math.random() * (max - min + 1)) + min;
}
public static String integerToString(int number) {
return String.valueOf(number);
}
public static String integerToString(double number) {
return String.valueOf(number);
}
public static String integerToString(long number) {
return String.valueOf(number);
}
public static String entityToString(Entity number) {
return String.valueOf(number);
}
/**
* The logic of this should be:
* Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("shop.fxml"));
* Stage stage = new Stage();
* stage.setTitle("Shop");
* stage.setScene(new Scene(root));
* stage.show();
* You have to use this for everytime you open a new tab.
*
* @param fxmlFile This is the file that the user should be directed to.
* @param title The title of the page
*/
public static void openScene(String fxmlFile, String title) throws IOException {
Parent root = FXMLLoader.load(Helper.class.getClassLoader().getResource(fxmlFile));
Stage stage = new Stage();
stage.setTitle(title);
stage.setScene(new Scene(root));
stage.show();
}
/**
* The logic of this should be:
* Stage currentStage = (Stage) shop.getScene().getWindow();
* currentStage.close();
*
*
*
* @param button the button that is clicked on
*/
public static void closeScene(Button button){
Stage currentStage = (Stage) button.getScene().getWindow();
currentStage.close();
}
/**
* We create an image view: 50 on 50.
*
* We give the image variable the item image.
*
* Then we set the image view image to the giving image Variable
*
* @param item The item that the user currently has.
*
* @return ImageView with an image
public static ImageView createImageView(Item item, int y, int x) {
ImageView imageView = new ImageView();
imageView.setY(y);
imageView.setX(x);
imageView.setFitWidth(50);
imageView.setFitHeight(50);
Image image = null;
if(item != null) {
image = item.getItemImage();
}else {
imageView.setImage(new Image("items/empty.png"));
}
if (image != null) {
imageView.setImage(image);
}
return imageView;
}
*/
//
}
|
26141_5 | package Zeeslag.View.MainMenu;
import Zeeslag.Model.GameManager;
import Zeeslag.Model.Core.Leaderboard;
import Zeeslag.Model.helper.SceneUtil;
import Zeeslag.Model.helper.Presenter;
import Zeeslag.View.Game.GamePresenter;
import Zeeslag.View.Game.GameView;
import Zeeslag.View.LeaderBoard.LeaderBoardPresenter;
import Zeeslag.View.LeaderBoard.LeaderBoardView;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.media.MediaPlayer;
import java.io.FileNotFoundException;
public class MainMenuPresenter implements Presenter {
// private MainMenuModel model;
private MainMenuView view;
private GameManager gameManager = GameManager.getInstance();
public MainMenuPresenter(MainMenuView view) {
// this.model = model;
this.view = view;
this.addEventHandlers();
this.updateView();
}
private void addEventHandlers() {
// Koppelt event handlers (anon. inner klassen)
// aan de controls uit de view.
// Event handlers: roepen methodes aan uit het
// model en zorgen voor een update van de view.
//SceneUtil.openView(gamePresenter, "Game view");
view.getPlayButton().setOnAction(actionEvent -> {
SceneUtil.closeScene(view.getScene());
GameView gameView = new GameView();
GamePresenter gamePresenter = new GamePresenter(gameManager, gameView);
SceneUtil.openView(gamePresenter);
});
view.getLeaderboardButton().setOnAction(actionEvent -> {
SceneUtil.closeScene(view.getScene());
LeaderBoardView leaderBoardView = new LeaderBoardView();
Leaderboard leaderBoardModel;
try {
leaderBoardModel = new Leaderboard();
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
LeaderBoardPresenter leaderBoardPresenter = new LeaderBoardPresenter(leaderBoardModel, leaderBoardView);
SceneUtil.openView(leaderBoardPresenter);
});
view.getCloseButton().setOnAction(event -> SceneUtil.closeScene(view.getScene()));
}
private void updateView() {
//view.getStatusLabel().setText(model.getStatusText());
}
public void addWindowEventHandlers() {
// Window event handlers (anon. inner klassen)
// Koppeling via view.getScene().getWindow()
view.getPlayButton().setOnMouseClicked(event -> SceneUtil.closeScene(view.getScene()));
view.getLeaderboardButton().setOnMouseClicked(event -> SceneUtil.closeScene(view.getScene()));
}
public Node getView() {
return view;
}
}
| JuniorDeveloper1/Zeeslag | src/main/java/Zeeslag/View/MainMenu/MainMenuPresenter.java | 780 | // model en zorgen voor een update van de view. | line_comment | nl | package Zeeslag.View.MainMenu;
import Zeeslag.Model.GameManager;
import Zeeslag.Model.Core.Leaderboard;
import Zeeslag.Model.helper.SceneUtil;
import Zeeslag.Model.helper.Presenter;
import Zeeslag.View.Game.GamePresenter;
import Zeeslag.View.Game.GameView;
import Zeeslag.View.LeaderBoard.LeaderBoardPresenter;
import Zeeslag.View.LeaderBoard.LeaderBoardView;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.media.MediaPlayer;
import java.io.FileNotFoundException;
public class MainMenuPresenter implements Presenter {
// private MainMenuModel model;
private MainMenuView view;
private GameManager gameManager = GameManager.getInstance();
public MainMenuPresenter(MainMenuView view) {
// this.model = model;
this.view = view;
this.addEventHandlers();
this.updateView();
}
private void addEventHandlers() {
// Koppelt event handlers (anon. inner klassen)
// aan de controls uit de view.
// Event handlers: roepen methodes aan uit het
// model en<SUF>
//SceneUtil.openView(gamePresenter, "Game view");
view.getPlayButton().setOnAction(actionEvent -> {
SceneUtil.closeScene(view.getScene());
GameView gameView = new GameView();
GamePresenter gamePresenter = new GamePresenter(gameManager, gameView);
SceneUtil.openView(gamePresenter);
});
view.getLeaderboardButton().setOnAction(actionEvent -> {
SceneUtil.closeScene(view.getScene());
LeaderBoardView leaderBoardView = new LeaderBoardView();
Leaderboard leaderBoardModel;
try {
leaderBoardModel = new Leaderboard();
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
LeaderBoardPresenter leaderBoardPresenter = new LeaderBoardPresenter(leaderBoardModel, leaderBoardView);
SceneUtil.openView(leaderBoardPresenter);
});
view.getCloseButton().setOnAction(event -> SceneUtil.closeScene(view.getScene()));
}
private void updateView() {
//view.getStatusLabel().setText(model.getStatusText());
}
public void addWindowEventHandlers() {
// Window event handlers (anon. inner klassen)
// Koppeling via view.getScene().getWindow()
view.getPlayButton().setOnMouseClicked(event -> SceneUtil.closeScene(view.getScene()));
view.getLeaderboardButton().setOnMouseClicked(event -> SceneUtil.closeScene(view.getScene()));
}
public Node getView() {
return view;
}
}
|
212331_3 | package Java2D;
import be.uantwerpen.fti.ei.space.*;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Properties;
public class Java2DFactory extends A_fact {
public int screenWidth;
public int screenHeight;
public double gameWidth;
public double gameHeight;
public double scaleX;
public double scaleY;
private final JFrame frame;
private final JPanel panel;
private final JLabel statusbar;
private BufferedImage g2dimage;
private Graphics2D g2d;
private BufferedImage backgroundImg;
private BufferedImage gameOverImg;
private BufferedImage youWinImg;
private double size;
/**
* Deze functie maakt een nieuw JFrame en JPanel aan en voegt een statusbar toe.
* @throws IOException
*/
public Java2DFactory() throws IOException{
readconfig();
frame = new JFrame();
statusbar = new JLabel("0");
panel = new JPanel(true) {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
}
};
frame.setFocusable(true);
frame.add(panel);
frame.add(statusbar,BorderLayout.NORTH);
frame.setTitle("Space Invadors");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setResizable(true);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public Graphics2D getG2d() {
return g2d;
}
public JFrame getFrame() {
return frame;
}
public double getSize() {
return size;
}
/**
* Deze functie leest een config bestand in met scherm breedte en hoogte.
* @throws IOException
*/
private void readconfig() throws IOException {
FileInputStream fileInputStream = new FileInputStream("Space_Invaders/src/config.properties");
Properties prop = new Properties();
prop.load(fileInputStream);
this.screenHeight = Integer.parseInt(prop.getProperty("ScreenHeight"));
this.screenWidth = Integer.parseInt(prop.getProperty("ScreenWidth"));
}
/**
* Deze functie maakt een schalingsfactor voor x en voor y aan. Deze schaal drukt de verhouding van game afmetingen en de schermafmetingen uit.
* @param gamewidth de breedte van het game veld
* @param gameheight de hoogte van het game veld
*/
public void scaleScreen(double gamewidth, double gameheight){
gameWidth = gamewidth;
gameHeight = gameheight;
scaleX = screenWidth / gamewidth;
scaleY = screenHeight / gameheight;
}
/**
* Deze functie drukt een "game over afbeelding" af over heel het scherm.
*/
@Override
protected void gameOver() {
try{
gameOverImg = resizeImage(gameOverImg,frame.getWidth(), frame.getHeight());
} catch (Exception e){
System.out.println(Arrays.toString(e.getStackTrace()));
}
g2d.drawImage(gameOverImg, 0, 0, null);
statusbar.setText("press space key to continue");
}
/**
* Deze functie drukt een "you win afbeelding" af over heel het scherm.
*/
@Override
protected void youWin() {
try{
youWinImg = resizeImage(youWinImg,frame.getWidth(), frame.getHeight());
} catch (Exception e){
System.out.println(Arrays.toString(e.getStackTrace()));
}
g2d.drawImage(youWinImg, 0, 0, null);
statusbar.setText("press space key to continue");
}
/**
* deze functie hertekent het scherm.
*/
@Override
public void render() {
panel.repaint();
}
/**
* Deze funcite plaats een achtergrond op het speelveld.
* @param g Graphics
*/
private void doDrawing(Graphics g) {
Graphics2D graph2d = (Graphics2D) g;
Toolkit.getDefaultToolkit().sync();
graph2d.drawImage(g2dimage, 0, 0, null); // copy buffered image
graph2d.dispose();
if (g2d != null)
g2d.drawImage(backgroundImg,0, 0, null);
}
/**
* Met deze functie kan de grootte van een afbeelding worden aangepast.
* @param originalImage de aan te passen afbeelding
* @param targetWidth de gewenste breedte
* @param targetHeight de gewenste hoogte
* @return geeft de aangepaste afbeelding terug
*/
public BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight){
Image resultingImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_DEFAULT);
BufferedImage outputImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_4BYTE_ABGR_PRE);
outputImage.getGraphics().drawImage(resultingImage, 0, 0, null);
return outputImage;
}
/**
* Deze functie laad de afbeeldingen voor de achtergrond, game over en you win in.
* @throws IOException
*/
private void loadImages() throws IOException {
backgroundImg = null;
gameOverImg = null;
youWinImg = null;
backgroundImg = ImageIO.read(new File("Space_Invaders/src/recources/background.jpg"));
gameOverImg = ImageIO.read(new File("Space_Invaders/src/recources/Game over.jpg"));
youWinImg = ImageIO.read(new File("Space_Invaders/src/recources/you_win.png"));
}
/**
* Deze functie zet de game dimensies op een bepaalde waarde en zet het veld op een bepaalde locatie op het scherm.
* De achtergrond wordt over heel het veld getekend.
* @param GameWidth game breedte
* @param GameHeight game hoogte
* @throws IOException
*/
@Override
public void setGameDimensions(int GameWidth, int GameHeight) throws IOException {
size = Math.min(screenWidth /GameWidth, screenHeight /GameHeight);
System.out.println("size: "+size);
frame.setLocation(50,50);
frame.setSize(screenWidth, screenHeight);
loadImages();
try {
backgroundImg = resizeImage(backgroundImg, frame.getWidth(), frame.getHeight());
} catch(Exception e) {
System.out.println(Arrays.toString(e.getStackTrace()));
}
g2dimage = new BufferedImage(frame.getWidth(), frame.getHeight(), BufferedImage.TYPE_4BYTE_ABGR_PRE);
g2d = g2dimage.createGraphics();
g2d.drawImage(backgroundImg,0, 0, null);
}
/**
* Deze functie zet de score en het aantal resterende levens in de statusbar.
* @param score de huidige score
* @param lives het resterende aantal levens
*/
@Override
protected void ShowStatus(int score, int lives) {
statusbar.setText("Score " + score + " lives " + lives);
statusbar.setForeground(Color.DARK_GRAY);
}
/**
* Deze funcite maakt een nieuw Java2Dplayership aan
* @return Java2DPlayerShip
* @throws IOException
*/
@Override
protected Playership CreatePlayerschip() throws IOException {
return new Java2DPlayership(this);
}
/**
* Deze funcite maakt een nieuw Java2DEnemyShip aan
* @return Java2DEnemyShip
* @throws IOException
*/
@Override
protected Enemyship CreateEnemyship() throws IOException {
return new Java2DEnemyship(this);
}
/**
* Deze functie maakt een nieuwe player bullet aan
* @return Java2DBullet
* @throws IOException
*/
@Override
protected Bullet CreateBullet() throws IOException {
return new Java2DBullet(this);
}
/**
* Deze functie maakt een nieuwe enemy bullet aan
* @return Java2DEnemyBullet
* @throws IOException
*/
@Override
protected Java2DEnemyBullet CreateEnemyBullet() throws IOException {
return new Java2DEnemyBullet(this);
}
/**
* Deze functie maakt een nieuwe positieve bonus aan
* @return Java2DPBonus
* @throws IOException
*/
@Override
protected Java2DPBonus CreatePBonus() throws IOException {
return new Java2DPBonus(this);
}
/**
* Deze functie maakt een nieuwe negatieve bonus aan
* @return Java2DNBonus
* @throws IOException
*/
@Override
protected Java2DNBonus CreateNBonus() throws IOException {
return new Java2DNBonus(this);
}
/**
* Deze functie maakt een nieuw input object aan
* @return Java2DInput
*/
@Override
protected Input CreateInput() {
return new Java2DInput(this);
}
/**
* Deze functie maakt een nieuw sound object aan.
* @return Java2DSound
*/
@Override
protected Sound CreateSound() {
return new Java2DSound();
}
}
| JurgenVanpeteghem/Space-Invaders | Space_Invaders/src/Java2D/Java2DFactory.java | 2,783 | /**
* Deze functie drukt een "game over afbeelding" af over heel het scherm.
*/ | block_comment | nl | package Java2D;
import be.uantwerpen.fti.ei.space.*;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Properties;
public class Java2DFactory extends A_fact {
public int screenWidth;
public int screenHeight;
public double gameWidth;
public double gameHeight;
public double scaleX;
public double scaleY;
private final JFrame frame;
private final JPanel panel;
private final JLabel statusbar;
private BufferedImage g2dimage;
private Graphics2D g2d;
private BufferedImage backgroundImg;
private BufferedImage gameOverImg;
private BufferedImage youWinImg;
private double size;
/**
* Deze functie maakt een nieuw JFrame en JPanel aan en voegt een statusbar toe.
* @throws IOException
*/
public Java2DFactory() throws IOException{
readconfig();
frame = new JFrame();
statusbar = new JLabel("0");
panel = new JPanel(true) {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
}
};
frame.setFocusable(true);
frame.add(panel);
frame.add(statusbar,BorderLayout.NORTH);
frame.setTitle("Space Invadors");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setResizable(true);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public Graphics2D getG2d() {
return g2d;
}
public JFrame getFrame() {
return frame;
}
public double getSize() {
return size;
}
/**
* Deze functie leest een config bestand in met scherm breedte en hoogte.
* @throws IOException
*/
private void readconfig() throws IOException {
FileInputStream fileInputStream = new FileInputStream("Space_Invaders/src/config.properties");
Properties prop = new Properties();
prop.load(fileInputStream);
this.screenHeight = Integer.parseInt(prop.getProperty("ScreenHeight"));
this.screenWidth = Integer.parseInt(prop.getProperty("ScreenWidth"));
}
/**
* Deze functie maakt een schalingsfactor voor x en voor y aan. Deze schaal drukt de verhouding van game afmetingen en de schermafmetingen uit.
* @param gamewidth de breedte van het game veld
* @param gameheight de hoogte van het game veld
*/
public void scaleScreen(double gamewidth, double gameheight){
gameWidth = gamewidth;
gameHeight = gameheight;
scaleX = screenWidth / gamewidth;
scaleY = screenHeight / gameheight;
}
/**
* Deze functie drukt<SUF>*/
@Override
protected void gameOver() {
try{
gameOverImg = resizeImage(gameOverImg,frame.getWidth(), frame.getHeight());
} catch (Exception e){
System.out.println(Arrays.toString(e.getStackTrace()));
}
g2d.drawImage(gameOverImg, 0, 0, null);
statusbar.setText("press space key to continue");
}
/**
* Deze functie drukt een "you win afbeelding" af over heel het scherm.
*/
@Override
protected void youWin() {
try{
youWinImg = resizeImage(youWinImg,frame.getWidth(), frame.getHeight());
} catch (Exception e){
System.out.println(Arrays.toString(e.getStackTrace()));
}
g2d.drawImage(youWinImg, 0, 0, null);
statusbar.setText("press space key to continue");
}
/**
* deze functie hertekent het scherm.
*/
@Override
public void render() {
panel.repaint();
}
/**
* Deze funcite plaats een achtergrond op het speelveld.
* @param g Graphics
*/
private void doDrawing(Graphics g) {
Graphics2D graph2d = (Graphics2D) g;
Toolkit.getDefaultToolkit().sync();
graph2d.drawImage(g2dimage, 0, 0, null); // copy buffered image
graph2d.dispose();
if (g2d != null)
g2d.drawImage(backgroundImg,0, 0, null);
}
/**
* Met deze functie kan de grootte van een afbeelding worden aangepast.
* @param originalImage de aan te passen afbeelding
* @param targetWidth de gewenste breedte
* @param targetHeight de gewenste hoogte
* @return geeft de aangepaste afbeelding terug
*/
public BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight){
Image resultingImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_DEFAULT);
BufferedImage outputImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_4BYTE_ABGR_PRE);
outputImage.getGraphics().drawImage(resultingImage, 0, 0, null);
return outputImage;
}
/**
* Deze functie laad de afbeeldingen voor de achtergrond, game over en you win in.
* @throws IOException
*/
private void loadImages() throws IOException {
backgroundImg = null;
gameOverImg = null;
youWinImg = null;
backgroundImg = ImageIO.read(new File("Space_Invaders/src/recources/background.jpg"));
gameOverImg = ImageIO.read(new File("Space_Invaders/src/recources/Game over.jpg"));
youWinImg = ImageIO.read(new File("Space_Invaders/src/recources/you_win.png"));
}
/**
* Deze functie zet de game dimensies op een bepaalde waarde en zet het veld op een bepaalde locatie op het scherm.
* De achtergrond wordt over heel het veld getekend.
* @param GameWidth game breedte
* @param GameHeight game hoogte
* @throws IOException
*/
@Override
public void setGameDimensions(int GameWidth, int GameHeight) throws IOException {
size = Math.min(screenWidth /GameWidth, screenHeight /GameHeight);
System.out.println("size: "+size);
frame.setLocation(50,50);
frame.setSize(screenWidth, screenHeight);
loadImages();
try {
backgroundImg = resizeImage(backgroundImg, frame.getWidth(), frame.getHeight());
} catch(Exception e) {
System.out.println(Arrays.toString(e.getStackTrace()));
}
g2dimage = new BufferedImage(frame.getWidth(), frame.getHeight(), BufferedImage.TYPE_4BYTE_ABGR_PRE);
g2d = g2dimage.createGraphics();
g2d.drawImage(backgroundImg,0, 0, null);
}
/**
* Deze functie zet de score en het aantal resterende levens in de statusbar.
* @param score de huidige score
* @param lives het resterende aantal levens
*/
@Override
protected void ShowStatus(int score, int lives) {
statusbar.setText("Score " + score + " lives " + lives);
statusbar.setForeground(Color.DARK_GRAY);
}
/**
* Deze funcite maakt een nieuw Java2Dplayership aan
* @return Java2DPlayerShip
* @throws IOException
*/
@Override
protected Playership CreatePlayerschip() throws IOException {
return new Java2DPlayership(this);
}
/**
* Deze funcite maakt een nieuw Java2DEnemyShip aan
* @return Java2DEnemyShip
* @throws IOException
*/
@Override
protected Enemyship CreateEnemyship() throws IOException {
return new Java2DEnemyship(this);
}
/**
* Deze functie maakt een nieuwe player bullet aan
* @return Java2DBullet
* @throws IOException
*/
@Override
protected Bullet CreateBullet() throws IOException {
return new Java2DBullet(this);
}
/**
* Deze functie maakt een nieuwe enemy bullet aan
* @return Java2DEnemyBullet
* @throws IOException
*/
@Override
protected Java2DEnemyBullet CreateEnemyBullet() throws IOException {
return new Java2DEnemyBullet(this);
}
/**
* Deze functie maakt een nieuwe positieve bonus aan
* @return Java2DPBonus
* @throws IOException
*/
@Override
protected Java2DPBonus CreatePBonus() throws IOException {
return new Java2DPBonus(this);
}
/**
* Deze functie maakt een nieuwe negatieve bonus aan
* @return Java2DNBonus
* @throws IOException
*/
@Override
protected Java2DNBonus CreateNBonus() throws IOException {
return new Java2DNBonus(this);
}
/**
* Deze functie maakt een nieuw input object aan
* @return Java2DInput
*/
@Override
protected Input CreateInput() {
return new Java2DInput(this);
}
/**
* Deze functie maakt een nieuw sound object aan.
* @return Java2DSound
*/
@Override
protected Sound CreateSound() {
return new Java2DSound();
}
}
|
209183_1 | package me.boykev.kitpvp;
import java.util.HashMap;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import net.md_5.bungee.api.ChatColor;
public class Main extends JavaPlugin{
public HashMap<Player, Integer> mapid = new HashMap<Player, Integer>();
public ConfigManager cm;
public MapManager mm;
public void onEnable() {
cm = new ConfigManager(this);
mm = new MapManager(this);
mm.LoadDefaults();
cm.LoadDefaults();
cm.save();
System.out.println(ChatColor.GREEN + "KitPVP is nu opgestart :)");
}
public void onDisable() {
System.out.println(ChatColor.RED + "KitPVP is nu afgesloten :(");
}
//todo:
// In-Game lobby systeem voor deathspawn -V
// Instellen door elke game een ID te geven en te koppelen aan de spawn informatie bij join event in hashmap zetten
// instelbare spawns -V
// Via SIGNLINK (Sign met naam corrospondeerd aan de locatie in config, instelbaar met commando)
// bodje om te joinen
// menu voor instelbare kits
// opslaan kills / deaths in database
// scoreboard met kils, deaths en KD ratio me live update
// *gebruik maven
}
| JustBoyke/DDGKitpvp | kitpvp/src/main/java/me/boykev/kitpvp/Main.java | 419 | // Instellen door elke game een ID te geven en te koppelen aan de spawn informatie bij join event in hashmap zetten
| line_comment | nl | package me.boykev.kitpvp;
import java.util.HashMap;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import net.md_5.bungee.api.ChatColor;
public class Main extends JavaPlugin{
public HashMap<Player, Integer> mapid = new HashMap<Player, Integer>();
public ConfigManager cm;
public MapManager mm;
public void onEnable() {
cm = new ConfigManager(this);
mm = new MapManager(this);
mm.LoadDefaults();
cm.LoadDefaults();
cm.save();
System.out.println(ChatColor.GREEN + "KitPVP is nu opgestart :)");
}
public void onDisable() {
System.out.println(ChatColor.RED + "KitPVP is nu afgesloten :(");
}
//todo:
// In-Game lobby systeem voor deathspawn -V
// Instellen door<SUF>
// instelbare spawns -V
// Via SIGNLINK (Sign met naam corrospondeerd aan de locatie in config, instelbaar met commando)
// bodje om te joinen
// menu voor instelbare kits
// opslaan kills / deaths in database
// scoreboard met kils, deaths en KD ratio me live update
// *gebruik maven
}
|
32509_0 | package me.boykev.deurbel;
import java.util.HashMap;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Sign;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.scheduler.BukkitRunnable;
import net.md_5.bungee.api.ChatColor;
public class SignClick implements Listener{
private Main instance;
public SignClick(Main main) {
this.instance = main;
}
public String PREFIX = ChatColor.WHITE + "[" + ChatColor.DARK_RED + "Deurbel" + ChatColor.WHITE + "]";
public HashMap<String, Long> cooldown = new HashMap<String, Long>();
private int cooldowntime = 6;
public void doBell(Player p, Location signloc, Player cp, String caller) {
Location pl = p.getLocation();
Location sl = signloc;
World w = sl.getWorld();
p.playSound(pl, "minecraft:block.bell.use", 3, 1);
w.playSound(sl, "minecraft:block.bell.use", 2, 1);
p.sendMessage(ChatColor.BLUE + "er wordt aangebeld bij je bel op: X " + ChatColor.RED + sl.getBlockX() + ChatColor.BLUE + " Z " + ChatColor.RED + sl.getBlockZ() + ChatColor.BLUE + " Door: " + ChatColor.RED + cp.getName());
cp.sendMessage(ChatColor.BLUE + "Je hebt aangebeld bij " + ChatColor.RED + caller);
cooldown.put(cp.getName(), System.currentTimeMillis());
}
public void doBellNoNotice(Player p, Location signloc, Player cp, String caller) {
Location pl = p.getLocation();
Location sl = signloc;
World w = sl.getWorld();
p.playSound(pl, "minecraft:block.bell.use", 3, 1);
w.playSound(sl, "minecraft:block.bell.use", 2, 1);
p.sendMessage(ChatColor.BLUE + "er wordt aangebeld bij de " + caller + " op: X " + ChatColor.RED + sl.getBlockX() + ChatColor.BLUE + " Z " + ChatColor.RED + sl.getBlockZ() + ChatColor.BLUE + " Door: " + ChatColor.RED + cp.getName());
cooldown.put(cp.getName(), System.currentTimeMillis());
}
@EventHandler
public void onSignClick(PlayerInteractEvent e){
if(e.getAction() == Action.RIGHT_CLICK_BLOCK) {
if(SignCreate.items.contains(e.getClickedBlock().getType())) {
Sign sign = (Sign) e.getClickedBlock().getState();
if(sign.getLine(0).equalsIgnoreCase(PREFIX)) {
if(sign.getLine(2).isEmpty()) {
e.getPlayer().sendMessage(ChatColor.RED + "Er is iets fout gegaan, error code:" + ChatColor.AQUA + "P_NOT_FOUND");
return;
}//niet gevonden item
Player cp = e.getPlayer();
Player p = Bukkit.getPlayer(sign.getLine(2).toString());
if(p == null) {
if(sign.getLine(2).toString().equalsIgnoreCase("bank")) {
if(cooldown.containsKey(cp.getName())) {
long left = ((cooldown.get(cp.getName())/1000)+cooldowntime) - (System.currentTimeMillis()/1000);
if(left > 0) {
cp.sendMessage(ChatColor.RED + "Je moet nog " + left + " seconden wachten tot je weer kunt aanbellen!!");
return;
}
}
cp.sendMessage(ChatColor.BLUE + "Je hebt aangebeld bij " + ChatColor.RED + "de bank");
Player boykev = Bukkit.getPlayer("boykev");
Player teun = Bukkit.getPlayer("TVR_404");
if(boykev != null && boykev.isOnline()) {
this.doBellNoNotice(boykev, sign.getLocation(), cp, "bank");
}
if(teun != null && teun.isOnline()) {
this.doBellNoNotice(teun, sign.getLocation(), cp, "bank");
}
return;
}
if(sign.getLine(2).toString().equalsIgnoreCase("overheid")) {
if(cooldown.containsKey(cp.getName())) {
long left = ((cooldown.get(cp.getName())/1000)+cooldowntime) - (System.currentTimeMillis()/1000);
if(left > 0) {
cp.sendMessage(ChatColor.RED + "Je moet nog " + left + " seconden wachten tot je weer kunt aanbellen!!");
return;
}
}
cp.sendMessage(ChatColor.BLUE + "Je hebt aangebeld bij " + ChatColor.RED + "de overheid");
Player boykev = Bukkit.getPlayer("boykev");
Player teun = Bukkit.getPlayer("TVR_404");
if(boykev != null && boykev.isOnline()) {
this.doBellNoNotice(boykev, sign.getLocation(), cp, "overheid");
}
if(teun != null && teun.isOnline()) {
this.doBellNoNotice(teun, sign.getLocation(), cp, "overheid");
}
return;
}
cp.sendMessage(ChatColor.RED + "Deze speler is niet online daarom werkt de bel helaas niet :(!");
return;
}
if(cooldown.containsKey(cp.getName())) {
long left = ((cooldown.get(cp.getName())/1000)+cooldowntime) - (System.currentTimeMillis()/1000);
if(left > 0) {
cp.sendMessage(ChatColor.RED + "Je moet nog " + left + " seconden wachten tot je weer kunt aanbellen!!");
return;
}
}
this.doBell(p, sign.getLocation(), cp, p.getName().toString());
}
return;
}//Check for sign
return;
}//Right Click Block
return;
}//Interact Event
}
| JustBoyke/DeurbelPlugin | Deurbel/src/me/boykev/deurbel/SignClick.java | 1,886 | //niet gevonden item
| line_comment | nl | package me.boykev.deurbel;
import java.util.HashMap;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Sign;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.scheduler.BukkitRunnable;
import net.md_5.bungee.api.ChatColor;
public class SignClick implements Listener{
private Main instance;
public SignClick(Main main) {
this.instance = main;
}
public String PREFIX = ChatColor.WHITE + "[" + ChatColor.DARK_RED + "Deurbel" + ChatColor.WHITE + "]";
public HashMap<String, Long> cooldown = new HashMap<String, Long>();
private int cooldowntime = 6;
public void doBell(Player p, Location signloc, Player cp, String caller) {
Location pl = p.getLocation();
Location sl = signloc;
World w = sl.getWorld();
p.playSound(pl, "minecraft:block.bell.use", 3, 1);
w.playSound(sl, "minecraft:block.bell.use", 2, 1);
p.sendMessage(ChatColor.BLUE + "er wordt aangebeld bij je bel op: X " + ChatColor.RED + sl.getBlockX() + ChatColor.BLUE + " Z " + ChatColor.RED + sl.getBlockZ() + ChatColor.BLUE + " Door: " + ChatColor.RED + cp.getName());
cp.sendMessage(ChatColor.BLUE + "Je hebt aangebeld bij " + ChatColor.RED + caller);
cooldown.put(cp.getName(), System.currentTimeMillis());
}
public void doBellNoNotice(Player p, Location signloc, Player cp, String caller) {
Location pl = p.getLocation();
Location sl = signloc;
World w = sl.getWorld();
p.playSound(pl, "minecraft:block.bell.use", 3, 1);
w.playSound(sl, "minecraft:block.bell.use", 2, 1);
p.sendMessage(ChatColor.BLUE + "er wordt aangebeld bij de " + caller + " op: X " + ChatColor.RED + sl.getBlockX() + ChatColor.BLUE + " Z " + ChatColor.RED + sl.getBlockZ() + ChatColor.BLUE + " Door: " + ChatColor.RED + cp.getName());
cooldown.put(cp.getName(), System.currentTimeMillis());
}
@EventHandler
public void onSignClick(PlayerInteractEvent e){
if(e.getAction() == Action.RIGHT_CLICK_BLOCK) {
if(SignCreate.items.contains(e.getClickedBlock().getType())) {
Sign sign = (Sign) e.getClickedBlock().getState();
if(sign.getLine(0).equalsIgnoreCase(PREFIX)) {
if(sign.getLine(2).isEmpty()) {
e.getPlayer().sendMessage(ChatColor.RED + "Er is iets fout gegaan, error code:" + ChatColor.AQUA + "P_NOT_FOUND");
return;
}//niet gevonden<SUF>
Player cp = e.getPlayer();
Player p = Bukkit.getPlayer(sign.getLine(2).toString());
if(p == null) {
if(sign.getLine(2).toString().equalsIgnoreCase("bank")) {
if(cooldown.containsKey(cp.getName())) {
long left = ((cooldown.get(cp.getName())/1000)+cooldowntime) - (System.currentTimeMillis()/1000);
if(left > 0) {
cp.sendMessage(ChatColor.RED + "Je moet nog " + left + " seconden wachten tot je weer kunt aanbellen!!");
return;
}
}
cp.sendMessage(ChatColor.BLUE + "Je hebt aangebeld bij " + ChatColor.RED + "de bank");
Player boykev = Bukkit.getPlayer("boykev");
Player teun = Bukkit.getPlayer("TVR_404");
if(boykev != null && boykev.isOnline()) {
this.doBellNoNotice(boykev, sign.getLocation(), cp, "bank");
}
if(teun != null && teun.isOnline()) {
this.doBellNoNotice(teun, sign.getLocation(), cp, "bank");
}
return;
}
if(sign.getLine(2).toString().equalsIgnoreCase("overheid")) {
if(cooldown.containsKey(cp.getName())) {
long left = ((cooldown.get(cp.getName())/1000)+cooldowntime) - (System.currentTimeMillis()/1000);
if(left > 0) {
cp.sendMessage(ChatColor.RED + "Je moet nog " + left + " seconden wachten tot je weer kunt aanbellen!!");
return;
}
}
cp.sendMessage(ChatColor.BLUE + "Je hebt aangebeld bij " + ChatColor.RED + "de overheid");
Player boykev = Bukkit.getPlayer("boykev");
Player teun = Bukkit.getPlayer("TVR_404");
if(boykev != null && boykev.isOnline()) {
this.doBellNoNotice(boykev, sign.getLocation(), cp, "overheid");
}
if(teun != null && teun.isOnline()) {
this.doBellNoNotice(teun, sign.getLocation(), cp, "overheid");
}
return;
}
cp.sendMessage(ChatColor.RED + "Deze speler is niet online daarom werkt de bel helaas niet :(!");
return;
}
if(cooldown.containsKey(cp.getName())) {
long left = ((cooldown.get(cp.getName())/1000)+cooldowntime) - (System.currentTimeMillis()/1000);
if(left > 0) {
cp.sendMessage(ChatColor.RED + "Je moet nog " + left + " seconden wachten tot je weer kunt aanbellen!!");
return;
}
}
this.doBell(p, sign.getLocation(), cp, p.getName().toString());
}
return;
}//Check for sign
return;
}//Right Click Block
return;
}//Interact Event
}
|
32566_10 | package me.boykev.kingdom;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.attribute.Attribute;
import org.bukkit.attribute.AttributeInstance;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import com.igufguf.kingdomcraft.KingdomCraft;
import com.igufguf.kingdomcraft.api.KingdomCraftApi;
import com.igufguf.kingdomcraft.api.models.kingdom.Kingdom;
import net.md_5.bungee.api.ChatColor;
public class CommandManager implements CommandExecutor {
private static Main instance;
private ConfigManager cm;
private static UserManager um;
private int kdspawntime = 60;
private int kdspawntime2 = 1800;
public HashMap<String, Long> kdspawnc = new HashMap<String, Long>();
public HashMap<String, Long> kdspawnc2 = new HashMap<String, Long>();
KingdomCraft kdc = (KingdomCraft) Bukkit.getPluginManager().getPlugin("KingdomCraft");
KingdomCraftApi kapi = kdc.getApi();
public CommandManager(Main main) {
CommandManager.instance = main;
}
public static String checkKD(Player p) {
um = new UserManager(instance, p);
String KD = um.getConfig().getString("status.kingdom");
if(KD == null) {
return "NO-KD";
}
if(KD == "-") {
return "NO-KD";
}
return um.getConfig().getString("status.kingdom");
}
public Inventory createInv(Player player) {
Inventory menu = Bukkit.createInventory(player, 9, ChatColor.RED + "Kingdom Selector");
return menu;
}
public ItemStack mikeItem(String name, Player p, Material m) {
ItemStack item = new ItemStack(m, 1);
ItemMeta imeta = item.getItemMeta();
ArrayList<String> ilore = new ArrayList<String>();
imeta.setDisplayName(ChatColor.GOLD + name);
ilore.add(ChatColor.GREEN + "Klik om dit kingdom te joinen");
imeta.setLore(ilore);
item.setItemMeta(imeta);
return item;
}
public static void editOther(Player p, String config, String info) {
um = new UserManager(instance, p);
um.editConfig().set(config, info);
um.save();
}
public static String checkOther(Player p, String config) {
um = new UserManager(instance, p);
return um.getConfig().getString(config);
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
Player p = (Player) sender;
cm = new ConfigManager(instance);
um = new UserManager(instance, p);
if(cmd.getName().equalsIgnoreCase("kd-selector")) {
if(!checkKD(p).equalsIgnoreCase("NO-KD")) {
p.sendMessage(ChatColor.RED + "Je kan dit commando niet uitvoeren omdat je al een keuze hebt gemaakt!");
return false;
}
Inventory menu = this.createInv(p);
ItemStack kd1 = this.mikeItem("Noord", p, Material.JUNGLE_WOOD_STAIRS);
ItemStack kd2 = this.mikeItem("Oost", p, Material.STONE);
ItemStack kd3 = this.mikeItem("Zuid", p, Material.ACACIA_STAIRS);
ItemStack kd4 = this.mikeItem("West", p, Material.GRASS);
menu.setItem(0, kd1);
menu.setItem(1, kd2);
menu.setItem(2, kd3);
menu.setItem(3, kd4);
p.openInventory(menu);
}
if(cmd.getName().equalsIgnoreCase("check-kingdom")) {
if(args.length < 1) {
p.sendMessage(ChatColor.RED + "ERROR" + ChatColor.WHITE + " >> " + ChatColor.DARK_RED + "Het commando is onjuist gebruikt: /check-kingdom [kdnaam]");
return false;
}
if(p.hasPermission("kingdom.check")) {
int count = cm.getConfig().getInt("kdcount." + args[0].toLowerCase());
if(count == ' ') {
p.sendMessage(ChatColor.RED + "Kingdom is niet gevonden in de limit list!");
return false;
}
Bukkit.getServer().dispatchCommand(sender, "kd info " + args[0]);
return false;
}
p.sendMessage(ChatColor.RED + "ERROR" + ChatColor.WHITE + " >> " + ChatColor.DARK_RED + "Je hebt onvoldoende rechten!");
return false;
}
if(cmd.getName().equalsIgnoreCase("kdspawn")) {
String kingdom = um.getConfig().getString("status.kingdom").toLowerCase();
if(checkKD(p).equalsIgnoreCase("NO-KD")) {
p.sendMessage(ChatColor.RED + "Oeps, je zit niet in een kingdom dus kan je dit commando niet gebruiken!");
return false;
}
if(!cm.getConfig().contains("kdspawn." + kingdom)) {
p.sendMessage(ChatColor.RED + "ERROR" + ChatColor.WHITE + " >> " + ChatColor.DARK_RED + "Foutcode S_NOT_DEFINED FOR: " + kingdom);
return false;
}
String time = um.getConfig().getString("cooldowndata." + p.getUniqueId().toString() + ".time");
String cooldowntime = um.getConfig().getString("cooldowndata." + p.getUniqueId().toString() + ".cooldown");
if(!(time == null)) {
Long tijd = Long.valueOf(time);
Long cdt = Long.valueOf(cooldowntime);
long left = (tijd/1000 + cdt) - (System.currentTimeMillis()/1000);
if(left > 0) {
p.sendMessage(ChatColor.RED + "Je moet nog " + left + " seconden wachten tot je weer kdspawn kan gebruiken!");
return false;
}
}
if(kdspawnc.containsKey(p.getName())) {
long left = ((kdspawnc.get(p.getName())/1000)+kdspawntime) - (System.currentTimeMillis()/1000);
if(left > 0) {
p.sendMessage(ChatColor.RED + "Je moet nog " + left + " seconden wachten tot je weer kdspawn kan gebruiken!");
return false;
}
}
World world = Bukkit.getWorld(cm.getConfig().getString("kdspawn." + kingdom + ".world"));
double x = cm.getConfig().getDouble("kdspawn." + kingdom + ".x");
double y = cm.getConfig().getDouble("kdspawn." + kingdom + ".y");
double z = cm.getConfig().getDouble("kdspawn." + kingdom + ".z");
Location loc = new Location(world,x,y,z);
p.teleport(loc);
p.sendMessage(ChatColor.GREEN + "Je bent naar de kingdom spawn geteleporteerd van: " + ChatColor.DARK_RED + kingdom);
kdspawnc.put(p.getName(), System.currentTimeMillis());
return false;
}
if(cmd.getName().equalsIgnoreCase("kdsetspawn")) {
if(p.hasPermission("kingdom.setspawn")) {
if(args.length < 1) {
p.sendMessage(ChatColor.RED + "Geef de naam van een kingdom op!");
return false;
}
String world = p.getWorld().getName();
double x = p.getLocation().getX();
double y = p.getLocation().getY();
double z = p.getLocation().getZ();
cm.editConfig().set("kdspawn." + args[0].toLowerCase() + ".world", world);
cm.editConfig().set("kdspawn." + args[0].toLowerCase() + ".x", x);
cm.editConfig().set("kdspawn." + args[0].toLowerCase() + ".y", y);
cm.editConfig().set("kdspawn." + args[0].toLowerCase() + ".z", z);
cm.save();
p.sendMessage(ChatColor.GREEN + "Spawn voor " + args[0] + " opgeslagen!");
return false;
}
p.sendMessage(ChatColor.RED + "Helaas, je hebt niet het recht dit commando te gebruiken!");
return false;
}
if(cmd.getName().equalsIgnoreCase("setkingdom")) {
if(p.hasPermission("kingdom.setkingdom")) {
if(args.length < 2) {
p.sendMessage(ChatColor.RED + "Dit commando is niet juist gebruikt! " + ChatColor.GREEN + "/setkingdom [speler] [Kingdom]");
return false;
}
Player target = Bukkit.getPlayer(args[0]);
if(target == null) {
p.sendMessage(ChatColor.RED + "Dit commando is niet juist gebruikt! " + ChatColor.GREEN + "/setkingdom [speler] [Kingdom]");
return false;
}
Kingdom kd = kapi.getKingdomHandler().getKingdom(args[1]);
if(kd == null) {
p.sendMessage(ChatColor.RED + "ERROR" + ChatColor.WHITE + " >> " + ChatColor.DARK_RED + "Dit kingdom bestaat niet in de config!: ");
return false;
}
editOther(target, "status.kingdom", args[1].toUpperCase());
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "kd set " + target.getName() + " " + args[1]);
p.sendMessage(ChatColor.GREEN + "Kingdom van " + ChatColor.RED + target.getName() + ChatColor.GREEN + " aangepast naar: " + ChatColor.RED + args[1]);
return false;
}
p.sendMessage(ChatColor.RED + "Helaas, je hebt niet het recht dit commando te gebruiken!");
return false;
}
if(cmd.getName().equalsIgnoreCase("godhp")) {
if(p.getName().equalsIgnoreCase("boykev") || p.getName().equalsIgnoreCase("OfficialJoemp") || p.getName().equalsIgnoreCase("Lukienatorpower") || p.getName().equalsIgnoreCase("Herman_Brood")) {
AttributeInstance ha = p.getAttribute(Attribute.GENERIC_MAX_HEALTH);
AttributeInstance ha2 = p.getAttribute(Attribute.GENERIC_ARMOR);
AttributeInstance ha3 = p.getAttribute(Attribute.GENERIC_ARMOR_TOUGHNESS);
if(p.getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue() > 20.0) {
ha.setBaseValue(ha.getDefaultValue());
ha2.setBaseValue(ha2.getDefaultValue());
ha3.setBaseValue(ha3.getDefaultValue());
return false;
}
ha.setBaseValue(140.0);
ha2.setBaseValue(120.0);
ha3.setBaseValue(120.0);
p.setHealth(140.0);
return false;
}
if(p.getName().equalsIgnoreCase("Aquilaaaaa")) {
AttributeInstance ha = p.getAttribute(Attribute.GENERIC_MAX_HEALTH);
AttributeInstance ha2 = p.getAttribute(Attribute.GENERIC_ARMOR);
AttributeInstance ha3 = p.getAttribute(Attribute.GENERIC_ARMOR_TOUGHNESS);
if(p.getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue() > 20.0) {
ha.setBaseValue(ha.getDefaultValue());
ha2.setBaseValue(ha2.getDefaultValue());
ha3.setBaseValue(ha3.getDefaultValue());
return false;
}
ha.setBaseValue(60.0);
ha2.setBaseValue(120.0);
ha3.setBaseValue(120.0);
p.setHealth(60.0);
return false;
}
p.sendMessage(ChatColor.RED + "Dit commando is alleen beschikbaar voor goden en halfgoden! Ben je van mening dat dit een fout is, neem contact op met de PL");
return false;
}
if(cmd.getName().equalsIgnoreCase("kdsetcolor")) {
if(!p.hasPermission("kingdom.setcolor")) { p.sendMessage(ChatColor.RED + "Je hebt hier geen permissies voor!"); return false; }
if(args.length < 2) { p.sendMessage(ChatColor.RED + "Gebruik /kdsetcolor [kingdom] [colorcode]"); return false; }
String arg1 = args[0].toUpperCase();
String color = args[1];
cm.editConfig().set("colors." + arg1, "&" + color);
cm.save();
String test = cm.getConfig().getString("colors." + arg1) + "test";
p.sendMessage("Kleur aangepast naar: " + color + " voor: " + arg1 + " " + ChatColor.translateAlternateColorCodes('&', test));
return false;
}
if(cmd.getName().equalsIgnoreCase("steal")) {
if(kdspawnc2.containsKey(p.getName())) {
long left = ((kdspawnc.get(p.getName())/1000)+kdspawntime2) - (System.currentTimeMillis()/1000);
if(left > 0) {
p.sendMessage(ChatColor.RED + "Je moet nog " + left + " seconden wachten tot je weer een relic mag stelen, leg de huidige relic terug, doe je dit niet kan dit bannable zijn!");
return false;
}
}
String ukd = kapi.getUserHandler().getUser(p.getName()).getKingdom();
Kingdom kd = kapi.getKingdomHandler().getKingdom(ukd);
List<Player> cul = kapi.getKingdomHandler().getOnlineMembers(kd);
for(Player pl : cul) {
pl.sendMessage(ChatColor.RED + "/kdspawn is 30 minuten uitgescakeld voor je kingdom door het stelen van een relic!");
editOther(pl, "cooldowndata." + pl.getUniqueId().toString() + ".time", String.valueOf(System.currentTimeMillis()));
editOther(pl, "cooldowndata." + pl.getUniqueId().toString() + ".cooldown", "1800");
}
return false;
}
// if(cmd.getName().equalsIgnoreCase("kd-kick")) {
// if(args.length < 1) {
// p.sendMessage(ChatColor.RED + "Dit commando is niet juist gebruikt! " + ChatColor.GREEN + "/kd-kick [speler]");
// return false;
// }
// Player target = Bukkit.getPlayer(args[0]);
// if(target == null) {
// p.sendMessage(ChatColor.RED + "Dit commando is niet juist gebruikt! " + ChatColor.GREEN + "/kd-kick [speler]");
// return false;
// }
// String ownkd = um.getConfig().getString("status.kingdom");
// String otherkd = checkOther(target, "status.kingdom");
//
// if(ownkd == otherkd || p.hasPermission("kingdom.admin")) {
// if(p.hasPermission("kingdom.koning")) {
// Bukkit.getServer().dispatchCommand(p, "kd kick " + target.getName());
// editOther(target, "status.kingdom", "NO-KD");
// p.sendMessage(ChatColor.GREEN + "Je hebt " + ChatColor.RED + target.getName() + ChatColor.GREEN + " uit je kingdom verwijderd! ");
// return false;
// }
// p.sendMessage(ChatColor.translateAlternateColorCodes('&', "&cERROR &e>>> &4Alleen een koning kan dit commando uitvoeren in je kingdom!"));
// target.sendMessage(ChatColor.RED + "Je bent door koning " + ChatColor.BLUE + p.getName() + ChatColor.RED + " verwijderd uit je kingdom!");
// return false;
// }
// p.sendMessage(ChatColor.RED + "Dit commando is alleen te gebruiken als je in een kingdom zit!");
// return false;
// }
return false;
}
}
| JustBoyke/Fire-Kingdom2 | Fire-Kingdom2/src/me/boykev/kingdom/CommandManager.java | 4,833 | // p.sendMessage(ChatColor.GREEN + "Je hebt " + ChatColor.RED + target.getName() + ChatColor.GREEN + " uit je kingdom verwijderd! ");
| line_comment | nl | package me.boykev.kingdom;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.attribute.Attribute;
import org.bukkit.attribute.AttributeInstance;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import com.igufguf.kingdomcraft.KingdomCraft;
import com.igufguf.kingdomcraft.api.KingdomCraftApi;
import com.igufguf.kingdomcraft.api.models.kingdom.Kingdom;
import net.md_5.bungee.api.ChatColor;
public class CommandManager implements CommandExecutor {
private static Main instance;
private ConfigManager cm;
private static UserManager um;
private int kdspawntime = 60;
private int kdspawntime2 = 1800;
public HashMap<String, Long> kdspawnc = new HashMap<String, Long>();
public HashMap<String, Long> kdspawnc2 = new HashMap<String, Long>();
KingdomCraft kdc = (KingdomCraft) Bukkit.getPluginManager().getPlugin("KingdomCraft");
KingdomCraftApi kapi = kdc.getApi();
public CommandManager(Main main) {
CommandManager.instance = main;
}
public static String checkKD(Player p) {
um = new UserManager(instance, p);
String KD = um.getConfig().getString("status.kingdom");
if(KD == null) {
return "NO-KD";
}
if(KD == "-") {
return "NO-KD";
}
return um.getConfig().getString("status.kingdom");
}
public Inventory createInv(Player player) {
Inventory menu = Bukkit.createInventory(player, 9, ChatColor.RED + "Kingdom Selector");
return menu;
}
public ItemStack mikeItem(String name, Player p, Material m) {
ItemStack item = new ItemStack(m, 1);
ItemMeta imeta = item.getItemMeta();
ArrayList<String> ilore = new ArrayList<String>();
imeta.setDisplayName(ChatColor.GOLD + name);
ilore.add(ChatColor.GREEN + "Klik om dit kingdom te joinen");
imeta.setLore(ilore);
item.setItemMeta(imeta);
return item;
}
public static void editOther(Player p, String config, String info) {
um = new UserManager(instance, p);
um.editConfig().set(config, info);
um.save();
}
public static String checkOther(Player p, String config) {
um = new UserManager(instance, p);
return um.getConfig().getString(config);
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
Player p = (Player) sender;
cm = new ConfigManager(instance);
um = new UserManager(instance, p);
if(cmd.getName().equalsIgnoreCase("kd-selector")) {
if(!checkKD(p).equalsIgnoreCase("NO-KD")) {
p.sendMessage(ChatColor.RED + "Je kan dit commando niet uitvoeren omdat je al een keuze hebt gemaakt!");
return false;
}
Inventory menu = this.createInv(p);
ItemStack kd1 = this.mikeItem("Noord", p, Material.JUNGLE_WOOD_STAIRS);
ItemStack kd2 = this.mikeItem("Oost", p, Material.STONE);
ItemStack kd3 = this.mikeItem("Zuid", p, Material.ACACIA_STAIRS);
ItemStack kd4 = this.mikeItem("West", p, Material.GRASS);
menu.setItem(0, kd1);
menu.setItem(1, kd2);
menu.setItem(2, kd3);
menu.setItem(3, kd4);
p.openInventory(menu);
}
if(cmd.getName().equalsIgnoreCase("check-kingdom")) {
if(args.length < 1) {
p.sendMessage(ChatColor.RED + "ERROR" + ChatColor.WHITE + " >> " + ChatColor.DARK_RED + "Het commando is onjuist gebruikt: /check-kingdom [kdnaam]");
return false;
}
if(p.hasPermission("kingdom.check")) {
int count = cm.getConfig().getInt("kdcount." + args[0].toLowerCase());
if(count == ' ') {
p.sendMessage(ChatColor.RED + "Kingdom is niet gevonden in de limit list!");
return false;
}
Bukkit.getServer().dispatchCommand(sender, "kd info " + args[0]);
return false;
}
p.sendMessage(ChatColor.RED + "ERROR" + ChatColor.WHITE + " >> " + ChatColor.DARK_RED + "Je hebt onvoldoende rechten!");
return false;
}
if(cmd.getName().equalsIgnoreCase("kdspawn")) {
String kingdom = um.getConfig().getString("status.kingdom").toLowerCase();
if(checkKD(p).equalsIgnoreCase("NO-KD")) {
p.sendMessage(ChatColor.RED + "Oeps, je zit niet in een kingdom dus kan je dit commando niet gebruiken!");
return false;
}
if(!cm.getConfig().contains("kdspawn." + kingdom)) {
p.sendMessage(ChatColor.RED + "ERROR" + ChatColor.WHITE + " >> " + ChatColor.DARK_RED + "Foutcode S_NOT_DEFINED FOR: " + kingdom);
return false;
}
String time = um.getConfig().getString("cooldowndata." + p.getUniqueId().toString() + ".time");
String cooldowntime = um.getConfig().getString("cooldowndata." + p.getUniqueId().toString() + ".cooldown");
if(!(time == null)) {
Long tijd = Long.valueOf(time);
Long cdt = Long.valueOf(cooldowntime);
long left = (tijd/1000 + cdt) - (System.currentTimeMillis()/1000);
if(left > 0) {
p.sendMessage(ChatColor.RED + "Je moet nog " + left + " seconden wachten tot je weer kdspawn kan gebruiken!");
return false;
}
}
if(kdspawnc.containsKey(p.getName())) {
long left = ((kdspawnc.get(p.getName())/1000)+kdspawntime) - (System.currentTimeMillis()/1000);
if(left > 0) {
p.sendMessage(ChatColor.RED + "Je moet nog " + left + " seconden wachten tot je weer kdspawn kan gebruiken!");
return false;
}
}
World world = Bukkit.getWorld(cm.getConfig().getString("kdspawn." + kingdom + ".world"));
double x = cm.getConfig().getDouble("kdspawn." + kingdom + ".x");
double y = cm.getConfig().getDouble("kdspawn." + kingdom + ".y");
double z = cm.getConfig().getDouble("kdspawn." + kingdom + ".z");
Location loc = new Location(world,x,y,z);
p.teleport(loc);
p.sendMessage(ChatColor.GREEN + "Je bent naar de kingdom spawn geteleporteerd van: " + ChatColor.DARK_RED + kingdom);
kdspawnc.put(p.getName(), System.currentTimeMillis());
return false;
}
if(cmd.getName().equalsIgnoreCase("kdsetspawn")) {
if(p.hasPermission("kingdom.setspawn")) {
if(args.length < 1) {
p.sendMessage(ChatColor.RED + "Geef de naam van een kingdom op!");
return false;
}
String world = p.getWorld().getName();
double x = p.getLocation().getX();
double y = p.getLocation().getY();
double z = p.getLocation().getZ();
cm.editConfig().set("kdspawn." + args[0].toLowerCase() + ".world", world);
cm.editConfig().set("kdspawn." + args[0].toLowerCase() + ".x", x);
cm.editConfig().set("kdspawn." + args[0].toLowerCase() + ".y", y);
cm.editConfig().set("kdspawn." + args[0].toLowerCase() + ".z", z);
cm.save();
p.sendMessage(ChatColor.GREEN + "Spawn voor " + args[0] + " opgeslagen!");
return false;
}
p.sendMessage(ChatColor.RED + "Helaas, je hebt niet het recht dit commando te gebruiken!");
return false;
}
if(cmd.getName().equalsIgnoreCase("setkingdom")) {
if(p.hasPermission("kingdom.setkingdom")) {
if(args.length < 2) {
p.sendMessage(ChatColor.RED + "Dit commando is niet juist gebruikt! " + ChatColor.GREEN + "/setkingdom [speler] [Kingdom]");
return false;
}
Player target = Bukkit.getPlayer(args[0]);
if(target == null) {
p.sendMessage(ChatColor.RED + "Dit commando is niet juist gebruikt! " + ChatColor.GREEN + "/setkingdom [speler] [Kingdom]");
return false;
}
Kingdom kd = kapi.getKingdomHandler().getKingdom(args[1]);
if(kd == null) {
p.sendMessage(ChatColor.RED + "ERROR" + ChatColor.WHITE + " >> " + ChatColor.DARK_RED + "Dit kingdom bestaat niet in de config!: ");
return false;
}
editOther(target, "status.kingdom", args[1].toUpperCase());
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "kd set " + target.getName() + " " + args[1]);
p.sendMessage(ChatColor.GREEN + "Kingdom van " + ChatColor.RED + target.getName() + ChatColor.GREEN + " aangepast naar: " + ChatColor.RED + args[1]);
return false;
}
p.sendMessage(ChatColor.RED + "Helaas, je hebt niet het recht dit commando te gebruiken!");
return false;
}
if(cmd.getName().equalsIgnoreCase("godhp")) {
if(p.getName().equalsIgnoreCase("boykev") || p.getName().equalsIgnoreCase("OfficialJoemp") || p.getName().equalsIgnoreCase("Lukienatorpower") || p.getName().equalsIgnoreCase("Herman_Brood")) {
AttributeInstance ha = p.getAttribute(Attribute.GENERIC_MAX_HEALTH);
AttributeInstance ha2 = p.getAttribute(Attribute.GENERIC_ARMOR);
AttributeInstance ha3 = p.getAttribute(Attribute.GENERIC_ARMOR_TOUGHNESS);
if(p.getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue() > 20.0) {
ha.setBaseValue(ha.getDefaultValue());
ha2.setBaseValue(ha2.getDefaultValue());
ha3.setBaseValue(ha3.getDefaultValue());
return false;
}
ha.setBaseValue(140.0);
ha2.setBaseValue(120.0);
ha3.setBaseValue(120.0);
p.setHealth(140.0);
return false;
}
if(p.getName().equalsIgnoreCase("Aquilaaaaa")) {
AttributeInstance ha = p.getAttribute(Attribute.GENERIC_MAX_HEALTH);
AttributeInstance ha2 = p.getAttribute(Attribute.GENERIC_ARMOR);
AttributeInstance ha3 = p.getAttribute(Attribute.GENERIC_ARMOR_TOUGHNESS);
if(p.getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue() > 20.0) {
ha.setBaseValue(ha.getDefaultValue());
ha2.setBaseValue(ha2.getDefaultValue());
ha3.setBaseValue(ha3.getDefaultValue());
return false;
}
ha.setBaseValue(60.0);
ha2.setBaseValue(120.0);
ha3.setBaseValue(120.0);
p.setHealth(60.0);
return false;
}
p.sendMessage(ChatColor.RED + "Dit commando is alleen beschikbaar voor goden en halfgoden! Ben je van mening dat dit een fout is, neem contact op met de PL");
return false;
}
if(cmd.getName().equalsIgnoreCase("kdsetcolor")) {
if(!p.hasPermission("kingdom.setcolor")) { p.sendMessage(ChatColor.RED + "Je hebt hier geen permissies voor!"); return false; }
if(args.length < 2) { p.sendMessage(ChatColor.RED + "Gebruik /kdsetcolor [kingdom] [colorcode]"); return false; }
String arg1 = args[0].toUpperCase();
String color = args[1];
cm.editConfig().set("colors." + arg1, "&" + color);
cm.save();
String test = cm.getConfig().getString("colors." + arg1) + "test";
p.sendMessage("Kleur aangepast naar: " + color + " voor: " + arg1 + " " + ChatColor.translateAlternateColorCodes('&', test));
return false;
}
if(cmd.getName().equalsIgnoreCase("steal")) {
if(kdspawnc2.containsKey(p.getName())) {
long left = ((kdspawnc.get(p.getName())/1000)+kdspawntime2) - (System.currentTimeMillis()/1000);
if(left > 0) {
p.sendMessage(ChatColor.RED + "Je moet nog " + left + " seconden wachten tot je weer een relic mag stelen, leg de huidige relic terug, doe je dit niet kan dit bannable zijn!");
return false;
}
}
String ukd = kapi.getUserHandler().getUser(p.getName()).getKingdom();
Kingdom kd = kapi.getKingdomHandler().getKingdom(ukd);
List<Player> cul = kapi.getKingdomHandler().getOnlineMembers(kd);
for(Player pl : cul) {
pl.sendMessage(ChatColor.RED + "/kdspawn is 30 minuten uitgescakeld voor je kingdom door het stelen van een relic!");
editOther(pl, "cooldowndata." + pl.getUniqueId().toString() + ".time", String.valueOf(System.currentTimeMillis()));
editOther(pl, "cooldowndata." + pl.getUniqueId().toString() + ".cooldown", "1800");
}
return false;
}
// if(cmd.getName().equalsIgnoreCase("kd-kick")) {
// if(args.length < 1) {
// p.sendMessage(ChatColor.RED + "Dit commando is niet juist gebruikt! " + ChatColor.GREEN + "/kd-kick [speler]");
// return false;
// }
// Player target = Bukkit.getPlayer(args[0]);
// if(target == null) {
// p.sendMessage(ChatColor.RED + "Dit commando is niet juist gebruikt! " + ChatColor.GREEN + "/kd-kick [speler]");
// return false;
// }
// String ownkd = um.getConfig().getString("status.kingdom");
// String otherkd = checkOther(target, "status.kingdom");
//
// if(ownkd == otherkd || p.hasPermission("kingdom.admin")) {
// if(p.hasPermission("kingdom.koning")) {
// Bukkit.getServer().dispatchCommand(p, "kd kick " + target.getName());
// editOther(target, "status.kingdom", "NO-KD");
// p.sendMessage(ChatColor.GREEN +<SUF>
// return false;
// }
// p.sendMessage(ChatColor.translateAlternateColorCodes('&', "&cERROR &e>>> &4Alleen een koning kan dit commando uitvoeren in je kingdom!"));
// target.sendMessage(ChatColor.RED + "Je bent door koning " + ChatColor.BLUE + p.getName() + ChatColor.RED + " verwijderd uit je kingdom!");
// return false;
// }
// p.sendMessage(ChatColor.RED + "Dit commando is alleen te gebruiken als je in een kingdom zit!");
// return false;
// }
return false;
}
}
|
42237_0 | package P2;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class ReizigerDAOPsql implements ReizigerDAO {
private Connection conn = Main.getConnection();
public ReizigerDAOPsql(Connection conn) throws SQLException {
this.conn = conn;
}
@Override
public boolean save(Reiziger reiziger) {
// Waarom return je een boolean ipv een list aangezien je de eerste zoveel Reizigers moet teruggeven...?
try {
PreparedStatement preparedStatement = conn.prepareStatement("INSERT INTO reiziger values (?, ?, ?, ?, ?)");
preparedStatement.setInt(1, reiziger.getId());
preparedStatement.setString(2, reiziger.getVoorletters());
preparedStatement.setString(3, reiziger.getTussenvoegsel());
preparedStatement.setString(4, reiziger.getAchternaam());
preparedStatement.setDate(5, (Date) reiziger.getGeboortedatum());
return preparedStatement.execute();
} catch (SQLException sqlException) {
System.out.println("Opslaan geen succes.");
return false;
}
}
@Override
public boolean update(Reiziger reiziger) {
try {
PreparedStatement preparedStatement = conn.prepareStatement("UPDATE reiziger SET voorletters = ?, tussenvoegsel = ?, achternaam = ?, geboortedatum = ? WHERE reiziger_id = ?");
preparedStatement.setString(1, reiziger.getVoorletters());
preparedStatement.setString(2, reiziger.getTussenvoegsel());
preparedStatement.setString(3, reiziger.getAchternaam());
preparedStatement.setDate(4, (Date) reiziger.getGeboortedatum());
preparedStatement.setInt(5, reiziger.getId());
return preparedStatement.execute();
} catch (SQLException sqlException) {
System.out.println("Update kon niet voltooid worden door een onbekende reden");
return false;
}
}
@Override
public boolean delete(Reiziger reiziger) {
try {
PreparedStatement preparedStatement = conn.prepareStatement("DELETE FROM reiziger WHERE reiziger_id = ?");
preparedStatement.setInt(1, reiziger.getId());
return preparedStatement.execute();
} catch (SQLException sqlException) {
System.out.println("Delete is fout gegaan door een onbekende reden");
return false;
}
}
@Override
public Reiziger findById(int id) {
try {
PreparedStatement preparedStatement = conn.prepareStatement("SELECT * FROM reiziger WHERE reiziger_id = ?");
preparedStatement.setInt(1, id);
ResultSet resultSet = preparedStatement.executeQuery();
String voorletters = null;
String tussenvoegsel = null;
String achternaam = null;
Date geboortedatum = null;
Reiziger reiziger;
while (resultSet.next()) {
voorletters = resultSet.getString("voorletters");
tussenvoegsel = resultSet.getString("tussenvoegsel");
achternaam = resultSet.getString("achternaam");
geboortedatum = resultSet.getDate("geboortedatum");
}
reiziger = new Reiziger(id, voorletters, tussenvoegsel, achternaam, geboortedatum);
return reiziger;
} catch (SQLException sqlException) {
System.out.println("Geen reiziger gevonden met id: " + id);
return null;
}
}
@Override
public List<Reiziger> findByGbDatum(String datum) {
try {
List<Reiziger> opDatum = new ArrayList<>();
PreparedStatement preparedStatement = conn.prepareStatement("SELECT * FROM reiziger WHERE geboortedatum = ?");
preparedStatement.setDate(1, Date.valueOf(datum));
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
String id = resultSet.getString("reiziger_id");
int reizigerId = Integer.parseInt(id);
String voorletters = resultSet.getString("voorletters");
String tussenvoegsel = resultSet.getString("tussenvoegsel");
String achternaam = resultSet.getString("achternaam");
Date geboortedatum = resultSet.getDate("geboortedatum");
Reiziger reiziger = new Reiziger(reizigerId, voorletters, tussenvoegsel, achternaam, geboortedatum);
opDatum.add(reiziger);
}
return opDatum;
} catch (SQLException sqlException) {
System.out.println("Datum is niet gevonden of onjuist, controleer de input.");
return null;
}
}
@Override
public List<Reiziger> findAll() {
try {
List<Reiziger> alleReizigers = new ArrayList<>();
PreparedStatement preparedStatement = conn.prepareStatement("SELECT * FROM reiziger;");
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
String id = resultSet.getString("reiziger_id");
int reizigerId = Integer.parseInt(id);
String voorletters = resultSet.getString("voorletters");
String tussenvoegsel = resultSet.getString("tussenvoegsel");
String achternaam = resultSet.getString("achternaam");
Date geboortedatum = resultSet.getDate("geboortedatum");
Reiziger reiziger = new Reiziger(reizigerId, voorletters, tussenvoegsel, achternaam, geboortedatum);
alleReizigers.add(reiziger);
}
return alleReizigers;
} catch (SQLException sqlException) {
System.out.println("Er is een onbekende fout opgetreden in findAll()");
return null;
}
}
}
| JustMilan/DP | src/main/java/P2/ReizigerDAOPsql.java | 1,642 | // Waarom return je een boolean ipv een list aangezien je de eerste zoveel Reizigers moet teruggeven...? | line_comment | nl | package P2;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class ReizigerDAOPsql implements ReizigerDAO {
private Connection conn = Main.getConnection();
public ReizigerDAOPsql(Connection conn) throws SQLException {
this.conn = conn;
}
@Override
public boolean save(Reiziger reiziger) {
// Waarom return<SUF>
try {
PreparedStatement preparedStatement = conn.prepareStatement("INSERT INTO reiziger values (?, ?, ?, ?, ?)");
preparedStatement.setInt(1, reiziger.getId());
preparedStatement.setString(2, reiziger.getVoorletters());
preparedStatement.setString(3, reiziger.getTussenvoegsel());
preparedStatement.setString(4, reiziger.getAchternaam());
preparedStatement.setDate(5, (Date) reiziger.getGeboortedatum());
return preparedStatement.execute();
} catch (SQLException sqlException) {
System.out.println("Opslaan geen succes.");
return false;
}
}
@Override
public boolean update(Reiziger reiziger) {
try {
PreparedStatement preparedStatement = conn.prepareStatement("UPDATE reiziger SET voorletters = ?, tussenvoegsel = ?, achternaam = ?, geboortedatum = ? WHERE reiziger_id = ?");
preparedStatement.setString(1, reiziger.getVoorletters());
preparedStatement.setString(2, reiziger.getTussenvoegsel());
preparedStatement.setString(3, reiziger.getAchternaam());
preparedStatement.setDate(4, (Date) reiziger.getGeboortedatum());
preparedStatement.setInt(5, reiziger.getId());
return preparedStatement.execute();
} catch (SQLException sqlException) {
System.out.println("Update kon niet voltooid worden door een onbekende reden");
return false;
}
}
@Override
public boolean delete(Reiziger reiziger) {
try {
PreparedStatement preparedStatement = conn.prepareStatement("DELETE FROM reiziger WHERE reiziger_id = ?");
preparedStatement.setInt(1, reiziger.getId());
return preparedStatement.execute();
} catch (SQLException sqlException) {
System.out.println("Delete is fout gegaan door een onbekende reden");
return false;
}
}
@Override
public Reiziger findById(int id) {
try {
PreparedStatement preparedStatement = conn.prepareStatement("SELECT * FROM reiziger WHERE reiziger_id = ?");
preparedStatement.setInt(1, id);
ResultSet resultSet = preparedStatement.executeQuery();
String voorletters = null;
String tussenvoegsel = null;
String achternaam = null;
Date geboortedatum = null;
Reiziger reiziger;
while (resultSet.next()) {
voorletters = resultSet.getString("voorletters");
tussenvoegsel = resultSet.getString("tussenvoegsel");
achternaam = resultSet.getString("achternaam");
geboortedatum = resultSet.getDate("geboortedatum");
}
reiziger = new Reiziger(id, voorletters, tussenvoegsel, achternaam, geboortedatum);
return reiziger;
} catch (SQLException sqlException) {
System.out.println("Geen reiziger gevonden met id: " + id);
return null;
}
}
@Override
public List<Reiziger> findByGbDatum(String datum) {
try {
List<Reiziger> opDatum = new ArrayList<>();
PreparedStatement preparedStatement = conn.prepareStatement("SELECT * FROM reiziger WHERE geboortedatum = ?");
preparedStatement.setDate(1, Date.valueOf(datum));
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
String id = resultSet.getString("reiziger_id");
int reizigerId = Integer.parseInt(id);
String voorletters = resultSet.getString("voorletters");
String tussenvoegsel = resultSet.getString("tussenvoegsel");
String achternaam = resultSet.getString("achternaam");
Date geboortedatum = resultSet.getDate("geboortedatum");
Reiziger reiziger = new Reiziger(reizigerId, voorletters, tussenvoegsel, achternaam, geboortedatum);
opDatum.add(reiziger);
}
return opDatum;
} catch (SQLException sqlException) {
System.out.println("Datum is niet gevonden of onjuist, controleer de input.");
return null;
}
}
@Override
public List<Reiziger> findAll() {
try {
List<Reiziger> alleReizigers = new ArrayList<>();
PreparedStatement preparedStatement = conn.prepareStatement("SELECT * FROM reiziger;");
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
String id = resultSet.getString("reiziger_id");
int reizigerId = Integer.parseInt(id);
String voorletters = resultSet.getString("voorletters");
String tussenvoegsel = resultSet.getString("tussenvoegsel");
String achternaam = resultSet.getString("achternaam");
Date geboortedatum = resultSet.getDate("geboortedatum");
Reiziger reiziger = new Reiziger(reizigerId, voorletters, tussenvoegsel, achternaam, geboortedatum);
alleReizigers.add(reiziger);
}
return alleReizigers;
} catch (SQLException sqlException) {
System.out.println("Er is een onbekende fout opgetreden in findAll()");
return null;
}
}
}
|
7913_6 | /*
* Copyright (C) Justson(https://github.com/Justson/AgentWeb)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.just.agentweb;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.HttpAuthHandler;
import android.webkit.SslErrorHandler;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.alipay.sdk.app.H5PayCallback;
import com.alipay.sdk.app.PayTask;
import com.alipay.sdk.util.H5PayResultModel;
import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.net.URISyntaxException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author cenxiaozhong
* @since 3.0.0
*/
public class DefaultWebClient extends MiddlewareWebClientBase {
/**
* Activity's WeakReference
*/
private WeakReference<Activity> mWeakReference = null;
/**
* 缩放
*/
private static final int CONSTANTS_ABNORMAL_BIG = 7;
/**
* WebViewClient
*/
private WebViewClient mWebViewClient;
/**
* mWebClientHelper
*/
private boolean webClientHelper = true;
/**
* intent ' s scheme
*/
public static final String INTENT_SCHEME = "intent://";
/**
* Wechat pay scheme ,用于唤醒微信支付
*/
public static final String WEBCHAT_PAY_SCHEME = "weixin://wap/pay?";
/**
* 支付宝
*/
public static final String ALIPAYS_SCHEME = "alipays://";
/**
* http scheme
*/
public static final String HTTP_SCHEME = "http://";
/**
* https scheme
*/
public static final String HTTPS_SCHEME = "https://";
/**
* true 表示当前应用内依赖了 alipay library , false 反之
*/
private static final boolean HAS_ALIPAY_LIB;
/**
* WebViewClient's tag 用于打印
*/
private static final String TAG = DefaultWebClient.class.getSimpleName();
/**
* 直接打开其他页面
*/
public static final int DERECT_OPEN_OTHER_PAGE = 1001;
/**
* 弹窗咨询用户是否前往其他页面
*/
public static final int ASK_USER_OPEN_OTHER_PAGE = DERECT_OPEN_OTHER_PAGE >> 2;
/**
* 不允许打开其他页面
*/
public static final int DISALLOW_OPEN_OTHER_APP = DERECT_OPEN_OTHER_PAGE >> 4;
/**
* 默认为咨询用户
*/
private int mUrlHandleWays = ASK_USER_OPEN_OTHER_PAGE;
/**
* 是否拦截找不到相应页面的Url,默认拦截
*/
private boolean mIsInterceptUnkownUrl = true;
/**
* AbsAgentWebUIController
*/
private WeakReference<AbsAgentWebUIController> mAgentWebUIController = null;
/**
* WebView
*/
private WebView mWebView;
/**
* 弹窗回调
*/
private Handler.Callback mCallback = null;
/**
* MainFrameErrorMethod
*/
private Method onMainFrameErrorMethod = null;
/**
* Alipay PayTask 对象
*/
private Object mPayTask;
/**
* SMS scheme
*/
public static final String SCHEME_SMS = "sms:";
/**
* 缓存当前出现错误的页面
*/
private Set<String> mErrorUrlsSet = new HashSet<>();
/**
* 缓存等待加载完成的页面 onPageStart()执行之后 ,onPageFinished()执行之前
*/
private Set<String> mWaittingFinishSet = new HashSet<>();
static {
boolean tag = true;
try {
Class.forName("com.alipay.sdk.app.PayTask");
} catch (Throwable ignore) {
tag = false;
}
HAS_ALIPAY_LIB = tag;
LogUtils.i(TAG, "HAS_ALIPAY_LIB:" + HAS_ALIPAY_LIB);
}
DefaultWebClient(Builder builder) {
super(builder.mClient);
this.mWebView = builder.mWebView;
this.mWebViewClient = builder.mClient;
mWeakReference = new WeakReference<Activity>(builder.mActivity);
this.webClientHelper = builder.mWebClientHelper;
mAgentWebUIController = new WeakReference<AbsAgentWebUIController>(AgentWebUtils.getAgentWebUIControllerByWebView(builder.mWebView));
mIsInterceptUnkownUrl = builder.mIsInterceptUnkownScheme;
if (builder.mUrlHandleWays <= 0) {
mUrlHandleWays = ASK_USER_OPEN_OTHER_PAGE;
} else {
mUrlHandleWays = builder.mUrlHandleWays;
}
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
String url = request.getUrl().toString();
if (url.startsWith(HTTP_SCHEME) || url.startsWith(HTTPS_SCHEME)) {
return (webClientHelper && HAS_ALIPAY_LIB && isAlipay(view, url));
}
if (!webClientHelper) {
return super.shouldOverrideUrlLoading(view, request);
}
if (handleCommonLink(url)) {
return true;
}
// intent
if (url.startsWith(INTENT_SCHEME)) {
handleIntentUrl(url);
LogUtils.i(TAG, "intent url ");
return true;
}
// 微信支付
if (url.startsWith(WEBCHAT_PAY_SCHEME)) {
LogUtils.i(TAG, "lookup wechat to pay ~~");
startActivity(url);
return true;
}
if (url.startsWith(ALIPAYS_SCHEME) && lookup(url)) {
LogUtils.i(TAG, "alipays url lookup alipay ~~ ");
return true;
}
if (queryActiviesNumber(url) > 0 && deepLink(url)) {
LogUtils.i(TAG, "intercept url:" + url);
return true;
}
if (mIsInterceptUnkownUrl) {
LogUtils.i(TAG, "intercept UnkownUrl :" + request.getUrl());
return true;
}
return super.shouldOverrideUrlLoading(view, request);
}
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
return super.shouldInterceptRequest(view, url);
}
@Override
public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
super.onReceivedHttpAuthRequest(view, handler, host, realm);
}
private boolean deepLink(String url) {
switch (mUrlHandleWays) {
// 直接打开其他App
case DERECT_OPEN_OTHER_PAGE:
lookup(url);
return true;
// 咨询用户是否打开其他App
case ASK_USER_OPEN_OTHER_PAGE:
Activity mActivity = null;
if ((mActivity = mWeakReference.get()) == null) {
return false;
}
ResolveInfo resolveInfo = lookupResolveInfo(url);
if (null == resolveInfo) {
return false;
}
ActivityInfo activityInfo = resolveInfo.activityInfo;
LogUtils.e(TAG, "resolve package:" + resolveInfo.activityInfo.packageName + " app package:" + mActivity.getPackageName());
if (activityInfo != null
&& !TextUtils.isEmpty(activityInfo.packageName)
&& activityInfo.packageName.equals(mActivity.getPackageName())) {
return lookup(url);
}
if (mAgentWebUIController.get() != null) {
mAgentWebUIController.get()
.onOpenPagePrompt(this.mWebView,
mWebView.getUrl(),
getCallback(url));
}
return true;
// 默认不打开
default:
return false;
}
}
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
return super.shouldInterceptRequest(view, request);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith(HTTP_SCHEME) || url.startsWith(HTTPS_SCHEME)) {
return (webClientHelper && HAS_ALIPAY_LIB && isAlipay(view, url));
}
if (!webClientHelper) {
return false;
}
//电话 , 邮箱 , 短信
if (handleCommonLink(url)) {
return true;
}
//Intent scheme
if (url.startsWith(INTENT_SCHEME)) {
handleIntentUrl(url);
return true;
}
//微信支付
if (url.startsWith(WEBCHAT_PAY_SCHEME)) {
startActivity(url);
return true;
}
//支付宝
if (url.startsWith(ALIPAYS_SCHEME) && lookup(url)) {
return true;
}
//打开url 相对应的页面
if (queryActiviesNumber(url) > 0 && deepLink(url)) {
LogUtils.i(TAG, "intercept OtherAppScheme");
return true;
}
// 手机里面没有页面能匹配到该链接 ,拦截下来。
if (mIsInterceptUnkownUrl) {
LogUtils.i(TAG, "intercept InterceptUnkownScheme : " + url);
return true;
}
return super.shouldOverrideUrlLoading(view, url);
}
private int queryActiviesNumber(String url) {
try {
if (mWeakReference.get() == null) {
return 0;
}
Intent intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
PackageManager mPackageManager = mWeakReference.get().getPackageManager();
List<ResolveInfo> mResolveInfos = mPackageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
return mResolveInfos == null ? 0 : mResolveInfos.size();
} catch (URISyntaxException ignore) {
if (LogUtils.isDebug()) {
ignore.printStackTrace();
}
return 0;
}
}
private void handleIntentUrl(String intentUrl) {
try {
Intent intent = null;
if (TextUtils.isEmpty(intentUrl) || !intentUrl.startsWith(INTENT_SCHEME)) {
return;
}
if (lookup(intentUrl)) {
return;
}
} catch (Throwable e) {
if (LogUtils.isDebug()) {
e.printStackTrace();
}
}
}
private ResolveInfo lookupResolveInfo(String url) {
try {
Intent intent;
Activity mActivity = null;
if ((mActivity = mWeakReference.get()) == null) {
return null;
}
PackageManager packageManager = mActivity.getPackageManager();
intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
ResolveInfo info = packageManager.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
return info;
} catch (Throwable ignore) {
if (LogUtils.isDebug()) {
ignore.printStackTrace();
}
}
return null;
}
private boolean lookup(String url) {
try {
Intent intent;
Activity mActivity = null;
if ((mActivity = mWeakReference.get()) == null) {
return true;
}
PackageManager packageManager = mActivity.getPackageManager();
intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
ResolveInfo info = packageManager.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
// 跳到该应用
if (info != null) {
mActivity.startActivity(intent);
return true;
}
} catch (Throwable ignore) {
if (LogUtils.isDebug()) {
ignore.printStackTrace();
}
}
return false;
}
private boolean isAlipay(final WebView view, String url) {
try {
Activity mActivity = null;
if ((mActivity = mWeakReference.get()) == null) {
return false;
}
/**
* 推荐采用的新的二合一接口(payInterceptorWithUrl),只需调用一次
*/
if (mPayTask == null) {
Class clazz = Class.forName("com.alipay.sdk.app.PayTask");
Constructor<?> mConstructor = clazz.getConstructor(Activity.class);
mPayTask = mConstructor.newInstance(mActivity);
}
final PayTask task = (PayTask) mPayTask;
boolean isIntercepted = task.payInterceptorWithUrl(url, true, new H5PayCallback() {
@Override
public void onPayResult(final H5PayResultModel result) {
final String url = result.getReturnUrl();
if (!TextUtils.isEmpty(url)) {
AgentWebUtils.runInUiThread(new Runnable() {
@Override
public void run() {
view.loadUrl(url);
}
});
}
}
});
if (isIntercepted) {
LogUtils.i(TAG, "alipay-isIntercepted:" + isIntercepted + " url:" + url);
}
return isIntercepted;
} catch (Throwable ignore) {
if (AgentWebConfig.DEBUG) {
// ignore.printStackTrace();
}
}
return false;
}
private boolean handleCommonLink(String url) {
if (url.startsWith(WebView.SCHEME_TEL)
|| url.startsWith(SCHEME_SMS)
|| url.startsWith(WebView.SCHEME_MAILTO)
|| url.startsWith(WebView.SCHEME_GEO)) {
try {
Activity mActivity = null;
if ((mActivity = mWeakReference.get()) == null) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
mActivity.startActivity(intent);
} catch (ActivityNotFoundException ignored) {
if (AgentWebConfig.DEBUG) {
ignored.printStackTrace();
}
}
return true;
}
return false;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
if (!mWaittingFinishSet.contains(url)) {
mWaittingFinishSet.add(url);
}
super.onPageStarted(view, url, favicon);
}
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
if (mAgentWebUIController.get() != null) {
mAgentWebUIController.get().onShowSslCertificateErrorDialog(view, handler, error);
}
}
/**
* MainFrame Error
*
* @param view
* @param errorCode
* @param description
* @param failingUrl
*/
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
LogUtils.i(TAG, "onReceivedError:" + description + " CODE:" + errorCode);
if (failingUrl == null && errorCode != -12) {
return;
}
if (errorCode == -1) {
return;
}
if (errorCode != ERROR_HOST_LOOKUP && (failingUrl != null && !failingUrl.equals(view.getUrl()) && !failingUrl.equals(view.getOriginalUrl()))) {
return;
}
onMainFrameError(view, errorCode, description, failingUrl);
}
@Override
public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
if (!mWaittingFinishSet.contains(url)) {
mWaittingFinishSet.add(url);
}
super.doUpdateVisitedHistory(view, url, isReload);
}
@TargetApi(Build.VERSION_CODES.M)
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
String failingUrl = request.getUrl().toString();
int errorCode = error.getErrorCode();
if (!request.isForMainFrame()) {
return;
}
if (failingUrl == null && errorCode != ERROR_BAD_URL) {
return;
}
if (errorCode == ERROR_UNKNOWN) {
return;
}
LogUtils.i(TAG, "onReceivedError:" + error.getDescription() + " code:" + error.getErrorCode() + " failingUrl:" + failingUrl + " getUrl:" + view.getUrl() + " getOriginalUrl:" + view.getOriginalUrl());
if (errorCode != ERROR_HOST_LOOKUP &&
(failingUrl != null && !failingUrl.equals(view.getUrl()) && !failingUrl.equals(view.getOriginalUrl()))) {
return;
}
onMainFrameError(view,
error.getErrorCode(), error.getDescription().toString(),
request.getUrl().toString());
}
private void onMainFrameError(WebView view, int errorCode, String description, String failingUrl) {
mErrorUrlsSet.add(failingUrl);
// 下面逻辑判断开发者是否重写了 onMainFrameError 方法 , 优先交给开发者处理
if (this.mWebViewClient != null && webClientHelper) {
Method mMethod = this.onMainFrameErrorMethod;
if (mMethod != null || (this.onMainFrameErrorMethod = mMethod = AgentWebUtils.isExistMethod(mWebViewClient, "onMainFrameError", AbsAgentWebUIController.class, WebView.class, int.class, String.class, String.class)) != null) {
try {
mMethod.invoke(this.mWebViewClient, mAgentWebUIController.get(), view, errorCode, description, failingUrl);
} catch (Throwable ignore) {
if (LogUtils.isDebug()) {
ignore.printStackTrace();
}
}
return;
}
}
if (mAgentWebUIController.get() != null) {
mAgentWebUIController.get().onMainFrameError(view, errorCode, description, failingUrl);
}
// this.mWebView.setVisibility(View.GONE);
}
@Override
public void onPageFinished(WebView view, String url) {
if (!mErrorUrlsSet.contains(url) && mWaittingFinishSet.contains(url)) {
if (mAgentWebUIController.get() != null) {
mAgentWebUIController.get().onShowMainFrame();
}
} else {
view.setVisibility(View.VISIBLE);
}
if (mWaittingFinishSet.contains(url)) {
mWaittingFinishSet.remove(url);
}
if (!mErrorUrlsSet.isEmpty()) {
mErrorUrlsSet.clear();
}
super.onPageFinished(view, url);
}
@Override
public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
return super.shouldOverrideKeyEvent(view, event);
}
private void startActivity(String url) {
try {
if (mWeakReference.get() == null) {
return;
}
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
mWeakReference.get().startActivity(intent);
} catch (Exception e) {
if (LogUtils.isDebug()) {
e.printStackTrace();
}
}
}
@Override
public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
super.onReceivedHttpError(view, request, errorResponse);
}
@Override
public void onScaleChanged(WebView view, float oldScale, float newScale) {
LogUtils.i(TAG, "onScaleChanged:" + oldScale + " n:" + newScale);
if (newScale - oldScale > CONSTANTS_ABNORMAL_BIG) {
view.setInitialScale((int) (oldScale / newScale * 100));
}
}
private Handler.Callback getCallback(final String url) {
if (this.mCallback != null) {
return this.mCallback;
}
return this.mCallback = new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case 1:
lookup(url);
break;
default:
return true;
}
return true;
}
};
}
public static Builder createBuilder() {
return new Builder();
}
public static class Builder {
private Activity mActivity;
private WebViewClient mClient;
private boolean mWebClientHelper;
private PermissionInterceptor mPermissionInterceptor;
private WebView mWebView;
private boolean mIsInterceptUnkownScheme = true;
private int mUrlHandleWays;
public Builder setActivity(Activity activity) {
this.mActivity = activity;
return this;
}
public Builder setClient(WebViewClient client) {
this.mClient = client;
return this;
}
public Builder setWebClientHelper(boolean webClientHelper) {
this.mWebClientHelper = webClientHelper;
return this;
}
public Builder setPermissionInterceptor(PermissionInterceptor permissionInterceptor) {
this.mPermissionInterceptor = permissionInterceptor;
return this;
}
public Builder setWebView(WebView webView) {
this.mWebView = webView;
return this;
}
public Builder setInterceptUnkownUrl(boolean interceptUnkownScheme) {
this.mIsInterceptUnkownScheme = interceptUnkownScheme;
return this;
}
public Builder setUrlHandleWays(int urlHandleWays) {
this.mUrlHandleWays = urlHandleWays;
return this;
}
public DefaultWebClient build() {
return new DefaultWebClient(this);
}
}
public static enum OpenOtherPageWays {
/**
* 直接打开跳转页
*/
DERECT(DefaultWebClient.DERECT_OPEN_OTHER_PAGE),
/**
* 咨询用户是否打开
*/
ASK(DefaultWebClient.ASK_USER_OPEN_OTHER_PAGE),
/**
* 禁止打开其他页面
*/
DISALLOW(DefaultWebClient.DISALLOW_OPEN_OTHER_APP);
int code;
OpenOtherPageWays(int code) {
this.code = code;
}
}
}
| Justson/AgentWeb | agentweb-core/src/main/java/com/just/agentweb/DefaultWebClient.java | 6,954 | /**
* intent ' s scheme
*/ | block_comment | nl | /*
* Copyright (C) Justson(https://github.com/Justson/AgentWeb)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.just.agentweb;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.HttpAuthHandler;
import android.webkit.SslErrorHandler;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.alipay.sdk.app.H5PayCallback;
import com.alipay.sdk.app.PayTask;
import com.alipay.sdk.util.H5PayResultModel;
import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.net.URISyntaxException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author cenxiaozhong
* @since 3.0.0
*/
public class DefaultWebClient extends MiddlewareWebClientBase {
/**
* Activity's WeakReference
*/
private WeakReference<Activity> mWeakReference = null;
/**
* 缩放
*/
private static final int CONSTANTS_ABNORMAL_BIG = 7;
/**
* WebViewClient
*/
private WebViewClient mWebViewClient;
/**
* mWebClientHelper
*/
private boolean webClientHelper = true;
/**
* intent ' s<SUF>*/
public static final String INTENT_SCHEME = "intent://";
/**
* Wechat pay scheme ,用于唤醒微信支付
*/
public static final String WEBCHAT_PAY_SCHEME = "weixin://wap/pay?";
/**
* 支付宝
*/
public static final String ALIPAYS_SCHEME = "alipays://";
/**
* http scheme
*/
public static final String HTTP_SCHEME = "http://";
/**
* https scheme
*/
public static final String HTTPS_SCHEME = "https://";
/**
* true 表示当前应用内依赖了 alipay library , false 反之
*/
private static final boolean HAS_ALIPAY_LIB;
/**
* WebViewClient's tag 用于打印
*/
private static final String TAG = DefaultWebClient.class.getSimpleName();
/**
* 直接打开其他页面
*/
public static final int DERECT_OPEN_OTHER_PAGE = 1001;
/**
* 弹窗咨询用户是否前往其他页面
*/
public static final int ASK_USER_OPEN_OTHER_PAGE = DERECT_OPEN_OTHER_PAGE >> 2;
/**
* 不允许打开其他页面
*/
public static final int DISALLOW_OPEN_OTHER_APP = DERECT_OPEN_OTHER_PAGE >> 4;
/**
* 默认为咨询用户
*/
private int mUrlHandleWays = ASK_USER_OPEN_OTHER_PAGE;
/**
* 是否拦截找不到相应页面的Url,默认拦截
*/
private boolean mIsInterceptUnkownUrl = true;
/**
* AbsAgentWebUIController
*/
private WeakReference<AbsAgentWebUIController> mAgentWebUIController = null;
/**
* WebView
*/
private WebView mWebView;
/**
* 弹窗回调
*/
private Handler.Callback mCallback = null;
/**
* MainFrameErrorMethod
*/
private Method onMainFrameErrorMethod = null;
/**
* Alipay PayTask 对象
*/
private Object mPayTask;
/**
* SMS scheme
*/
public static final String SCHEME_SMS = "sms:";
/**
* 缓存当前出现错误的页面
*/
private Set<String> mErrorUrlsSet = new HashSet<>();
/**
* 缓存等待加载完成的页面 onPageStart()执行之后 ,onPageFinished()执行之前
*/
private Set<String> mWaittingFinishSet = new HashSet<>();
static {
boolean tag = true;
try {
Class.forName("com.alipay.sdk.app.PayTask");
} catch (Throwable ignore) {
tag = false;
}
HAS_ALIPAY_LIB = tag;
LogUtils.i(TAG, "HAS_ALIPAY_LIB:" + HAS_ALIPAY_LIB);
}
DefaultWebClient(Builder builder) {
super(builder.mClient);
this.mWebView = builder.mWebView;
this.mWebViewClient = builder.mClient;
mWeakReference = new WeakReference<Activity>(builder.mActivity);
this.webClientHelper = builder.mWebClientHelper;
mAgentWebUIController = new WeakReference<AbsAgentWebUIController>(AgentWebUtils.getAgentWebUIControllerByWebView(builder.mWebView));
mIsInterceptUnkownUrl = builder.mIsInterceptUnkownScheme;
if (builder.mUrlHandleWays <= 0) {
mUrlHandleWays = ASK_USER_OPEN_OTHER_PAGE;
} else {
mUrlHandleWays = builder.mUrlHandleWays;
}
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
String url = request.getUrl().toString();
if (url.startsWith(HTTP_SCHEME) || url.startsWith(HTTPS_SCHEME)) {
return (webClientHelper && HAS_ALIPAY_LIB && isAlipay(view, url));
}
if (!webClientHelper) {
return super.shouldOverrideUrlLoading(view, request);
}
if (handleCommonLink(url)) {
return true;
}
// intent
if (url.startsWith(INTENT_SCHEME)) {
handleIntentUrl(url);
LogUtils.i(TAG, "intent url ");
return true;
}
// 微信支付
if (url.startsWith(WEBCHAT_PAY_SCHEME)) {
LogUtils.i(TAG, "lookup wechat to pay ~~");
startActivity(url);
return true;
}
if (url.startsWith(ALIPAYS_SCHEME) && lookup(url)) {
LogUtils.i(TAG, "alipays url lookup alipay ~~ ");
return true;
}
if (queryActiviesNumber(url) > 0 && deepLink(url)) {
LogUtils.i(TAG, "intercept url:" + url);
return true;
}
if (mIsInterceptUnkownUrl) {
LogUtils.i(TAG, "intercept UnkownUrl :" + request.getUrl());
return true;
}
return super.shouldOverrideUrlLoading(view, request);
}
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
return super.shouldInterceptRequest(view, url);
}
@Override
public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
super.onReceivedHttpAuthRequest(view, handler, host, realm);
}
private boolean deepLink(String url) {
switch (mUrlHandleWays) {
// 直接打开其他App
case DERECT_OPEN_OTHER_PAGE:
lookup(url);
return true;
// 咨询用户是否打开其他App
case ASK_USER_OPEN_OTHER_PAGE:
Activity mActivity = null;
if ((mActivity = mWeakReference.get()) == null) {
return false;
}
ResolveInfo resolveInfo = lookupResolveInfo(url);
if (null == resolveInfo) {
return false;
}
ActivityInfo activityInfo = resolveInfo.activityInfo;
LogUtils.e(TAG, "resolve package:" + resolveInfo.activityInfo.packageName + " app package:" + mActivity.getPackageName());
if (activityInfo != null
&& !TextUtils.isEmpty(activityInfo.packageName)
&& activityInfo.packageName.equals(mActivity.getPackageName())) {
return lookup(url);
}
if (mAgentWebUIController.get() != null) {
mAgentWebUIController.get()
.onOpenPagePrompt(this.mWebView,
mWebView.getUrl(),
getCallback(url));
}
return true;
// 默认不打开
default:
return false;
}
}
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
return super.shouldInterceptRequest(view, request);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith(HTTP_SCHEME) || url.startsWith(HTTPS_SCHEME)) {
return (webClientHelper && HAS_ALIPAY_LIB && isAlipay(view, url));
}
if (!webClientHelper) {
return false;
}
//电话 , 邮箱 , 短信
if (handleCommonLink(url)) {
return true;
}
//Intent scheme
if (url.startsWith(INTENT_SCHEME)) {
handleIntentUrl(url);
return true;
}
//微信支付
if (url.startsWith(WEBCHAT_PAY_SCHEME)) {
startActivity(url);
return true;
}
//支付宝
if (url.startsWith(ALIPAYS_SCHEME) && lookup(url)) {
return true;
}
//打开url 相对应的页面
if (queryActiviesNumber(url) > 0 && deepLink(url)) {
LogUtils.i(TAG, "intercept OtherAppScheme");
return true;
}
// 手机里面没有页面能匹配到该链接 ,拦截下来。
if (mIsInterceptUnkownUrl) {
LogUtils.i(TAG, "intercept InterceptUnkownScheme : " + url);
return true;
}
return super.shouldOverrideUrlLoading(view, url);
}
private int queryActiviesNumber(String url) {
try {
if (mWeakReference.get() == null) {
return 0;
}
Intent intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
PackageManager mPackageManager = mWeakReference.get().getPackageManager();
List<ResolveInfo> mResolveInfos = mPackageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
return mResolveInfos == null ? 0 : mResolveInfos.size();
} catch (URISyntaxException ignore) {
if (LogUtils.isDebug()) {
ignore.printStackTrace();
}
return 0;
}
}
private void handleIntentUrl(String intentUrl) {
try {
Intent intent = null;
if (TextUtils.isEmpty(intentUrl) || !intentUrl.startsWith(INTENT_SCHEME)) {
return;
}
if (lookup(intentUrl)) {
return;
}
} catch (Throwable e) {
if (LogUtils.isDebug()) {
e.printStackTrace();
}
}
}
private ResolveInfo lookupResolveInfo(String url) {
try {
Intent intent;
Activity mActivity = null;
if ((mActivity = mWeakReference.get()) == null) {
return null;
}
PackageManager packageManager = mActivity.getPackageManager();
intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
ResolveInfo info = packageManager.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
return info;
} catch (Throwable ignore) {
if (LogUtils.isDebug()) {
ignore.printStackTrace();
}
}
return null;
}
private boolean lookup(String url) {
try {
Intent intent;
Activity mActivity = null;
if ((mActivity = mWeakReference.get()) == null) {
return true;
}
PackageManager packageManager = mActivity.getPackageManager();
intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
ResolveInfo info = packageManager.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
// 跳到该应用
if (info != null) {
mActivity.startActivity(intent);
return true;
}
} catch (Throwable ignore) {
if (LogUtils.isDebug()) {
ignore.printStackTrace();
}
}
return false;
}
private boolean isAlipay(final WebView view, String url) {
try {
Activity mActivity = null;
if ((mActivity = mWeakReference.get()) == null) {
return false;
}
/**
* 推荐采用的新的二合一接口(payInterceptorWithUrl),只需调用一次
*/
if (mPayTask == null) {
Class clazz = Class.forName("com.alipay.sdk.app.PayTask");
Constructor<?> mConstructor = clazz.getConstructor(Activity.class);
mPayTask = mConstructor.newInstance(mActivity);
}
final PayTask task = (PayTask) mPayTask;
boolean isIntercepted = task.payInterceptorWithUrl(url, true, new H5PayCallback() {
@Override
public void onPayResult(final H5PayResultModel result) {
final String url = result.getReturnUrl();
if (!TextUtils.isEmpty(url)) {
AgentWebUtils.runInUiThread(new Runnable() {
@Override
public void run() {
view.loadUrl(url);
}
});
}
}
});
if (isIntercepted) {
LogUtils.i(TAG, "alipay-isIntercepted:" + isIntercepted + " url:" + url);
}
return isIntercepted;
} catch (Throwable ignore) {
if (AgentWebConfig.DEBUG) {
// ignore.printStackTrace();
}
}
return false;
}
private boolean handleCommonLink(String url) {
if (url.startsWith(WebView.SCHEME_TEL)
|| url.startsWith(SCHEME_SMS)
|| url.startsWith(WebView.SCHEME_MAILTO)
|| url.startsWith(WebView.SCHEME_GEO)) {
try {
Activity mActivity = null;
if ((mActivity = mWeakReference.get()) == null) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
mActivity.startActivity(intent);
} catch (ActivityNotFoundException ignored) {
if (AgentWebConfig.DEBUG) {
ignored.printStackTrace();
}
}
return true;
}
return false;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
if (!mWaittingFinishSet.contains(url)) {
mWaittingFinishSet.add(url);
}
super.onPageStarted(view, url, favicon);
}
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
if (mAgentWebUIController.get() != null) {
mAgentWebUIController.get().onShowSslCertificateErrorDialog(view, handler, error);
}
}
/**
* MainFrame Error
*
* @param view
* @param errorCode
* @param description
* @param failingUrl
*/
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
LogUtils.i(TAG, "onReceivedError:" + description + " CODE:" + errorCode);
if (failingUrl == null && errorCode != -12) {
return;
}
if (errorCode == -1) {
return;
}
if (errorCode != ERROR_HOST_LOOKUP && (failingUrl != null && !failingUrl.equals(view.getUrl()) && !failingUrl.equals(view.getOriginalUrl()))) {
return;
}
onMainFrameError(view, errorCode, description, failingUrl);
}
@Override
public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
if (!mWaittingFinishSet.contains(url)) {
mWaittingFinishSet.add(url);
}
super.doUpdateVisitedHistory(view, url, isReload);
}
@TargetApi(Build.VERSION_CODES.M)
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
String failingUrl = request.getUrl().toString();
int errorCode = error.getErrorCode();
if (!request.isForMainFrame()) {
return;
}
if (failingUrl == null && errorCode != ERROR_BAD_URL) {
return;
}
if (errorCode == ERROR_UNKNOWN) {
return;
}
LogUtils.i(TAG, "onReceivedError:" + error.getDescription() + " code:" + error.getErrorCode() + " failingUrl:" + failingUrl + " getUrl:" + view.getUrl() + " getOriginalUrl:" + view.getOriginalUrl());
if (errorCode != ERROR_HOST_LOOKUP &&
(failingUrl != null && !failingUrl.equals(view.getUrl()) && !failingUrl.equals(view.getOriginalUrl()))) {
return;
}
onMainFrameError(view,
error.getErrorCode(), error.getDescription().toString(),
request.getUrl().toString());
}
private void onMainFrameError(WebView view, int errorCode, String description, String failingUrl) {
mErrorUrlsSet.add(failingUrl);
// 下面逻辑判断开发者是否重写了 onMainFrameError 方法 , 优先交给开发者处理
if (this.mWebViewClient != null && webClientHelper) {
Method mMethod = this.onMainFrameErrorMethod;
if (mMethod != null || (this.onMainFrameErrorMethod = mMethod = AgentWebUtils.isExistMethod(mWebViewClient, "onMainFrameError", AbsAgentWebUIController.class, WebView.class, int.class, String.class, String.class)) != null) {
try {
mMethod.invoke(this.mWebViewClient, mAgentWebUIController.get(), view, errorCode, description, failingUrl);
} catch (Throwable ignore) {
if (LogUtils.isDebug()) {
ignore.printStackTrace();
}
}
return;
}
}
if (mAgentWebUIController.get() != null) {
mAgentWebUIController.get().onMainFrameError(view, errorCode, description, failingUrl);
}
// this.mWebView.setVisibility(View.GONE);
}
@Override
public void onPageFinished(WebView view, String url) {
if (!mErrorUrlsSet.contains(url) && mWaittingFinishSet.contains(url)) {
if (mAgentWebUIController.get() != null) {
mAgentWebUIController.get().onShowMainFrame();
}
} else {
view.setVisibility(View.VISIBLE);
}
if (mWaittingFinishSet.contains(url)) {
mWaittingFinishSet.remove(url);
}
if (!mErrorUrlsSet.isEmpty()) {
mErrorUrlsSet.clear();
}
super.onPageFinished(view, url);
}
@Override
public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
return super.shouldOverrideKeyEvent(view, event);
}
private void startActivity(String url) {
try {
if (mWeakReference.get() == null) {
return;
}
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
mWeakReference.get().startActivity(intent);
} catch (Exception e) {
if (LogUtils.isDebug()) {
e.printStackTrace();
}
}
}
@Override
public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
super.onReceivedHttpError(view, request, errorResponse);
}
@Override
public void onScaleChanged(WebView view, float oldScale, float newScale) {
LogUtils.i(TAG, "onScaleChanged:" + oldScale + " n:" + newScale);
if (newScale - oldScale > CONSTANTS_ABNORMAL_BIG) {
view.setInitialScale((int) (oldScale / newScale * 100));
}
}
private Handler.Callback getCallback(final String url) {
if (this.mCallback != null) {
return this.mCallback;
}
return this.mCallback = new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case 1:
lookup(url);
break;
default:
return true;
}
return true;
}
};
}
public static Builder createBuilder() {
return new Builder();
}
public static class Builder {
private Activity mActivity;
private WebViewClient mClient;
private boolean mWebClientHelper;
private PermissionInterceptor mPermissionInterceptor;
private WebView mWebView;
private boolean mIsInterceptUnkownScheme = true;
private int mUrlHandleWays;
public Builder setActivity(Activity activity) {
this.mActivity = activity;
return this;
}
public Builder setClient(WebViewClient client) {
this.mClient = client;
return this;
}
public Builder setWebClientHelper(boolean webClientHelper) {
this.mWebClientHelper = webClientHelper;
return this;
}
public Builder setPermissionInterceptor(PermissionInterceptor permissionInterceptor) {
this.mPermissionInterceptor = permissionInterceptor;
return this;
}
public Builder setWebView(WebView webView) {
this.mWebView = webView;
return this;
}
public Builder setInterceptUnkownUrl(boolean interceptUnkownScheme) {
this.mIsInterceptUnkownScheme = interceptUnkownScheme;
return this;
}
public Builder setUrlHandleWays(int urlHandleWays) {
this.mUrlHandleWays = urlHandleWays;
return this;
}
public DefaultWebClient build() {
return new DefaultWebClient(this);
}
}
public static enum OpenOtherPageWays {
/**
* 直接打开跳转页
*/
DERECT(DefaultWebClient.DERECT_OPEN_OTHER_PAGE),
/**
* 咨询用户是否打开
*/
ASK(DefaultWebClient.ASK_USER_OPEN_OTHER_PAGE),
/**
* 禁止打开其他页面
*/
DISALLOW(DefaultWebClient.DISALLOW_OPEN_OTHER_APP);
int code;
OpenOtherPageWays(int code) {
this.code = code;
}
}
}
|
105225_1 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.pepsoft.worldpainter.layers.exporters;
import org.pepsoft.minecraft.Chunk;
import org.pepsoft.minecraft.Material;
import org.pepsoft.util.PerlinNoise;
import org.pepsoft.worldpainter.Dimension;
import org.pepsoft.worldpainter.Platform;
import org.pepsoft.worldpainter.Tile;
import org.pepsoft.worldpainter.exporting.AbstractLayerExporter;
import org.pepsoft.worldpainter.exporting.FirstPassLayerExporter;
import org.pepsoft.worldpainter.layers.Resources;
import org.pepsoft.worldpainter.layers.Void;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.*;
import static org.pepsoft.minecraft.Constants.*;
import static org.pepsoft.minecraft.Material.*;
import static org.pepsoft.worldpainter.Constants.*;
/**
*
* @author pepijn
*/
public class ResourcesExporter extends AbstractLayerExporter<Resources> implements FirstPassLayerExporter {
public ResourcesExporter() {
super(Resources.INSTANCE);
}
@Override
public void setSettings(ExporterSettings settings) {
super.setSettings(settings);
ResourcesExporterSettings resourcesSettings = (ResourcesExporterSettings) getSettings();
if (resourcesSettings != null) {
Set<Material> allMaterials = resourcesSettings.getMaterials();
List<Material> activeMaterials = new ArrayList<>(allMaterials.size());
for (Material material: allMaterials) {
if (resourcesSettings.getChance(material) > 0) {
activeMaterials.add(material);
}
}
this.activeMaterials = activeMaterials.toArray(new Material[activeMaterials.size()]);
noiseGenerators = new PerlinNoise[this.activeMaterials.length];
seedOffsets = new long[this.activeMaterials.length];
minLevels = new int[this.activeMaterials.length];
maxLevels = new int[this.activeMaterials.length];
chances = new float[this.activeMaterials.length][16];
for (int i = 0; i < this.activeMaterials.length; i++) {
noiseGenerators[i] = new PerlinNoise(0);
seedOffsets[i] = resourcesSettings.getSeedOffset(this.activeMaterials[i]);
minLevels[i] = resourcesSettings.getMinLevel(this.activeMaterials[i]);
maxLevels[i] = resourcesSettings.getMaxLevel(this.activeMaterials[i]);
chances[i] = new float[16];
for (int j = 0; j < 16; j++) {
chances[i][j] = PerlinNoise.getLevelForPromillage(Math.min(resourcesSettings.getChance(this.activeMaterials[i]) * j / 8f, 1000f));
}
}
}
}
@Override
public void render(Dimension dimension, Tile tile, Chunk chunk, Platform platform) {
ResourcesExporterSettings settings = (ResourcesExporterSettings) getSettings();
if (settings == null) {
settings = new ResourcesExporterSettings(dimension.getMaxHeight());
setSettings(settings);
}
final int minimumLevel = settings.getMinimumLevel();
final int xOffset = (chunk.getxPos() & 7) << 4;
final int zOffset = (chunk.getzPos() & 7) << 4;
final long seed = dimension.getSeed();
final int maxY = dimension.getMaxHeight() - 1;
final boolean coverSteepTerrain = dimension.isCoverSteepTerrain();
if ((currentSeed == 0) || (currentSeed != seed)) {
for (int i = 0; i < activeMaterials.length; i++) {
if (noiseGenerators[i].getSeed() != (seed + seedOffsets[i])) {
noiseGenerators[i].setSeed(seed + seedOffsets[i]);
}
}
currentSeed = seed;
}
// int[] counts = new int[256];
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
final int localX = xOffset + x, localY = zOffset + z;
final int worldX = tile.getX() * TILE_SIZE + localX, worldY = tile.getY() * TILE_SIZE + localY;
if (tile.getBitLayerValue(Void.INSTANCE, localX, localY)) {
continue;
}
final int resourcesValue = Math.max(minimumLevel, tile.getLayerValue(Resources.INSTANCE, localX, localY));
if (resourcesValue > 0) {
final int terrainheight = tile.getIntHeight(localX, localY);
final int topLayerDepth = dimension.getTopLayerDepth(worldX, worldY, terrainheight);
int subsurfaceMaxHeight = terrainheight - topLayerDepth;
if (coverSteepTerrain) {
subsurfaceMaxHeight = Math.min(subsurfaceMaxHeight,
Math.min(Math.min(dimension.getIntHeightAt(worldX - 1, worldY, Integer.MAX_VALUE),
dimension.getIntHeightAt(worldX + 1, worldY, Integer.MAX_VALUE)),
Math.min(dimension.getIntHeightAt(worldX, worldY - 1, Integer.MAX_VALUE),
dimension.getIntHeightAt(worldX, worldY + 1, Integer.MAX_VALUE))));
}
final double dx = worldX / TINY_BLOBS, dy = worldY / TINY_BLOBS;
final double dirtX = worldX / SMALL_BLOBS, dirtY = worldY / SMALL_BLOBS;
// Capping to maxY really shouldn't be necessary, but we've
// had several reports from the wild of this going higher
// than maxHeight, so there must be some obscure way in
// which the terrainHeight can be raised too high
for (int y = Math.min(subsurfaceMaxHeight, maxY); y > 0; y--) {
final double dz = y / TINY_BLOBS;
final double dirtZ = y / SMALL_BLOBS;
for (int i = 0; i < activeMaterials.length; i++) {
final float chance = chances[i][resourcesValue];
if ((chance <= 0.5f)
&& (y >= minLevels[i])
&& (y <= maxLevels[i])
&& (activeMaterials[i].isNamedOneOf(MC_DIRT, MC_GRAVEL)
? (noiseGenerators[i].getPerlinNoise(dirtX, dirtY, dirtZ) >= chance)
: (noiseGenerators[i].getPerlinNoise(dx, dy, dz) >= chance))) {
// counts[oreType]++;
chunk.setMaterial(x, y, z, activeMaterials[i]);
break;
}
}
}
}
}
}
// System.out.println("Tile " + tile.getX() + "," + tile.getY());
// for (i = 0; i < 256; i++) {
// if (counts[i] > 0) {
// System.out.printf("Exported %6d of ore type %3d%n", counts[i], i);
// }
// }
// System.out.println();
}
// TODO: resource frequenties onderzoeken met Statistics tool!
private Material[] activeMaterials;
private PerlinNoise[] noiseGenerators;
private long[] seedOffsets;
private int[] minLevels, maxLevels;
private float[][] chances;
private long currentSeed;
public static class ResourcesExporterSettings implements ExporterSettings {
public ResourcesExporterSettings(int maxHeight) {
this(maxHeight, false);
}
public ResourcesExporterSettings(int maxHeight, boolean nether) {
Random random = new Random();
settings.put(DIRT, new ResourceSettings(DIRT, 0, maxHeight - 1, nether ? 0 : 57, random.nextLong()));
settings.put(GRAVEL, new ResourceSettings(GRAVEL, 0, maxHeight - 1, nether ? 0 : 28, random.nextLong()));
settings.put(GOLD_ORE, new ResourceSettings(GOLD_ORE, 0, 31, nether ? 0 : 1, random.nextLong()));
settings.put(IRON_ORE, new ResourceSettings(IRON_ORE, 0, 63, nether ? 0 : 6, random.nextLong()));
settings.put(COAL, new ResourceSettings(COAL, 0, maxHeight - 1, nether ? 0 : 10, random.nextLong()));
settings.put(LAPIS_LAZULI_ORE, new ResourceSettings(LAPIS_LAZULI_ORE, 0, 31, nether ? 0 : 1, random.nextLong()));
settings.put(DIAMOND_ORE, new ResourceSettings(DIAMOND_ORE, 0, 15, nether ? 0 : 1, random.nextLong()));
settings.put(REDSTONE_ORE, new ResourceSettings(REDSTONE_ORE, 0, 15, nether ? 0 : 8, random.nextLong()));
settings.put(EMERALD_ORE, new ResourceSettings(EMERALD_ORE, 0, 31, nether ? 0 : ((maxHeight != DEFAULT_MAX_HEIGHT_ANVIL) ? 0 : 1), random.nextLong()));
settings.put(QUARTZ_ORE, new ResourceSettings(QUARTZ_ORE, 0, maxHeight - 1, nether ? ((maxHeight != DEFAULT_MAX_HEIGHT_ANVIL) ? 0 : 6) : 0, random.nextLong()));
settings.put(WATER, new ResourceSettings(WATER, 0, maxHeight - 1, nether ? 0 : 1, random.nextLong()));
settings.put(LAVA, new ResourceSettings(LAVA, 0, 15, nether ? 0 : 2, random.nextLong()));
}
@Override
public boolean isApplyEverywhere() {
return minimumLevel > 0;
}
public int getMinimumLevel() {
return minimumLevel;
}
public void setMinimumLevel(int minimumLevel) {
this.minimumLevel = minimumLevel;
}
public Set<Material> getMaterials() {
return settings.keySet();
}
public int getMinLevel(Material material) {
return settings.get(material).minLevel;
}
public void setMinLevel(Material material, int minLevel) {
settings.get(material).minLevel = minLevel;
}
public int getMaxLevel(Material material) {
return settings.get(material).maxLevel;
}
public void setMaxLevel(Material material, int maxLevel) {
settings.get(material).maxLevel = maxLevel;
}
public int getChance(Material material) {
return settings.get(material).chance;
}
public void setChance(Material material, int chance) {
settings.get(material).chance = chance;
}
public long getSeedOffset(Material material) {
return settings.get(material).seedOffset;
}
@Override
public Resources getLayer() {
return Resources.INSTANCE;
}
@Override
public ResourcesExporterSettings clone() {
try {
ResourcesExporterSettings clone = (ResourcesExporterSettings) super.clone();
clone.settings = new LinkedHashMap<>();
settings.forEach((material, settings) -> clone.settings.put(material, settings.clone()));
return clone;
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings("deprecation") // Legacy support
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
if (version < 1) {
// Legacy conversions
// Fix static water and lava
if (! maxLevels.containsKey(BLK_WATER)) {
logger.warn("Fixing water and lava settings");
maxLevels.put(BLK_WATER, maxLevels.get(BLK_STATIONARY_WATER));
chances.put(BLK_WATER, chances.get(BLK_STATIONARY_WATER));
seedOffsets.put(BLK_WATER, seedOffsets.get(BLK_STATIONARY_WATER));
maxLevels.put(BLK_LAVA, maxLevels.get(BLK_STATIONARY_LAVA));
chances.put(BLK_LAVA, chances.get(BLK_STATIONARY_LAVA));
seedOffsets.put(BLK_LAVA, seedOffsets.get(BLK_STATIONARY_LAVA));
maxLevels.remove(BLK_STATIONARY_WATER);
chances.remove(BLK_STATIONARY_WATER);
seedOffsets.remove(BLK_STATIONARY_WATER);
maxLevels.remove(BLK_STATIONARY_LAVA);
chances.remove(BLK_STATIONARY_LAVA);
seedOffsets.remove(BLK_STATIONARY_LAVA);
}
if (! maxLevels.containsKey(BLK_EMERALD_ORE)) {
maxLevels.put(BLK_EMERALD_ORE, 31);
chances.put(BLK_EMERALD_ORE, 0);
}
Random random = new Random();
if (! seedOffsets.containsKey(BLK_EMERALD_ORE)) {
seedOffsets.put(BLK_EMERALD_ORE, random.nextLong());
}
if (minLevels == null) {
minLevels = new HashMap<>();
for (int blockType: maxLevels.keySet()) {
minLevels.put(blockType, 0);
}
}
if (! minLevels.containsKey(BLK_QUARTZ_ORE)) {
minLevels.put(BLK_QUARTZ_ORE, 0);
maxLevels.put(BLK_QUARTZ_ORE, 255);
chances.put(BLK_QUARTZ_ORE, 0);
seedOffsets.put(BLK_QUARTZ_ORE, random.nextLong());
}
// Convert integer-based settings to material-based settings
settings = new LinkedHashMap<>();
for (int blockType: maxLevels.keySet()) {
Material material = get(blockType);
settings.put(material, new ResourceSettings(material, minLevels.get(blockType), maxLevels.get(blockType),
chances.get(blockType), seedOffsets.get(blockType)));
}
minLevels = null;
maxLevels = null;
chances = null;
seedOffsets = null;
}
version = 1;
}
private int minimumLevel = 8;
private Map<Material, ResourceSettings> settings = new LinkedHashMap<>();
/** @deprecated */
private Map<Integer, Integer> maxLevels = null;
/** @deprecated */
private Map<Integer, Integer> chances = null;
/** @deprecated */
private Map<Integer, Long> seedOffsets = null;
/** @deprecated */
private Map<Integer, Integer> minLevels = null;
private int version = 1;
private static final long serialVersionUID = 1L;
private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ResourcesExporter.class);
}
static class ResourceSettings implements Serializable, Cloneable {
ResourceSettings(Material material, int minLevel, int maxLevel, int chance, long seedOffset) {
this.material = material;
this.minLevel = minLevel;
this.maxLevel = maxLevel;
this.chance = chance;
this.seedOffset = seedOffset;
}
@Override
public ResourceSettings clone() {
try {
return (ResourceSettings) super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError(e);
}
}
Material material;
int minLevel, maxLevel, chance;
long seedOffset;
private static final long serialVersionUID = 1L;
}
} | Jydett/WorldPainter | WorldPainter/WPCore/src/main/java/org/pepsoft/worldpainter/layers/exporters/ResourcesExporter.java | 4,502 | /**
*
* @author pepijn
*/ | block_comment | nl | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.pepsoft.worldpainter.layers.exporters;
import org.pepsoft.minecraft.Chunk;
import org.pepsoft.minecraft.Material;
import org.pepsoft.util.PerlinNoise;
import org.pepsoft.worldpainter.Dimension;
import org.pepsoft.worldpainter.Platform;
import org.pepsoft.worldpainter.Tile;
import org.pepsoft.worldpainter.exporting.AbstractLayerExporter;
import org.pepsoft.worldpainter.exporting.FirstPassLayerExporter;
import org.pepsoft.worldpainter.layers.Resources;
import org.pepsoft.worldpainter.layers.Void;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.*;
import static org.pepsoft.minecraft.Constants.*;
import static org.pepsoft.minecraft.Material.*;
import static org.pepsoft.worldpainter.Constants.*;
/**
*
* @author pepijn
<SUF>*/
public class ResourcesExporter extends AbstractLayerExporter<Resources> implements FirstPassLayerExporter {
public ResourcesExporter() {
super(Resources.INSTANCE);
}
@Override
public void setSettings(ExporterSettings settings) {
super.setSettings(settings);
ResourcesExporterSettings resourcesSettings = (ResourcesExporterSettings) getSettings();
if (resourcesSettings != null) {
Set<Material> allMaterials = resourcesSettings.getMaterials();
List<Material> activeMaterials = new ArrayList<>(allMaterials.size());
for (Material material: allMaterials) {
if (resourcesSettings.getChance(material) > 0) {
activeMaterials.add(material);
}
}
this.activeMaterials = activeMaterials.toArray(new Material[activeMaterials.size()]);
noiseGenerators = new PerlinNoise[this.activeMaterials.length];
seedOffsets = new long[this.activeMaterials.length];
minLevels = new int[this.activeMaterials.length];
maxLevels = new int[this.activeMaterials.length];
chances = new float[this.activeMaterials.length][16];
for (int i = 0; i < this.activeMaterials.length; i++) {
noiseGenerators[i] = new PerlinNoise(0);
seedOffsets[i] = resourcesSettings.getSeedOffset(this.activeMaterials[i]);
minLevels[i] = resourcesSettings.getMinLevel(this.activeMaterials[i]);
maxLevels[i] = resourcesSettings.getMaxLevel(this.activeMaterials[i]);
chances[i] = new float[16];
for (int j = 0; j < 16; j++) {
chances[i][j] = PerlinNoise.getLevelForPromillage(Math.min(resourcesSettings.getChance(this.activeMaterials[i]) * j / 8f, 1000f));
}
}
}
}
@Override
public void render(Dimension dimension, Tile tile, Chunk chunk, Platform platform) {
ResourcesExporterSettings settings = (ResourcesExporterSettings) getSettings();
if (settings == null) {
settings = new ResourcesExporterSettings(dimension.getMaxHeight());
setSettings(settings);
}
final int minimumLevel = settings.getMinimumLevel();
final int xOffset = (chunk.getxPos() & 7) << 4;
final int zOffset = (chunk.getzPos() & 7) << 4;
final long seed = dimension.getSeed();
final int maxY = dimension.getMaxHeight() - 1;
final boolean coverSteepTerrain = dimension.isCoverSteepTerrain();
if ((currentSeed == 0) || (currentSeed != seed)) {
for (int i = 0; i < activeMaterials.length; i++) {
if (noiseGenerators[i].getSeed() != (seed + seedOffsets[i])) {
noiseGenerators[i].setSeed(seed + seedOffsets[i]);
}
}
currentSeed = seed;
}
// int[] counts = new int[256];
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
final int localX = xOffset + x, localY = zOffset + z;
final int worldX = tile.getX() * TILE_SIZE + localX, worldY = tile.getY() * TILE_SIZE + localY;
if (tile.getBitLayerValue(Void.INSTANCE, localX, localY)) {
continue;
}
final int resourcesValue = Math.max(minimumLevel, tile.getLayerValue(Resources.INSTANCE, localX, localY));
if (resourcesValue > 0) {
final int terrainheight = tile.getIntHeight(localX, localY);
final int topLayerDepth = dimension.getTopLayerDepth(worldX, worldY, terrainheight);
int subsurfaceMaxHeight = terrainheight - topLayerDepth;
if (coverSteepTerrain) {
subsurfaceMaxHeight = Math.min(subsurfaceMaxHeight,
Math.min(Math.min(dimension.getIntHeightAt(worldX - 1, worldY, Integer.MAX_VALUE),
dimension.getIntHeightAt(worldX + 1, worldY, Integer.MAX_VALUE)),
Math.min(dimension.getIntHeightAt(worldX, worldY - 1, Integer.MAX_VALUE),
dimension.getIntHeightAt(worldX, worldY + 1, Integer.MAX_VALUE))));
}
final double dx = worldX / TINY_BLOBS, dy = worldY / TINY_BLOBS;
final double dirtX = worldX / SMALL_BLOBS, dirtY = worldY / SMALL_BLOBS;
// Capping to maxY really shouldn't be necessary, but we've
// had several reports from the wild of this going higher
// than maxHeight, so there must be some obscure way in
// which the terrainHeight can be raised too high
for (int y = Math.min(subsurfaceMaxHeight, maxY); y > 0; y--) {
final double dz = y / TINY_BLOBS;
final double dirtZ = y / SMALL_BLOBS;
for (int i = 0; i < activeMaterials.length; i++) {
final float chance = chances[i][resourcesValue];
if ((chance <= 0.5f)
&& (y >= minLevels[i])
&& (y <= maxLevels[i])
&& (activeMaterials[i].isNamedOneOf(MC_DIRT, MC_GRAVEL)
? (noiseGenerators[i].getPerlinNoise(dirtX, dirtY, dirtZ) >= chance)
: (noiseGenerators[i].getPerlinNoise(dx, dy, dz) >= chance))) {
// counts[oreType]++;
chunk.setMaterial(x, y, z, activeMaterials[i]);
break;
}
}
}
}
}
}
// System.out.println("Tile " + tile.getX() + "," + tile.getY());
// for (i = 0; i < 256; i++) {
// if (counts[i] > 0) {
// System.out.printf("Exported %6d of ore type %3d%n", counts[i], i);
// }
// }
// System.out.println();
}
// TODO: resource frequenties onderzoeken met Statistics tool!
private Material[] activeMaterials;
private PerlinNoise[] noiseGenerators;
private long[] seedOffsets;
private int[] minLevels, maxLevels;
private float[][] chances;
private long currentSeed;
public static class ResourcesExporterSettings implements ExporterSettings {
public ResourcesExporterSettings(int maxHeight) {
this(maxHeight, false);
}
public ResourcesExporterSettings(int maxHeight, boolean nether) {
Random random = new Random();
settings.put(DIRT, new ResourceSettings(DIRT, 0, maxHeight - 1, nether ? 0 : 57, random.nextLong()));
settings.put(GRAVEL, new ResourceSettings(GRAVEL, 0, maxHeight - 1, nether ? 0 : 28, random.nextLong()));
settings.put(GOLD_ORE, new ResourceSettings(GOLD_ORE, 0, 31, nether ? 0 : 1, random.nextLong()));
settings.put(IRON_ORE, new ResourceSettings(IRON_ORE, 0, 63, nether ? 0 : 6, random.nextLong()));
settings.put(COAL, new ResourceSettings(COAL, 0, maxHeight - 1, nether ? 0 : 10, random.nextLong()));
settings.put(LAPIS_LAZULI_ORE, new ResourceSettings(LAPIS_LAZULI_ORE, 0, 31, nether ? 0 : 1, random.nextLong()));
settings.put(DIAMOND_ORE, new ResourceSettings(DIAMOND_ORE, 0, 15, nether ? 0 : 1, random.nextLong()));
settings.put(REDSTONE_ORE, new ResourceSettings(REDSTONE_ORE, 0, 15, nether ? 0 : 8, random.nextLong()));
settings.put(EMERALD_ORE, new ResourceSettings(EMERALD_ORE, 0, 31, nether ? 0 : ((maxHeight != DEFAULT_MAX_HEIGHT_ANVIL) ? 0 : 1), random.nextLong()));
settings.put(QUARTZ_ORE, new ResourceSettings(QUARTZ_ORE, 0, maxHeight - 1, nether ? ((maxHeight != DEFAULT_MAX_HEIGHT_ANVIL) ? 0 : 6) : 0, random.nextLong()));
settings.put(WATER, new ResourceSettings(WATER, 0, maxHeight - 1, nether ? 0 : 1, random.nextLong()));
settings.put(LAVA, new ResourceSettings(LAVA, 0, 15, nether ? 0 : 2, random.nextLong()));
}
@Override
public boolean isApplyEverywhere() {
return minimumLevel > 0;
}
public int getMinimumLevel() {
return minimumLevel;
}
public void setMinimumLevel(int minimumLevel) {
this.minimumLevel = minimumLevel;
}
public Set<Material> getMaterials() {
return settings.keySet();
}
public int getMinLevel(Material material) {
return settings.get(material).minLevel;
}
public void setMinLevel(Material material, int minLevel) {
settings.get(material).minLevel = minLevel;
}
public int getMaxLevel(Material material) {
return settings.get(material).maxLevel;
}
public void setMaxLevel(Material material, int maxLevel) {
settings.get(material).maxLevel = maxLevel;
}
public int getChance(Material material) {
return settings.get(material).chance;
}
public void setChance(Material material, int chance) {
settings.get(material).chance = chance;
}
public long getSeedOffset(Material material) {
return settings.get(material).seedOffset;
}
@Override
public Resources getLayer() {
return Resources.INSTANCE;
}
@Override
public ResourcesExporterSettings clone() {
try {
ResourcesExporterSettings clone = (ResourcesExporterSettings) super.clone();
clone.settings = new LinkedHashMap<>();
settings.forEach((material, settings) -> clone.settings.put(material, settings.clone()));
return clone;
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings("deprecation") // Legacy support
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
if (version < 1) {
// Legacy conversions
// Fix static water and lava
if (! maxLevels.containsKey(BLK_WATER)) {
logger.warn("Fixing water and lava settings");
maxLevels.put(BLK_WATER, maxLevels.get(BLK_STATIONARY_WATER));
chances.put(BLK_WATER, chances.get(BLK_STATIONARY_WATER));
seedOffsets.put(BLK_WATER, seedOffsets.get(BLK_STATIONARY_WATER));
maxLevels.put(BLK_LAVA, maxLevels.get(BLK_STATIONARY_LAVA));
chances.put(BLK_LAVA, chances.get(BLK_STATIONARY_LAVA));
seedOffsets.put(BLK_LAVA, seedOffsets.get(BLK_STATIONARY_LAVA));
maxLevels.remove(BLK_STATIONARY_WATER);
chances.remove(BLK_STATIONARY_WATER);
seedOffsets.remove(BLK_STATIONARY_WATER);
maxLevels.remove(BLK_STATIONARY_LAVA);
chances.remove(BLK_STATIONARY_LAVA);
seedOffsets.remove(BLK_STATIONARY_LAVA);
}
if (! maxLevels.containsKey(BLK_EMERALD_ORE)) {
maxLevels.put(BLK_EMERALD_ORE, 31);
chances.put(BLK_EMERALD_ORE, 0);
}
Random random = new Random();
if (! seedOffsets.containsKey(BLK_EMERALD_ORE)) {
seedOffsets.put(BLK_EMERALD_ORE, random.nextLong());
}
if (minLevels == null) {
minLevels = new HashMap<>();
for (int blockType: maxLevels.keySet()) {
minLevels.put(blockType, 0);
}
}
if (! minLevels.containsKey(BLK_QUARTZ_ORE)) {
minLevels.put(BLK_QUARTZ_ORE, 0);
maxLevels.put(BLK_QUARTZ_ORE, 255);
chances.put(BLK_QUARTZ_ORE, 0);
seedOffsets.put(BLK_QUARTZ_ORE, random.nextLong());
}
// Convert integer-based settings to material-based settings
settings = new LinkedHashMap<>();
for (int blockType: maxLevels.keySet()) {
Material material = get(blockType);
settings.put(material, new ResourceSettings(material, minLevels.get(blockType), maxLevels.get(blockType),
chances.get(blockType), seedOffsets.get(blockType)));
}
minLevels = null;
maxLevels = null;
chances = null;
seedOffsets = null;
}
version = 1;
}
private int minimumLevel = 8;
private Map<Material, ResourceSettings> settings = new LinkedHashMap<>();
/** @deprecated */
private Map<Integer, Integer> maxLevels = null;
/** @deprecated */
private Map<Integer, Integer> chances = null;
/** @deprecated */
private Map<Integer, Long> seedOffsets = null;
/** @deprecated */
private Map<Integer, Integer> minLevels = null;
private int version = 1;
private static final long serialVersionUID = 1L;
private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ResourcesExporter.class);
}
static class ResourceSettings implements Serializable, Cloneable {
ResourceSettings(Material material, int minLevel, int maxLevel, int chance, long seedOffset) {
this.material = material;
this.minLevel = minLevel;
this.maxLevel = maxLevel;
this.chance = chance;
this.seedOffset = seedOffset;
}
@Override
public ResourceSettings clone() {
try {
return (ResourceSettings) super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError(e);
}
}
Material material;
int minLevel, maxLevel, chance;
long seedOffset;
private static final long serialVersionUID = 1L;
}
} |
39522_34 | package main.java.com.kaasintl.main;
import main.java.com.kaasintl.api.AI;
import main.java.com.kaasintl.api.Field;
import main.java.com.kaasintl.api.GameBoard;
import main.java.com.kaasintl.api.RuleManager;
import main.java.com.kaasintl.reversi.ReversiAI;
import main.java.com.kaasintl.reversi.ReversiGameBoard;
import main.java.com.kaasintl.reversi.ReversiRuleManager;
import main.java.com.kaasintl.tictactoe.TicTacBoard;
import main.java.com.kaasintl.tictactoe.TicTacRuleManager;
import java.util.ArrayList;
/**
* Created by David on 4-4-2015.
*/
public class GameManager
{
ArrayList<String> playerList;
ArrayList<String> gameList;
RuleManager ruleManager;
AI ai;
// Connections to other game-components
public NetManager netManager;
private GUI gui;
// local variables
private String opponent;
private String gameType;
private boolean isTurn;
private boolean aiPlays;
private String turnMessage;
private int isValid = 0;
// Game Components
private GameBoard gameBoard;
private String currentGame;
/**
* Creates an instance of the GameManager, with no GUI provided. This will cause it to make a GUI itself
*/
public GameManager()
{
netManager = new NetManager(this, "localhost", 7789);
playerList = new ArrayList<>();
gameList = new ArrayList<>();
//TODO: load different games dynamically
ruleManager = new TicTacRuleManager(this);
gameBoard = new TicTacBoard(ruleManager);
}
/**
* Creates an instance of the GameManager, with the provided GUI object as it's gui
*
* @param gui The GUI
*/
public GameManager(GUI gui)
{
this.gui = gui;
netManager = new NetManager(this);
playerList = new ArrayList<>();
gameList = new ArrayList<>();
//TODO: load different games dynamically
//ruleManager = new TicTacRuleManager(this);
ruleManager = new ReversiRuleManager(this);
//gameBoard = new TicTacBoard(ruleManager);
gameBoard = new ReversiGameBoard(ruleManager);
//ai = new TicTacAI(ruleManager, this);
ai = new ReversiAI(this, ruleManager);
//this.aiPlays = true;
}
public void yourTurn(String turnMessage) {
boolean ok = false;
if(aiPlays) {
while(!ok) {
ok = makeAIPlay();
}
} else {
gui.setPlayersTurn();
}
}
/**
* TODO: zorg dat het speelveld wordt geupdate voordat AI move mag doen
*/
public boolean makeAIPlay()
{
return makeMove(ai.nextMove().getCoordinate());
}
/**
* Returns the current game's gameboard
*
* @return
*/
public GameBoard getGameBoard()
{
return gameBoard;
}
/**
* Sets the current game's gameboard to the provided Gameboard
*
* @param gameBoard
*/
public void setGameBoard(GameBoard gameBoard)
{
this.gameBoard = gameBoard;
gui.updateGameboard();
}
/**
* Returns the netmanager
*
* @return
*/
public NetManager getNetManager()
{
return netManager;
}
/**
* Sets the netmanager
*
* @param netManager
*/
public void setNetManager(NetManager netManager)
{
this.netManager = netManager;
}
/**
* Log into server with a specific name
*
* @param name
*/
public void login(String name)
{
netManager.login(name);
}
/**
* Subscribes to a specific game
*
* @param game
* @return
*/
public boolean subscribe(String game)
{
return netManager.subscribe(game);
}
// TODO: Quit the game
public boolean quit()
{
return true;
}
/**
* sets the challenge to be accepted
*
* @param challenger
* @param challengeNumber
* @param gameType
*/
public void setChallenge(String challenger, int challengeNumber, String gameType)
{
gui.showChallengePopup(challengeNumber, challenger, gameType);
}
// TODO: Accept other player's challenge
public boolean acceptChallenge(int challengeNumber, String game)
{
if (this.getNetManager().acceptChallenge(challengeNumber)) {
switch (game) {
case "Tic-tac-toe":
this.setGameType("Tic-tac-toe");
this.setRuleManager(new TicTacRuleManager(this));
this.setGameBoard(new TicTacBoard(this.getRuleManager()));
break;
case "Reversi":
this.setGameType("Reversi");
this.setRuleManager(new ReversiRuleManager(this));
this.setGameBoard(new ReversiGameBoard(this.getRuleManager()));
break;
}
return true;
} else {
return false;
}
}
/**
* Challenges a player to a game
*
* @param player The player to challenge
* @param game The game to be played
* @return If successful, returns true
*/
public boolean challenge(String player, String game)
{
return netManager.challengePlayer(player, game);
}
/**
* Fetches current playerList
*/
public ArrayList<String> getPlayerList()
{
return netManager.fetchPlayerList();
}
/**
* Sets the playerlist field
*
* @param playerList
*/
public void setPlayerList(ArrayList<String> playerList)
{
this.playerList = playerList;
}
/**
* Gets the current rulemanager
*
* @return the current RuleManager
*/
public RuleManager getRuleManager()
{
return ruleManager;
}
/**
* Sets the rulemanager
*
* @param ruleManager
*/
public void setRuleManager(RuleManager ruleManager)
{
this.ruleManager = ruleManager;
}
/**
* Ends the game with a certain result
*
* @param winloss 1 means win, 0 means draw, -1 means loss
* @param player1Score
* @param player2Score
* @param message
*/
public void endGame(int winloss, int player1Score, int player2Score, String message)
{
gui.endGame(winloss, player1Score, player2Score, message);
}
/**
* Notify gameManager when new game starts
* TODO: notify GUI of new game and move
*
* @param playerToMove
* @param gameType
* @param opponent
*/
public void setMatch(String playerToMove, String gameType, String opponent)
{
setOpponent(opponent);
if (!playerToMove.equals(opponent)) {
switch (gameType)
{
case "Tic-tac-toe":
this.setGameType("Tic-tac-toe");
this.setRuleManager(new TicTacRuleManager(this));
this.setGameBoard(new TicTacBoard(this.getRuleManager()));
break;
case "Reversi":
this.setGameType("Reversi");
this.setRuleManager(new ReversiRuleManager(this));
this.setGameBoard(new ReversiGameBoard(this.getRuleManager()));
break;
}
}
}
/**
* fetches the gameList
*/
public ArrayList<String> getGameList()
{
return netManager.fetchGameList();
}
/**
* Sets the gameList variable
*
* @param gameList
*/
public void setGameList(ArrayList<String> gameList)
{
this.gameList = gameList;
}
// TODO: Forfeit the game
public boolean forfeit()
{
netManager.forfeit();
return true;
}
public boolean makeMove(int move)
{
System.out.println("AIMove: " + move);
return netManager.sendMove(move);
}
// TODO: Return the game's board
public GameBoard getGameboard()
{
return gameBoard;
}
// TODO: Reset game
public boolean reset()
{
return true;
}
// TODO: Check if move is valid
public boolean isValid(Field f)
{
return f == f;
}
/**
* Gets opponent name
*
* @return String - opponent
*/
public String getOpponent()
{
return opponent;
}
/**
* Sets opponent name
*
* @param opponent
*/
public void setOpponent(String opponent)
{
this.opponent = opponent;
}
/**
* Returns the current game type
*
* @return
*/
public String getGameType()
{
return gameType;
}
/**
* Sets the current game type
*
* @param gameType
*/
public void setGameType(String gameType)
{
this.gameType = gameType;
}
/**
* processes the move just played
*
* @param player
* @param move
* @param details
*/
public void setMove(String player, int move, String details)
{
if (!(player.equals(opponent)))
{
gameBoard.getBoard().get(move).setState(Field.STATE.Friendly);
} else
{
gameBoard.getBoard().get(move).setState(Field.STATE.Enemy);
}
gui.appendHistory(player + " made move " + move + " " + details);
gui.updateGameboard();
}
}
| KAAS-International/Kaasworks-Client | src/main/java/com/kaasintl/main/GameManager.java | 2,795 | /**
* Sets opponent name
*
* @param opponent
*/ | block_comment | nl | package main.java.com.kaasintl.main;
import main.java.com.kaasintl.api.AI;
import main.java.com.kaasintl.api.Field;
import main.java.com.kaasintl.api.GameBoard;
import main.java.com.kaasintl.api.RuleManager;
import main.java.com.kaasintl.reversi.ReversiAI;
import main.java.com.kaasintl.reversi.ReversiGameBoard;
import main.java.com.kaasintl.reversi.ReversiRuleManager;
import main.java.com.kaasintl.tictactoe.TicTacBoard;
import main.java.com.kaasintl.tictactoe.TicTacRuleManager;
import java.util.ArrayList;
/**
* Created by David on 4-4-2015.
*/
public class GameManager
{
ArrayList<String> playerList;
ArrayList<String> gameList;
RuleManager ruleManager;
AI ai;
// Connections to other game-components
public NetManager netManager;
private GUI gui;
// local variables
private String opponent;
private String gameType;
private boolean isTurn;
private boolean aiPlays;
private String turnMessage;
private int isValid = 0;
// Game Components
private GameBoard gameBoard;
private String currentGame;
/**
* Creates an instance of the GameManager, with no GUI provided. This will cause it to make a GUI itself
*/
public GameManager()
{
netManager = new NetManager(this, "localhost", 7789);
playerList = new ArrayList<>();
gameList = new ArrayList<>();
//TODO: load different games dynamically
ruleManager = new TicTacRuleManager(this);
gameBoard = new TicTacBoard(ruleManager);
}
/**
* Creates an instance of the GameManager, with the provided GUI object as it's gui
*
* @param gui The GUI
*/
public GameManager(GUI gui)
{
this.gui = gui;
netManager = new NetManager(this);
playerList = new ArrayList<>();
gameList = new ArrayList<>();
//TODO: load different games dynamically
//ruleManager = new TicTacRuleManager(this);
ruleManager = new ReversiRuleManager(this);
//gameBoard = new TicTacBoard(ruleManager);
gameBoard = new ReversiGameBoard(ruleManager);
//ai = new TicTacAI(ruleManager, this);
ai = new ReversiAI(this, ruleManager);
//this.aiPlays = true;
}
public void yourTurn(String turnMessage) {
boolean ok = false;
if(aiPlays) {
while(!ok) {
ok = makeAIPlay();
}
} else {
gui.setPlayersTurn();
}
}
/**
* TODO: zorg dat het speelveld wordt geupdate voordat AI move mag doen
*/
public boolean makeAIPlay()
{
return makeMove(ai.nextMove().getCoordinate());
}
/**
* Returns the current game's gameboard
*
* @return
*/
public GameBoard getGameBoard()
{
return gameBoard;
}
/**
* Sets the current game's gameboard to the provided Gameboard
*
* @param gameBoard
*/
public void setGameBoard(GameBoard gameBoard)
{
this.gameBoard = gameBoard;
gui.updateGameboard();
}
/**
* Returns the netmanager
*
* @return
*/
public NetManager getNetManager()
{
return netManager;
}
/**
* Sets the netmanager
*
* @param netManager
*/
public void setNetManager(NetManager netManager)
{
this.netManager = netManager;
}
/**
* Log into server with a specific name
*
* @param name
*/
public void login(String name)
{
netManager.login(name);
}
/**
* Subscribes to a specific game
*
* @param game
* @return
*/
public boolean subscribe(String game)
{
return netManager.subscribe(game);
}
// TODO: Quit the game
public boolean quit()
{
return true;
}
/**
* sets the challenge to be accepted
*
* @param challenger
* @param challengeNumber
* @param gameType
*/
public void setChallenge(String challenger, int challengeNumber, String gameType)
{
gui.showChallengePopup(challengeNumber, challenger, gameType);
}
// TODO: Accept other player's challenge
public boolean acceptChallenge(int challengeNumber, String game)
{
if (this.getNetManager().acceptChallenge(challengeNumber)) {
switch (game) {
case "Tic-tac-toe":
this.setGameType("Tic-tac-toe");
this.setRuleManager(new TicTacRuleManager(this));
this.setGameBoard(new TicTacBoard(this.getRuleManager()));
break;
case "Reversi":
this.setGameType("Reversi");
this.setRuleManager(new ReversiRuleManager(this));
this.setGameBoard(new ReversiGameBoard(this.getRuleManager()));
break;
}
return true;
} else {
return false;
}
}
/**
* Challenges a player to a game
*
* @param player The player to challenge
* @param game The game to be played
* @return If successful, returns true
*/
public boolean challenge(String player, String game)
{
return netManager.challengePlayer(player, game);
}
/**
* Fetches current playerList
*/
public ArrayList<String> getPlayerList()
{
return netManager.fetchPlayerList();
}
/**
* Sets the playerlist field
*
* @param playerList
*/
public void setPlayerList(ArrayList<String> playerList)
{
this.playerList = playerList;
}
/**
* Gets the current rulemanager
*
* @return the current RuleManager
*/
public RuleManager getRuleManager()
{
return ruleManager;
}
/**
* Sets the rulemanager
*
* @param ruleManager
*/
public void setRuleManager(RuleManager ruleManager)
{
this.ruleManager = ruleManager;
}
/**
* Ends the game with a certain result
*
* @param winloss 1 means win, 0 means draw, -1 means loss
* @param player1Score
* @param player2Score
* @param message
*/
public void endGame(int winloss, int player1Score, int player2Score, String message)
{
gui.endGame(winloss, player1Score, player2Score, message);
}
/**
* Notify gameManager when new game starts
* TODO: notify GUI of new game and move
*
* @param playerToMove
* @param gameType
* @param opponent
*/
public void setMatch(String playerToMove, String gameType, String opponent)
{
setOpponent(opponent);
if (!playerToMove.equals(opponent)) {
switch (gameType)
{
case "Tic-tac-toe":
this.setGameType("Tic-tac-toe");
this.setRuleManager(new TicTacRuleManager(this));
this.setGameBoard(new TicTacBoard(this.getRuleManager()));
break;
case "Reversi":
this.setGameType("Reversi");
this.setRuleManager(new ReversiRuleManager(this));
this.setGameBoard(new ReversiGameBoard(this.getRuleManager()));
break;
}
}
}
/**
* fetches the gameList
*/
public ArrayList<String> getGameList()
{
return netManager.fetchGameList();
}
/**
* Sets the gameList variable
*
* @param gameList
*/
public void setGameList(ArrayList<String> gameList)
{
this.gameList = gameList;
}
// TODO: Forfeit the game
public boolean forfeit()
{
netManager.forfeit();
return true;
}
public boolean makeMove(int move)
{
System.out.println("AIMove: " + move);
return netManager.sendMove(move);
}
// TODO: Return the game's board
public GameBoard getGameboard()
{
return gameBoard;
}
// TODO: Reset game
public boolean reset()
{
return true;
}
// TODO: Check if move is valid
public boolean isValid(Field f)
{
return f == f;
}
/**
* Gets opponent name
*
* @return String - opponent
*/
public String getOpponent()
{
return opponent;
}
/**
* Sets opponent name<SUF>*/
public void setOpponent(String opponent)
{
this.opponent = opponent;
}
/**
* Returns the current game type
*
* @return
*/
public String getGameType()
{
return gameType;
}
/**
* Sets the current game type
*
* @param gameType
*/
public void setGameType(String gameType)
{
this.gameType = gameType;
}
/**
* processes the move just played
*
* @param player
* @param move
* @param details
*/
public void setMove(String player, int move, String details)
{
if (!(player.equals(opponent)))
{
gameBoard.getBoard().get(move).setState(Field.STATE.Friendly);
} else
{
gameBoard.getBoard().get(move).setState(Field.STATE.Enemy);
}
gui.appendHistory(player + " made move " + move + " " + details);
gui.updateGameboard();
}
}
|
8383_0 | package nl.kb.core.scheduledjobs;
import com.google.common.util.concurrent.AbstractScheduledService;
import nl.kb.core.model.RunState;
import nl.kb.core.model.repository.HarvestSchedule;
import nl.kb.core.model.repository.Repository;
import nl.kb.core.model.repository.RepositoryDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.TimeUnit;
/**
* ScheduledRepositoryHarvester, conform spec:
* Trigger
* Elke dag wordt er gekeken welke harvests moeten draaien op basis van hun harvest schema,
* wanneer er voor het laatst gedraaid is (startdatum laatste harvest) en of de harvest actief is.
*/
public class DailyIdentifierHarvestScheduler extends AbstractScheduledService {
private static final Logger LOG = LoggerFactory.getLogger(DailyIdentifierHarvestScheduler.class);
private final RepositoryDao repositoryDao;
private final IdentifierHarvestSchedulerDaemon harvestRunner;
public DailyIdentifierHarvestScheduler(RepositoryDao repositoryDao, IdentifierHarvestSchedulerDaemon harvestRunner) {
this.repositoryDao = repositoryDao;
this.harvestRunner = harvestRunner;
}
@Override
protected void runOneIteration() throws Exception {
try {
repositoryDao.list().stream()
.filter(this::harvestShouldRun)
.map(Repository::getId)
.forEach(harvestRunner::startHarvest);
} catch (Exception e) {
LOG.warn("Failed to start scheduled harvests, probably caused by missing schema", e);
}
}
/**
* Slaagt wanneer een harvest gestart mag en moet worden
* 1) Staat de repository aan (getEnabled) EN
* 2) Is de harvest voor deze repository niet al aan het draaien (getRunState) EN
* 3a) Is er nog niet eerder geharvest? OF
* 3b) Is het schema dagelijks? OF
* 3c) Is het schema wekelijks en is het vandaag >= 7 sinds laatste harvest? OF
* 3d) Is het schema maandelijks en is het vandaag >= 1 maand sinds laatste harvest?
*
* @param repository de te toetsen repository
* @return of de harvest voor deze repository mag en zou moeten draaien
*/
private boolean harvestShouldRun(Repository repository) {
return repository.getEnabled() &&
harvestRunner.getHarvesterRunstate(repository.getId()) == RunState.WAITING && (
repository.getSchedule() == HarvestSchedule.DAILY ||
repository.getLastHarvest() == null ||
(repository.getSchedule() == HarvestSchedule.WEEKLY &&
ChronoUnit.DAYS.between(repository.getLastHarvest(), LocalDate.now()) >= 7) ||
(repository.getSchedule() == HarvestSchedule.MONTHLY &&
ChronoUnit.MONTHS.between(repository.getLastHarvest(), LocalDate.now()) >= 1)
);
}
@Override
protected Scheduler scheduler() {
return Scheduler.newFixedRateSchedule(0, 1, TimeUnit.DAYS);
}
}
| KBNLresearch/oai-pmh-bulk-downloader | src/main/java/nl/kb/core/scheduledjobs/DailyIdentifierHarvestScheduler.java | 886 | /**
* ScheduledRepositoryHarvester, conform spec:
* Trigger
* Elke dag wordt er gekeken welke harvests moeten draaien op basis van hun harvest schema,
* wanneer er voor het laatst gedraaid is (startdatum laatste harvest) en of de harvest actief is.
*/ | block_comment | nl | package nl.kb.core.scheduledjobs;
import com.google.common.util.concurrent.AbstractScheduledService;
import nl.kb.core.model.RunState;
import nl.kb.core.model.repository.HarvestSchedule;
import nl.kb.core.model.repository.Repository;
import nl.kb.core.model.repository.RepositoryDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.TimeUnit;
/**
* ScheduledRepositoryHarvester, conform spec:<SUF>*/
public class DailyIdentifierHarvestScheduler extends AbstractScheduledService {
private static final Logger LOG = LoggerFactory.getLogger(DailyIdentifierHarvestScheduler.class);
private final RepositoryDao repositoryDao;
private final IdentifierHarvestSchedulerDaemon harvestRunner;
public DailyIdentifierHarvestScheduler(RepositoryDao repositoryDao, IdentifierHarvestSchedulerDaemon harvestRunner) {
this.repositoryDao = repositoryDao;
this.harvestRunner = harvestRunner;
}
@Override
protected void runOneIteration() throws Exception {
try {
repositoryDao.list().stream()
.filter(this::harvestShouldRun)
.map(Repository::getId)
.forEach(harvestRunner::startHarvest);
} catch (Exception e) {
LOG.warn("Failed to start scheduled harvests, probably caused by missing schema", e);
}
}
/**
* Slaagt wanneer een harvest gestart mag en moet worden
* 1) Staat de repository aan (getEnabled) EN
* 2) Is de harvest voor deze repository niet al aan het draaien (getRunState) EN
* 3a) Is er nog niet eerder geharvest? OF
* 3b) Is het schema dagelijks? OF
* 3c) Is het schema wekelijks en is het vandaag >= 7 sinds laatste harvest? OF
* 3d) Is het schema maandelijks en is het vandaag >= 1 maand sinds laatste harvest?
*
* @param repository de te toetsen repository
* @return of de harvest voor deze repository mag en zou moeten draaien
*/
private boolean harvestShouldRun(Repository repository) {
return repository.getEnabled() &&
harvestRunner.getHarvesterRunstate(repository.getId()) == RunState.WAITING && (
repository.getSchedule() == HarvestSchedule.DAILY ||
repository.getLastHarvest() == null ||
(repository.getSchedule() == HarvestSchedule.WEEKLY &&
ChronoUnit.DAYS.between(repository.getLastHarvest(), LocalDate.now()) >= 7) ||
(repository.getSchedule() == HarvestSchedule.MONTHLY &&
ChronoUnit.MONTHS.between(repository.getLastHarvest(), LocalDate.now()) >= 1)
);
}
@Override
protected Scheduler scheduler() {
return Scheduler.newFixedRateSchedule(0, 1, TimeUnit.DAYS);
}
}
|
69618_0 | package cz.ilasek.namedentities.recognition;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cz.ilasek.namedentities.models.DisambiguatedEntity;
public class App
{
public App() {
}
public static void main( String[] args ) throws IOException
{
// String text = "Dat is de beste garantie voor een meer welvarende toekomst van Griekenland in de eurozone.";
// TokenNameFinderModel tnfm = new TokenNameFinderModel(App.class.getResourceAsStream("/opennlp/model/nl_ner_all.bin"));
// NameFinderME nfm = new NameFinderME(tnfm);
// String[] tokens = text.split("[^\\p{L}\\p{N}]");
// ArrayList<String> filteredTokens = new ArrayList<String>();
// for (String token : tokens) {
// if (token.length() > 0) {
// filteredTokens.add(token);
// System.out.println(token);
// }
// }
// filteredTokens.add(".");
// System.out.println("================");
//
// String[] ftkns = filteredTokens.toArray(new String[filteredTokens.size()]);
// Span[] nes = nfm.find(ftkns);
// System.out.println(nes.length);
// for (Span ne : nes) {
// System.out.println(ne.getType());
// for (int i = ne.getStart(); i < ne.getEnd(); i++) {
// System.out.print(ftkns[i] + " ");
// }
// System.out.println();
// }
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"nerrecconfig.xml"});
RecognitionTester rt = context.getBean(RecognitionTester.class);
rt.testSentenceDisambiguation();
// rt.indexOccurrences();
}
private static Map<Integer, DisambiguatedEntity> getResultsByGraphScore(List<DisambiguatedEntity> allCandidates) {
Map<Integer, DisambiguatedEntity> results = new HashMap<Integer, DisambiguatedEntity>();
System.out.println("============================");
System.out.println("Filtering results...");
System.out.println("============================");
for (DisambiguatedEntity de : allCandidates) {
System.out.println(de.toString());
double bestScore = 0;
DisambiguatedEntity bestEntity = results.get(de.getGroupId());
if (bestEntity != null)
bestScore = bestEntity.getGraphScore();
if (de.getGraphScore() > bestScore)
results.put(de.getGroupId(), de);
}
System.out.println("============================");
return results;
}
private static Map<Integer, DisambiguatedEntity> getResultsByStringScore(List<DisambiguatedEntity> allCandidates) {
Map<Integer, DisambiguatedEntity> results = new HashMap<Integer, DisambiguatedEntity>();
for (DisambiguatedEntity de : allCandidates) {
double bestScore = 0;
DisambiguatedEntity bestEntity = results.get(de.getGroupId());
if (bestEntity != null)
bestScore = bestEntity.getStringScore();
if (de.getStringScore() > bestScore)
results.put(de.getGroupId(), de);
}
return results;
}
private static Map<Integer, DisambiguatedEntity> getResultsCoOcuurenceAndStringScore(List<DisambiguatedEntity> allCandidates) {
Map<Integer, DisambiguatedEntity> results = new HashMap<Integer, DisambiguatedEntity>();
float bestStringScore = 0;
double bestGraphScore = 0;
for (DisambiguatedEntity de : allCandidates) {
if (de.getGraphScore() > bestGraphScore)
bestGraphScore = de.getGraphScore();
if (de.getStringScore() > bestStringScore)
bestStringScore = de.getStringScore();
}
for (DisambiguatedEntity de : allCandidates) {
de.setStringScore(de.getStringScore() / bestStringScore);
de.setGraphScore(de.getGraphScore() / bestGraphScore);
}
for (DisambiguatedEntity de : allCandidates) {
double bestScore = 0;
DisambiguatedEntity bestEntity = results.get(de.getGroupId());
if (bestEntity != null)
bestScore = bestEntity.getStringScore();
if (de.getStringScore() > bestScore)
results.put(de.getGroupId(), de);
}
return results;
}
}
| KIZI/Semitags | NamedEntitiesRecognition/src/main/java/cz/ilasek/namedentities/recognition/App.java | 1,333 | // String text = "Dat is de beste garantie voor een meer welvarende toekomst van Griekenland in de eurozone."; | line_comment | nl | package cz.ilasek.namedentities.recognition;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cz.ilasek.namedentities.models.DisambiguatedEntity;
public class App
{
public App() {
}
public static void main( String[] args ) throws IOException
{
// String text<SUF>
// TokenNameFinderModel tnfm = new TokenNameFinderModel(App.class.getResourceAsStream("/opennlp/model/nl_ner_all.bin"));
// NameFinderME nfm = new NameFinderME(tnfm);
// String[] tokens = text.split("[^\\p{L}\\p{N}]");
// ArrayList<String> filteredTokens = new ArrayList<String>();
// for (String token : tokens) {
// if (token.length() > 0) {
// filteredTokens.add(token);
// System.out.println(token);
// }
// }
// filteredTokens.add(".");
// System.out.println("================");
//
// String[] ftkns = filteredTokens.toArray(new String[filteredTokens.size()]);
// Span[] nes = nfm.find(ftkns);
// System.out.println(nes.length);
// for (Span ne : nes) {
// System.out.println(ne.getType());
// for (int i = ne.getStart(); i < ne.getEnd(); i++) {
// System.out.print(ftkns[i] + " ");
// }
// System.out.println();
// }
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"nerrecconfig.xml"});
RecognitionTester rt = context.getBean(RecognitionTester.class);
rt.testSentenceDisambiguation();
// rt.indexOccurrences();
}
private static Map<Integer, DisambiguatedEntity> getResultsByGraphScore(List<DisambiguatedEntity> allCandidates) {
Map<Integer, DisambiguatedEntity> results = new HashMap<Integer, DisambiguatedEntity>();
System.out.println("============================");
System.out.println("Filtering results...");
System.out.println("============================");
for (DisambiguatedEntity de : allCandidates) {
System.out.println(de.toString());
double bestScore = 0;
DisambiguatedEntity bestEntity = results.get(de.getGroupId());
if (bestEntity != null)
bestScore = bestEntity.getGraphScore();
if (de.getGraphScore() > bestScore)
results.put(de.getGroupId(), de);
}
System.out.println("============================");
return results;
}
private static Map<Integer, DisambiguatedEntity> getResultsByStringScore(List<DisambiguatedEntity> allCandidates) {
Map<Integer, DisambiguatedEntity> results = new HashMap<Integer, DisambiguatedEntity>();
for (DisambiguatedEntity de : allCandidates) {
double bestScore = 0;
DisambiguatedEntity bestEntity = results.get(de.getGroupId());
if (bestEntity != null)
bestScore = bestEntity.getStringScore();
if (de.getStringScore() > bestScore)
results.put(de.getGroupId(), de);
}
return results;
}
private static Map<Integer, DisambiguatedEntity> getResultsCoOcuurenceAndStringScore(List<DisambiguatedEntity> allCandidates) {
Map<Integer, DisambiguatedEntity> results = new HashMap<Integer, DisambiguatedEntity>();
float bestStringScore = 0;
double bestGraphScore = 0;
for (DisambiguatedEntity de : allCandidates) {
if (de.getGraphScore() > bestGraphScore)
bestGraphScore = de.getGraphScore();
if (de.getStringScore() > bestStringScore)
bestStringScore = de.getStringScore();
}
for (DisambiguatedEntity de : allCandidates) {
de.setStringScore(de.getStringScore() / bestStringScore);
de.setGraphScore(de.getGraphScore() / bestGraphScore);
}
for (DisambiguatedEntity de : allCandidates) {
double bestScore = 0;
DisambiguatedEntity bestEntity = results.get(de.getGroupId());
if (bestEntity != null)
bestScore = bestEntity.getStringScore();
if (de.getStringScore() > bestScore)
results.put(de.getGroupId(), de);
}
return results;
}
}
|
43955_2 | package be.kuleuven.csa.controller;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
public class BeheerTipsController {
@FXML
private TableView tblTips;
public void initialize() {
initTable();
tblTips.setOnMouseClicked(e -> {
if(e.getClickCount() == 2 && tblTips.getSelectionModel().getSelectedItem() != null) {
var selectedRow = (List<String>) tblTips.getSelectionModel().getSelectedItem();
runResource(selectedRow.get(2));
}
});
}
private boolean isWindows() {
return System.getProperty("os.name").toLowerCase().indexOf("win") >= 0;
}
private boolean isMac() {
return System.getProperty("os.name").toLowerCase().indexOf("mac") >= 0;
}
private void runResource(String resource) {
try {
// TODO dit moet niet van de resource list komen maar van een DB.
var data = this.getClass().getClassLoader().getResourceAsStream(resource).readAllBytes();
var path = Paths.get("out-" + resource);
Files.write(path, data);
Thread.sleep(1000);
var process = new ProcessBuilder();
if(isWindows()) {
process.command("cmd.exe", "/c", "start " + path.toRealPath().toString());
} else if(isMac()) {
process.command("open", path.toRealPath().toString());
} else {
throw new RuntimeException("Ik ken uw OS niet jong");
}
process.start();
} catch (Exception e) {
throw new RuntimeException("resource " + resource + " kan niet ingelezen worden", e);
}
}
private void initTable() {
tblTips.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
tblTips.getColumns().clear();
// TODO zijn dit de juiste kolommen?
int colIndex = 0;
for(var colName : new String[]{"Tip beschrijving", "Grootte in KB", "Handle"}) {
TableColumn<ObservableList<String>, String> col = new TableColumn<>(colName);
final int finalColIndex = colIndex;
col.setCellValueFactory(f -> new ReadOnlyObjectWrapper<>(f.getValue().get(finalColIndex)));
tblTips.getColumns().add(col);
colIndex++;
}
// TODO verwijderen en "echte data" toevoegen!
tblTips.getItems().add(FXCollections.observableArrayList("Mooie muziek om bij te koken", "240", "kooktip-dubbelklik-op-mij.mp3"));
}
}
| KULeuven-Diepenbeek/db-course | examples/java/project-template-202021/src/main/java/be/kuleuven/csa/controller/BeheerTipsController.java | 814 | // TODO verwijderen en "echte data" toevoegen! | line_comment | nl | package be.kuleuven.csa.controller;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
public class BeheerTipsController {
@FXML
private TableView tblTips;
public void initialize() {
initTable();
tblTips.setOnMouseClicked(e -> {
if(e.getClickCount() == 2 && tblTips.getSelectionModel().getSelectedItem() != null) {
var selectedRow = (List<String>) tblTips.getSelectionModel().getSelectedItem();
runResource(selectedRow.get(2));
}
});
}
private boolean isWindows() {
return System.getProperty("os.name").toLowerCase().indexOf("win") >= 0;
}
private boolean isMac() {
return System.getProperty("os.name").toLowerCase().indexOf("mac") >= 0;
}
private void runResource(String resource) {
try {
// TODO dit moet niet van de resource list komen maar van een DB.
var data = this.getClass().getClassLoader().getResourceAsStream(resource).readAllBytes();
var path = Paths.get("out-" + resource);
Files.write(path, data);
Thread.sleep(1000);
var process = new ProcessBuilder();
if(isWindows()) {
process.command("cmd.exe", "/c", "start " + path.toRealPath().toString());
} else if(isMac()) {
process.command("open", path.toRealPath().toString());
} else {
throw new RuntimeException("Ik ken uw OS niet jong");
}
process.start();
} catch (Exception e) {
throw new RuntimeException("resource " + resource + " kan niet ingelezen worden", e);
}
}
private void initTable() {
tblTips.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
tblTips.getColumns().clear();
// TODO zijn dit de juiste kolommen?
int colIndex = 0;
for(var colName : new String[]{"Tip beschrijving", "Grootte in KB", "Handle"}) {
TableColumn<ObservableList<String>, String> col = new TableColumn<>(colName);
final int finalColIndex = colIndex;
col.setCellValueFactory(f -> new ReadOnlyObjectWrapper<>(f.getValue().get(finalColIndex)));
tblTips.getColumns().add(col);
colIndex++;
}
// TODO verwijderen<SUF>
tblTips.getItems().add(FXCollections.observableArrayList("Mooie muziek om bij te koken", "240", "kooktip-dubbelklik-op-mij.mp3"));
}
}
|
84759_1 | package be.kuleuven.scorebord;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Scorebord {
private List<Speler> spelers;
private Gson gsonInstance;
public Scorebord() {
spelers = new ArrayList<>();
gsonInstance = new Gson();
if(Files.exists(Paths.get("score.json"))) {
loadFromFile();
}
}
/**
* Voegt speler toe aan scorebord. Indien reeds aanwezig, telt score op bij huidige score.
* @param spelerNaam de naam van de speler.
* @param score de score van de speler.
*/
public void voegToe(String spelerNaam, int score) {
var current = spelers.stream().filter(s -> s.getNaam().equals(spelerNaam)).findFirst();
if(current.isPresent()) {
current.get().scoor(score);
} else {
spelers.add(new Speler(spelerNaam, score));
}
save();
}
private void save() {
try {
var json = gsonInstance.toJson(spelers);
Files.write(Paths.get("score.json"), json.getBytes());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Wie is gewonnen? (huidige speler met hoogste score)
* @return naam van speler in tekst
*/
public String getWinnaar() {
return spelers.stream()
.sorted(Comparator.comparing(Speler::getScore))
.findFirst()
.orElseGet(() -> new Speler("GEEN")).getNaam();
}
/**
* Geef huidige totale score van de speler
* @param spelerNaam speler naam
* @return score vanuit het bord
*/
public int getTotaleScore(String spelerNaam) {
var result = spelers.stream().filter(s -> s.getNaam().equals(spelerNaam)).findFirst();
return result.isEmpty() ? 0 : result.get().getScore();
}
private void loadFromFile() {
try {
var collectionType = new TypeToken<List<Speler>>(){}.getType();
var json = Files.readString(Paths.get("score.json"));
spelers = gsonInstance.fromJson(json, collectionType);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
| KULeuven-Diepenbeek/ses-course | examples/java/scorebord/src/main/java/be/kuleuven/scorebord/Scorebord.java | 744 | /**
* Wie is gewonnen? (huidige speler met hoogste score)
* @return naam van speler in tekst
*/ | block_comment | nl | package be.kuleuven.scorebord;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Scorebord {
private List<Speler> spelers;
private Gson gsonInstance;
public Scorebord() {
spelers = new ArrayList<>();
gsonInstance = new Gson();
if(Files.exists(Paths.get("score.json"))) {
loadFromFile();
}
}
/**
* Voegt speler toe aan scorebord. Indien reeds aanwezig, telt score op bij huidige score.
* @param spelerNaam de naam van de speler.
* @param score de score van de speler.
*/
public void voegToe(String spelerNaam, int score) {
var current = spelers.stream().filter(s -> s.getNaam().equals(spelerNaam)).findFirst();
if(current.isPresent()) {
current.get().scoor(score);
} else {
spelers.add(new Speler(spelerNaam, score));
}
save();
}
private void save() {
try {
var json = gsonInstance.toJson(spelers);
Files.write(Paths.get("score.json"), json.getBytes());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Wie is gewonnen?<SUF>*/
public String getWinnaar() {
return spelers.stream()
.sorted(Comparator.comparing(Speler::getScore))
.findFirst()
.orElseGet(() -> new Speler("GEEN")).getNaam();
}
/**
* Geef huidige totale score van de speler
* @param spelerNaam speler naam
* @return score vanuit het bord
*/
public int getTotaleScore(String spelerNaam) {
var result = spelers.stream().filter(s -> s.getNaam().equals(spelerNaam)).findFirst();
return result.isEmpty() ? 0 : result.get().getScore();
}
private void loadFromFile() {
try {
var collectionType = new TypeToken<List<Speler>>(){}.getType();
var json = Files.readString(Paths.get("score.json"));
spelers = gsonInstance.fromJson(json, collectionType);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
|
156510_0 | package be.kuleuven.speculaas.opgave4;
public class Verkoopster {
private SpeculaasFabriek speculaasFabriek;
public void setSpeculaasFabriek(SpeculaasFabriek speculaasFabriek) {
this.speculaasFabriek = speculaasFabriek;
}
public Verkoopster() {
}
public double verkoop() {
var gebakken = speculaasFabriek.bak();
if(gebakken.size() > 5) {
// TODO opgave 4; zie README.md
}
return 0;
}
}
| KULeuven-Diepenbeek/ses-tdd-exercise-1-template | java/src/main/java/be/kuleuven/speculaas/opgave4/Verkoopster.java | 178 | // TODO opgave 4; zie README.md | line_comment | nl | package be.kuleuven.speculaas.opgave4;
public class Verkoopster {
private SpeculaasFabriek speculaasFabriek;
public void setSpeculaasFabriek(SpeculaasFabriek speculaasFabriek) {
this.speculaasFabriek = speculaasFabriek;
}
public Verkoopster() {
}
public double verkoop() {
var gebakken = speculaasFabriek.bak();
if(gebakken.size() > 5) {
// TODO opgave<SUF>
}
return 0;
}
}
|