file_id
stringlengths
5
10
content
stringlengths
110
41.7k
repo
stringlengths
7
108
path
stringlengths
8
211
token_length
int64
35
8.19k
original_comment
stringlengths
11
5.72k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
prompt
stringlengths
73
41.6k
12568_14
/* * Copyright (c) 2004-2020 The YAWL Foundation. All rights reserved. * The YAWL Foundation is a collaboration of individuals and * organisations who are committed to improving workflow technology. * * This file is part of YAWL. YAWL is free software: you can * redistribute it and/or modify it under the terms of the GNU Lesser * General Public License as published by the Free Software Foundation. * * YAWL 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 Lesser General * Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with YAWL. If not, see <http://www.gnu.org/licenses/>. */ package org.yawlfoundation.yawl.wsif; import org.yawlfoundation.yawl.engine.interfce.AuthenticationConfig; import org.apache.wsif.*; import org.apache.wsif.providers.ProviderUtils; import org.apache.wsif.providers.soap.apachesoap.WSIFDynamicProvider_ApacheSOAP; import org.apache.wsif.util.WSIFPluggableProviders; import org.apache.wsif.util.WSIFUtils; import org.jdom2.Element; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import javax.wsdl.*; import javax.xml.namespace.QName; import java.util.*; /** * @author Sanjiva Weerawarana * @author Alekander Slominski * @author Lachlan Aldred */ public class WSIFInvoker { public static HashMap invokeMethod(String wsdlLocation, String portName, String operationName, Element inputDataDoc, AuthenticationConfig authconfig) { System.out.println("XMLOutputter = " + new XMLOutputter(Format.getPrettyFormat()).outputString(inputDataDoc)); System.out.println("wsdl location = " + wsdlLocation); System.out.println("port name = " + portName); System.out.println("operation name = " + operationName); List<String> argsV = new ArrayList<String>(); for (Element element : inputDataDoc.getChildren()) { argsV.add(element.getText()); } String[] args = new String[argsV.size()]; argsV.toArray(args); return invokeMethod( wsdlLocation, operationName, null, null, portName, null, args, 0, authconfig); } public static HashMap invokeMethod(String wsdlLocation, String operationName, String inputName, String outputName, String portName, String protocol, String[] args, int argShift, AuthenticationConfig authconfig) { for (String arg : args) { System.out.println("argValue: " + arg); } HashMap map = new HashMap(); try { String serviceNS = null; String serviceName = null; String portTypeNS = null; String portTypeName = null; // The default SOAP provider is the Apache AXIS provider. If soap was specified // then change the Apache SOAP provider if ("soap".equals(protocol)) { WSIFPluggableProviders.overrideDefaultProvider( "http://schemas.xmlsoap.org/wsdl/soap/", new WSIFDynamicProvider_ApacheSOAP()); } System.out.println("Reading WSDL document from '" + wsdlLocation + "'"); Definition wsdlDefinition = null; if (authconfig == null) { return null; } String userName = authconfig.getUserName(); String password = authconfig.getPassword(); String proxyHost = authconfig.getProxyHost(); String proxyPort = authconfig.getProxyPort(); if (userName != null && userName.length() > 0 && password != null && password.length() > 0 && proxyHost != null && password.length() > 0 && proxyPort != null && proxyPort.length() > 0) { System.getProperties().put("http.proxyHost", proxyHost); System.getProperties().put("http.proxyPort", proxyPort); java.net.PasswordAuthentication pa = new java.net.PasswordAuthentication( userName, password.toCharArray()); wsdlDefinition = WSIFUtils.readWSDLThroughAuthProxy(wsdlLocation, pa); } else { wsdlDefinition = WSIFUtils.readWSDL(null, wsdlLocation); } System.out.println("Preparing WSIF dynamic invocation"); Service service = WSIFUtils.selectService(wsdlDefinition, serviceNS, serviceName); Map portTypes = WSIFUtils.getAllItems(wsdlDefinition, "PortType"); // Really there should be a way to specify the portType // for now just try to find one with the portName if (portTypes.size() > 1 && portName != null) { for (Iterator i = portTypes.keySet().iterator(); i.hasNext();) { QName qn = (QName) i.next(); System.out.println("qn.getLocalPart() = " + qn.getLocalPart()); if (portName.equals(qn.getLocalPart())) { portTypeName = qn.getLocalPart(); portTypeNS = qn.getNamespaceURI(); System.out.println("portTypeName = " + portTypeName); System.out.println("portTypeNS = " + portTypeNS); break; } } } PortType portType = WSIFUtils.selectPortType(wsdlDefinition, portTypeNS, portTypeName); WSIFServiceFactory factory = WSIFServiceFactory.newInstance(); WSIFService dpf = factory.getService(wsdlDefinition, service, portType); WSIFMessage ctx = dpf.getContext(); ctx.setObjectPart(WSIFConstants.CONTEXT_HTTP_PROXY_USER, authconfig.getUserName()); ctx.setObjectPart(WSIFConstants.CONTEXT_HTTP_PROXY_PSWD, authconfig.getPassword()); dpf.setContext(ctx); WSIFPort port = null; if (portName == null) { port = dpf.getPort(); } else { port = dpf.getPort(portName); } if (inputName == null && outputName == null) { // retrieve list of operations List operationList = portType.getOperations(); // try to find input and output names for the operation specified boolean found = false; for (Iterator i = operationList.iterator(); i.hasNext();) { Operation op = (Operation) i.next(); String name = op.getName(); if (!name.equals(operationName)) { continue; } if (found) { throw new RuntimeException( "Operation '" + operationName + "' is overloaded. " + "Please specify the operation in the form " + "'operationName:inputMessageName:outputMesssageName'" + " to distinguish it"); } found = true; Input opInput = op.getInput(); inputName = (opInput.getName() == null) ? null : opInput.getName(); Output opOutput = op.getOutput(); outputName = (opOutput.getName() == null) ? null : opOutput.getName(); } } WSIFOperation operation = port.createOperation(operationName, inputName, outputName); WSIFMessage input = operation.createInputMessage(); WSIFMessage output = operation.createOutputMessage(); WSIFMessage fault = operation.createFaultMessage(); // retrieve list of names and types for input and names for output List operationList = portType.getOperations(); // find portType operation to prepare in/oout message w/ parts boolean found = false; String[] outNames = new String[0]; Class[] outTypes = new Class[0]; for (Iterator i = operationList.iterator(); i.hasNext();) { Operation op = (Operation) i.next(); String name = op.getName(); if (!name.equals(operationName)) { continue; } if (found) { throw new RuntimeException("overloaded operations are not supported in this sample"); } found = true; //System.err.println("op = "+op); Input opInput = op.getInput(); // first determine list of arguments String[] inNames = new String[0]; Class[] inTypes = new Class[0]; if (opInput != null) { List parts = opInput.getMessage().getOrderedParts(null); unWrapIfWrappedDocLit(parts, name, wsdlDefinition); int count = parts.size(); inNames = new String[count]; inTypes = new Class[count]; retrieveSignature(parts, inNames, inTypes); } // now prepare out parameters for (int pos = 0; pos < inNames.length; ++pos) { String arg = args[pos + argShift]; Object value = null; Class c = inTypes[pos]; if (c.equals(String.class)) { value = arg; } else if (c.equals(Double.TYPE)) { value = new Double(arg); } else if (c.equals(Float.TYPE)) { value = new Float(arg); } else if (c.equals(Integer.TYPE)) { value = new Integer(arg); } else if (c.equals(Boolean.TYPE)) { value = Boolean.valueOf(arg); } else { throw new RuntimeException("not know how to convert '" + arg + "' into " + c); } input.setObjectPart(inNames[pos], value); } Output opOutput = op.getOutput(); if (opOutput != null) { List parts = opOutput.getMessage().getOrderedParts(null); unWrapIfWrappedDocLit(parts, name + "Response", wsdlDefinition); int count = parts.size(); outNames = new String[count]; outTypes = new Class[count]; retrieveSignature(parts, outNames, outTypes); } } if (!found) { throw new RuntimeException( "no operation " + operationName + " was found in port type " + portType.getQName()); } System.out.println("Executing operation " + operationName); operation.executeRequestResponseOperation(input, output, fault); for (int pos = 0; pos < outNames.length; ++pos) { String name = outNames[pos]; map.put(name, output.getObjectPart(name)); } System.getProperties().remove("http.proxyHost"); System.getProperties().remove("http.proxyPort"); } catch (WSDLException e) { e.printStackTrace(); System.out.println("" + "\n\n" + "#########################################################################\n" + "################### Warning From YAWL Engine ###################\n" + "#########################################################################\n" + "#### \n" + "#### \n" + "#### Engine failed to read the WSDL file needed to invoke \n" + "#### the service. This is either because: \n" + "#### a) The authenication settings are not correct. \n" + "#### This can be checked by pointing a browser to \n" + "#### http://localhost:8080/yawlWSInvoker and \n" + "#### following the on screen instructions. \n" + "#### b) The WSDL at " + wsdlLocation + " is currently\n" + "#### unavailable. \n" + "#### \n" + "#### \n" + "#########################################################################\n" + "#########################################################################\n" + "#########################################################################\n" + "\n\n"); } catch (WSIFException e) { e.printStackTrace(); } return map; } private static void retrieveSignature( List parts, String[] names, Class[] types) { // get parts in correct order for (int i = 0; i < names.length; ++i) { Part part = (Part) parts.get(i); names[i] = part.getName(); QName partType = part.getTypeName(); if (partType == null) { partType = part.getElementName(); } if (partType == null) { throw new RuntimeException( "part " + names[i] + " must have type name declared"); } // only limited number of types is supported // cheerfully ignoring schema namespace ... String s = partType.getLocalPart(); if ("string".equals(s)) { types[i] = String.class; } else if ("double".equals(s) || "decimal".equals(s)) { types[i] = Double.TYPE; } else if ("float".equals(s)) { types[i] = Float.TYPE; } else if ("int".equals(s)) { types[i] = Integer.TYPE; } else if ("boolean".equals(s)) { types[i] = Boolean.TYPE; } else { throw new RuntimeException( "part type " + partType + " not supported in this sample"); } } } /** * Unwraps the top level part if this a wrapped DocLit message. */ private static void unWrapIfWrappedDocLit(List parts, String operationName, Definition def) throws WSIFException { Part p = ProviderUtils.getWrapperPart(parts, operationName); if (p != null) { List unWrappedParts = ProviderUtils.unWrapPart(p, def); if (unWrappedParts != null && unWrappedParts.size() > 0) { parts.remove(p); parts.addAll(unWrappedParts); } } } }
yawlfoundation/yawl
src/org/yawlfoundation/yawl/wsif/WSIFInvoker.java
3,489
// get parts in correct order
line_comment
nl
/* * Copyright (c) 2004-2020 The YAWL Foundation. All rights reserved. * The YAWL Foundation is a collaboration of individuals and * organisations who are committed to improving workflow technology. * * This file is part of YAWL. YAWL is free software: you can * redistribute it and/or modify it under the terms of the GNU Lesser * General Public License as published by the Free Software Foundation. * * YAWL 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 Lesser General * Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with YAWL. If not, see <http://www.gnu.org/licenses/>. */ package org.yawlfoundation.yawl.wsif; import org.yawlfoundation.yawl.engine.interfce.AuthenticationConfig; import org.apache.wsif.*; import org.apache.wsif.providers.ProviderUtils; import org.apache.wsif.providers.soap.apachesoap.WSIFDynamicProvider_ApacheSOAP; import org.apache.wsif.util.WSIFPluggableProviders; import org.apache.wsif.util.WSIFUtils; import org.jdom2.Element; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import javax.wsdl.*; import javax.xml.namespace.QName; import java.util.*; /** * @author Sanjiva Weerawarana * @author Alekander Slominski * @author Lachlan Aldred */ public class WSIFInvoker { public static HashMap invokeMethod(String wsdlLocation, String portName, String operationName, Element inputDataDoc, AuthenticationConfig authconfig) { System.out.println("XMLOutputter = " + new XMLOutputter(Format.getPrettyFormat()).outputString(inputDataDoc)); System.out.println("wsdl location = " + wsdlLocation); System.out.println("port name = " + portName); System.out.println("operation name = " + operationName); List<String> argsV = new ArrayList<String>(); for (Element element : inputDataDoc.getChildren()) { argsV.add(element.getText()); } String[] args = new String[argsV.size()]; argsV.toArray(args); return invokeMethod( wsdlLocation, operationName, null, null, portName, null, args, 0, authconfig); } public static HashMap invokeMethod(String wsdlLocation, String operationName, String inputName, String outputName, String portName, String protocol, String[] args, int argShift, AuthenticationConfig authconfig) { for (String arg : args) { System.out.println("argValue: " + arg); } HashMap map = new HashMap(); try { String serviceNS = null; String serviceName = null; String portTypeNS = null; String portTypeName = null; // The default SOAP provider is the Apache AXIS provider. If soap was specified // then change the Apache SOAP provider if ("soap".equals(protocol)) { WSIFPluggableProviders.overrideDefaultProvider( "http://schemas.xmlsoap.org/wsdl/soap/", new WSIFDynamicProvider_ApacheSOAP()); } System.out.println("Reading WSDL document from '" + wsdlLocation + "'"); Definition wsdlDefinition = null; if (authconfig == null) { return null; } String userName = authconfig.getUserName(); String password = authconfig.getPassword(); String proxyHost = authconfig.getProxyHost(); String proxyPort = authconfig.getProxyPort(); if (userName != null && userName.length() > 0 && password != null && password.length() > 0 && proxyHost != null && password.length() > 0 && proxyPort != null && proxyPort.length() > 0) { System.getProperties().put("http.proxyHost", proxyHost); System.getProperties().put("http.proxyPort", proxyPort); java.net.PasswordAuthentication pa = new java.net.PasswordAuthentication( userName, password.toCharArray()); wsdlDefinition = WSIFUtils.readWSDLThroughAuthProxy(wsdlLocation, pa); } else { wsdlDefinition = WSIFUtils.readWSDL(null, wsdlLocation); } System.out.println("Preparing WSIF dynamic invocation"); Service service = WSIFUtils.selectService(wsdlDefinition, serviceNS, serviceName); Map portTypes = WSIFUtils.getAllItems(wsdlDefinition, "PortType"); // Really there should be a way to specify the portType // for now just try to find one with the portName if (portTypes.size() > 1 && portName != null) { for (Iterator i = portTypes.keySet().iterator(); i.hasNext();) { QName qn = (QName) i.next(); System.out.println("qn.getLocalPart() = " + qn.getLocalPart()); if (portName.equals(qn.getLocalPart())) { portTypeName = qn.getLocalPart(); portTypeNS = qn.getNamespaceURI(); System.out.println("portTypeName = " + portTypeName); System.out.println("portTypeNS = " + portTypeNS); break; } } } PortType portType = WSIFUtils.selectPortType(wsdlDefinition, portTypeNS, portTypeName); WSIFServiceFactory factory = WSIFServiceFactory.newInstance(); WSIFService dpf = factory.getService(wsdlDefinition, service, portType); WSIFMessage ctx = dpf.getContext(); ctx.setObjectPart(WSIFConstants.CONTEXT_HTTP_PROXY_USER, authconfig.getUserName()); ctx.setObjectPart(WSIFConstants.CONTEXT_HTTP_PROXY_PSWD, authconfig.getPassword()); dpf.setContext(ctx); WSIFPort port = null; if (portName == null) { port = dpf.getPort(); } else { port = dpf.getPort(portName); } if (inputName == null && outputName == null) { // retrieve list of operations List operationList = portType.getOperations(); // try to find input and output names for the operation specified boolean found = false; for (Iterator i = operationList.iterator(); i.hasNext();) { Operation op = (Operation) i.next(); String name = op.getName(); if (!name.equals(operationName)) { continue; } if (found) { throw new RuntimeException( "Operation '" + operationName + "' is overloaded. " + "Please specify the operation in the form " + "'operationName:inputMessageName:outputMesssageName'" + " to distinguish it"); } found = true; Input opInput = op.getInput(); inputName = (opInput.getName() == null) ? null : opInput.getName(); Output opOutput = op.getOutput(); outputName = (opOutput.getName() == null) ? null : opOutput.getName(); } } WSIFOperation operation = port.createOperation(operationName, inputName, outputName); WSIFMessage input = operation.createInputMessage(); WSIFMessage output = operation.createOutputMessage(); WSIFMessage fault = operation.createFaultMessage(); // retrieve list of names and types for input and names for output List operationList = portType.getOperations(); // find portType operation to prepare in/oout message w/ parts boolean found = false; String[] outNames = new String[0]; Class[] outTypes = new Class[0]; for (Iterator i = operationList.iterator(); i.hasNext();) { Operation op = (Operation) i.next(); String name = op.getName(); if (!name.equals(operationName)) { continue; } if (found) { throw new RuntimeException("overloaded operations are not supported in this sample"); } found = true; //System.err.println("op = "+op); Input opInput = op.getInput(); // first determine list of arguments String[] inNames = new String[0]; Class[] inTypes = new Class[0]; if (opInput != null) { List parts = opInput.getMessage().getOrderedParts(null); unWrapIfWrappedDocLit(parts, name, wsdlDefinition); int count = parts.size(); inNames = new String[count]; inTypes = new Class[count]; retrieveSignature(parts, inNames, inTypes); } // now prepare out parameters for (int pos = 0; pos < inNames.length; ++pos) { String arg = args[pos + argShift]; Object value = null; Class c = inTypes[pos]; if (c.equals(String.class)) { value = arg; } else if (c.equals(Double.TYPE)) { value = new Double(arg); } else if (c.equals(Float.TYPE)) { value = new Float(arg); } else if (c.equals(Integer.TYPE)) { value = new Integer(arg); } else if (c.equals(Boolean.TYPE)) { value = Boolean.valueOf(arg); } else { throw new RuntimeException("not know how to convert '" + arg + "' into " + c); } input.setObjectPart(inNames[pos], value); } Output opOutput = op.getOutput(); if (opOutput != null) { List parts = opOutput.getMessage().getOrderedParts(null); unWrapIfWrappedDocLit(parts, name + "Response", wsdlDefinition); int count = parts.size(); outNames = new String[count]; outTypes = new Class[count]; retrieveSignature(parts, outNames, outTypes); } } if (!found) { throw new RuntimeException( "no operation " + operationName + " was found in port type " + portType.getQName()); } System.out.println("Executing operation " + operationName); operation.executeRequestResponseOperation(input, output, fault); for (int pos = 0; pos < outNames.length; ++pos) { String name = outNames[pos]; map.put(name, output.getObjectPart(name)); } System.getProperties().remove("http.proxyHost"); System.getProperties().remove("http.proxyPort"); } catch (WSDLException e) { e.printStackTrace(); System.out.println("" + "\n\n" + "#########################################################################\n" + "################### Warning From YAWL Engine ###################\n" + "#########################################################################\n" + "#### \n" + "#### \n" + "#### Engine failed to read the WSDL file needed to invoke \n" + "#### the service. This is either because: \n" + "#### a) The authenication settings are not correct. \n" + "#### This can be checked by pointing a browser to \n" + "#### http://localhost:8080/yawlWSInvoker and \n" + "#### following the on screen instructions. \n" + "#### b) The WSDL at " + wsdlLocation + " is currently\n" + "#### unavailable. \n" + "#### \n" + "#### \n" + "#########################################################################\n" + "#########################################################################\n" + "#########################################################################\n" + "\n\n"); } catch (WSIFException e) { e.printStackTrace(); } return map; } private static void retrieveSignature( List parts, String[] names, Class[] types) { // get parts<SUF> for (int i = 0; i < names.length; ++i) { Part part = (Part) parts.get(i); names[i] = part.getName(); QName partType = part.getTypeName(); if (partType == null) { partType = part.getElementName(); } if (partType == null) { throw new RuntimeException( "part " + names[i] + " must have type name declared"); } // only limited number of types is supported // cheerfully ignoring schema namespace ... String s = partType.getLocalPart(); if ("string".equals(s)) { types[i] = String.class; } else if ("double".equals(s) || "decimal".equals(s)) { types[i] = Double.TYPE; } else if ("float".equals(s)) { types[i] = Float.TYPE; } else if ("int".equals(s)) { types[i] = Integer.TYPE; } else if ("boolean".equals(s)) { types[i] = Boolean.TYPE; } else { throw new RuntimeException( "part type " + partType + " not supported in this sample"); } } } /** * Unwraps the top level part if this a wrapped DocLit message. */ private static void unWrapIfWrappedDocLit(List parts, String operationName, Definition def) throws WSIFException { Part p = ProviderUtils.getWrapperPart(parts, operationName); if (p != null) { List unWrappedParts = ProviderUtils.unWrapPart(p, def); if (unWrappedParts != null && unWrappedParts.size() > 0) { parts.remove(p); parts.addAll(unWrappedParts); } } } }
153995_10
/* * Copyright 2010 Mario Zechner ([email protected]), Nathan Sweet ([email protected]) * * 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.badlogic.invaders; import com.badlogic.gdx.Application.ApplicationType; import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.InputAdapter; import com.badlogic.gdx.audio.Music; import com.badlogic.gdx.graphics.FPSLogger; import com.badlogic.invaders.screens.GameLoop; import com.badlogic.invaders.screens.GameOver; import com.badlogic.invaders.screens.InvadersScreen; import com.badlogic.invaders.screens.MainMenu; public class Invaders extends Game { /** Music needs to be a class property to prevent being disposed. */ private Music music; private FPSLogger fps; @Override public void render () { InvadersScreen currentScreen = getScreen(); // update the screen currentScreen.render(Gdx.graphics.getDeltaTime()); // When the screen is done we change to the // next screen. Ideally the screen transitions are handled // in the screen itself or in a proper state machine. if (currentScreen.isDone()) { // dispose the resources of the current screen currentScreen.dispose(); // if the current screen is a main menu screen we switch to // the game loop if (currentScreen instanceof MainMenu) { setScreen(new GameLoop()); } else { // if the current screen is a game loop screen we switch to the // game over screen if (currentScreen instanceof GameLoop) { setScreen(new GameOver()); } else if (currentScreen instanceof GameOver) { // if the current screen is a game over screen we switch to the // main menu screen setScreen(new MainMenu()); } } } fps.log(); } @Override public void create () { setScreen(new MainMenu()); music = Gdx.audio.newMusic(Gdx.files.getFileHandle("data/8.12.mp3", FileType.Internal)); music.setLooping(true); music.play(); Gdx.input.setInputProcessor(new InputAdapter() { @Override public boolean keyUp (int keycode) { if (keycode == Keys.ENTER && Gdx.app.getType() == ApplicationType.WebGL) { if (!Gdx.graphics.isFullscreen()) Gdx.graphics.setDisplayMode(Gdx.graphics.getDisplayModes()[0]); } return true; } }); fps = new FPSLogger(); } /** For this game each of our screens is an instance of InvadersScreen. * @return the currently active {@link InvadersScreen}. */ @Override public InvadersScreen getScreen () { return (InvadersScreen)super.getScreen(); } }
haroldcalayan/libgdx-demo-invaders
core/src/com/badlogic/invaders/Invaders.java
858
// game over screen
line_comment
nl
/* * Copyright 2010 Mario Zechner ([email protected]), Nathan Sweet ([email protected]) * * 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.badlogic.invaders; import com.badlogic.gdx.Application.ApplicationType; import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.InputAdapter; import com.badlogic.gdx.audio.Music; import com.badlogic.gdx.graphics.FPSLogger; import com.badlogic.invaders.screens.GameLoop; import com.badlogic.invaders.screens.GameOver; import com.badlogic.invaders.screens.InvadersScreen; import com.badlogic.invaders.screens.MainMenu; public class Invaders extends Game { /** Music needs to be a class property to prevent being disposed. */ private Music music; private FPSLogger fps; @Override public void render () { InvadersScreen currentScreen = getScreen(); // update the screen currentScreen.render(Gdx.graphics.getDeltaTime()); // When the screen is done we change to the // next screen. Ideally the screen transitions are handled // in the screen itself or in a proper state machine. if (currentScreen.isDone()) { // dispose the resources of the current screen currentScreen.dispose(); // if the current screen is a main menu screen we switch to // the game loop if (currentScreen instanceof MainMenu) { setScreen(new GameLoop()); } else { // if the current screen is a game loop screen we switch to the // game over<SUF> if (currentScreen instanceof GameLoop) { setScreen(new GameOver()); } else if (currentScreen instanceof GameOver) { // if the current screen is a game over screen we switch to the // main menu screen setScreen(new MainMenu()); } } } fps.log(); } @Override public void create () { setScreen(new MainMenu()); music = Gdx.audio.newMusic(Gdx.files.getFileHandle("data/8.12.mp3", FileType.Internal)); music.setLooping(true); music.play(); Gdx.input.setInputProcessor(new InputAdapter() { @Override public boolean keyUp (int keycode) { if (keycode == Keys.ENTER && Gdx.app.getType() == ApplicationType.WebGL) { if (!Gdx.graphics.isFullscreen()) Gdx.graphics.setDisplayMode(Gdx.graphics.getDisplayModes()[0]); } return true; } }); fps = new FPSLogger(); } /** For this game each of our screens is an instance of InvadersScreen. * @return the currently active {@link InvadersScreen}. */ @Override public InvadersScreen getScreen () { return (InvadersScreen)super.getScreen(); } }
203435_1
package com.example.pattern.model; public class PersonenAuto extends Product { private double gewicht; private double motorinhoud; public PersonenAuto(String merk, double gewicht, double motorinhoud) { super(merk); this.gewicht = gewicht; this.motorinhoud = motorinhoud; } public double getGewicht() { return gewicht; } public double getMotorinhoud() { return motorinhoud; } @Override public double getHuurPrijs() { return 50.0; // Huurprijs is 50 euro per dag } @Override public double getVerzekeringPrijs() { return 0.01 * motorinhoud; // Verzekering is 0,01 euro per cc motorinhoud per dag } }
Ozancann01/pattern
src/main/java/com/example/pattern/model/PersonenAuto.java
203
// Verzekering is 0,01 euro per cc motorinhoud per dag
line_comment
nl
package com.example.pattern.model; public class PersonenAuto extends Product { private double gewicht; private double motorinhoud; public PersonenAuto(String merk, double gewicht, double motorinhoud) { super(merk); this.gewicht = gewicht; this.motorinhoud = motorinhoud; } public double getGewicht() { return gewicht; } public double getMotorinhoud() { return motorinhoud; } @Override public double getHuurPrijs() { return 50.0; // Huurprijs is 50 euro per dag } @Override public double getVerzekeringPrijs() { return 0.01 * motorinhoud; // Verzekering is<SUF> } }
26207_24
package utilities; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.StringTokenizer; /** * Deze class representeert een datum object en voorziet elementaire testen * * @author Mathy Paesen * @date 24 september 2009 */ public class Date implements Comparable<Date> { public static final int LONG_JUL = 1000; // berekening van Julian datum public static final int LEAP_YEAR = 366; public static final int NORMAL_YEAR = 365; public static final int AANTAL_MAANDEN = 12; public static final int CORRECTIE_MAAND = 1; // maanden worden bewaard van 0 - 11 public static final int EERSTE_MAAND = 0; public static final int LAATSTE_MAAND = 11; public static final int DATUM_CORRECT = 0; public static final int DAG_KLEINER = -1; public static final int MAAND_KLEINER = -2; public static final int JAAR_KLEINER = -3; public static final int DAG_GROTER = 1; public static final int MAAND_GROTER = 2; public static final int JAAR_GROTER = 3; public static final String SEPARATOR = "/"; public static final String[] MAAND_TEXT = { "Januari", "Februari", "Maart", "April", "Mei", "Juni", "Juli", "Augustus", "September", "Oktober", "November", "December" }; private int dag; private int maand; private int jaar; private long longDate; public Date() throws DatumException { GregorianCalendar gc; gc = new GregorianCalendar(); this.setDag(gc.get(Calendar.DATE)); this.setMaand(gc.get(Calendar.MONTH)); this.setJaar(gc.get(Calendar.YEAR)); testDatum(); } public Date(long l)throws DatumException{ Calendar cal = new GregorianCalendar(); cal.setTime(new java.util.Date(l)); this.setDag(cal.get(Calendar.DATE)); this.setMaand(cal.get(Calendar.MONTH)); this.setJaar(cal.get(Calendar.YEAR)); testDatum(); } public Date(int dag, int maand, int jaar) throws DatumException { super(); this.setDag(dag); this.setMaand(maand); this.setJaar(jaar); testDatum(); } public Date(Date date) throws DatumException { this(date.getDag(), date.getMaand() , date .getJaar()); testDatum(); } public Date(String datum) throws DatumException { /* DD/MM/JJJJ */ StringTokenizer tokenizer = new StringTokenizer(datum, SEPARATOR); int i = 0; while (tokenizer.hasMoreTokens()) { switch (i) { case 0: this.setDag(Integer.parseInt((String) tokenizer.nextElement())); break; case 1: this.setMaand(Integer.parseInt((String) tokenizer.nextElement()) ); // maanden worden bewaard van 0 - 11 break; case 2: this.setJaar(Integer.parseInt((String) tokenizer.nextElement())); break; default: this.setDag(0); this.setMaand(0); this.setJaar(0); } i++; } testDatum(); } /** * Indien een datum object niet correct is wordt een DatumException * gegenereerd * * @throws DatumException */ private void testDatum() throws DatumException { // maand 0-11 GregorianCalendar testDatum = new GregorianCalendar(this.jaar, this.maand, this.dag); testDatum.setLenient(false);// enkel correcte datums toegelaten (geen // omrekening) try { testDatum.get(Calendar.YEAR); testDatum.get(Calendar.MONTH); testDatum.get(Calendar.DAY_OF_MONTH); } catch (Exception e) { throw new DatumException(this); } longDate = testDatum.getTime().getTime(); } public int getDag() { return dag; } public void setDag(int dag) { this.dag = dag; } public int getMaand() { return maand; // maanden worden bewaard van 0 - 11 } public void setMaand(int maand) { this.maand = maand; } public int getJaar() { return jaar; } public void setJaar(int jaar) { this.jaar = jaar; } /** * Enkel correcte data mogen toegelaten worden. * * @param jaar * @param maand * @param dag * @return true, false */ public boolean setDatum(int dag, int maand, int jaar) { boolean correct = false; try { new Date(dag, maand, jaar); this.setDag(dag); this.setMaand(maand); this.setJaar(jaar); correct = true; } catch (DatumException e) { correct = false; System.err.println("[" + jaar + SEPARATOR + maand + SEPARATOR + dag + "]" + e); } return correct; } /** * Date in USA formaat * * @return MM/DD/YYYY */ public String getDatumInAmerikaansFormaat() { return String.format("%s%s%s", getMaand()+CORRECTIE_MAAND + SEPARATOR, getDag() + SEPARATOR, getJaar()); } /** * Date in EUR formaat * * @return DD/MM/YYYY */ public String getDatumInEuropeesFormaat() { return String.format("%s%s%s", getDag() + SEPARATOR, getMaand()+CORRECTIE_MAAND + SEPARATOR, getJaar()); } /** * @return Januari, ..., December */ public String getMaandText() { if (getMaand() > LAATSTE_MAAND || getMaand() < EERSTE_MAAND) { return "Verkeerde maand"; } return MAAND_TEXT[getMaand()]; } /* * String representatie van deze datum * * @see java.lang.Object#toString() */ @Override public String toString() { return getDag() + " " + getMaandText() + " " + getJaar(); } public String toString(String sep) { return getDag() + sep + getMaand() + sep + getJaar(); } /** * Is deze datum gelijk aan een ander datum object * * @param date * @return */ public boolean equals(Date date) { if (this.getDag() != date.getDag()) { return false; } else if (this.getMaand() != date.getMaand()) { return false; } else if (this.getJaar() != date.getJaar()) { return false; } return true; } /** * 0 Deze datum en de parameter datum zijn gelijk -1 Als de dag van de maand * van deze datum kleiner is dan die van een ander datum object -2 Als de * maand van deze datum kleiner is dan die van een ander datum object -3 Als * het jaar van deze datum kleiner is dan die van een ander datum object * * @param date * @return -1, -2, -3, 0 */ public int compareTo(Date date) { if (this.getJaar() < date.getJaar()) { return JAAR_KLEINER; } if (this.getJaar() > date.getJaar()) { return JAAR_GROTER; } if (this.getMaand() < date.getMaand()) { return MAAND_KLEINER; } if (this.getMaand() > date.getMaand()) { return MAAND_GROTER; } if (this.getDag() < date.getDag()) { return DAG_KLEINER; } if (this.getDag() > date.getDag()) { return DAG_GROTER; } return DATUM_CORRECT; } /** * Is deze datum kleiner dan een ander datum object * * @param date * @return */ public boolean kleinerDan(Date date) { if (this.compareTo(date) < DATUM_CORRECT) { return true; } return false; } /** * Bereken het verschil in jaren tussen deze datum en een ander datum object * * @param date * @return */ public int verschilInJaren(Date date) { return this.getJaar() - date.getJaar(); } /** * Bereken het verschil in maanden tussen deze datum en een ander datum * object * * @param date * @return */ public int verschilInMaanden(Date date) { int verschil = this.verschilInJaren(date); verschil *= AANTAL_MAANDEN; verschil += (this.getMaand() - date.getMaand()); return verschil; } /** * Bereken het verschil in dagen tussen deze datum en een ander datum object * * @param date * @return */ public int verschilInDagen(Date date) { int verschil = 0; Date test; try { test = new Date(this); for (int i = 0; i < this.verschilInJaren(date); i++) { test.setJaar(test.getJaar() - 1); verschil += test.aantalDagen(); } } catch (DatumException e) { e.printStackTrace(); } verschil += this.dagVanHetJaar() - date.dagVanHetJaar(); return verschil; } /** * Schrikkeljaar of niet * * @return true, false */ public boolean isLeapYear() { if ((this.getJaar() % 400 == 0) || ((this.getJaar() % 4 == 0) && (this.getJaar() % 100 != 0))) { return true; } return false; } /** * Bereken aantal dagen van een maand * * @return { 31, 28/29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } */ public int dagVanHetJaar() { int dagen[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int totaal = 0; for (int maand = 0; maand < this.getMaand(); maand++) { // huidige maand nog niet meetellen totaal += dagen[maand]; if (this.isLeapYear() && maand == 1) { totaal += 1; // 29 ipv 28 dagen } } totaal += this.getDag(); return totaal; } /** * Dag van het jaar * * @return xxx/1-366 */ public int julianDatum() { int totaal = this.getJaar() * LONG_JUL; return totaal += dagVanHetJaar(); } /** * Aantal dagen van het jaar * * @return 365 of 366 */ public int aantalDagen() { if (this.isLeapYear()) { return LEAP_YEAR; } return NORMAL_YEAR; } /** * Wijzig een datum met een aantal dagen (+/-) * * @param aantalDagen */ public void veranderDatum(int aantalDagen) { this.setDag(this.getDag() + aantalDagen); GregorianCalendar gc = new GregorianCalendar(); gc.setLenient(true); gc.set(this.getJaar(), this.getMaand(), this.getDag()); this.setDag(gc.get(Calendar.DAY_OF_MONTH)); this.setMaand(gc.get(Calendar.MONTH)); this.setJaar(gc.get(Calendar.YEAR)); } /** * Berekening van een Unieke int Wordt gebruikt door de equals method * * @return int */ public int hashCode() { return julianDatum(); } /** * Geeft steeds de laatste dag van de maand * * @param Date * @return Date * @throws DatumException */ public static Date laatsteDagVanDeMaand(Date date) throws DatumException { GregorianCalendar gc = new GregorianCalendar(date.jaar, date.maand, date.getDag()); int dagVanDeMaand = gc.get(Calendar.DAY_OF_MONTH); gc.add(Calendar.MONTH, 1); gc.add(Calendar.DAY_OF_MONTH, -dagVanDeMaand); return new Date(gc.get(Calendar.DATE), gc.get(Calendar.MONTH) , gc.get(Calendar.YEAR)); // GregorianCalendar kent enkel maanden tussen 0-11 } /** * @param Date * [] * @return Date[] */ public static Date[] sorteerDatums(Date[] datums) { Date hulp; for (int i = 0; i < datums.length - 1; i++) { for (int j = 0; j < datums.length - 1; j++) { if (datums[j + 1].kleinerDan(datums[j])) { hulp = datums[j]; datums[j] = datums[j + 1]; datums[j + 1] = hulp; } } } return datums; } public long getTimeInMilliSeconds(){ return longDate; // } }
PeterDeBlock/basinv
basinv/src/utilities/Date.java
3,853
/** * Wijzig een datum met een aantal dagen (+/-) * * @param aantalDagen */
block_comment
nl
package utilities; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.StringTokenizer; /** * Deze class representeert een datum object en voorziet elementaire testen * * @author Mathy Paesen * @date 24 september 2009 */ public class Date implements Comparable<Date> { public static final int LONG_JUL = 1000; // berekening van Julian datum public static final int LEAP_YEAR = 366; public static final int NORMAL_YEAR = 365; public static final int AANTAL_MAANDEN = 12; public static final int CORRECTIE_MAAND = 1; // maanden worden bewaard van 0 - 11 public static final int EERSTE_MAAND = 0; public static final int LAATSTE_MAAND = 11; public static final int DATUM_CORRECT = 0; public static final int DAG_KLEINER = -1; public static final int MAAND_KLEINER = -2; public static final int JAAR_KLEINER = -3; public static final int DAG_GROTER = 1; public static final int MAAND_GROTER = 2; public static final int JAAR_GROTER = 3; public static final String SEPARATOR = "/"; public static final String[] MAAND_TEXT = { "Januari", "Februari", "Maart", "April", "Mei", "Juni", "Juli", "Augustus", "September", "Oktober", "November", "December" }; private int dag; private int maand; private int jaar; private long longDate; public Date() throws DatumException { GregorianCalendar gc; gc = new GregorianCalendar(); this.setDag(gc.get(Calendar.DATE)); this.setMaand(gc.get(Calendar.MONTH)); this.setJaar(gc.get(Calendar.YEAR)); testDatum(); } public Date(long l)throws DatumException{ Calendar cal = new GregorianCalendar(); cal.setTime(new java.util.Date(l)); this.setDag(cal.get(Calendar.DATE)); this.setMaand(cal.get(Calendar.MONTH)); this.setJaar(cal.get(Calendar.YEAR)); testDatum(); } public Date(int dag, int maand, int jaar) throws DatumException { super(); this.setDag(dag); this.setMaand(maand); this.setJaar(jaar); testDatum(); } public Date(Date date) throws DatumException { this(date.getDag(), date.getMaand() , date .getJaar()); testDatum(); } public Date(String datum) throws DatumException { /* DD/MM/JJJJ */ StringTokenizer tokenizer = new StringTokenizer(datum, SEPARATOR); int i = 0; while (tokenizer.hasMoreTokens()) { switch (i) { case 0: this.setDag(Integer.parseInt((String) tokenizer.nextElement())); break; case 1: this.setMaand(Integer.parseInt((String) tokenizer.nextElement()) ); // maanden worden bewaard van 0 - 11 break; case 2: this.setJaar(Integer.parseInt((String) tokenizer.nextElement())); break; default: this.setDag(0); this.setMaand(0); this.setJaar(0); } i++; } testDatum(); } /** * Indien een datum object niet correct is wordt een DatumException * gegenereerd * * @throws DatumException */ private void testDatum() throws DatumException { // maand 0-11 GregorianCalendar testDatum = new GregorianCalendar(this.jaar, this.maand, this.dag); testDatum.setLenient(false);// enkel correcte datums toegelaten (geen // omrekening) try { testDatum.get(Calendar.YEAR); testDatum.get(Calendar.MONTH); testDatum.get(Calendar.DAY_OF_MONTH); } catch (Exception e) { throw new DatumException(this); } longDate = testDatum.getTime().getTime(); } public int getDag() { return dag; } public void setDag(int dag) { this.dag = dag; } public int getMaand() { return maand; // maanden worden bewaard van 0 - 11 } public void setMaand(int maand) { this.maand = maand; } public int getJaar() { return jaar; } public void setJaar(int jaar) { this.jaar = jaar; } /** * Enkel correcte data mogen toegelaten worden. * * @param jaar * @param maand * @param dag * @return true, false */ public boolean setDatum(int dag, int maand, int jaar) { boolean correct = false; try { new Date(dag, maand, jaar); this.setDag(dag); this.setMaand(maand); this.setJaar(jaar); correct = true; } catch (DatumException e) { correct = false; System.err.println("[" + jaar + SEPARATOR + maand + SEPARATOR + dag + "]" + e); } return correct; } /** * Date in USA formaat * * @return MM/DD/YYYY */ public String getDatumInAmerikaansFormaat() { return String.format("%s%s%s", getMaand()+CORRECTIE_MAAND + SEPARATOR, getDag() + SEPARATOR, getJaar()); } /** * Date in EUR formaat * * @return DD/MM/YYYY */ public String getDatumInEuropeesFormaat() { return String.format("%s%s%s", getDag() + SEPARATOR, getMaand()+CORRECTIE_MAAND + SEPARATOR, getJaar()); } /** * @return Januari, ..., December */ public String getMaandText() { if (getMaand() > LAATSTE_MAAND || getMaand() < EERSTE_MAAND) { return "Verkeerde maand"; } return MAAND_TEXT[getMaand()]; } /* * String representatie van deze datum * * @see java.lang.Object#toString() */ @Override public String toString() { return getDag() + " " + getMaandText() + " " + getJaar(); } public String toString(String sep) { return getDag() + sep + getMaand() + sep + getJaar(); } /** * Is deze datum gelijk aan een ander datum object * * @param date * @return */ public boolean equals(Date date) { if (this.getDag() != date.getDag()) { return false; } else if (this.getMaand() != date.getMaand()) { return false; } else if (this.getJaar() != date.getJaar()) { return false; } return true; } /** * 0 Deze datum en de parameter datum zijn gelijk -1 Als de dag van de maand * van deze datum kleiner is dan die van een ander datum object -2 Als de * maand van deze datum kleiner is dan die van een ander datum object -3 Als * het jaar van deze datum kleiner is dan die van een ander datum object * * @param date * @return -1, -2, -3, 0 */ public int compareTo(Date date) { if (this.getJaar() < date.getJaar()) { return JAAR_KLEINER; } if (this.getJaar() > date.getJaar()) { return JAAR_GROTER; } if (this.getMaand() < date.getMaand()) { return MAAND_KLEINER; } if (this.getMaand() > date.getMaand()) { return MAAND_GROTER; } if (this.getDag() < date.getDag()) { return DAG_KLEINER; } if (this.getDag() > date.getDag()) { return DAG_GROTER; } return DATUM_CORRECT; } /** * Is deze datum kleiner dan een ander datum object * * @param date * @return */ public boolean kleinerDan(Date date) { if (this.compareTo(date) < DATUM_CORRECT) { return true; } return false; } /** * Bereken het verschil in jaren tussen deze datum en een ander datum object * * @param date * @return */ public int verschilInJaren(Date date) { return this.getJaar() - date.getJaar(); } /** * Bereken het verschil in maanden tussen deze datum en een ander datum * object * * @param date * @return */ public int verschilInMaanden(Date date) { int verschil = this.verschilInJaren(date); verschil *= AANTAL_MAANDEN; verschil += (this.getMaand() - date.getMaand()); return verschil; } /** * Bereken het verschil in dagen tussen deze datum en een ander datum object * * @param date * @return */ public int verschilInDagen(Date date) { int verschil = 0; Date test; try { test = new Date(this); for (int i = 0; i < this.verschilInJaren(date); i++) { test.setJaar(test.getJaar() - 1); verschil += test.aantalDagen(); } } catch (DatumException e) { e.printStackTrace(); } verschil += this.dagVanHetJaar() - date.dagVanHetJaar(); return verschil; } /** * Schrikkeljaar of niet * * @return true, false */ public boolean isLeapYear() { if ((this.getJaar() % 400 == 0) || ((this.getJaar() % 4 == 0) && (this.getJaar() % 100 != 0))) { return true; } return false; } /** * Bereken aantal dagen van een maand * * @return { 31, 28/29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } */ public int dagVanHetJaar() { int dagen[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int totaal = 0; for (int maand = 0; maand < this.getMaand(); maand++) { // huidige maand nog niet meetellen totaal += dagen[maand]; if (this.isLeapYear() && maand == 1) { totaal += 1; // 29 ipv 28 dagen } } totaal += this.getDag(); return totaal; } /** * Dag van het jaar * * @return xxx/1-366 */ public int julianDatum() { int totaal = this.getJaar() * LONG_JUL; return totaal += dagVanHetJaar(); } /** * Aantal dagen van het jaar * * @return 365 of 366 */ public int aantalDagen() { if (this.isLeapYear()) { return LEAP_YEAR; } return NORMAL_YEAR; } /** * Wijzig een datum<SUF>*/ public void veranderDatum(int aantalDagen) { this.setDag(this.getDag() + aantalDagen); GregorianCalendar gc = new GregorianCalendar(); gc.setLenient(true); gc.set(this.getJaar(), this.getMaand(), this.getDag()); this.setDag(gc.get(Calendar.DAY_OF_MONTH)); this.setMaand(gc.get(Calendar.MONTH)); this.setJaar(gc.get(Calendar.YEAR)); } /** * Berekening van een Unieke int Wordt gebruikt door de equals method * * @return int */ public int hashCode() { return julianDatum(); } /** * Geeft steeds de laatste dag van de maand * * @param Date * @return Date * @throws DatumException */ public static Date laatsteDagVanDeMaand(Date date) throws DatumException { GregorianCalendar gc = new GregorianCalendar(date.jaar, date.maand, date.getDag()); int dagVanDeMaand = gc.get(Calendar.DAY_OF_MONTH); gc.add(Calendar.MONTH, 1); gc.add(Calendar.DAY_OF_MONTH, -dagVanDeMaand); return new Date(gc.get(Calendar.DATE), gc.get(Calendar.MONTH) , gc.get(Calendar.YEAR)); // GregorianCalendar kent enkel maanden tussen 0-11 } /** * @param Date * [] * @return Date[] */ public static Date[] sorteerDatums(Date[] datums) { Date hulp; for (int i = 0; i < datums.length - 1; i++) { for (int j = 0; j < datums.length - 1; j++) { if (datums[j + 1].kleinerDan(datums[j])) { hulp = datums[j]; datums[j] = datums[j + 1]; datums[j + 1] = hulp; } } } return datums; } public long getTimeInMilliSeconds(){ return longDate; // } }
15737_0
package inleidingJava; import java.util.Random; public class DeelKaarten { private String[] kleuren = {"Ruiten", "Klaver", "Harten", "Schoppen"}; private String[] kaarten = {"twee", "drie", "vier", "vijf", "zes", "zeven", "acht", "negen", "tien", "boer", "vrouw", "heer", "aas"}; private String[] deck = new String[52]; private String[] speler1 = new String[13]; private String[] speler2 = new String[13]; private String[] speler3 = new String[13]; private String[] speler4 = new String[13]; public DeelKaarten() { int index = 0; //vul deck met kaarten for (int i = 0; i < kleuren.length; i++) { String kleur = kleuren[i]; for (int j = 0; j < kaarten.length; j++) { String kaart = kaarten[j]; deck[index] = kleur + " " + kaart; index++; } } for (int i = 0; i < 13; i++) { speler1[i] = deelKaart(); speler2[i] = deelKaart(); speler3[i] = deelKaart(); speler4[i] = deelKaart(); } } private String deelKaart() { int random = new Random().nextInt(deck.length); String kaart = deck[random]; String[] hulpLijst = new String[deck.length - 1]; int hulpindex = 0; for (int i = 0; i < deck.length; i++) { if (i != random) { hulpLijst[hulpindex] = deck[i]; hulpindex++; } } deck = hulpLijst; return kaart; } public String deelEnkeleKaart() { return speler1[new Random().nextInt(13)]; } public String maakTabel() { String tabel = "<table class=\"table\" id=\"kaart_tabel\">" + "<tr><th>Speler 1</th><th>Speler 2</th><th>Speler 3</th><th>Speler 4</th></tr>"; for (int i = 0; i < 13; i++) { tabel += "<tr>"; tabel += "<td>" + speler1[i] + "</td>"; tabel += "<td>" + speler2[i] + "</td>"; tabel += "<td>" + speler3[i] + "</td>"; tabel += "<td>" + speler4[i] + "</td>"; tabel += "</tr>"; } tabel += "</table>"; return tabel; } }
pieeet/ao-roc-dev
rocdevcursussen/src/main/java/inleidingJava/DeelKaarten.java
697
//vul deck met kaarten
line_comment
nl
package inleidingJava; import java.util.Random; public class DeelKaarten { private String[] kleuren = {"Ruiten", "Klaver", "Harten", "Schoppen"}; private String[] kaarten = {"twee", "drie", "vier", "vijf", "zes", "zeven", "acht", "negen", "tien", "boer", "vrouw", "heer", "aas"}; private String[] deck = new String[52]; private String[] speler1 = new String[13]; private String[] speler2 = new String[13]; private String[] speler3 = new String[13]; private String[] speler4 = new String[13]; public DeelKaarten() { int index = 0; //vul deck<SUF> for (int i = 0; i < kleuren.length; i++) { String kleur = kleuren[i]; for (int j = 0; j < kaarten.length; j++) { String kaart = kaarten[j]; deck[index] = kleur + " " + kaart; index++; } } for (int i = 0; i < 13; i++) { speler1[i] = deelKaart(); speler2[i] = deelKaart(); speler3[i] = deelKaart(); speler4[i] = deelKaart(); } } private String deelKaart() { int random = new Random().nextInt(deck.length); String kaart = deck[random]; String[] hulpLijst = new String[deck.length - 1]; int hulpindex = 0; for (int i = 0; i < deck.length; i++) { if (i != random) { hulpLijst[hulpindex] = deck[i]; hulpindex++; } } deck = hulpLijst; return kaart; } public String deelEnkeleKaart() { return speler1[new Random().nextInt(13)]; } public String maakTabel() { String tabel = "<table class=\"table\" id=\"kaart_tabel\">" + "<tr><th>Speler 1</th><th>Speler 2</th><th>Speler 3</th><th>Speler 4</th></tr>"; for (int i = 0; i < 13; i++) { tabel += "<tr>"; tabel += "<td>" + speler1[i] + "</td>"; tabel += "<td>" + speler2[i] + "</td>"; tabel += "<td>" + speler3[i] + "</td>"; tabel += "<td>" + speler4[i] + "</td>"; tabel += "</tr>"; } tabel += "</table>"; return tabel; } }
43350_3
package nl.novi.techiteasy.controllers; import nl.novi.techiteasy.exceptions.RecordNotFoundException; import nl.novi.techiteasy.exceptions.TelevisionNameTooLongException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; @ControllerAdvice // @ControllerAdvice - Om een Exception controller aan te geven. Verwijst (En stuurt waarschijnlijk aan) in de code naar elk van de custom exceptions in het mapje: exceptions. public class ExceptionController { // Deze exception handler vangt elke RecordNotFoundException op die naar de gebruiker gegooid wordt en returned daar voor in de plaats een ResponseEntity met de Message en de NOT_FOUND-status (404) // Custom exception 1 @ExceptionHandler(value = RecordNotFoundException.class) // Verwijst naar dit bestand public ResponseEntity<Object> exception(RecordNotFoundException exception) { return new ResponseEntity<>(exception.getMessage(), HttpStatus.NOT_FOUND); } // Exception handler met message. Constructor in het Exception bestand super(message) // IndexOutOfBoundsException ioe is al een bestaande Java Exception. @ExceptionHandler(value = IndexOutOfBoundsException.class) public ResponseEntity<Object> exception(IndexOutOfBoundsException exception) { return new ResponseEntity<>("Dit id staat niet in de database", HttpStatus.NOT_FOUND); } // Exception zonder message (super()) // Custom exception 2 // Zonder deze handler krijg je een error status 500 @ExceptionHandler(value = TelevisionNameTooLongException.class) public ResponseEntity<String> exception(TelevisionNameTooLongException exception) { return new ResponseEntity<>(exception.getMessage(), HttpStatus.BAD_REQUEST); // .getMessage: "Televisienaam is te lang" } }
Aphelion-im/Les-10-uitwerking-opdracht-backend-spring-boot-tech-it-easy-controller
src/main/java/nl/novi/techiteasy/controllers/ExceptionController.java
428
// Verwijst naar dit bestand
line_comment
nl
package nl.novi.techiteasy.controllers; import nl.novi.techiteasy.exceptions.RecordNotFoundException; import nl.novi.techiteasy.exceptions.TelevisionNameTooLongException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; @ControllerAdvice // @ControllerAdvice - Om een Exception controller aan te geven. Verwijst (En stuurt waarschijnlijk aan) in de code naar elk van de custom exceptions in het mapje: exceptions. public class ExceptionController { // Deze exception handler vangt elke RecordNotFoundException op die naar de gebruiker gegooid wordt en returned daar voor in de plaats een ResponseEntity met de Message en de NOT_FOUND-status (404) // Custom exception 1 @ExceptionHandler(value = RecordNotFoundException.class) // Verwijst naar<SUF> public ResponseEntity<Object> exception(RecordNotFoundException exception) { return new ResponseEntity<>(exception.getMessage(), HttpStatus.NOT_FOUND); } // Exception handler met message. Constructor in het Exception bestand super(message) // IndexOutOfBoundsException ioe is al een bestaande Java Exception. @ExceptionHandler(value = IndexOutOfBoundsException.class) public ResponseEntity<Object> exception(IndexOutOfBoundsException exception) { return new ResponseEntity<>("Dit id staat niet in de database", HttpStatus.NOT_FOUND); } // Exception zonder message (super()) // Custom exception 2 // Zonder deze handler krijg je een error status 500 @ExceptionHandler(value = TelevisionNameTooLongException.class) public ResponseEntity<String> exception(TelevisionNameTooLongException exception) { return new ResponseEntity<>(exception.getMessage(), HttpStatus.BAD_REQUEST); // .getMessage: "Televisienaam is te lang" } }
13775_23
package herkansing.ipmedt4.groep6; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; /** * * * @author Duncan Pronk * @author Lisa Uiterwijk * @author Deborah Tjin * @version 2.0 * * hierin worden alle acts gemaakt. * */ public class Acts extends Activity { //maak 2 arraylisten aan voor de knoppen en evenementen //De rest zijn speciale ints TextView txt; Button button; JSONArray jArray; ArrayList<Button> knoppen; ArrayList <String> evenementen; int iz = 1000; int please = 1000; int buttonid = 1000; int graag = 0; int stuurid; // Lisa private Dialog myDialog; private MediaPlayer mp; // Einde Lisa @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.acts); // declareer de arraylists knoppen = new ArrayList<Button>(); evenementen = new ArrayList<String>(); // maak zolang het resultaat op het scherm past een listview aan // en vul deze met de resultaten uit de arraylist // dit staat nog in debug mode, met vastte waardes // Lisa: om terug te gaan naar de home pagina ImageView imgview1 = (ImageView)findViewById(R.id.ImageView01); imgview1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Lisa: geluid dat je hoort als er op de home button word gedrukt mp = MediaPlayer.create(Acts.this, R.raw.terug); mp.setOnCompletionListener(new OnCompletionListener() { public void onCompletion(MediaPlayer mp) { // TODO Auto-generated method stub mp.release(); } }); mp.start(); Intent intent = new Intent(); intent.setClass(getApplicationContext(), MainActivity.class); startActivity(intent); } }); //Lisa: om naar de Help pagina te gaan ImageView imgview2 = (ImageView)findViewById(R.id.ImageView02); imgview2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Lisa: geluid voor de button als er geklikt word mp = MediaPlayer.create(Acts.this, R.raw.klik); mp.setOnCompletionListener(new OnCompletionListener() { public void onCompletion(MediaPlayer mp) { // TODO Auto-generated method stub mp.release(); } }); mp.start(); // Einde Lisa Intent intent = new Intent(); intent.setClass(getApplicationContext(), Help.class); startActivity(intent); } }); //Einde: Lisa // Lisa: Dialog toegevoegd zodat de zoekknop die het niet doet, netjes afgehandeld word d.m.v. // een Dialog. Gekozen voor een Dialog, zodat ik zelf de layout van de dialog kan bepalen. ImageButton myButton = (ImageButton)findViewById(R.id.imageButton6); myButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Lisa: geluid voor de button als er geklikt word mp = MediaPlayer.create(Acts.this, R.raw.klik); mp.setOnCompletionListener(new OnCompletionListener() { public void onCompletion(MediaPlayer mp) { // TODO Auto-generated method stub mp.release(); } }); mp.start(); // Einde Lisa myDialog = new Dialog(Acts.this, R.style.FullHeightDialog); // maak nieuw myDialog aan // en haal de default titel weg myDialog.setContentView(R.layout.dialogzoek); myDialog.setCancelable(true); ImageView imageView = (ImageView)myDialog.findViewById(R.id.imageView1); imageView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //Lisa: geluid dat je hoort als er op "Ok" word gedrukt mp = MediaPlayer.create(Acts.this, R.raw.terug); mp.setOnCompletionListener(new OnCompletionListener() { public void onCompletion(MediaPlayer mp) { // TODO Auto-generated method stub mp.release(); } }); mp.start(); myDialog.dismiss(); } }); myDialog.show(); } }); // Einde Lisa for (int i = 0; i < 5; i++) { RelativeLayout rl = (RelativeLayout) findViewById(R.id.RL1); //maak de knop aan button = new Button(this); // button.setText("Evenement" + i); Debug button.setId(buttonid); buttonid++; int width = 1000; int height = 100; // button.setText(result); Debug // voeg de knop toe aan de layout knoppen.add(button); // geeft de button een mooie style button.setBackgroundColor(Color.TRANSPARENT); button.setBackgroundResource(R.drawable.rectangle); // handel de button pressed af button.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View arg0) { // Lisa: geluid voor de button als er geklikt word mp = MediaPlayer.create(Acts.this, R.raw.klik); mp.setOnCompletionListener(new OnCompletionListener() { public void onCompletion(MediaPlayer mp) { // TODO Auto-generated method stub mp.release(); } }); mp.start(); // Einde Lisa // kijk welke button ingedrukt is // Dit roept de goede query aan in de acts klasse Intent intent = new Intent(); intent.setClass(getApplicationContext(), LosseActs.class); startActivity(intent); } }); // Einde Duncan // Deborah // Geef de relative layout de waardes, zodat alles goed staat // Daarna zet ik de button goed erin met de Rules en Margins // Als I groter of kleiner is dan 0, dan wordt het scherm aangepast if (i == 0) { RelativeLayout.LayoutParams rlp1 = new RelativeLayout.LayoutParams( width, height); //rlp1.addRule(RelativeLayout.ALIGN_PARENT_TOP); rlp1.addRule(RelativeLayout.ALIGN_PARENT_LEFT); rlp1.topMargin = 140; // Lisa: op 140 gezet ipv 100 zodat er genoeg speling zit voor de // knoppen en het zoekveld en de zoekknop // Einde Lisa rlp1.bottomMargin = 10; button.setLayoutParams(rlp1); rl.addView(button, rlp1); } else { RelativeLayout.LayoutParams rlp1 = new RelativeLayout.LayoutParams( width, height); rlp1.addRule(RelativeLayout.ALIGN_PARENT_LEFT); rlp1.addRule(RelativeLayout.BELOW, button.getId() - 1); rlp1.bottomMargin = 10; button.setLayoutParams(rlp1); rl.addView(button, rlp1); } } // Roep de methode aan die de webserver aanroept new ShowDialogAsyncTask().execute(); } // het ophalen van het id uit de MainActivity public int setButtonId(int id) { stuurid = id; return stuurid; } // Einde Deborah // Duncan & Lisa private class ShowDialogAsyncTask extends AsyncTask<Void, Void, String> { // Een asynctask is een methode om een network thread te draaien op // hoofdklasse. Het heeft 3 methodes, maar kan er ook 4 hebben. @Override protected void onPreExecute() { // Update de tekst op het scherm, zodra de methode wordt aangeroepen // zolang de positie binnen de arraylist valt, wordt de tekst aangehouden // Zodra de lijst volledig is, wordt de postExecute aangeroepen super.onPreExecute(); // debug Log.i("test","pre-execute"); // Voor LogCat for(int pos = 0; pos < knoppen.size(); pos++) { Button b = (Button)findViewById(iz); b.setText("Even geduld AUB." ); iz++; } } // Hierin wordt de webserver aangeroepen, HTTP Post en Get sturen een // verzoek naar een bestand en halen het resultaat terug // De query zit voor de evenementen in de eve.php op de webserver @Override protected String doInBackground(Void... params) { // debug Log.i("test","background"); // Voor LogCat InputStream is = null; String result = ""; // Dit is nodig om aan te sturen, maar in deze klasse // heeft het geen nut, in de andere klassen stuur ik de button id mee, om // het goeie evenementen terug te halen ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("test","test")); // http post, hierin wordt de bestand aangeroepen, zoals eerder gezegd // De try is altijd nodig om fouten af te handelen, anders kan de app en de // server crashen //Lisa de string url is aangemaakt, om het zo te vergemakkelijken op de regel 218 //de url betreft de url waar php code staat try{ String url = "http://api.evenementenmail.nl/act.php"; HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch(Exception e) { Log.e("log_tag", "Error in http connection "+e.toString()); // Voor LogCat } //einde Lisa // Gelijk met de get krijgen we een resultaat. hierin wordt het resultaat omgezet // naar een string, via een Stringbuilder try { BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result=sb.toString(); } catch(Exception e) { Log.e("log_tag", "Error converting result "+e.toString()); // Voor LogCat } // Hier parsen ik de json data, Vanuit de jArray wordt het omgezet in een arraylist // Ook trimmen we het resultaat, zodat de Json tekens wegvallen String returnString = ""; try { jArray = new JSONArray(result); for(int i=0;i<jArray.length();i++){ returnString += jArray.getJSONObject(i).getString("naam"); returnString = returnString.trim(); } } catch(JSONException e) { Log.e("log_tag", "Error parsing data "+e.toString()); // Voor LogCat } return returnString; } // Zodra de arraylist gevuld is, wordt de arraylist uitgelezen en omgezet // naar de textviews. Voor de zekerheid trim ik hier nog een keer en replace // ik de rest van de tekens @Override protected void onPostExecute(String result) { super.onPostExecute(result); result = result.trim(); // debug Log.i("test","POST"); // Voor LogCat if (jArray != null) { int len = jArray.length(); for (int i=0;i<len;i++){ try { String ajb = jArray.get(i).toString(); String aub = ajb.replace("{", ""); aub = aub.replace("}", ""); aub = aub.replace("\"", ""); aub = aub.replace("naam:", ""); evenementen.add(aub); } catch (JSONException e) { e.printStackTrace(); } } } // geef elke button een eigen Unieke ID voor de hierboven aangegeven // button pressed. for(int pos = 0; pos < knoppen.size(); pos++) { Button bt = (Button)findViewById(please); bt.setText(evenementen.get(graag) ); please++; graag++; } } } }
crazytim412/herkansing.ipmedt4.oplevering
src/herkansing/ipmedt4/groep6/Acts.java
4,012
// voeg de knop toe aan de layout
line_comment
nl
package herkansing.ipmedt4.groep6; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; /** * * * @author Duncan Pronk * @author Lisa Uiterwijk * @author Deborah Tjin * @version 2.0 * * hierin worden alle acts gemaakt. * */ public class Acts extends Activity { //maak 2 arraylisten aan voor de knoppen en evenementen //De rest zijn speciale ints TextView txt; Button button; JSONArray jArray; ArrayList<Button> knoppen; ArrayList <String> evenementen; int iz = 1000; int please = 1000; int buttonid = 1000; int graag = 0; int stuurid; // Lisa private Dialog myDialog; private MediaPlayer mp; // Einde Lisa @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.acts); // declareer de arraylists knoppen = new ArrayList<Button>(); evenementen = new ArrayList<String>(); // maak zolang het resultaat op het scherm past een listview aan // en vul deze met de resultaten uit de arraylist // dit staat nog in debug mode, met vastte waardes // Lisa: om terug te gaan naar de home pagina ImageView imgview1 = (ImageView)findViewById(R.id.ImageView01); imgview1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Lisa: geluid dat je hoort als er op de home button word gedrukt mp = MediaPlayer.create(Acts.this, R.raw.terug); mp.setOnCompletionListener(new OnCompletionListener() { public void onCompletion(MediaPlayer mp) { // TODO Auto-generated method stub mp.release(); } }); mp.start(); Intent intent = new Intent(); intent.setClass(getApplicationContext(), MainActivity.class); startActivity(intent); } }); //Lisa: om naar de Help pagina te gaan ImageView imgview2 = (ImageView)findViewById(R.id.ImageView02); imgview2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Lisa: geluid voor de button als er geklikt word mp = MediaPlayer.create(Acts.this, R.raw.klik); mp.setOnCompletionListener(new OnCompletionListener() { public void onCompletion(MediaPlayer mp) { // TODO Auto-generated method stub mp.release(); } }); mp.start(); // Einde Lisa Intent intent = new Intent(); intent.setClass(getApplicationContext(), Help.class); startActivity(intent); } }); //Einde: Lisa // Lisa: Dialog toegevoegd zodat de zoekknop die het niet doet, netjes afgehandeld word d.m.v. // een Dialog. Gekozen voor een Dialog, zodat ik zelf de layout van de dialog kan bepalen. ImageButton myButton = (ImageButton)findViewById(R.id.imageButton6); myButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Lisa: geluid voor de button als er geklikt word mp = MediaPlayer.create(Acts.this, R.raw.klik); mp.setOnCompletionListener(new OnCompletionListener() { public void onCompletion(MediaPlayer mp) { // TODO Auto-generated method stub mp.release(); } }); mp.start(); // Einde Lisa myDialog = new Dialog(Acts.this, R.style.FullHeightDialog); // maak nieuw myDialog aan // en haal de default titel weg myDialog.setContentView(R.layout.dialogzoek); myDialog.setCancelable(true); ImageView imageView = (ImageView)myDialog.findViewById(R.id.imageView1); imageView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //Lisa: geluid dat je hoort als er op "Ok" word gedrukt mp = MediaPlayer.create(Acts.this, R.raw.terug); mp.setOnCompletionListener(new OnCompletionListener() { public void onCompletion(MediaPlayer mp) { // TODO Auto-generated method stub mp.release(); } }); mp.start(); myDialog.dismiss(); } }); myDialog.show(); } }); // Einde Lisa for (int i = 0; i < 5; i++) { RelativeLayout rl = (RelativeLayout) findViewById(R.id.RL1); //maak de knop aan button = new Button(this); // button.setText("Evenement" + i); Debug button.setId(buttonid); buttonid++; int width = 1000; int height = 100; // button.setText(result); Debug // voeg de<SUF> knoppen.add(button); // geeft de button een mooie style button.setBackgroundColor(Color.TRANSPARENT); button.setBackgroundResource(R.drawable.rectangle); // handel de button pressed af button.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View arg0) { // Lisa: geluid voor de button als er geklikt word mp = MediaPlayer.create(Acts.this, R.raw.klik); mp.setOnCompletionListener(new OnCompletionListener() { public void onCompletion(MediaPlayer mp) { // TODO Auto-generated method stub mp.release(); } }); mp.start(); // Einde Lisa // kijk welke button ingedrukt is // Dit roept de goede query aan in de acts klasse Intent intent = new Intent(); intent.setClass(getApplicationContext(), LosseActs.class); startActivity(intent); } }); // Einde Duncan // Deborah // Geef de relative layout de waardes, zodat alles goed staat // Daarna zet ik de button goed erin met de Rules en Margins // Als I groter of kleiner is dan 0, dan wordt het scherm aangepast if (i == 0) { RelativeLayout.LayoutParams rlp1 = new RelativeLayout.LayoutParams( width, height); //rlp1.addRule(RelativeLayout.ALIGN_PARENT_TOP); rlp1.addRule(RelativeLayout.ALIGN_PARENT_LEFT); rlp1.topMargin = 140; // Lisa: op 140 gezet ipv 100 zodat er genoeg speling zit voor de // knoppen en het zoekveld en de zoekknop // Einde Lisa rlp1.bottomMargin = 10; button.setLayoutParams(rlp1); rl.addView(button, rlp1); } else { RelativeLayout.LayoutParams rlp1 = new RelativeLayout.LayoutParams( width, height); rlp1.addRule(RelativeLayout.ALIGN_PARENT_LEFT); rlp1.addRule(RelativeLayout.BELOW, button.getId() - 1); rlp1.bottomMargin = 10; button.setLayoutParams(rlp1); rl.addView(button, rlp1); } } // Roep de methode aan die de webserver aanroept new ShowDialogAsyncTask().execute(); } // het ophalen van het id uit de MainActivity public int setButtonId(int id) { stuurid = id; return stuurid; } // Einde Deborah // Duncan & Lisa private class ShowDialogAsyncTask extends AsyncTask<Void, Void, String> { // Een asynctask is een methode om een network thread te draaien op // hoofdklasse. Het heeft 3 methodes, maar kan er ook 4 hebben. @Override protected void onPreExecute() { // Update de tekst op het scherm, zodra de methode wordt aangeroepen // zolang de positie binnen de arraylist valt, wordt de tekst aangehouden // Zodra de lijst volledig is, wordt de postExecute aangeroepen super.onPreExecute(); // debug Log.i("test","pre-execute"); // Voor LogCat for(int pos = 0; pos < knoppen.size(); pos++) { Button b = (Button)findViewById(iz); b.setText("Even geduld AUB." ); iz++; } } // Hierin wordt de webserver aangeroepen, HTTP Post en Get sturen een // verzoek naar een bestand en halen het resultaat terug // De query zit voor de evenementen in de eve.php op de webserver @Override protected String doInBackground(Void... params) { // debug Log.i("test","background"); // Voor LogCat InputStream is = null; String result = ""; // Dit is nodig om aan te sturen, maar in deze klasse // heeft het geen nut, in de andere klassen stuur ik de button id mee, om // het goeie evenementen terug te halen ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("test","test")); // http post, hierin wordt de bestand aangeroepen, zoals eerder gezegd // De try is altijd nodig om fouten af te handelen, anders kan de app en de // server crashen //Lisa de string url is aangemaakt, om het zo te vergemakkelijken op de regel 218 //de url betreft de url waar php code staat try{ String url = "http://api.evenementenmail.nl/act.php"; HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch(Exception e) { Log.e("log_tag", "Error in http connection "+e.toString()); // Voor LogCat } //einde Lisa // Gelijk met de get krijgen we een resultaat. hierin wordt het resultaat omgezet // naar een string, via een Stringbuilder try { BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result=sb.toString(); } catch(Exception e) { Log.e("log_tag", "Error converting result "+e.toString()); // Voor LogCat } // Hier parsen ik de json data, Vanuit de jArray wordt het omgezet in een arraylist // Ook trimmen we het resultaat, zodat de Json tekens wegvallen String returnString = ""; try { jArray = new JSONArray(result); for(int i=0;i<jArray.length();i++){ returnString += jArray.getJSONObject(i).getString("naam"); returnString = returnString.trim(); } } catch(JSONException e) { Log.e("log_tag", "Error parsing data "+e.toString()); // Voor LogCat } return returnString; } // Zodra de arraylist gevuld is, wordt de arraylist uitgelezen en omgezet // naar de textviews. Voor de zekerheid trim ik hier nog een keer en replace // ik de rest van de tekens @Override protected void onPostExecute(String result) { super.onPostExecute(result); result = result.trim(); // debug Log.i("test","POST"); // Voor LogCat if (jArray != null) { int len = jArray.length(); for (int i=0;i<len;i++){ try { String ajb = jArray.get(i).toString(); String aub = ajb.replace("{", ""); aub = aub.replace("}", ""); aub = aub.replace("\"", ""); aub = aub.replace("naam:", ""); evenementen.add(aub); } catch (JSONException e) { e.printStackTrace(); } } } // geef elke button een eigen Unieke ID voor de hierboven aangegeven // button pressed. for(int pos = 0; pos < knoppen.size(); pos++) { Button bt = (Button)findViewById(please); bt.setText(evenementen.get(graag) ); please++; graag++; } } } }
194829_18
/* * OffenePflege * Copyright (C) 2006-2012 Torsten Löhr * This program is free software; you can redistribute it and/or modify it under the terms of the * GNU General Public License V2 as published by the Free Software Foundation * * 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, write to * the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA * www.offene-pflege.de * ------------------------ * Auf deutsch (freie Übersetzung. Rechtlich gilt die englische Version) * Dieses Programm ist freie Software. Sie können es unter den Bedingungen der GNU General Public License, * wie von der Free Software Foundation veröffentlicht, weitergeben und/oder modifizieren, gemäß Version 2 der Lizenz. * * Die Veröffentlichung dieses Programms erfolgt in der Hoffnung, daß es Ihnen von Nutzen sein wird, aber * OHNE IRGENDEINE GARANTIE, sogar ohne die implizite Garantie der MARKTREIFE oder der VERWENDBARKEIT FÜR EINEN * BESTIMMTEN ZWECK. Details finden Sie in der GNU General Public License. * * Sie sollten ein Exemplar der GNU General Public License zusammen mit diesem Programm erhalten haben. Falls nicht, * schreiben Sie an die Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA. * */ package op.care.info; import com.jgoodies.forms.factories.CC; import com.jgoodies.forms.layout.FormLayout; import com.jidesoft.popup.JidePopup; import entity.EntityTools; import entity.info.ICD; import entity.info.ResInfo; import entity.info.ResInfoTools; import entity.prescription.GP; import entity.prescription.GPTools; import entity.prescription.Hospital; import entity.prescription.HospitalTools; import gui.GUITools; import op.OPDE; import op.residents.PnlEditGP; import op.residents.PnlEditHospital; import op.threads.DisplayMessage; import op.tools.MyJDialog; import op.tools.SYSConst; import op.tools.SYSTools; import org.apache.commons.collections.Closure; import org.jdesktop.swingx.HorizontalLayout; import org.jdesktop.swingx.JXSearchField; import javax.persistence.EntityManager; import javax.persistence.Query; import javax.swing.*; import javax.swing.border.SoftBevelBorder; import javax.swing.event.ListSelectionListener; import java.awt.*; import java.awt.event.ActionEvent; import java.util.Properties; /** * @author root */ public class DlgDiag extends MyJDialog { public static final String internalClassID = "nursingrecords.info.dlg.diags"; private ListSelectionListener lsl; private String text; private ResInfo diag; private Closure actionBlock; /** * Creates new form DlgVorlage */ public DlgDiag(ResInfo diag, Closure actionBlock) { super(false); this.diag = diag; this.actionBlock = actionBlock; initComponents(); initDialog(); // setVisible(true); } private void initDialog() { fillCMBs(); String tooltip = SYSTools.xx("nursingrecords.info.dlg.diags.tx.tooltip").replace('[', '<').replace(']', '>'); lblTX.setToolTipText(SYSTools.toHTMLForScreen("<p style=\"width:300px;\">" + tooltip + "</p>")); txtSuche.setPrompt(SYSTools.xx("misc.msg.search")); lblDiagBy.setText(SYSTools.xx("nursingrecords.info.dlg.diags.by")); lblSide.setText(SYSTools.xx("misc.msg.diag.side")); lblSecurity.setText(SYSTools.xx("misc.msg.diag.security")); lblInterval.setText(SYSTools.xx("nursingrecords.info.dlg.interval_noconstraints")); lblInterval.setIcon(SYSConst.icon22intervalNoConstraints); reloadTable(); OPDE.getDisplayManager().addSubMessage(new DisplayMessage(SYSTools.xx("nursingrecords.info.dlg.diags"), 10)); } private void txtSucheActionPerformed(ActionEvent e) { reloadTable(); } private void btnAddGPActionPerformed(ActionEvent e) { final PnlEditGP pnlGP = new PnlEditGP(new GP()); JidePopup popup = GUITools.createPanelPopup(pnlGP, o -> { if (o != null) { GP gp = EntityTools.merge((GP) o); cmbArzt.setModel(new DefaultComboBoxModel(new GP[]{gp})); } }, btnAddGP); GUITools.showPopup(popup, SwingConstants.EAST); } private void btnAddHospitalActionPerformed(ActionEvent e) { final PnlEditHospital pnlHospital = new PnlEditHospital(new Hospital()); JidePopup popup = GUITools.createPanelPopup(pnlHospital, o -> { if (o != null) { Hospital hospital = EntityTools.merge((Hospital) o); cmbKH.setModel(new DefaultComboBoxModel(new Hospital[]{hospital})); } }, btnAddHospital); GUITools.showPopup(popup, SwingConstants.EAST); } private void fillCMBs() { EntityManager em = OPDE.createEM(); Query queryArzt = em.createQuery("SELECT a FROM GP a WHERE a.status >= 0 ORDER BY a.name, a.vorname"); java.util.List<GP> listAerzte = queryArzt.getResultList(); listAerzte.add(0, null); Query queryKH = em.createQuery("SELECT k FROM Hospital k WHERE k.state >= 0 ORDER BY k.name"); java.util.List<Hospital> listKH = queryKH.getResultList(); listKH.add(0, null); em.close(); cmbArzt.setModel(new DefaultComboBoxModel(listAerzte.toArray())); cmbArzt.setRenderer(GPTools.getRenderer()); cmbArzt.setSelectedIndex(0); cmbKH.setModel(new DefaultComboBoxModel(listKH.toArray())); cmbKH.setRenderer(HospitalTools.getKHRenderer()); cmbKH.setSelectedIndex(0); cmbSicherheit.setModel(new DefaultComboBoxModel(new String[]{ SYSTools.xx("misc.msg.diag.security.na"), SYSTools.xx("misc.msg.diag.security.confirmed"), SYSTools.xx("misc.msg.diag.security.suspected"), SYSTools.xx("misc.msg.diag.security.rulingout"), SYSTools.xx("misc.msg.diag.security.conditionafter") })); cmbSicherheit.setSelectedIndex(1); cmbKoerper.setModel(new DefaultComboBoxModel(new String[]{ SYSTools.xx("misc.msg.diag.side.na"), SYSTools.xx("misc.msg.diag.side.left"), SYSTools.xx("misc.msg.diag.side.right"), SYSTools.xx("misc.msg.diag.side.both") })); } /** * This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the PrinterForm Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new JPanel(); txtSuche = new JXSearchField(); lblTX = new JLabel(); jspDiagnosen = new JScrollPane(); lstDiag = new JList(); lblDiagBy = new JLabel(); cmbArzt = new JComboBox<>(); btnAddGP = new JButton(); cmbKH = new JComboBox<>(); btnAddHospital = new JButton(); lblSecurity = new JLabel(); lblSide = new JLabel(); cmbKoerper = new JComboBox<>(); cmbSicherheit = new JComboBox<>(); jScrollPane1 = new JScrollPane(); txtBemerkung = new JTextArea(); lblInterval = new JLabel(); panel1 = new JPanel(); btnCancel = new JButton(); btnOK = new JButton(); //======== this ======== Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout()); //======== jPanel1 ======== { jPanel1.setBorder(new SoftBevelBorder(SoftBevelBorder.RAISED)); jPanel1.setLayout(new FormLayout( "default, $lcgap, pref, $lcgap, default:grow, $ugap, pref, $lcgap, default:grow, 2*($lcgap, default)", "default, $lgap, fill:default, $lgap, fill:104dlu:grow, $lgap, fill:default, $lgap, default, $lgap, fill:default, $lgap, fill:89dlu:grow, $ugap, default, $lgap, default")); //---- txtSuche ---- txtSuche.setFont(new Font("Arial", Font.PLAIN, 14)); txtSuche.addActionListener(e -> txtSucheActionPerformed(e)); jPanel1.add(txtSuche, CC.xywh(3, 3, 7, 1)); //---- lblTX ---- lblTX.setText(null); lblTX.setIcon(new ImageIcon(getClass().getResource("/artwork/22x22/ambulance2.png"))); jPanel1.add(lblTX, CC.xy(11, 3)); //======== jspDiagnosen ======== { //---- lstDiag ---- lstDiag.setFont(new Font("Arial", Font.PLAIN, 14)); jspDiagnosen.setViewportView(lstDiag); } jPanel1.add(jspDiagnosen, CC.xywh(3, 5, 9, 1)); //---- lblDiagBy ---- lblDiagBy.setText("Festgestellt durch:"); lblDiagBy.setFont(new Font("Arial", Font.PLAIN, 14)); jPanel1.add(lblDiagBy, CC.xy(3, 7, CC.RIGHT, CC.DEFAULT)); //---- cmbArzt ---- cmbArzt.setModel(new DefaultComboBoxModel<>(new String[]{ "Item 1", "Item 2", "Item 3", "Item 4" })); cmbArzt.setFont(new Font("Arial", Font.PLAIN, 14)); jPanel1.add(cmbArzt, CC.xywh(5, 7, 5, 1)); //---- btnAddGP ---- btnAddGP.setText(null); btnAddGP.setBorder(null); btnAddGP.setContentAreaFilled(false); btnAddGP.setIcon(new ImageIcon(getClass().getResource("/artwork/22x22/bw/add.png"))); btnAddGP.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); btnAddGP.setSelectedIcon(new ImageIcon(getClass().getResource("/artwork/22x22/bw/pressed.png"))); btnAddGP.addActionListener(e -> btnAddGPActionPerformed(e)); jPanel1.add(btnAddGP, CC.xy(11, 7)); //---- cmbKH ---- cmbKH.setModel(new DefaultComboBoxModel<>(new String[]{ "Item 1", "Item 2", "Item 3", "Item 4" })); cmbKH.setFont(new Font("Arial", Font.PLAIN, 14)); jPanel1.add(cmbKH, CC.xywh(5, 9, 5, 1)); //---- btnAddHospital ---- btnAddHospital.setText(null); btnAddHospital.setIcon(new ImageIcon(getClass().getResource("/artwork/22x22/bw/add.png"))); btnAddHospital.setBorder(null); btnAddHospital.setContentAreaFilled(false); btnAddHospital.setBorderPainted(false); btnAddHospital.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); btnAddHospital.setSelectedIcon(new ImageIcon(getClass().getResource("/artwork/22x22/bw/pressed.png"))); btnAddHospital.addActionListener(e -> btnAddHospitalActionPerformed(e)); jPanel1.add(btnAddHospital, CC.xy(11, 9)); //---- lblSecurity ---- lblSecurity.setText("Diagnosesicherheit:"); lblSecurity.setFont(new Font("Arial", Font.PLAIN, 14)); jPanel1.add(lblSecurity, CC.xy(7, 11)); //---- lblSide ---- lblSide.setText("K\u00f6rperseite:"); lblSide.setFont(new Font("Arial", Font.PLAIN, 14)); jPanel1.add(lblSide, CC.xy(3, 11, CC.RIGHT, CC.DEFAULT)); //---- cmbKoerper ---- cmbKoerper.setModel(new DefaultComboBoxModel<>(new String[]{ "Nicht festgelegt", "links", "rechts", "beidseitig" })); cmbKoerper.setFont(new Font("Arial", Font.PLAIN, 14)); jPanel1.add(cmbKoerper, CC.xy(5, 11)); //---- cmbSicherheit ---- cmbSicherheit.setModel(new DefaultComboBoxModel<>(new String[]{ "Nicht festgelegt", "gesichert", "Verdacht auf", "Ausschlu\u00df von", "Zustand nach" })); cmbSicherheit.setFont(new Font("Arial", Font.PLAIN, 14)); jPanel1.add(cmbSicherheit, CC.xywh(9, 11, 3, 1)); //======== jScrollPane1 ======== { //---- txtBemerkung ---- txtBemerkung.setColumns(20); txtBemerkung.setRows(5); txtBemerkung.setFont(new Font("Arial", Font.PLAIN, 14)); jScrollPane1.setViewportView(txtBemerkung); } jPanel1.add(jScrollPane1, CC.xywh(3, 13, 9, 1)); //---- lblInterval ---- lblInterval.setText("text"); jPanel1.add(lblInterval, CC.xywh(3, 15, 5, 1)); //======== panel1 ======== { panel1.setLayout(new HorizontalLayout(5)); //---- btnCancel ---- btnCancel.setIcon(new ImageIcon(getClass().getResource("/artwork/22x22/cancel.png"))); btnCancel.setText(null); btnCancel.addActionListener(e -> btnCancelActionPerformed(e)); panel1.add(btnCancel); //---- btnOK ---- btnOK.setIcon(new ImageIcon(getClass().getResource("/artwork/22x22/apply.png"))); btnOK.setText(null); btnOK.addActionListener(e -> btnOKActionPerformed(e)); panel1.add(btnOK); } jPanel1.add(panel1, CC.xywh(7, 15, 5, 1, CC.RIGHT, CC.DEFAULT)); } contentPane.add(jPanel1, BorderLayout.CENTER); setSize(730, 565); setLocationRelativeTo(getOwner()); }// </editor-fold>//GEN-END:initComponents private void btnOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOKActionPerformed if (saveOK()) { save(); dispose(); } }//GEN-LAST:event_btnOKActionPerformed private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed diag = null; dispose(); }//GEN-LAST:event_btnCancelActionPerformed @Override public void dispose() { super.dispose(); actionBlock.execute(diag); } private boolean saveOK() { boolean saveOK = true; if (cmbArzt.getSelectedItem() == null && cmbKH.getSelectedItem() == null) { OPDE.getDisplayManager().addSubMessage(new DisplayMessage(SYSTools.xx("misc.msg.gpANDhospitalempty"))); saveOK = false; } if (lstDiag.getSelectedValue() == null) { OPDE.getDisplayManager().addSubMessage(new DisplayMessage(SYSTools.xx("nursingrecords.info.dlg.diags.emptydiag"))); saveOK = false; } return saveOK; } private void save() { GP doc = (GP) cmbArzt.getSelectedItem(); Hospital kh = (Hospital) cmbKH.getSelectedItem(); ICD icd = (ICD) lstDiag.getSelectedValue(); Properties props = new Properties(); props.put("icd", icd.getICD10()); props.put("text", icd.getText()); props.put("koerperseite", cmbKoerper.getSelectedItem()); props.put("diagnosesicherheit", cmbSicherheit.getSelectedItem()); props.put("arztid", doc == null ? "null" : doc.getArztID().toString()); props.put("khid", kh == null ? "null" : kh.getKhid().toString()); String html = ""; html += "<br/>" + SYSConst.html_bold(icd.getICD10() + ": " + icd.getText()) + "<br/>"; html += SYSTools.xx("nursingrecords.info.dlg.diags.by") + ": "; if (kh != null) { html += SYSConst.html_bold(HospitalTools.getFullName(kh)); } if (doc != null) { if (kh != null) { html += "<br/>" + SYSTools.xx("misc.msg.confirmedby") + ": "; } html += SYSConst.html_bold(GPTools.getFullName(doc)) + "<br/>"; } html += SYSTools.xx("misc.msg.diag.side") + ": " + SYSConst.html_bold(cmbKoerper.getSelectedItem().toString()) + "<br/>"; html += SYSTools.xx("misc.msg.diag.security") + ": " + SYSConst.html_bold(cmbSicherheit.getSelectedItem().toString()) + "<br/>"; ResInfoTools.setContent(diag, props); diag.setHtml(html); diag.setText(txtBemerkung.getText().trim()); } private void reloadTable() { if (txtSuche.getText().isEmpty()) { lstDiag.setModel(new DefaultListModel()); return; } EntityManager em = OPDE.createEM(); Query query = em.createQuery("SELECT i FROM ICD i WHERE i.icd10 LIKE :icd10 OR i.text like :text ORDER BY i.icd10 "); String suche = "%" + txtSuche.getText() + "%"; query.setParameter("icd10", suche); query.setParameter("text", suche); lstDiag.setModel(SYSTools.list2dlm(query.getResultList())); em.close(); lstDiag.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); } // Variables declaration - do not modify//GEN-BEGIN:variables private JPanel jPanel1; private JXSearchField txtSuche; private JLabel lblTX; private JScrollPane jspDiagnosen; private JList lstDiag; private JLabel lblDiagBy; private JComboBox<String> cmbArzt; private JButton btnAddGP; private JComboBox<String> cmbKH; private JButton btnAddHospital; private JLabel lblSecurity; private JLabel lblSide; private JComboBox<String> cmbKoerper; private JComboBox<String> cmbSicherheit; private JScrollPane jScrollPane1; private JTextArea txtBemerkung; private JLabel lblInterval; private JPanel panel1; private JButton btnCancel; private JButton btnOK; // End of variables declaration//GEN-END:variables }
thebpc/Offene-Pflege.de
src/op/care/info/DlgDiag.java
4,910
//---- cmbKoerper ----
line_comment
nl
/* * OffenePflege * Copyright (C) 2006-2012 Torsten Löhr * This program is free software; you can redistribute it and/or modify it under the terms of the * GNU General Public License V2 as published by the Free Software Foundation * * 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, write to * the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA * www.offene-pflege.de * ------------------------ * Auf deutsch (freie Übersetzung. Rechtlich gilt die englische Version) * Dieses Programm ist freie Software. Sie können es unter den Bedingungen der GNU General Public License, * wie von der Free Software Foundation veröffentlicht, weitergeben und/oder modifizieren, gemäß Version 2 der Lizenz. * * Die Veröffentlichung dieses Programms erfolgt in der Hoffnung, daß es Ihnen von Nutzen sein wird, aber * OHNE IRGENDEINE GARANTIE, sogar ohne die implizite Garantie der MARKTREIFE oder der VERWENDBARKEIT FÜR EINEN * BESTIMMTEN ZWECK. Details finden Sie in der GNU General Public License. * * Sie sollten ein Exemplar der GNU General Public License zusammen mit diesem Programm erhalten haben. Falls nicht, * schreiben Sie an die Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA. * */ package op.care.info; import com.jgoodies.forms.factories.CC; import com.jgoodies.forms.layout.FormLayout; import com.jidesoft.popup.JidePopup; import entity.EntityTools; import entity.info.ICD; import entity.info.ResInfo; import entity.info.ResInfoTools; import entity.prescription.GP; import entity.prescription.GPTools; import entity.prescription.Hospital; import entity.prescription.HospitalTools; import gui.GUITools; import op.OPDE; import op.residents.PnlEditGP; import op.residents.PnlEditHospital; import op.threads.DisplayMessage; import op.tools.MyJDialog; import op.tools.SYSConst; import op.tools.SYSTools; import org.apache.commons.collections.Closure; import org.jdesktop.swingx.HorizontalLayout; import org.jdesktop.swingx.JXSearchField; import javax.persistence.EntityManager; import javax.persistence.Query; import javax.swing.*; import javax.swing.border.SoftBevelBorder; import javax.swing.event.ListSelectionListener; import java.awt.*; import java.awt.event.ActionEvent; import java.util.Properties; /** * @author root */ public class DlgDiag extends MyJDialog { public static final String internalClassID = "nursingrecords.info.dlg.diags"; private ListSelectionListener lsl; private String text; private ResInfo diag; private Closure actionBlock; /** * Creates new form DlgVorlage */ public DlgDiag(ResInfo diag, Closure actionBlock) { super(false); this.diag = diag; this.actionBlock = actionBlock; initComponents(); initDialog(); // setVisible(true); } private void initDialog() { fillCMBs(); String tooltip = SYSTools.xx("nursingrecords.info.dlg.diags.tx.tooltip").replace('[', '<').replace(']', '>'); lblTX.setToolTipText(SYSTools.toHTMLForScreen("<p style=\"width:300px;\">" + tooltip + "</p>")); txtSuche.setPrompt(SYSTools.xx("misc.msg.search")); lblDiagBy.setText(SYSTools.xx("nursingrecords.info.dlg.diags.by")); lblSide.setText(SYSTools.xx("misc.msg.diag.side")); lblSecurity.setText(SYSTools.xx("misc.msg.diag.security")); lblInterval.setText(SYSTools.xx("nursingrecords.info.dlg.interval_noconstraints")); lblInterval.setIcon(SYSConst.icon22intervalNoConstraints); reloadTable(); OPDE.getDisplayManager().addSubMessage(new DisplayMessage(SYSTools.xx("nursingrecords.info.dlg.diags"), 10)); } private void txtSucheActionPerformed(ActionEvent e) { reloadTable(); } private void btnAddGPActionPerformed(ActionEvent e) { final PnlEditGP pnlGP = new PnlEditGP(new GP()); JidePopup popup = GUITools.createPanelPopup(pnlGP, o -> { if (o != null) { GP gp = EntityTools.merge((GP) o); cmbArzt.setModel(new DefaultComboBoxModel(new GP[]{gp})); } }, btnAddGP); GUITools.showPopup(popup, SwingConstants.EAST); } private void btnAddHospitalActionPerformed(ActionEvent e) { final PnlEditHospital pnlHospital = new PnlEditHospital(new Hospital()); JidePopup popup = GUITools.createPanelPopup(pnlHospital, o -> { if (o != null) { Hospital hospital = EntityTools.merge((Hospital) o); cmbKH.setModel(new DefaultComboBoxModel(new Hospital[]{hospital})); } }, btnAddHospital); GUITools.showPopup(popup, SwingConstants.EAST); } private void fillCMBs() { EntityManager em = OPDE.createEM(); Query queryArzt = em.createQuery("SELECT a FROM GP a WHERE a.status >= 0 ORDER BY a.name, a.vorname"); java.util.List<GP> listAerzte = queryArzt.getResultList(); listAerzte.add(0, null); Query queryKH = em.createQuery("SELECT k FROM Hospital k WHERE k.state >= 0 ORDER BY k.name"); java.util.List<Hospital> listKH = queryKH.getResultList(); listKH.add(0, null); em.close(); cmbArzt.setModel(new DefaultComboBoxModel(listAerzte.toArray())); cmbArzt.setRenderer(GPTools.getRenderer()); cmbArzt.setSelectedIndex(0); cmbKH.setModel(new DefaultComboBoxModel(listKH.toArray())); cmbKH.setRenderer(HospitalTools.getKHRenderer()); cmbKH.setSelectedIndex(0); cmbSicherheit.setModel(new DefaultComboBoxModel(new String[]{ SYSTools.xx("misc.msg.diag.security.na"), SYSTools.xx("misc.msg.diag.security.confirmed"), SYSTools.xx("misc.msg.diag.security.suspected"), SYSTools.xx("misc.msg.diag.security.rulingout"), SYSTools.xx("misc.msg.diag.security.conditionafter") })); cmbSicherheit.setSelectedIndex(1); cmbKoerper.setModel(new DefaultComboBoxModel(new String[]{ SYSTools.xx("misc.msg.diag.side.na"), SYSTools.xx("misc.msg.diag.side.left"), SYSTools.xx("misc.msg.diag.side.right"), SYSTools.xx("misc.msg.diag.side.both") })); } /** * This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the PrinterForm Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new JPanel(); txtSuche = new JXSearchField(); lblTX = new JLabel(); jspDiagnosen = new JScrollPane(); lstDiag = new JList(); lblDiagBy = new JLabel(); cmbArzt = new JComboBox<>(); btnAddGP = new JButton(); cmbKH = new JComboBox<>(); btnAddHospital = new JButton(); lblSecurity = new JLabel(); lblSide = new JLabel(); cmbKoerper = new JComboBox<>(); cmbSicherheit = new JComboBox<>(); jScrollPane1 = new JScrollPane(); txtBemerkung = new JTextArea(); lblInterval = new JLabel(); panel1 = new JPanel(); btnCancel = new JButton(); btnOK = new JButton(); //======== this ======== Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout()); //======== jPanel1 ======== { jPanel1.setBorder(new SoftBevelBorder(SoftBevelBorder.RAISED)); jPanel1.setLayout(new FormLayout( "default, $lcgap, pref, $lcgap, default:grow, $ugap, pref, $lcgap, default:grow, 2*($lcgap, default)", "default, $lgap, fill:default, $lgap, fill:104dlu:grow, $lgap, fill:default, $lgap, default, $lgap, fill:default, $lgap, fill:89dlu:grow, $ugap, default, $lgap, default")); //---- txtSuche ---- txtSuche.setFont(new Font("Arial", Font.PLAIN, 14)); txtSuche.addActionListener(e -> txtSucheActionPerformed(e)); jPanel1.add(txtSuche, CC.xywh(3, 3, 7, 1)); //---- lblTX ---- lblTX.setText(null); lblTX.setIcon(new ImageIcon(getClass().getResource("/artwork/22x22/ambulance2.png"))); jPanel1.add(lblTX, CC.xy(11, 3)); //======== jspDiagnosen ======== { //---- lstDiag ---- lstDiag.setFont(new Font("Arial", Font.PLAIN, 14)); jspDiagnosen.setViewportView(lstDiag); } jPanel1.add(jspDiagnosen, CC.xywh(3, 5, 9, 1)); //---- lblDiagBy ---- lblDiagBy.setText("Festgestellt durch:"); lblDiagBy.setFont(new Font("Arial", Font.PLAIN, 14)); jPanel1.add(lblDiagBy, CC.xy(3, 7, CC.RIGHT, CC.DEFAULT)); //---- cmbArzt ---- cmbArzt.setModel(new DefaultComboBoxModel<>(new String[]{ "Item 1", "Item 2", "Item 3", "Item 4" })); cmbArzt.setFont(new Font("Arial", Font.PLAIN, 14)); jPanel1.add(cmbArzt, CC.xywh(5, 7, 5, 1)); //---- btnAddGP ---- btnAddGP.setText(null); btnAddGP.setBorder(null); btnAddGP.setContentAreaFilled(false); btnAddGP.setIcon(new ImageIcon(getClass().getResource("/artwork/22x22/bw/add.png"))); btnAddGP.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); btnAddGP.setSelectedIcon(new ImageIcon(getClass().getResource("/artwork/22x22/bw/pressed.png"))); btnAddGP.addActionListener(e -> btnAddGPActionPerformed(e)); jPanel1.add(btnAddGP, CC.xy(11, 7)); //---- cmbKH ---- cmbKH.setModel(new DefaultComboBoxModel<>(new String[]{ "Item 1", "Item 2", "Item 3", "Item 4" })); cmbKH.setFont(new Font("Arial", Font.PLAIN, 14)); jPanel1.add(cmbKH, CC.xywh(5, 9, 5, 1)); //---- btnAddHospital ---- btnAddHospital.setText(null); btnAddHospital.setIcon(new ImageIcon(getClass().getResource("/artwork/22x22/bw/add.png"))); btnAddHospital.setBorder(null); btnAddHospital.setContentAreaFilled(false); btnAddHospital.setBorderPainted(false); btnAddHospital.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); btnAddHospital.setSelectedIcon(new ImageIcon(getClass().getResource("/artwork/22x22/bw/pressed.png"))); btnAddHospital.addActionListener(e -> btnAddHospitalActionPerformed(e)); jPanel1.add(btnAddHospital, CC.xy(11, 9)); //---- lblSecurity ---- lblSecurity.setText("Diagnosesicherheit:"); lblSecurity.setFont(new Font("Arial", Font.PLAIN, 14)); jPanel1.add(lblSecurity, CC.xy(7, 11)); //---- lblSide ---- lblSide.setText("K\u00f6rperseite:"); lblSide.setFont(new Font("Arial", Font.PLAIN, 14)); jPanel1.add(lblSide, CC.xy(3, 11, CC.RIGHT, CC.DEFAULT)); //---- cmbKoerper<SUF> cmbKoerper.setModel(new DefaultComboBoxModel<>(new String[]{ "Nicht festgelegt", "links", "rechts", "beidseitig" })); cmbKoerper.setFont(new Font("Arial", Font.PLAIN, 14)); jPanel1.add(cmbKoerper, CC.xy(5, 11)); //---- cmbSicherheit ---- cmbSicherheit.setModel(new DefaultComboBoxModel<>(new String[]{ "Nicht festgelegt", "gesichert", "Verdacht auf", "Ausschlu\u00df von", "Zustand nach" })); cmbSicherheit.setFont(new Font("Arial", Font.PLAIN, 14)); jPanel1.add(cmbSicherheit, CC.xywh(9, 11, 3, 1)); //======== jScrollPane1 ======== { //---- txtBemerkung ---- txtBemerkung.setColumns(20); txtBemerkung.setRows(5); txtBemerkung.setFont(new Font("Arial", Font.PLAIN, 14)); jScrollPane1.setViewportView(txtBemerkung); } jPanel1.add(jScrollPane1, CC.xywh(3, 13, 9, 1)); //---- lblInterval ---- lblInterval.setText("text"); jPanel1.add(lblInterval, CC.xywh(3, 15, 5, 1)); //======== panel1 ======== { panel1.setLayout(new HorizontalLayout(5)); //---- btnCancel ---- btnCancel.setIcon(new ImageIcon(getClass().getResource("/artwork/22x22/cancel.png"))); btnCancel.setText(null); btnCancel.addActionListener(e -> btnCancelActionPerformed(e)); panel1.add(btnCancel); //---- btnOK ---- btnOK.setIcon(new ImageIcon(getClass().getResource("/artwork/22x22/apply.png"))); btnOK.setText(null); btnOK.addActionListener(e -> btnOKActionPerformed(e)); panel1.add(btnOK); } jPanel1.add(panel1, CC.xywh(7, 15, 5, 1, CC.RIGHT, CC.DEFAULT)); } contentPane.add(jPanel1, BorderLayout.CENTER); setSize(730, 565); setLocationRelativeTo(getOwner()); }// </editor-fold>//GEN-END:initComponents private void btnOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOKActionPerformed if (saveOK()) { save(); dispose(); } }//GEN-LAST:event_btnOKActionPerformed private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed diag = null; dispose(); }//GEN-LAST:event_btnCancelActionPerformed @Override public void dispose() { super.dispose(); actionBlock.execute(diag); } private boolean saveOK() { boolean saveOK = true; if (cmbArzt.getSelectedItem() == null && cmbKH.getSelectedItem() == null) { OPDE.getDisplayManager().addSubMessage(new DisplayMessage(SYSTools.xx("misc.msg.gpANDhospitalempty"))); saveOK = false; } if (lstDiag.getSelectedValue() == null) { OPDE.getDisplayManager().addSubMessage(new DisplayMessage(SYSTools.xx("nursingrecords.info.dlg.diags.emptydiag"))); saveOK = false; } return saveOK; } private void save() { GP doc = (GP) cmbArzt.getSelectedItem(); Hospital kh = (Hospital) cmbKH.getSelectedItem(); ICD icd = (ICD) lstDiag.getSelectedValue(); Properties props = new Properties(); props.put("icd", icd.getICD10()); props.put("text", icd.getText()); props.put("koerperseite", cmbKoerper.getSelectedItem()); props.put("diagnosesicherheit", cmbSicherheit.getSelectedItem()); props.put("arztid", doc == null ? "null" : doc.getArztID().toString()); props.put("khid", kh == null ? "null" : kh.getKhid().toString()); String html = ""; html += "<br/>" + SYSConst.html_bold(icd.getICD10() + ": " + icd.getText()) + "<br/>"; html += SYSTools.xx("nursingrecords.info.dlg.diags.by") + ": "; if (kh != null) { html += SYSConst.html_bold(HospitalTools.getFullName(kh)); } if (doc != null) { if (kh != null) { html += "<br/>" + SYSTools.xx("misc.msg.confirmedby") + ": "; } html += SYSConst.html_bold(GPTools.getFullName(doc)) + "<br/>"; } html += SYSTools.xx("misc.msg.diag.side") + ": " + SYSConst.html_bold(cmbKoerper.getSelectedItem().toString()) + "<br/>"; html += SYSTools.xx("misc.msg.diag.security") + ": " + SYSConst.html_bold(cmbSicherheit.getSelectedItem().toString()) + "<br/>"; ResInfoTools.setContent(diag, props); diag.setHtml(html); diag.setText(txtBemerkung.getText().trim()); } private void reloadTable() { if (txtSuche.getText().isEmpty()) { lstDiag.setModel(new DefaultListModel()); return; } EntityManager em = OPDE.createEM(); Query query = em.createQuery("SELECT i FROM ICD i WHERE i.icd10 LIKE :icd10 OR i.text like :text ORDER BY i.icd10 "); String suche = "%" + txtSuche.getText() + "%"; query.setParameter("icd10", suche); query.setParameter("text", suche); lstDiag.setModel(SYSTools.list2dlm(query.getResultList())); em.close(); lstDiag.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); } // Variables declaration - do not modify//GEN-BEGIN:variables private JPanel jPanel1; private JXSearchField txtSuche; private JLabel lblTX; private JScrollPane jspDiagnosen; private JList lstDiag; private JLabel lblDiagBy; private JComboBox<String> cmbArzt; private JButton btnAddGP; private JComboBox<String> cmbKH; private JButton btnAddHospital; private JLabel lblSecurity; private JLabel lblSide; private JComboBox<String> cmbKoerper; private JComboBox<String> cmbSicherheit; private JScrollPane jScrollPane1; private JTextArea txtBemerkung; private JLabel lblInterval; private JPanel panel1; private JButton btnCancel; private JButton btnOK; // End of variables declaration//GEN-END:variables }
105227_16
package nl.hva.dmci.ict.sortingsearching.weigthedgraph; import java.util.LinkedList; import nl.hva.dmci.ict.sortingsearching.tileworld.TileType; import nl.hva.dmci.ict.sortingsearching.tileworld.TileWorldUtil; /** * The {@code EdgeWeightedDigraph} class represents a edge-weighted * digraph of vertices named 0 through <em>V</em> - 1, where each * directed edge is of type {@link DirectedEdge} and has a real-valued weight. * It supports the following two primary operations: add a directed edge * to the digraph and iterate over all of edges incident from a given vertex. * It also provides * methods for returning the number of vertices <em>V</em> and the number * of edges <em>E</em>. Parallel edges and self-loops are permitted. * <p> * This implementation uses an adjacency-lists representation, which * is a vertex-indexed array of @link{Bag} objects. * All operations take constant time (in the worst case) except * iterating over the edges incident from a given vertex, which takes * time proportional to the number of such edges. * <p> * For additional documentation, * see <a href="http://algs4.cs.princeton.edu/44sp">Section 4.4</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * Overgenomen uit de library algs4-package.jar van Robert Sedgwick * Aanpassingen specifiek t.b.v. PO2 Sorting&amp;Searching * * @author Robert Sedgewick * @author Kevin Wayne * @author Eric Ravestein * @author Nico Tromp */ public class EdgeWeightedDigraph { private final int V; private int E; private final int startIndex; private final int endIndex; private final LinkedList<DirectedEdge>[] adj; private final TileWorldUtil t; private final int breedte; private final int hoogte; /** * Constructor maakt een Digraph aan met V knooppunten (vertices) * Direct overgenomen uit Sedgwick. T.b.v. Floyd-Warshall * @param V aantal knooppunten */ public EdgeWeightedDigraph(int V) { if (V < 0) { throw new IllegalArgumentException("Number of vertices in a Digraph must be nonnegative"); } this.V = V; this.E = 0; hoogte = 0; breedte = 0; t = null; startIndex = 0; endIndex = 0; adj = (LinkedList<DirectedEdge>[]) new LinkedList[V]; for (int v = 0; v < V; v++) { adj[v] = new LinkedList<DirectedEdge>(); } } /** * Constructor. * Leest de TileWorldUtil in van bitmap fileName+".png" en maakt de adjacency list adj * * @param fileName filenaam van de bitmap */ public EdgeWeightedDigraph(String fileName) { t = new TileWorldUtil(fileName + ".png"); // Aantal knopen hoogte = t.getHeight(); breedte = t.getWidth(); this.V = hoogte * breedte; // Start- en Eindindex this.startIndex = t.findStartIndex(); this.endIndex = t.findEndIndex(); this.E = 0; adj = (LinkedList<DirectedEdge>[]) new LinkedList[V]; int v; for (v = 0; v < V; v++) { adj[v] = findAdjacent(v); } } /** * getter voor het aantal knooppunten * @return aantal knooppunten */ public int V() { return V; } /** * Bewaart de bitmap onder de naam fileName. * @param fileName naam van de bitmap */ public void save(String fileName) { t.save(fileName); } /** * Maakt een Digraph met een adjacency matrix in plaats van een * adjacencylist. * Nodig voor Floyd=Warshall algoritme. * * @return een Digraph met Adjacencymatrix in plaats van list. */ public AdjMatrixEdgeWeightedDigraph createAdjMatrixEdgeWeightedDigraph() { AdjMatrixEdgeWeightedDigraph g; Iterable<DirectedEdge> edges; g = new AdjMatrixEdgeWeightedDigraph(V); edges = edges(); for (DirectedEdge d : edges) { g.addEdge(d); } return g; } /** * Zoekt alle aanliggende knoopunten van knooppunt v. * * @param v het te onderzoeken knooppunt * @return LinkedList van alle aanliggende (=bereikbare) * knooppunten met de cost om daar te komen. */ private LinkedList<DirectedEdge> findAdjacent(int v) { LinkedList<DirectedEdge> b; int x, y; TileType tt; double diagonalCost, cost; x = t.oneDimToTwoDimXCoordinate(v); y = t.oneDimToTwoDimYCoordinate(v); tt = t.getTileType(x, y); diagonalCost = tt.getDiagonalCost(); cost = tt.getCost(); b = new LinkedList<DirectedEdge>(); if (x > 0) { // naar Links b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x - 1, y), cost)); if (y > 0) { // Links onder b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x - 1, y - 1), diagonalCost)); } if (y < hoogte - 1) { // Links boven b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x - 1, y + 1), diagonalCost)); } } if (x < breedte - 1) { // Rechts b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x + 1, y), cost)); if (y > 0) { // Rechts onder b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x + 1, y - 1), diagonalCost)); } if (y < hoogte - 1) { // Rechts boven b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x + 1, y + 1), diagonalCost)); } } if (y > 0) { // Onder b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x, y - 1), cost)); } if (y < hoogte - 1) { // Boven b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x, y + 1), cost)); } return b; } /** * Geeft de x coordinaat van knooppunt v in de bitmap. * * @param v index van knoopunt v * @return x coordinaat */ public int getX(int v) { return t.oneDimToTwoDimXCoordinate(v); } /** * Geeft de y coordinaat van knooppunt v in de bitmap. * * @param v index van knoopunt v * @return x coordinaat */ public int getY(int v) { return t.oneDimToTwoDimYCoordinate(v); } /** * Geeft de index in de adjacency list van het knooppunt dat in de TileWorldUtil t een coordinaat (x,y) heeft. * @param x x-coordinaat van te onderzoeken punt * @param y y-coordinaat van te onderzoeken punt * @return index van dit punt in de adjacencylist adj */ public int getIndex(int x, int y) { return t.twoDimIndexToOneDimIndex(x, y); } /** * Bepaalt alle aanliggende edges van knooppunt v * @param v het te onderzoeken knooppunt * @return lijst van edges die beginnen of eindigen in v */ public Iterable<DirectedEdge> adj(int v) { return adj[v]; } /** * Maakt een grote list van alle edges in de Digraph * @return LinkedList met alle edges */ public Iterable<DirectedEdge> edges() { LinkedList<DirectedEdge> list; list = new LinkedList<DirectedEdge>(); for (int v = 0; v < V; v++) { for (DirectedEdge e : adj[v]) { list.add(e); } } return list; } /** * getter voor het Startpunt van het te zoeken pad. * * @return index in de adjacency list van het startpunt */ public int getStart() { return (startIndex); } /** * getter voor het Eindpunt van het te zoeken pad. * * @return index in de adjacency list van het startpunt */ public int getEnd() { return (endIndex); } /** * Laat de bitmap zien in een jFrame * @param filename naam van de bitmap * @param title aanvullende titel ter specificatie van de bitmap */ public void show(String filename, String title) { t.show(filename + ".png " + title, 10, 0, 0); } /** * Tekent het pad sp in de juiste kleur in de bitmap. * @param sp het te tekenen pad */ public void tekenPad(Iterable<DirectedEdge> sp) { TileType tt = TileType.PATH; int x, y; for (DirectedEdge de : sp) { x = t.oneDimToTwoDimXCoordinate(de.from()); y = t.oneDimToTwoDimYCoordinate(de.from()); t.setTileType(x, y, tt); } } /** * Adds the directed edge e to the edge-weighted digraph. * * Uit Sedgwick: tbv Floyd-Warshall * @param e the edge */ public void addEdge(DirectedEdge e) { int v = e.from(); adj[v].add(e); E++; } }
robertbakker/Sorting_Searching_Assignments
src/nl/hva/dmci/ict/sortingsearching/weigthedgraph/EdgeWeightedDigraph.java
2,682
/** * Laat de bitmap zien in een jFrame * @param filename naam van de bitmap * @param title aanvullende titel ter specificatie van de bitmap */
block_comment
nl
package nl.hva.dmci.ict.sortingsearching.weigthedgraph; import java.util.LinkedList; import nl.hva.dmci.ict.sortingsearching.tileworld.TileType; import nl.hva.dmci.ict.sortingsearching.tileworld.TileWorldUtil; /** * The {@code EdgeWeightedDigraph} class represents a edge-weighted * digraph of vertices named 0 through <em>V</em> - 1, where each * directed edge is of type {@link DirectedEdge} and has a real-valued weight. * It supports the following two primary operations: add a directed edge * to the digraph and iterate over all of edges incident from a given vertex. * It also provides * methods for returning the number of vertices <em>V</em> and the number * of edges <em>E</em>. Parallel edges and self-loops are permitted. * <p> * This implementation uses an adjacency-lists representation, which * is a vertex-indexed array of @link{Bag} objects. * All operations take constant time (in the worst case) except * iterating over the edges incident from a given vertex, which takes * time proportional to the number of such edges. * <p> * For additional documentation, * see <a href="http://algs4.cs.princeton.edu/44sp">Section 4.4</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * Overgenomen uit de library algs4-package.jar van Robert Sedgwick * Aanpassingen specifiek t.b.v. PO2 Sorting&amp;Searching * * @author Robert Sedgewick * @author Kevin Wayne * @author Eric Ravestein * @author Nico Tromp */ public class EdgeWeightedDigraph { private final int V; private int E; private final int startIndex; private final int endIndex; private final LinkedList<DirectedEdge>[] adj; private final TileWorldUtil t; private final int breedte; private final int hoogte; /** * Constructor maakt een Digraph aan met V knooppunten (vertices) * Direct overgenomen uit Sedgwick. T.b.v. Floyd-Warshall * @param V aantal knooppunten */ public EdgeWeightedDigraph(int V) { if (V < 0) { throw new IllegalArgumentException("Number of vertices in a Digraph must be nonnegative"); } this.V = V; this.E = 0; hoogte = 0; breedte = 0; t = null; startIndex = 0; endIndex = 0; adj = (LinkedList<DirectedEdge>[]) new LinkedList[V]; for (int v = 0; v < V; v++) { adj[v] = new LinkedList<DirectedEdge>(); } } /** * Constructor. * Leest de TileWorldUtil in van bitmap fileName+".png" en maakt de adjacency list adj * * @param fileName filenaam van de bitmap */ public EdgeWeightedDigraph(String fileName) { t = new TileWorldUtil(fileName + ".png"); // Aantal knopen hoogte = t.getHeight(); breedte = t.getWidth(); this.V = hoogte * breedte; // Start- en Eindindex this.startIndex = t.findStartIndex(); this.endIndex = t.findEndIndex(); this.E = 0; adj = (LinkedList<DirectedEdge>[]) new LinkedList[V]; int v; for (v = 0; v < V; v++) { adj[v] = findAdjacent(v); } } /** * getter voor het aantal knooppunten * @return aantal knooppunten */ public int V() { return V; } /** * Bewaart de bitmap onder de naam fileName. * @param fileName naam van de bitmap */ public void save(String fileName) { t.save(fileName); } /** * Maakt een Digraph met een adjacency matrix in plaats van een * adjacencylist. * Nodig voor Floyd=Warshall algoritme. * * @return een Digraph met Adjacencymatrix in plaats van list. */ public AdjMatrixEdgeWeightedDigraph createAdjMatrixEdgeWeightedDigraph() { AdjMatrixEdgeWeightedDigraph g; Iterable<DirectedEdge> edges; g = new AdjMatrixEdgeWeightedDigraph(V); edges = edges(); for (DirectedEdge d : edges) { g.addEdge(d); } return g; } /** * Zoekt alle aanliggende knoopunten van knooppunt v. * * @param v het te onderzoeken knooppunt * @return LinkedList van alle aanliggende (=bereikbare) * knooppunten met de cost om daar te komen. */ private LinkedList<DirectedEdge> findAdjacent(int v) { LinkedList<DirectedEdge> b; int x, y; TileType tt; double diagonalCost, cost; x = t.oneDimToTwoDimXCoordinate(v); y = t.oneDimToTwoDimYCoordinate(v); tt = t.getTileType(x, y); diagonalCost = tt.getDiagonalCost(); cost = tt.getCost(); b = new LinkedList<DirectedEdge>(); if (x > 0) { // naar Links b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x - 1, y), cost)); if (y > 0) { // Links onder b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x - 1, y - 1), diagonalCost)); } if (y < hoogte - 1) { // Links boven b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x - 1, y + 1), diagonalCost)); } } if (x < breedte - 1) { // Rechts b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x + 1, y), cost)); if (y > 0) { // Rechts onder b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x + 1, y - 1), diagonalCost)); } if (y < hoogte - 1) { // Rechts boven b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x + 1, y + 1), diagonalCost)); } } if (y > 0) { // Onder b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x, y - 1), cost)); } if (y < hoogte - 1) { // Boven b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x, y + 1), cost)); } return b; } /** * Geeft de x coordinaat van knooppunt v in de bitmap. * * @param v index van knoopunt v * @return x coordinaat */ public int getX(int v) { return t.oneDimToTwoDimXCoordinate(v); } /** * Geeft de y coordinaat van knooppunt v in de bitmap. * * @param v index van knoopunt v * @return x coordinaat */ public int getY(int v) { return t.oneDimToTwoDimYCoordinate(v); } /** * Geeft de index in de adjacency list van het knooppunt dat in de TileWorldUtil t een coordinaat (x,y) heeft. * @param x x-coordinaat van te onderzoeken punt * @param y y-coordinaat van te onderzoeken punt * @return index van dit punt in de adjacencylist adj */ public int getIndex(int x, int y) { return t.twoDimIndexToOneDimIndex(x, y); } /** * Bepaalt alle aanliggende edges van knooppunt v * @param v het te onderzoeken knooppunt * @return lijst van edges die beginnen of eindigen in v */ public Iterable<DirectedEdge> adj(int v) { return adj[v]; } /** * Maakt een grote list van alle edges in de Digraph * @return LinkedList met alle edges */ public Iterable<DirectedEdge> edges() { LinkedList<DirectedEdge> list; list = new LinkedList<DirectedEdge>(); for (int v = 0; v < V; v++) { for (DirectedEdge e : adj[v]) { list.add(e); } } return list; } /** * getter voor het Startpunt van het te zoeken pad. * * @return index in de adjacency list van het startpunt */ public int getStart() { return (startIndex); } /** * getter voor het Eindpunt van het te zoeken pad. * * @return index in de adjacency list van het startpunt */ public int getEnd() { return (endIndex); } /** * Laat de bitmap<SUF>*/ public void show(String filename, String title) { t.show(filename + ".png " + title, 10, 0, 0); } /** * Tekent het pad sp in de juiste kleur in de bitmap. * @param sp het te tekenen pad */ public void tekenPad(Iterable<DirectedEdge> sp) { TileType tt = TileType.PATH; int x, y; for (DirectedEdge de : sp) { x = t.oneDimToTwoDimXCoordinate(de.from()); y = t.oneDimToTwoDimYCoordinate(de.from()); t.setTileType(x, y, tt); } } /** * Adds the directed edge e to the edge-weighted digraph. * * Uit Sedgwick: tbv Floyd-Warshall * @param e the edge */ public void addEdge(DirectedEdge e) { int v = e.from(); adj[v].add(e); E++; } }
69088_0
import domain.*; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.query.Query; import javax.persistence.metamodel.EntityType; import javax.persistence.metamodel.Metamodel; import java.sql.SQLException; import java.util.List; /** * 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 { 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(); } } public static void testDAOHibernate() { AdresDAOHibernate adao = new AdresDAOHibernate(getSession()); ReizigerDAOHibernate rdao = new ReizigerDAOHibernate(getSession()); OVChipkaartDAOHibernate odao = new OVChipkaartDAOHibernate(getSession()); ProductDAOHibernate pdao = new ProductDAOHibernate(getSession()); Reiziger reiziger = new Reiziger(15, "M", "", "Dol", java.sql.Date.valueOf("2001-02-03")); Adres adres = new Adres(15, "2968GB", "15", "Waal", "Waal", 15); OVChipkaart ovChipkaart = new OVChipkaart(11115, java.sql.Date.valueOf("2029-09-10"), 3, 1010.10f, 15); Product product = new Product(15, "TEST DP7", "TEST PRODUCT VOOR DP7", 10.00f); System.out.println("------ REIZIGER -----"); System.out.println("--- save + findAll ---"); System.out.println(rdao.findAll()); rdao.save(reiziger); System.out.println(rdao.findAll()); System.out.println("--- update + findById ---"); System.out.println(rdao.findById(reiziger.getId())); System.out.println("\n\n------ ADRES -----"); System.out.println("--- save + findAll ---"); System.out.println(adao.findAll()); adao.save(adres); System.out.println(adao.findAll()); System.out.println("--- update + findByReiziger ---"); adres.setHuisnummer("15a"); adao.update(adres); System.out.println(adao.findByReiziger(reiziger)); System.out.println("--- delete ---"); adao.delete(adres); System.out.println(adao.findAll()); System.out.println("\n\n------ PRODUCT -----"); System.out.println("--- save + findAll ---"); System.out.println(pdao.findAll()); pdao.save(product); System.out.println(pdao.findAll()); System.out.println("--- update ---"); product.setPrijs(20.00f); System.out.println(pdao.findAll()); System.out.println("\n\n------ OVCHIPKAART + findByReiziger -----"); System.out.println("--- save ---"); odao.save(ovChipkaart); System.out.println(odao.findByReiziger(reiziger)); System.out.println("--- update ---"); ovChipkaart.setSaldo(2020.20f); odao.update(ovChipkaart); System.out.println(odao.findByReiziger(reiziger)); // System.out.println("--- wijs product toe ---"); // ovChipkaart.getProductList().add(product); // odao.update(ovChipkaart); // System.out.println(odao.findByReiziger(reiziger)); System.out.println("\n\n----- DELETE ALLE -----"); System.out.println("--- delete ovchipkaart ---"); odao.delete(ovChipkaart); System.out.println("--- delete product ---"); pdao.delete(product); System.out.println(pdao.findAll()); System.out.println("---- delete reiziger ----"); rdao.delete(reiziger); System.out.println(rdao.findById(reiziger.getId())); } }
thijmon/hibernateDAO
src/main/java/Main.java
1,383
/** * 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 domain.*; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.query.Query; import javax.persistence.metamodel.EntityType; import javax.persistence.metamodel.Metamodel; import java.sql.SQLException; import java.util.List; /** * 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 { 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(); } } public static void testDAOHibernate() { AdresDAOHibernate adao = new AdresDAOHibernate(getSession()); ReizigerDAOHibernate rdao = new ReizigerDAOHibernate(getSession()); OVChipkaartDAOHibernate odao = new OVChipkaartDAOHibernate(getSession()); ProductDAOHibernate pdao = new ProductDAOHibernate(getSession()); Reiziger reiziger = new Reiziger(15, "M", "", "Dol", java.sql.Date.valueOf("2001-02-03")); Adres adres = new Adres(15, "2968GB", "15", "Waal", "Waal", 15); OVChipkaart ovChipkaart = new OVChipkaart(11115, java.sql.Date.valueOf("2029-09-10"), 3, 1010.10f, 15); Product product = new Product(15, "TEST DP7", "TEST PRODUCT VOOR DP7", 10.00f); System.out.println("------ REIZIGER -----"); System.out.println("--- save + findAll ---"); System.out.println(rdao.findAll()); rdao.save(reiziger); System.out.println(rdao.findAll()); System.out.println("--- update + findById ---"); System.out.println(rdao.findById(reiziger.getId())); System.out.println("\n\n------ ADRES -----"); System.out.println("--- save + findAll ---"); System.out.println(adao.findAll()); adao.save(adres); System.out.println(adao.findAll()); System.out.println("--- update + findByReiziger ---"); adres.setHuisnummer("15a"); adao.update(adres); System.out.println(adao.findByReiziger(reiziger)); System.out.println("--- delete ---"); adao.delete(adres); System.out.println(adao.findAll()); System.out.println("\n\n------ PRODUCT -----"); System.out.println("--- save + findAll ---"); System.out.println(pdao.findAll()); pdao.save(product); System.out.println(pdao.findAll()); System.out.println("--- update ---"); product.setPrijs(20.00f); System.out.println(pdao.findAll()); System.out.println("\n\n------ OVCHIPKAART + findByReiziger -----"); System.out.println("--- save ---"); odao.save(ovChipkaart); System.out.println(odao.findByReiziger(reiziger)); System.out.println("--- update ---"); ovChipkaart.setSaldo(2020.20f); odao.update(ovChipkaart); System.out.println(odao.findByReiziger(reiziger)); // System.out.println("--- wijs product toe ---"); // ovChipkaart.getProductList().add(product); // odao.update(ovChipkaart); // System.out.println(odao.findByReiziger(reiziger)); System.out.println("\n\n----- DELETE ALLE -----"); System.out.println("--- delete ovchipkaart ---"); odao.delete(ovChipkaart); System.out.println("--- delete product ---"); pdao.delete(product); System.out.println(pdao.findAll()); System.out.println("---- delete reiziger ----"); rdao.delete(reiziger); System.out.println(rdao.findById(reiziger.getId())); } }
108734_4
package com.iiatimd.portfolioappv2.Fragments; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.widget.SearchView; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import com.google.android.material.appbar.MaterialToolbar; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.iiatimd.portfolioappv2.Adapters.ProjectsAdapter; import com.iiatimd.portfolioappv2.Entities.Project; import com.iiatimd.portfolioappv2.Entities.ProjectCall; import com.iiatimd.portfolioappv2.Entities.User; import com.iiatimd.portfolioappv2.HomeActivity; import com.iiatimd.portfolioappv2.Network.ApiService; import com.iiatimd.portfolioappv2.Network.RetrofitBuilder; import com.iiatimd.portfolioappv2.R; import com.iiatimd.portfolioappv2.TokenManager; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Objects; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class HomeFragment extends Fragment { private View view; public static RecyclerView recyclerViewHome; public static ArrayList<Project> arrayList; private SwipeRefreshLayout refreshLayout; private ProjectsAdapter projectAdapter; private SharedPreferences sharedPreferences; private SharedPreferences projectPreferences; private static final String TAG = "HomeFragment"; ApiService service; // TokenManager tokenManager; Call<ProjectCall> callProject; public HomeFragment(){} @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view = inflater.inflate(R.layout.layout_home,container,false); service = RetrofitBuilder.createServiceWithAuth(ApiService.class, ((HomeActivity)getContext()).getToken()); init(); return view; } private void init(){ projectPreferences = getContext().getApplicationContext().getSharedPreferences("projects", Context.MODE_PRIVATE); sharedPreferences = Objects.requireNonNull(getContext()).getApplicationContext().getSharedPreferences("user", Context.MODE_PRIVATE); recyclerViewHome = view.findViewById(R.id.recyclerHome); recyclerViewHome.setHasFixedSize(true); recyclerViewHome.setLayoutManager(new LinearLayoutManager(getContext().getApplicationContext())); refreshLayout = view.findViewById(R.id.swipeHome); MaterialToolbar toolbar = view.findViewById(R.id.toolbarHome); ((HomeActivity)getContext()).setSupportActionBar(toolbar); setHasOptionsMenu(true); getProjects(); // Swipe down voor een refresh van de pagina refreshLayout.setOnRefreshListener(() -> getProjects()); } private void getProjects() { arrayList = new ArrayList<>(); refreshLayout.setRefreshing(true); // Maak een API request call callProject = service.myProjects(); callProject.enqueue(new Callback<ProjectCall>() { @Override public void onResponse(Call<ProjectCall> call, Response<ProjectCall> response) { Log.w(TAG, "onResponse: " + response); // Log.w(TAG, "onResponse: " + response.body().getProjects().get(2).getWebsite()); // Log.w(TAG, "onResponse: " + response.body().getProjects()); for (int i = 0; i < response.body().getProjects().toArray().length; i++) { // Maak user object User user = new User(); user.setId(response.body().getProjects().get(i).getUser().getId()); user.setName(response.body().getProjects().get(i).getUser().getName()); user.setLastname(response.body().getProjects().get(i).getUser().getLastname()); user.setPhoto(response.body().getProjects().get(i).getUser().getPhoto()); // Maak project object per iteratie Project project = new Project(); project.setUser(user); project.setId(response.body().getProjects().get(i).getId()); project.setPhoto(response.body().getProjects().get(i).getPhoto()); project.setProjectName(response.body().getProjects().get(i).getProjectName()); project.setWebsite(response.body().getProjects().get(i).getWebsite()); project.setOpdrachtgever(response.body().getProjects().get(i).getOpdrachtgever()); project.setAantalUur(response.body().getProjects().get(i).getAantalUur()); project.setDatumOplevering(response.body().getProjects().get(i).getDatumOplerving()); project.setDate(response.body().getProjects().get(i).getDate()); project.setDesc(response.body().getProjects().get(i).getDesc()); arrayList.add(project); } saveData(); projectAdapter = new ProjectsAdapter(Objects.requireNonNull(getContext()), arrayList); recyclerViewHome.setAdapter(projectAdapter); // Log.w(TAG, "onResponse: " + arrayList ); } @Override public void onFailure(Call<ProjectCall> call, Throwable t) { Log.w(TAG, "onFailure: " + t.getMessage() ); Log.w(TAG, "onFailure: Project data wordt uit geheugen gehaald" ); Gson gson = new Gson(); String json = projectPreferences.getString("projects", null); Type type = new TypeToken<ArrayList<Project>>() {}.getType(); arrayList = gson.fromJson(json, type); projectAdapter = new ProjectsAdapter(Objects.requireNonNull(getContext().getApplicationContext()), arrayList); recyclerViewHome.setAdapter(projectAdapter); // Laat weten dat je offline bent en dus data uit geheugen ziet Toast.makeText(getActivity().getApplicationContext(), "Je bent offline. Data is niet up to date en wordt opgehaald uit geheugen", Toast.LENGTH_LONG).show(); } }); refreshLayout.setRefreshing(false); } private void saveData() { Log.w(TAG, "saveData: Data word opgeslagen"); SharedPreferences.Editor editor = projectPreferences.edit(); Gson gson = new Gson(); String json = gson.toJson(arrayList); editor.putString("projects", json); editor.commit(); } @Override public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) { inflater.inflate(R.menu.menu_search,menu); MenuItem item = menu.findItem(R.id.search); SearchView searchView = (SearchView)item.getActionView(); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(String newText) { projectAdapter.getFilter().filter(newText); return false; } }); super.onCreateOptionsMenu(menu, inflater); } @Override // NOTE Wordt enkel gebruikt als hidden state veranderd of de fragment public void onHiddenChanged(boolean hidden) { if (!hidden){ getProjects(); } super.onHiddenChanged(hidden); } }
student-techlife/Portfolio-Android-App
app/src/main/java/com/iiatimd/portfolioappv2/Fragments/HomeFragment.java
1,870
// Maak user object
line_comment
nl
package com.iiatimd.portfolioappv2.Fragments; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.widget.SearchView; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import com.google.android.material.appbar.MaterialToolbar; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.iiatimd.portfolioappv2.Adapters.ProjectsAdapter; import com.iiatimd.portfolioappv2.Entities.Project; import com.iiatimd.portfolioappv2.Entities.ProjectCall; import com.iiatimd.portfolioappv2.Entities.User; import com.iiatimd.portfolioappv2.HomeActivity; import com.iiatimd.portfolioappv2.Network.ApiService; import com.iiatimd.portfolioappv2.Network.RetrofitBuilder; import com.iiatimd.portfolioappv2.R; import com.iiatimd.portfolioappv2.TokenManager; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Objects; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class HomeFragment extends Fragment { private View view; public static RecyclerView recyclerViewHome; public static ArrayList<Project> arrayList; private SwipeRefreshLayout refreshLayout; private ProjectsAdapter projectAdapter; private SharedPreferences sharedPreferences; private SharedPreferences projectPreferences; private static final String TAG = "HomeFragment"; ApiService service; // TokenManager tokenManager; Call<ProjectCall> callProject; public HomeFragment(){} @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view = inflater.inflate(R.layout.layout_home,container,false); service = RetrofitBuilder.createServiceWithAuth(ApiService.class, ((HomeActivity)getContext()).getToken()); init(); return view; } private void init(){ projectPreferences = getContext().getApplicationContext().getSharedPreferences("projects", Context.MODE_PRIVATE); sharedPreferences = Objects.requireNonNull(getContext()).getApplicationContext().getSharedPreferences("user", Context.MODE_PRIVATE); recyclerViewHome = view.findViewById(R.id.recyclerHome); recyclerViewHome.setHasFixedSize(true); recyclerViewHome.setLayoutManager(new LinearLayoutManager(getContext().getApplicationContext())); refreshLayout = view.findViewById(R.id.swipeHome); MaterialToolbar toolbar = view.findViewById(R.id.toolbarHome); ((HomeActivity)getContext()).setSupportActionBar(toolbar); setHasOptionsMenu(true); getProjects(); // Swipe down voor een refresh van de pagina refreshLayout.setOnRefreshListener(() -> getProjects()); } private void getProjects() { arrayList = new ArrayList<>(); refreshLayout.setRefreshing(true); // Maak een API request call callProject = service.myProjects(); callProject.enqueue(new Callback<ProjectCall>() { @Override public void onResponse(Call<ProjectCall> call, Response<ProjectCall> response) { Log.w(TAG, "onResponse: " + response); // Log.w(TAG, "onResponse: " + response.body().getProjects().get(2).getWebsite()); // Log.w(TAG, "onResponse: " + response.body().getProjects()); for (int i = 0; i < response.body().getProjects().toArray().length; i++) { // Maak user<SUF> User user = new User(); user.setId(response.body().getProjects().get(i).getUser().getId()); user.setName(response.body().getProjects().get(i).getUser().getName()); user.setLastname(response.body().getProjects().get(i).getUser().getLastname()); user.setPhoto(response.body().getProjects().get(i).getUser().getPhoto()); // Maak project object per iteratie Project project = new Project(); project.setUser(user); project.setId(response.body().getProjects().get(i).getId()); project.setPhoto(response.body().getProjects().get(i).getPhoto()); project.setProjectName(response.body().getProjects().get(i).getProjectName()); project.setWebsite(response.body().getProjects().get(i).getWebsite()); project.setOpdrachtgever(response.body().getProjects().get(i).getOpdrachtgever()); project.setAantalUur(response.body().getProjects().get(i).getAantalUur()); project.setDatumOplevering(response.body().getProjects().get(i).getDatumOplerving()); project.setDate(response.body().getProjects().get(i).getDate()); project.setDesc(response.body().getProjects().get(i).getDesc()); arrayList.add(project); } saveData(); projectAdapter = new ProjectsAdapter(Objects.requireNonNull(getContext()), arrayList); recyclerViewHome.setAdapter(projectAdapter); // Log.w(TAG, "onResponse: " + arrayList ); } @Override public void onFailure(Call<ProjectCall> call, Throwable t) { Log.w(TAG, "onFailure: " + t.getMessage() ); Log.w(TAG, "onFailure: Project data wordt uit geheugen gehaald" ); Gson gson = new Gson(); String json = projectPreferences.getString("projects", null); Type type = new TypeToken<ArrayList<Project>>() {}.getType(); arrayList = gson.fromJson(json, type); projectAdapter = new ProjectsAdapter(Objects.requireNonNull(getContext().getApplicationContext()), arrayList); recyclerViewHome.setAdapter(projectAdapter); // Laat weten dat je offline bent en dus data uit geheugen ziet Toast.makeText(getActivity().getApplicationContext(), "Je bent offline. Data is niet up to date en wordt opgehaald uit geheugen", Toast.LENGTH_LONG).show(); } }); refreshLayout.setRefreshing(false); } private void saveData() { Log.w(TAG, "saveData: Data word opgeslagen"); SharedPreferences.Editor editor = projectPreferences.edit(); Gson gson = new Gson(); String json = gson.toJson(arrayList); editor.putString("projects", json); editor.commit(); } @Override public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) { inflater.inflate(R.menu.menu_search,menu); MenuItem item = menu.findItem(R.id.search); SearchView searchView = (SearchView)item.getActionView(); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(String newText) { projectAdapter.getFilter().filter(newText); return false; } }); super.onCreateOptionsMenu(menu, inflater); } @Override // NOTE Wordt enkel gebruikt als hidden state veranderd of de fragment public void onHiddenChanged(boolean hidden) { if (!hidden){ getProjects(); } super.onHiddenChanged(hidden); } }
9714_5
package Question17_7; import CtCILibrary.AssortedMethods; public class Question { public static String[] digits = {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"}; public static String[] teens = {"Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"}; public static String[] tens = {"Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}; public static String[] bigs = {"", "Thousand", "Million", "Billion"}; public static String numToString(int number) { if (number == 0) { return "Zero"; } if (number < 0) { return "Negative " + numToString(-1 * number); } int count = 0; String str = ""; while (number > 0) { if (number % 1000 != 0) { str = numToString100(number % 1000) + bigs[count] + " " + str; } number /= 1000; count++; } return str; } public static String numToString100(int number) { String str = ""; /* Convert hundreds place */ if (number >= 100) { str += digits[number / 100 - 1] + " Hundred "; number %= 100; } /* Convert tens place */ if (number >= 11 && number <= 19) { return str + teens[number - 11] + " "; } else if (number == 10 || number >= 20) { str += tens[number / 10 - 1] + " "; number %= 10; } /* Convert ones place */ if (number >= 1 && number <= 9) { str += digits[number - 1] + " "; } return str; } public static void main(String[] args) { /* numbers between 100000 and 1000000 */ for (int i = 0; i < 8; i++) { int value = (int) Math.pow(10, i); String s = numToString(-1 * value); System.out.println(value + ": " + s); } /* numbers between 0 and 100 */ for (int i = 0; i < 10; i++) { int value = AssortedMethods.randomIntInRange(0, 100); String s = numToString(value); System.out.println(value + ": " + s); } /* numbers between 100 and 1000 */ for (int i = 0; i < 10; i++) { int value = AssortedMethods.randomIntInRange(100, 1000); String s = numToString(value); System.out.println(value + ": " + s); } /* numbers between 1000 and 100000 */ for (int i = 0; i < 10; i++) { int value = AssortedMethods.randomIntInRange(1000, 100000); String s = numToString(value); System.out.println(value + ": " + s); } /* numbers between 100000 and 100000000 */ for (int i = 0; i < 10; i++) { int value = AssortedMethods.randomIntInRange(100000, 100000000); String s = numToString(value); System.out.println(value + ": " + s); } /* numbers between 100000000 and 1000000000 */ for (int i = 0; i < 10; i++) { int value = AssortedMethods.randomIntInRange(100000000, 1000000000); String s = numToString(value); System.out.println(value + ": " + s); } /* numbers between 1000000000 and Integer.MAX_VALUE */ for (int i = 0; i < 10; i++) { int value = AssortedMethods.randomIntInRange(1000000000, Integer.MAX_VALUE); String s = numToString(value); System.out.println(value + ": " + s); } } }
careercup/ctci
java/Chapter 17/Question17_7/Question.java
1,265
/* numbers between 100 and 1000 */
block_comment
nl
package Question17_7; import CtCILibrary.AssortedMethods; public class Question { public static String[] digits = {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"}; public static String[] teens = {"Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"}; public static String[] tens = {"Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}; public static String[] bigs = {"", "Thousand", "Million", "Billion"}; public static String numToString(int number) { if (number == 0) { return "Zero"; } if (number < 0) { return "Negative " + numToString(-1 * number); } int count = 0; String str = ""; while (number > 0) { if (number % 1000 != 0) { str = numToString100(number % 1000) + bigs[count] + " " + str; } number /= 1000; count++; } return str; } public static String numToString100(int number) { String str = ""; /* Convert hundreds place */ if (number >= 100) { str += digits[number / 100 - 1] + " Hundred "; number %= 100; } /* Convert tens place */ if (number >= 11 && number <= 19) { return str + teens[number - 11] + " "; } else if (number == 10 || number >= 20) { str += tens[number / 10 - 1] + " "; number %= 10; } /* Convert ones place */ if (number >= 1 && number <= 9) { str += digits[number - 1] + " "; } return str; } public static void main(String[] args) { /* numbers between 100000 and 1000000 */ for (int i = 0; i < 8; i++) { int value = (int) Math.pow(10, i); String s = numToString(-1 * value); System.out.println(value + ": " + s); } /* numbers between 0 and 100 */ for (int i = 0; i < 10; i++) { int value = AssortedMethods.randomIntInRange(0, 100); String s = numToString(value); System.out.println(value + ": " + s); } /* numbers between 100<SUF>*/ for (int i = 0; i < 10; i++) { int value = AssortedMethods.randomIntInRange(100, 1000); String s = numToString(value); System.out.println(value + ": " + s); } /* numbers between 1000 and 100000 */ for (int i = 0; i < 10; i++) { int value = AssortedMethods.randomIntInRange(1000, 100000); String s = numToString(value); System.out.println(value + ": " + s); } /* numbers between 100000 and 100000000 */ for (int i = 0; i < 10; i++) { int value = AssortedMethods.randomIntInRange(100000, 100000000); String s = numToString(value); System.out.println(value + ": " + s); } /* numbers between 100000000 and 1000000000 */ for (int i = 0; i < 10; i++) { int value = AssortedMethods.randomIntInRange(100000000, 1000000000); String s = numToString(value); System.out.println(value + ": " + s); } /* numbers between 1000000000 and Integer.MAX_VALUE */ for (int i = 0; i < 10; i++) { int value = AssortedMethods.randomIntInRange(1000000000, Integer.MAX_VALUE); String s = numToString(value); System.out.println(value + ": " + s); } } }
190641_0
package Assign1_InleidingJava2018.H04; import java.awt.*; import java.applet.*; public class H04_4 extends Applet { /** opdracht * Drie kinderen hebben het volgende gewicht: * * Valerie: 40 kg * Jeroen: 100 kg * Hans: 80 kg * Maak van deze gegevens een staafdiagram, waarbij elke kolom een eigen kleur heeft. * De namen van de kinderen staan onder het staafdiagram en de verdeling van de schaal * staat naast de diagram met daarbij om de 20 de verdeling. */ public void init() { setSize(800, 800); } public void paint(Graphics g) { // graph setBackground(Color.WHITE); g.drawLine( 200, 100, 200, 600); g.drawLine(200, 600, 550, 600); g.drawString("Personen", 555, 607); g.drawString("Gewicht (KG)", 125, 80); g.drawString("100kg", 162, 100); g.drawString(" 80kg", 162, 200); g.drawString(" 60kg", 162, 300); g.drawString(" 40kg", 162, 400); g.drawString(" 20kg", 162, 500); g.drawString(" 0kg", 162, 600); g.drawString("Valerie", 250, 615); g.drawString("Jeroen", 355, 615); g.drawString("Hans", 460, 615); // 100px = 20kg g.setColor(Color.RED); g.fillRect(250, 400, 50, 200); g.setColor(Color.BLUE); g.fillRect(350, 100, 50, 500); g.setColor(Color.ORANGE); g.fillRect(450, 200, 50, 400); g.setColor(Color.BLACK); g.drawRect(250, 400, 50, 200); g.drawRect(350, 100, 50, 500); g.drawRect(450, 200, 50, 400); } }
Lights-Uni-Projects/ROC-Assignments
Java/H04/H04_4.java
707
/** opdracht * Drie kinderen hebben het volgende gewicht: * * Valerie: 40 kg * Jeroen: 100 kg * Hans: 80 kg * Maak van deze gegevens een staafdiagram, waarbij elke kolom een eigen kleur heeft. * De namen van de kinderen staan onder het staafdiagram en de verdeling van de schaal * staat naast de diagram met daarbij om de 20 de verdeling. */
block_comment
nl
package Assign1_InleidingJava2018.H04; import java.awt.*; import java.applet.*; public class H04_4 extends Applet { /** opdracht <SUF>*/ public void init() { setSize(800, 800); } public void paint(Graphics g) { // graph setBackground(Color.WHITE); g.drawLine( 200, 100, 200, 600); g.drawLine(200, 600, 550, 600); g.drawString("Personen", 555, 607); g.drawString("Gewicht (KG)", 125, 80); g.drawString("100kg", 162, 100); g.drawString(" 80kg", 162, 200); g.drawString(" 60kg", 162, 300); g.drawString(" 40kg", 162, 400); g.drawString(" 20kg", 162, 500); g.drawString(" 0kg", 162, 600); g.drawString("Valerie", 250, 615); g.drawString("Jeroen", 355, 615); g.drawString("Hans", 460, 615); // 100px = 20kg g.setColor(Color.RED); g.fillRect(250, 400, 50, 200); g.setColor(Color.BLUE); g.fillRect(350, 100, 50, 500); g.setColor(Color.ORANGE); g.fillRect(450, 200, 50, 400); g.setColor(Color.BLACK); g.drawRect(250, 400, 50, 200); g.drawRect(350, 100, 50, 500); g.drawRect(450, 200, 50, 400); } }
103881_34
import Classes.*; import SupportiveThreads.GameInfoListReceiver; import interfaces.AppServerInterface; import interfaces.DatabaseInterface; import interfaces.DispatchInterface; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import java.util.*; public class AppServiceImpl extends UnicastRemoteObject implements AppServerInterface { /*--------------- CONNECTIONS ---------------------*/ private DatabaseInterface databaseImpl; //een willekeurige waarvan we reads gaan doen private DatabaseInterface masterDatabaseImpl; // de database via welke de writes gebeuren private DispatchInterface dispatchImpl; /*--------------- ATTRIBUTES ----------------------*/ private ArrayList<Game> gamesLijst = new ArrayList<>(); //game bevat GameInfo en GameState public ArrayList<GameInfo> gameInfos = new ArrayList<>(); private BackupGames backup; private AppServerInterface destinationBackup; private static Map<String, byte[]> imageCache = new HashMap<>(); private static LinkedList<String> imageCacheSequence = new LinkedList<>(); GameInfoListReceiver gilr; /*-------------- CONSTRUCTOR ----------------------*/ public AppServiceImpl() throws RemoteException { try { /*---------- DISPATCH CONN ---------------*/ dispatchImpl = (DispatchInterface) LocateRegistry.getRegistry("localhost", 1902).lookup("DispatchService"); /*----------DATABASE CONN ----------------*/ int databaseServerPoort = getWillekeurigeDatabaseServerPoort(); System.out.println("connecting with DBServer on port " + databaseServerPoort); Registry dataRegistry = LocateRegistry.getRegistry("localhost", databaseServerPoort); databaseImpl = (DatabaseInterface) dataRegistry.lookup("DatabaseService"); //connection met masterdatabase if(databaseServerPoort != 1940){ Registry masterDataRegistry = LocateRegistry.getRegistry("localhost", 1940); masterDatabaseImpl = (DatabaseInterface) dataRegistry.lookup("DatabaseService"); } else{ masterDatabaseImpl = databaseImpl; } System.out.println("succesvol verbonden met masterDatabasePoort"); // alle game infos uit database halen + thread voor updates van gameinfo opstarten // gameInfos.addAll(databaseImpl.getGameInfoList()); gilr = new GameInfoListReceiver(this, databaseImpl, gameInfos); gilr.start(); } catch (Exception e) { e.printStackTrace(); } } /*-------------- OWN METHODS ----------------------*/ private int getWillekeurigeDatabaseServerPoort() { int willekeurigGetal = (int) (Math.random() * 2 + 1); // willekeurig getal tussen 1 en 3 switch (willekeurigGetal) { case 1: return 1950; case 2: return 1960; case 3: return 1970; default: return 1950; } } private synchronized void updateScores(String username, int roosterSize, int eindScore, String command) throws RemoteException { masterDatabaseImpl.updateScores(username, roosterSize, eindScore, command, true); } private HashMap<String, String> generateResultEndGame(HashMap<String, Integer> puntenLijst) { HashMap<String, String> returnHm = new HashMap<>(); ArrayList<String> winners= new ArrayList<>(); int max= Collections.max(puntenLijst.values()); for (String speler : puntenLijst.keySet()) { int punt= puntenLijst.get(speler); if(punt == max){ winners.add(speler); } } if(winners.size()==1){ String winner= winners.get(0); for (String speler : puntenLijst.keySet()) { if(!speler.equals(winner)){ returnHm.put(speler, "LOSS"); } else{ returnHm.put(speler, "WIN"); } } } else{ for (String speler : puntenLijst.keySet()) { if (!winners.contains(speler)) { returnHm.put(speler, "LOSS"); } } for (String winner : winners) { returnHm.put(winner, "DRAW"); } } return returnHm; } /** * @param gamesLijst, de te checken lijst van games * @param gameId * @return true als er al een game in deze lijst zit met deze gameId, * false als er nog geen game in de lijst zit */ private boolean reedsGameMetDezeID(ArrayList<Game> gamesLijst, int gameId) { for (Game game : gamesLijst) { if (game.getGameInfo().getGameId() == gameId) { return true; } } return false; } private boolean vergelijkGameInfoList(List<GameInfo> oudeList, List<GameInfo> gameInfoList){ if(oudeList.size()!=gameInfoList.size()){ return false; } else{ for (GameInfo gameInfo : gameInfoList) { GameInfo foundGameInfo = null; for (GameInfo info : oudeList) { if(info.getGameId()==gameInfo.getGameId()){ foundGameInfo =info; if(info.getSpelers().size()!=gameInfo.getSpelers().size()){ return false; } break; } } if(foundGameInfo == null){ return false; } } } return true; } /*--------------- SERVICES ------------------------*/ // APPSERVERINFO // @Override public int getPortNumber() throws RemoteException { return AppServerMain.thisappServerpoort; } @Override public boolean testConnection() { return true; } @Override public void close() throws RemoteException { ArrayList<Game> toDelete= new ArrayList<>(gamesLijst); for (Game game : toDelete) { dispatchImpl.changeGameServer(this, game); // het probleem is dat de dispatcher games zal verwijderen van deze appserver terwijl dat ie ier aant itereren is erover } dispatchImpl.unregisterAppserver(AppServerMain.thisappServerpoort); System.exit(0); } // USER MANAGER // /** * Deze methode checkt of credentials juist zijn, indien true, aanmaken van token * * @param username username * @param paswoord plain text * @return AppServerInterface definieert de connectie tussen deze client en appserver * @throws RemoteException */ @Override public boolean loginUser(String username, String paswoord) throws RemoteException { //als credentials juist zijn if (databaseImpl.checkUserCred(username, paswoord)) { //maak nieuwe token voor deze persoon aan masterDatabaseImpl.createToken(username, paswoord, true); return true; } else { return false; } } /** * inloggen met token * * @param token * @param username * @return * @throws RemoteException */ @Override public boolean loginWithToken(String token, String username) throws RemoteException { if (databaseImpl.isTokenValid(username, token)) { return true; } else { return false; } } /** * token timestamp op 0 zetten in db * * @param username naam van user die uitgelogd wordt * @throws RemoteException */ @Override public void logoutUser(String username) throws RemoteException { masterDatabaseImpl.cancelToken(username, true); } /** * opvragen van token * * @param username * @return * @throws RemoteException */ @Override public String getToken(String username) throws RemoteException { return databaseImpl.getToken(username); } // GAME INFO // @Override public boolean prepareForNewGame() throws RemoteException { if(gamesLijst.size()>=3){ return false; } return true; } @Override public void addGameInBackup(Game game) throws RemoteException { backup.getGameList().add(game); } @Override public AppServerInterface getDestinationBackup() throws RemoteException { return destinationBackup; } @Override public synchronized int createGame(String activeUser, int dimensies, char set, int aantalSpelers) throws RemoteException { //gameId maken, kijken als nog niet reeds bestaat int gameId = (int) (Math.random() * 1000); while (reedsGameMetDezeID(gamesLijst, gameId)) { gameId = (int) (Math.random() * 1000); } Game game = new Game(gameId, activeUser, dimensies, set, aantalSpelers, AppServerMain.thisappServerpoort); gamesLijst.add(game); //todo: remove the printing of the kaartjes game.getGameState().printSequence(); System.out.println("game door " + activeUser + " aangemaakt!"); System.out.println("gameslist grootte is nu: " + gamesLijst.size()); // game info doorgeven aan database masterDatabaseImpl.addGameInfo(game.getGameInfo(), true); if(destinationBackup!=null){ destinationBackup.addGameInBackup(game); } return gameId; } @Override public int getNumberOfGames() throws RemoteException { return gamesLijst.size(); } @Override public synchronized ArrayList<GameInfo> getGameInfoLijst(boolean dummy) throws RemoteException { ArrayList<GameInfo> oudeList= new ArrayList<>(gameInfos); while (vergelijkGameInfoList(oudeList, gameInfos)) { try { wait(); System.out.println("game info lijst werd genotified"); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("size van gameinfos" + gameInfos.size()); return new ArrayList<>(gameInfos); } @Override public ArrayList<GameInfo> getGameInfoLijst() throws RemoteException { return new ArrayList<>(gameInfos); } @Override public ArrayList<Game> getGamesLijst() throws RemoteException { return gamesLijst; } @Override public Game getGame(int currentGameId) { for (Game game : gamesLijst) { if (game.getGameId() == currentGameId) { return game; } } return null; } @Override public GameInfo getGameInfo(int gameId) throws RemoteException { for (Game game : gamesLijst) { if (game.getGameId() == gameId) { return game.getGameInfo(); } } //als er geen game gevonden is met de gameId return new GameInfo(); // leeg object, herkennen dan in da spel daar } @Override public GameState getGameState(int gameId) throws RemoteException { for (Game game : gamesLijst) { if (game.getGameId() == gameId) { return game.getGameState(); } } System.out.println("getGameState in AppserverImpl, mag niet gebeuren"); return null; } @Override public boolean hasGame(int gameId) throws RemoteException { if (this.getGameInfo(gameId).getAppServerPoort() == AppServerMain.thisappServerpoort) { return true; } else { return false; } } // GAME ACTIONS // @Override public boolean join(String activeUser, int currentGameIdAttempt) throws RemoteException { //aanpassing omdat er ook nog moet gejoined worden in de gameState if (this.getGameInfo(currentGameIdAttempt).join(activeUser)) { // als je kan joinen bij gameinfo kan je joinen bij gamestate this.getGameState(currentGameIdAttempt).join(activeUser); masterDatabaseImpl.updateGameInfo(getGameInfo(currentGameIdAttempt), true); return true; } else { System.out.println("joinen loopt fout in appServiceImpl.java"); return false; } } @Override public void leaveGame(int currentGameId, String username) throws RemoteException { this.getGameInfo(currentGameId).playerLeaves(username); } @Override public boolean changeInPlayers(int currentGameId, int aantalSpelers) throws RemoteException { if (this.getGameInfo(currentGameId).changeInPlayers(aantalSpelers)) { //System.out.println("er is verandering in users ontdekt"); return true; } else { //System.out.println("er geen verandering in users ontdekt"); return false; } } @Override public boolean changeInTurn(int currentGameId, String userTurn) throws RemoteException { return this.getGameState(currentGameId).changeInTurn(userTurn); } /** * wordt getriggerd wanneer een speler op een kaartje klikt, zorgt ervoor dat de andere speler ook het kaartje zal * omdraaien door het commando in z'n inbox te laten verschijnen, die 2e speler pullt dan het commando en executet * het * * @param commando : "FLIP" + uniqueTileId * @param activeUser : de actieve user die het triggerd * @param currentGameId : voor het huidige spelletje (als hij er meerdere heeft lopen) * @throws RemoteException */ @Override public void executeFlipCommando(Commando commando, String activeUser, int currentGameId) throws RemoteException { HashMap<String, Boolean> values = getGameState(currentGameId).executeCommando(commando, activeUser); // values(0) = backup boolean // values(1) = game finished boolean if (values.get("BACKUP")){ if (destinationBackup != null) { destinationBackup.updateBackupGS(getGameState(currentGameId)); } } if (values.get("DONE")){ // game is klaar // update scores naar DB GameState thisGameState = getGameState(currentGameId); GameInfo thisGameInfo = getGameInfo(currentGameId); int roosterSize = thisGameInfo.getRoosterSize(); HashMap<String, Integer> puntenLijst = thisGameState.getPunten(); HashMap<String, String> resultatenLijst = generateResultEndGame(puntenLijst); new Thread(new Runnable() { @Override public void run() { try { // voor elke speler natuurlijk for (String speler : thisGameState.getSpelers()) { updateScores(speler, roosterSize, puntenLijst.get(speler), resultatenLijst.get(speler)); } // gameinfo en gamestate verwijderen uit databaseServer deleteGame(currentGameId); // game finishen in dispatcher ( checken als een AS moet afgesloten worden) dispatchImpl.gameFinished(); } catch (RemoteException e) { System.out.println(""); } } }).start(); } } @Override public List<Commando> getInbox(String userName, int currentGameId) throws RemoteException { // System.out.println("AppServiceImpl : getInbox: door user: "+userName); return getGameState(currentGameId).getInbox(userName); } @Override public void spectate(int gameId, String username) throws RemoteException { getGame(gameId).getGameState().getSpectators().add(username); } @Override public void unsubscribeSpecator(int gameId, String username) throws RemoteException { getGame(gameId).getGameState().getSpectators().remove(username); getGame(gameId).getGameState().getInboxSpectators().remove(username); } // ASK / PUSH METADATA // /** * vraag aan db om een bytestream die een image voorstelt te geven * * @param naam de id van de image * @return de image in een array van bytes * @throws RemoteException */ @Override public byte[] getImage(String naam) throws RemoteException { byte[] afbeelding = imageCache.get(naam); if (afbeelding == null) { afbeelding = databaseImpl.getImage(naam); imageCache.put(naam, afbeelding); imageCacheSequence.add(naam); } else { int found= -1; for (int i = 0; i < imageCacheSequence.size(); i++) { String elem= imageCacheSequence.get(i); if(elem.equals(naam)){ found=i; } } imageCacheSequence.remove(found); imageCacheSequence.add(naam); } if (imageCache.size() > 36) { String removeImage = imageCacheSequence.removeFirst(); imageCache.remove(removeImage); } return afbeelding; } /** * vraag aan db om een bytestream die een image voorstelt te storen * * @param naam de id van de image * @param afbeelding de image in een array van bytes * @throws RemoteException */ @Override public void storeImage(String naam, byte[] afbeelding) throws RemoteException { masterDatabaseImpl.storeImage(naam, afbeelding, true); } // HANDLING GAMES INTERNALLY // /** * de gameInfo moet overal verwijderd worden. * op deze appserver * op de backupAppserver * op de databaszq * de gameState moet op deze appserver en zijn backup verwijderd worden * enkel op deze appserver * en in de backupappserver * * eerst de gameState verwijderen * * eerst de backupGameState verwijderen * * @param gameId de id van de game * @throws RemoteException */ @Override public void deleteGame(int gameId) throws RemoteException { //eerst in de backup hiervan gaan verwijderen if (destinationBackup!=null) { destinationBackup.deleteBackupGame(gameId); // zowel gameInfo als GameState } removeGameFromRunningGames(getGame(gameId)); // de gameInfo in de databases verwijderen masterDatabaseImpl.deleteGameInfo(gameId, true); System.out.println("klaar met gameInfo " + gameId + " te verwijderen op DB's"); } @Override public synchronized void removeGameFromRunningGames(Game game) throws RemoteException { //dan pas lokaal de gameState verijwderen int gameId= game.getGameId(); gamesLijst.remove(game); System.out.println("gameState met id: " + gameId + " succesvol verwijderd op appserver"); //nu de gameState lokaal verwijderen // MOET GEDAAN WORDEN DOOR GAMEINFOLISTRECEIVER //GameInfo gameInfo = getGameInfo(gameId); //gameInfos.remove(gameInfo); //System.out.println("gameInfo met id: " + gameId + " succesvol verwijderd op appserver"); } @Override public void deleteBackupGame(int gameId) throws RemoteException { backup.getGameList().remove(backup.getGame(gameId)); } @Override public void takeOverGame(Game game) throws RemoteException { game.getGameInfo().setAppServerPoort(AppServerMain.thisappServerpoort); masterDatabaseImpl.updateGameInfo(game.getGameInfo(), true); gamesLijst.add(game); } // HANDLING SCORE TABLE // @Override public ArrayList<Score> getScores() throws RemoteException { return databaseImpl.getScores(); } // BACKUP // @Override public void takeBackupFrom(int appserverpoort) throws RemoteException { backup = new BackupGames(appserverpoort); System.out.println("I just took a backup from " + backup.getAppserverPoort()); for (Game game : backup.getGameList()) { System.out.println(game); } } @Override public void setDestinationBackup(int appserverBackupPoort) throws RemoteException { if(appserverBackupPoort!=0){ try { destinationBackup = (AppServerInterface) LocateRegistry.getRegistry("localhost", appserverBackupPoort).lookup("AppserverService"); } catch (NotBoundException e) { e.printStackTrace(); } }else{ destinationBackup=null; } } @Override public void updateBackupGS(GameState gameState) throws RemoteException { //if (!backup.getGame(gameState.getGameId()).getGameState().getAandeBeurt().equals(gameState.getAandeBeurt())) { backup.getGame(gameState.getGameId()).setGameState(gameState); System.out.println("backup UPGEDATE"); for (Game game : backup.getGameList()) { System.out.println(game); } // } } @Override public BackupGames getBackup() throws RemoteException { return backup; } @Override public synchronized void notifyGameInfoList() throws RemoteException { notifyAll(); } }
aaronhallaert/DS_Project
ApplicationServer/src/AppServiceImpl.java
5,203
// gameinfo en gamestate verwijderen uit databaseServer
line_comment
nl
import Classes.*; import SupportiveThreads.GameInfoListReceiver; import interfaces.AppServerInterface; import interfaces.DatabaseInterface; import interfaces.DispatchInterface; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import java.util.*; public class AppServiceImpl extends UnicastRemoteObject implements AppServerInterface { /*--------------- CONNECTIONS ---------------------*/ private DatabaseInterface databaseImpl; //een willekeurige waarvan we reads gaan doen private DatabaseInterface masterDatabaseImpl; // de database via welke de writes gebeuren private DispatchInterface dispatchImpl; /*--------------- ATTRIBUTES ----------------------*/ private ArrayList<Game> gamesLijst = new ArrayList<>(); //game bevat GameInfo en GameState public ArrayList<GameInfo> gameInfos = new ArrayList<>(); private BackupGames backup; private AppServerInterface destinationBackup; private static Map<String, byte[]> imageCache = new HashMap<>(); private static LinkedList<String> imageCacheSequence = new LinkedList<>(); GameInfoListReceiver gilr; /*-------------- CONSTRUCTOR ----------------------*/ public AppServiceImpl() throws RemoteException { try { /*---------- DISPATCH CONN ---------------*/ dispatchImpl = (DispatchInterface) LocateRegistry.getRegistry("localhost", 1902).lookup("DispatchService"); /*----------DATABASE CONN ----------------*/ int databaseServerPoort = getWillekeurigeDatabaseServerPoort(); System.out.println("connecting with DBServer on port " + databaseServerPoort); Registry dataRegistry = LocateRegistry.getRegistry("localhost", databaseServerPoort); databaseImpl = (DatabaseInterface) dataRegistry.lookup("DatabaseService"); //connection met masterdatabase if(databaseServerPoort != 1940){ Registry masterDataRegistry = LocateRegistry.getRegistry("localhost", 1940); masterDatabaseImpl = (DatabaseInterface) dataRegistry.lookup("DatabaseService"); } else{ masterDatabaseImpl = databaseImpl; } System.out.println("succesvol verbonden met masterDatabasePoort"); // alle game infos uit database halen + thread voor updates van gameinfo opstarten // gameInfos.addAll(databaseImpl.getGameInfoList()); gilr = new GameInfoListReceiver(this, databaseImpl, gameInfos); gilr.start(); } catch (Exception e) { e.printStackTrace(); } } /*-------------- OWN METHODS ----------------------*/ private int getWillekeurigeDatabaseServerPoort() { int willekeurigGetal = (int) (Math.random() * 2 + 1); // willekeurig getal tussen 1 en 3 switch (willekeurigGetal) { case 1: return 1950; case 2: return 1960; case 3: return 1970; default: return 1950; } } private synchronized void updateScores(String username, int roosterSize, int eindScore, String command) throws RemoteException { masterDatabaseImpl.updateScores(username, roosterSize, eindScore, command, true); } private HashMap<String, String> generateResultEndGame(HashMap<String, Integer> puntenLijst) { HashMap<String, String> returnHm = new HashMap<>(); ArrayList<String> winners= new ArrayList<>(); int max= Collections.max(puntenLijst.values()); for (String speler : puntenLijst.keySet()) { int punt= puntenLijst.get(speler); if(punt == max){ winners.add(speler); } } if(winners.size()==1){ String winner= winners.get(0); for (String speler : puntenLijst.keySet()) { if(!speler.equals(winner)){ returnHm.put(speler, "LOSS"); } else{ returnHm.put(speler, "WIN"); } } } else{ for (String speler : puntenLijst.keySet()) { if (!winners.contains(speler)) { returnHm.put(speler, "LOSS"); } } for (String winner : winners) { returnHm.put(winner, "DRAW"); } } return returnHm; } /** * @param gamesLijst, de te checken lijst van games * @param gameId * @return true als er al een game in deze lijst zit met deze gameId, * false als er nog geen game in de lijst zit */ private boolean reedsGameMetDezeID(ArrayList<Game> gamesLijst, int gameId) { for (Game game : gamesLijst) { if (game.getGameInfo().getGameId() == gameId) { return true; } } return false; } private boolean vergelijkGameInfoList(List<GameInfo> oudeList, List<GameInfo> gameInfoList){ if(oudeList.size()!=gameInfoList.size()){ return false; } else{ for (GameInfo gameInfo : gameInfoList) { GameInfo foundGameInfo = null; for (GameInfo info : oudeList) { if(info.getGameId()==gameInfo.getGameId()){ foundGameInfo =info; if(info.getSpelers().size()!=gameInfo.getSpelers().size()){ return false; } break; } } if(foundGameInfo == null){ return false; } } } return true; } /*--------------- SERVICES ------------------------*/ // APPSERVERINFO // @Override public int getPortNumber() throws RemoteException { return AppServerMain.thisappServerpoort; } @Override public boolean testConnection() { return true; } @Override public void close() throws RemoteException { ArrayList<Game> toDelete= new ArrayList<>(gamesLijst); for (Game game : toDelete) { dispatchImpl.changeGameServer(this, game); // het probleem is dat de dispatcher games zal verwijderen van deze appserver terwijl dat ie ier aant itereren is erover } dispatchImpl.unregisterAppserver(AppServerMain.thisappServerpoort); System.exit(0); } // USER MANAGER // /** * Deze methode checkt of credentials juist zijn, indien true, aanmaken van token * * @param username username * @param paswoord plain text * @return AppServerInterface definieert de connectie tussen deze client en appserver * @throws RemoteException */ @Override public boolean loginUser(String username, String paswoord) throws RemoteException { //als credentials juist zijn if (databaseImpl.checkUserCred(username, paswoord)) { //maak nieuwe token voor deze persoon aan masterDatabaseImpl.createToken(username, paswoord, true); return true; } else { return false; } } /** * inloggen met token * * @param token * @param username * @return * @throws RemoteException */ @Override public boolean loginWithToken(String token, String username) throws RemoteException { if (databaseImpl.isTokenValid(username, token)) { return true; } else { return false; } } /** * token timestamp op 0 zetten in db * * @param username naam van user die uitgelogd wordt * @throws RemoteException */ @Override public void logoutUser(String username) throws RemoteException { masterDatabaseImpl.cancelToken(username, true); } /** * opvragen van token * * @param username * @return * @throws RemoteException */ @Override public String getToken(String username) throws RemoteException { return databaseImpl.getToken(username); } // GAME INFO // @Override public boolean prepareForNewGame() throws RemoteException { if(gamesLijst.size()>=3){ return false; } return true; } @Override public void addGameInBackup(Game game) throws RemoteException { backup.getGameList().add(game); } @Override public AppServerInterface getDestinationBackup() throws RemoteException { return destinationBackup; } @Override public synchronized int createGame(String activeUser, int dimensies, char set, int aantalSpelers) throws RemoteException { //gameId maken, kijken als nog niet reeds bestaat int gameId = (int) (Math.random() * 1000); while (reedsGameMetDezeID(gamesLijst, gameId)) { gameId = (int) (Math.random() * 1000); } Game game = new Game(gameId, activeUser, dimensies, set, aantalSpelers, AppServerMain.thisappServerpoort); gamesLijst.add(game); //todo: remove the printing of the kaartjes game.getGameState().printSequence(); System.out.println("game door " + activeUser + " aangemaakt!"); System.out.println("gameslist grootte is nu: " + gamesLijst.size()); // game info doorgeven aan database masterDatabaseImpl.addGameInfo(game.getGameInfo(), true); if(destinationBackup!=null){ destinationBackup.addGameInBackup(game); } return gameId; } @Override public int getNumberOfGames() throws RemoteException { return gamesLijst.size(); } @Override public synchronized ArrayList<GameInfo> getGameInfoLijst(boolean dummy) throws RemoteException { ArrayList<GameInfo> oudeList= new ArrayList<>(gameInfos); while (vergelijkGameInfoList(oudeList, gameInfos)) { try { wait(); System.out.println("game info lijst werd genotified"); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("size van gameinfos" + gameInfos.size()); return new ArrayList<>(gameInfos); } @Override public ArrayList<GameInfo> getGameInfoLijst() throws RemoteException { return new ArrayList<>(gameInfos); } @Override public ArrayList<Game> getGamesLijst() throws RemoteException { return gamesLijst; } @Override public Game getGame(int currentGameId) { for (Game game : gamesLijst) { if (game.getGameId() == currentGameId) { return game; } } return null; } @Override public GameInfo getGameInfo(int gameId) throws RemoteException { for (Game game : gamesLijst) { if (game.getGameId() == gameId) { return game.getGameInfo(); } } //als er geen game gevonden is met de gameId return new GameInfo(); // leeg object, herkennen dan in da spel daar } @Override public GameState getGameState(int gameId) throws RemoteException { for (Game game : gamesLijst) { if (game.getGameId() == gameId) { return game.getGameState(); } } System.out.println("getGameState in AppserverImpl, mag niet gebeuren"); return null; } @Override public boolean hasGame(int gameId) throws RemoteException { if (this.getGameInfo(gameId).getAppServerPoort() == AppServerMain.thisappServerpoort) { return true; } else { return false; } } // GAME ACTIONS // @Override public boolean join(String activeUser, int currentGameIdAttempt) throws RemoteException { //aanpassing omdat er ook nog moet gejoined worden in de gameState if (this.getGameInfo(currentGameIdAttempt).join(activeUser)) { // als je kan joinen bij gameinfo kan je joinen bij gamestate this.getGameState(currentGameIdAttempt).join(activeUser); masterDatabaseImpl.updateGameInfo(getGameInfo(currentGameIdAttempt), true); return true; } else { System.out.println("joinen loopt fout in appServiceImpl.java"); return false; } } @Override public void leaveGame(int currentGameId, String username) throws RemoteException { this.getGameInfo(currentGameId).playerLeaves(username); } @Override public boolean changeInPlayers(int currentGameId, int aantalSpelers) throws RemoteException { if (this.getGameInfo(currentGameId).changeInPlayers(aantalSpelers)) { //System.out.println("er is verandering in users ontdekt"); return true; } else { //System.out.println("er geen verandering in users ontdekt"); return false; } } @Override public boolean changeInTurn(int currentGameId, String userTurn) throws RemoteException { return this.getGameState(currentGameId).changeInTurn(userTurn); } /** * wordt getriggerd wanneer een speler op een kaartje klikt, zorgt ervoor dat de andere speler ook het kaartje zal * omdraaien door het commando in z'n inbox te laten verschijnen, die 2e speler pullt dan het commando en executet * het * * @param commando : "FLIP" + uniqueTileId * @param activeUser : de actieve user die het triggerd * @param currentGameId : voor het huidige spelletje (als hij er meerdere heeft lopen) * @throws RemoteException */ @Override public void executeFlipCommando(Commando commando, String activeUser, int currentGameId) throws RemoteException { HashMap<String, Boolean> values = getGameState(currentGameId).executeCommando(commando, activeUser); // values(0) = backup boolean // values(1) = game finished boolean if (values.get("BACKUP")){ if (destinationBackup != null) { destinationBackup.updateBackupGS(getGameState(currentGameId)); } } if (values.get("DONE")){ // game is klaar // update scores naar DB GameState thisGameState = getGameState(currentGameId); GameInfo thisGameInfo = getGameInfo(currentGameId); int roosterSize = thisGameInfo.getRoosterSize(); HashMap<String, Integer> puntenLijst = thisGameState.getPunten(); HashMap<String, String> resultatenLijst = generateResultEndGame(puntenLijst); new Thread(new Runnable() { @Override public void run() { try { // voor elke speler natuurlijk for (String speler : thisGameState.getSpelers()) { updateScores(speler, roosterSize, puntenLijst.get(speler), resultatenLijst.get(speler)); } // gameinfo en<SUF> deleteGame(currentGameId); // game finishen in dispatcher ( checken als een AS moet afgesloten worden) dispatchImpl.gameFinished(); } catch (RemoteException e) { System.out.println(""); } } }).start(); } } @Override public List<Commando> getInbox(String userName, int currentGameId) throws RemoteException { // System.out.println("AppServiceImpl : getInbox: door user: "+userName); return getGameState(currentGameId).getInbox(userName); } @Override public void spectate(int gameId, String username) throws RemoteException { getGame(gameId).getGameState().getSpectators().add(username); } @Override public void unsubscribeSpecator(int gameId, String username) throws RemoteException { getGame(gameId).getGameState().getSpectators().remove(username); getGame(gameId).getGameState().getInboxSpectators().remove(username); } // ASK / PUSH METADATA // /** * vraag aan db om een bytestream die een image voorstelt te geven * * @param naam de id van de image * @return de image in een array van bytes * @throws RemoteException */ @Override public byte[] getImage(String naam) throws RemoteException { byte[] afbeelding = imageCache.get(naam); if (afbeelding == null) { afbeelding = databaseImpl.getImage(naam); imageCache.put(naam, afbeelding); imageCacheSequence.add(naam); } else { int found= -1; for (int i = 0; i < imageCacheSequence.size(); i++) { String elem= imageCacheSequence.get(i); if(elem.equals(naam)){ found=i; } } imageCacheSequence.remove(found); imageCacheSequence.add(naam); } if (imageCache.size() > 36) { String removeImage = imageCacheSequence.removeFirst(); imageCache.remove(removeImage); } return afbeelding; } /** * vraag aan db om een bytestream die een image voorstelt te storen * * @param naam de id van de image * @param afbeelding de image in een array van bytes * @throws RemoteException */ @Override public void storeImage(String naam, byte[] afbeelding) throws RemoteException { masterDatabaseImpl.storeImage(naam, afbeelding, true); } // HANDLING GAMES INTERNALLY // /** * de gameInfo moet overal verwijderd worden. * op deze appserver * op de backupAppserver * op de databaszq * de gameState moet op deze appserver en zijn backup verwijderd worden * enkel op deze appserver * en in de backupappserver * * eerst de gameState verwijderen * * eerst de backupGameState verwijderen * * @param gameId de id van de game * @throws RemoteException */ @Override public void deleteGame(int gameId) throws RemoteException { //eerst in de backup hiervan gaan verwijderen if (destinationBackup!=null) { destinationBackup.deleteBackupGame(gameId); // zowel gameInfo als GameState } removeGameFromRunningGames(getGame(gameId)); // de gameInfo in de databases verwijderen masterDatabaseImpl.deleteGameInfo(gameId, true); System.out.println("klaar met gameInfo " + gameId + " te verwijderen op DB's"); } @Override public synchronized void removeGameFromRunningGames(Game game) throws RemoteException { //dan pas lokaal de gameState verijwderen int gameId= game.getGameId(); gamesLijst.remove(game); System.out.println("gameState met id: " + gameId + " succesvol verwijderd op appserver"); //nu de gameState lokaal verwijderen // MOET GEDAAN WORDEN DOOR GAMEINFOLISTRECEIVER //GameInfo gameInfo = getGameInfo(gameId); //gameInfos.remove(gameInfo); //System.out.println("gameInfo met id: " + gameId + " succesvol verwijderd op appserver"); } @Override public void deleteBackupGame(int gameId) throws RemoteException { backup.getGameList().remove(backup.getGame(gameId)); } @Override public void takeOverGame(Game game) throws RemoteException { game.getGameInfo().setAppServerPoort(AppServerMain.thisappServerpoort); masterDatabaseImpl.updateGameInfo(game.getGameInfo(), true); gamesLijst.add(game); } // HANDLING SCORE TABLE // @Override public ArrayList<Score> getScores() throws RemoteException { return databaseImpl.getScores(); } // BACKUP // @Override public void takeBackupFrom(int appserverpoort) throws RemoteException { backup = new BackupGames(appserverpoort); System.out.println("I just took a backup from " + backup.getAppserverPoort()); for (Game game : backup.getGameList()) { System.out.println(game); } } @Override public void setDestinationBackup(int appserverBackupPoort) throws RemoteException { if(appserverBackupPoort!=0){ try { destinationBackup = (AppServerInterface) LocateRegistry.getRegistry("localhost", appserverBackupPoort).lookup("AppserverService"); } catch (NotBoundException e) { e.printStackTrace(); } }else{ destinationBackup=null; } } @Override public void updateBackupGS(GameState gameState) throws RemoteException { //if (!backup.getGame(gameState.getGameId()).getGameState().getAandeBeurt().equals(gameState.getAandeBeurt())) { backup.getGame(gameState.getGameId()).setGameState(gameState); System.out.println("backup UPGEDATE"); for (Game game : backup.getGameList()) { System.out.println(game); } // } } @Override public BackupGames getBackup() throws RemoteException { return backup; } @Override public synchronized void notifyGameInfoList() throws RemoteException { notifyAll(); } }
8041_3
package domain; import java.util.Objects; public class Opdracht{ public static final String CATEGORIE_AARDRIJKSKUNDE = "Aardrijkskunde"; public static final String CATEGORIE_GESCHIEDENIS = "Geschiedenis"; public static final String CATEGORIE_NEDERLANDS = "Nederlands"; public static final String CATEGORIE_WISKUNDE = "Wiskunde"; public static final String CATEGORIE_WETENSCHAPPEN = "Wetenschappen"; public static final String[] CATEGORIEEN = { CATEGORIE_AARDRIJKSKUNDE, CATEGORIE_GESCHIEDENIS, CATEGORIE_NEDERLANDS, CATEGORIE_WISKUNDE, CATEGORIE_WETENSCHAPPEN }; /** * Deze id wordt toegekend door de OpdrachtDatabase klasse wanneer een * opdracht aan de opdrachtendatabase wordt toegevoegd. (deze ID begint met * 1 en wordt altijd met 1 verhoogd) */ private int opdrachtID; /** * De String vraag bevat de vraag die bij de opdracht behoort. Op een vraag * moet kunnen geantwoord worden met 1 woord of getal. Voorbeeld: Wat is * de hoofdstad van Frankrijk? */ private String vraag; /** * De String antwoord bevat het verwachte antwoord op de vraag. Voorbeeld * bij voorgaande vraag is het juiste antwoord: Parijs. */ private String antwoord; /** * De boolean isHoofdletterGevoelig geeft aan of men bij het evalueren van * het antwoord al dan niet rekening zal houden met het gebruik van * hoofdletters. Indien niet zal bijvoorbeeld Parijs en parijs als hetzelfde * antwoord beschouwd worden. */ private boolean isHoofdletterGevoelig; /** * De String antwoordhint is een hulp voor de quizkandidaat bij het zoeken * naar het juiste antwoord. Voorbeeld: bij de bovenstaande vraag kan een * antwoordhint zijn: Men vindt er de Eifel toren. Een antwoordhint is * optioneel bij een opdracht (hoeft niet verplicht ingevuld te worden bij * elke opdracht) */ private String antwoordHint; /** * De String categorie geeft aan tot welke categorie deze opdracht behoort. * We maken opdrachten van 5 categorien: Aardrijkskunde, Geschiedenis, * Nederlands, Wetenschappen en Wiskunde */ private String categorie; /** * De auteur is de naam van wie heeft deze opdracht bedacht. */ private String auteur; /** * Contructor voor het maken van een opdracht MET hint * * @param id * de id voor deze opdracht (moet uit de opdrachten db komen) * @param vraag * de vraag voor deze opdracht * @param antwoord * het 1-woord-of-getal antwoord * @param hoofdlettergevoelig * geeft aan of bij het antwoord rekening gehouden moet worden * met hoofdletters * @param hint * de antwoord-hint * @param categorie * een van de vijf bovenaan gedefinieerde categorieen * @param auteur * de naam van de bedenker van deze opdracht */ public Opdracht(int id, String vraag, String antwoord, boolean hoofdlettergevoelig, String hint, String categorie, String auteur) { this.opdrachtID = id; this.vraag = vraag; this.antwoord = antwoord; this.isHoofdletterGevoelig = hoofdlettergevoelig; this.antwoordHint = hint; this.categorie = categorie; this.auteur = auteur; } /** * Constructor voor het maken van een opdracht ZONDER hint * * @param id * de id voor deze opdracht (moet uit de opdrachten db komen) * @param vraag * de vraag voor deze opdracht * @param antwoord * het 1-woord-of-getal antwoord * @param hoofdlettergevoelig * geeft aan of bij het antwoord rekening gehouden moet worden * met hoofdletters * @param categorie * categorie een van de vijf bovenaan gedefinieerde categorieen * @param auteur * de naam van de bedenker van deze opdracht */ public Opdracht(int id, String vraag, String antwoord, boolean hoofdlettergevoelig, String categorie, String auteur) { this(id,vraag, antwoord, hoofdlettergevoelig, "Er werd geen hint voorzien voor deze opdracht", categorie, auteur); } public int getOpdrachtID() { return opdrachtID; } public String getVraag() { return vraag; } public String getAntwoord() { return antwoord; } public boolean isHoofdletterGevoelig() { return isHoofdletterGevoelig; } public String getAntwoordHint() { return antwoordHint; } public String getCategorie() { return categorie; } public String getAuteur() { return auteur; } /** * Methode om de gelijkheid van twee opdrachten te checken * * @return true als ze gelijk zijn */ @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Opdracht opdracht = (Opdracht) o; return opdrachtID == opdracht.opdrachtID && isHoofdletterGevoelig == opdracht.isHoofdletterGevoelig && Objects.equals(vraag, opdracht.vraag) && Objects.equals(antwoord, opdracht.antwoord) && Objects.equals(antwoordHint, opdracht.antwoordHint) && Objects.equals(categorie, opdracht.categorie) && Objects.equals(auteur, opdracht.auteur); } /** * Methode om deze opdracht volledig uit te schrijven */ public String toString() { String dezeOpdracht = ""; dezeOpdracht += getOpdrachtID() + " - " + getCategorie() + "\n"; dezeOpdracht += "auteur: " + getAuteur() + "\n"; dezeOpdracht += "vraag: " + getVraag() + "\n"; dezeOpdracht += "hint: " + getAntwoordHint() + "\n"; dezeOpdracht += (isHoofdletterGevoelig() ? "" : "niet ") + "hoofdlettergevoelig \n"; dezeOpdracht += "antwoord: " + getAntwoord() + "\n"; dezeOpdracht += "---------------------------------------------"; return dezeOpdracht; } }
martijnmeeldijk/TI-oplossingen
Semester_2/OOP/JCF1 legit/src/domain/Opdracht.java
1,651
/** * De boolean isHoofdletterGevoelig geeft aan of men bij het evalueren van * het antwoord al dan niet rekening zal houden met het gebruik van * hoofdletters. Indien niet zal bijvoorbeeld Parijs en parijs als hetzelfde * antwoord beschouwd worden. */
block_comment
nl
package domain; import java.util.Objects; public class Opdracht{ public static final String CATEGORIE_AARDRIJKSKUNDE = "Aardrijkskunde"; public static final String CATEGORIE_GESCHIEDENIS = "Geschiedenis"; public static final String CATEGORIE_NEDERLANDS = "Nederlands"; public static final String CATEGORIE_WISKUNDE = "Wiskunde"; public static final String CATEGORIE_WETENSCHAPPEN = "Wetenschappen"; public static final String[] CATEGORIEEN = { CATEGORIE_AARDRIJKSKUNDE, CATEGORIE_GESCHIEDENIS, CATEGORIE_NEDERLANDS, CATEGORIE_WISKUNDE, CATEGORIE_WETENSCHAPPEN }; /** * Deze id wordt toegekend door de OpdrachtDatabase klasse wanneer een * opdracht aan de opdrachtendatabase wordt toegevoegd. (deze ID begint met * 1 en wordt altijd met 1 verhoogd) */ private int opdrachtID; /** * De String vraag bevat de vraag die bij de opdracht behoort. Op een vraag * moet kunnen geantwoord worden met 1 woord of getal. Voorbeeld: Wat is * de hoofdstad van Frankrijk? */ private String vraag; /** * De String antwoord bevat het verwachte antwoord op de vraag. Voorbeeld * bij voorgaande vraag is het juiste antwoord: Parijs. */ private String antwoord; /** * De boolean isHoofdletterGevoelig<SUF>*/ private boolean isHoofdletterGevoelig; /** * De String antwoordhint is een hulp voor de quizkandidaat bij het zoeken * naar het juiste antwoord. Voorbeeld: bij de bovenstaande vraag kan een * antwoordhint zijn: Men vindt er de Eifel toren. Een antwoordhint is * optioneel bij een opdracht (hoeft niet verplicht ingevuld te worden bij * elke opdracht) */ private String antwoordHint; /** * De String categorie geeft aan tot welke categorie deze opdracht behoort. * We maken opdrachten van 5 categorien: Aardrijkskunde, Geschiedenis, * Nederlands, Wetenschappen en Wiskunde */ private String categorie; /** * De auteur is de naam van wie heeft deze opdracht bedacht. */ private String auteur; /** * Contructor voor het maken van een opdracht MET hint * * @param id * de id voor deze opdracht (moet uit de opdrachten db komen) * @param vraag * de vraag voor deze opdracht * @param antwoord * het 1-woord-of-getal antwoord * @param hoofdlettergevoelig * geeft aan of bij het antwoord rekening gehouden moet worden * met hoofdletters * @param hint * de antwoord-hint * @param categorie * een van de vijf bovenaan gedefinieerde categorieen * @param auteur * de naam van de bedenker van deze opdracht */ public Opdracht(int id, String vraag, String antwoord, boolean hoofdlettergevoelig, String hint, String categorie, String auteur) { this.opdrachtID = id; this.vraag = vraag; this.antwoord = antwoord; this.isHoofdletterGevoelig = hoofdlettergevoelig; this.antwoordHint = hint; this.categorie = categorie; this.auteur = auteur; } /** * Constructor voor het maken van een opdracht ZONDER hint * * @param id * de id voor deze opdracht (moet uit de opdrachten db komen) * @param vraag * de vraag voor deze opdracht * @param antwoord * het 1-woord-of-getal antwoord * @param hoofdlettergevoelig * geeft aan of bij het antwoord rekening gehouden moet worden * met hoofdletters * @param categorie * categorie een van de vijf bovenaan gedefinieerde categorieen * @param auteur * de naam van de bedenker van deze opdracht */ public Opdracht(int id, String vraag, String antwoord, boolean hoofdlettergevoelig, String categorie, String auteur) { this(id,vraag, antwoord, hoofdlettergevoelig, "Er werd geen hint voorzien voor deze opdracht", categorie, auteur); } public int getOpdrachtID() { return opdrachtID; } public String getVraag() { return vraag; } public String getAntwoord() { return antwoord; } public boolean isHoofdletterGevoelig() { return isHoofdletterGevoelig; } public String getAntwoordHint() { return antwoordHint; } public String getCategorie() { return categorie; } public String getAuteur() { return auteur; } /** * Methode om de gelijkheid van twee opdrachten te checken * * @return true als ze gelijk zijn */ @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Opdracht opdracht = (Opdracht) o; return opdrachtID == opdracht.opdrachtID && isHoofdletterGevoelig == opdracht.isHoofdletterGevoelig && Objects.equals(vraag, opdracht.vraag) && Objects.equals(antwoord, opdracht.antwoord) && Objects.equals(antwoordHint, opdracht.antwoordHint) && Objects.equals(categorie, opdracht.categorie) && Objects.equals(auteur, opdracht.auteur); } /** * Methode om deze opdracht volledig uit te schrijven */ public String toString() { String dezeOpdracht = ""; dezeOpdracht += getOpdrachtID() + " - " + getCategorie() + "\n"; dezeOpdracht += "auteur: " + getAuteur() + "\n"; dezeOpdracht += "vraag: " + getVraag() + "\n"; dezeOpdracht += "hint: " + getAntwoordHint() + "\n"; dezeOpdracht += (isHoofdletterGevoelig() ? "" : "niet ") + "hoofdlettergevoelig \n"; dezeOpdracht += "antwoord: " + getAntwoord() + "\n"; dezeOpdracht += "---------------------------------------------"; return dezeOpdracht; } }
194301_0
package be.ipeters.brol.cpbelcar.services; import java.time.LocalDate; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.apache.ibatis.javassist.bytecode.Descriptor.Iterator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import be.ipeters.brol.cpbelcar.domain.Car; import be.ipeters.brol.cpbelcar.domain.CarProduct; import be.ipeters.brol.cpbelcar.domain.Production; import be.ipeters.brol.cpbelcar.mappers.CarMapper; @Service public class CarService implements CrudService<Car, Integer> { private boolean isCarCreationPossible = false; private Integer pcgetProductId; private Integer partStock = 0; private Integer carStock = 0; private Double partPrice=0.0; private Double carPrice = 0.0; private Integer partId = 0; private Production production; @Autowired private CarMapper carMapper; @Autowired private SupplierOrderService supplierorderService; @Autowired private CarProductService cpService; @Autowired private ProductService productService; @Autowired private ProductionService productionService; public CarService() { super(); } public CarService(CarMapper carMock) { this.carMapper = carMock; } @Override public void save(Car entity) { /* * bij een nieuwe wagen van een bepaald type dient de stock +1 te worden * tegelijk 4 parts -1 */ checkPartsAvailable(entity.getId()); if (isCarCreationPossible) { // verminder de stock van elk onderdeel partId=entity.getId(); adaptPartStock( partId); // carMapper.insert(entity); // not creating a new line in the table, so update the stock this.updateStockPlusOne(entity); filloutProduction(); productionService.save(production); System.out.println("We have: "+production.getDescription()); } else { System.out.println("Not all parts are available..."); } } protected void filloutProduction() { // fill out the fields orderId, orderlineId, description, lastUpdate production=new Production(1, 1, 1, "created car of type "+partId, LocalDate.now()); } protected void adaptPartStock(Integer carId) { // verminder stock van elk van de 4 parts met id=partID List<CarProduct> cpList = cpService.findAllById(carId); System.out.println("carId=" + carId + ", size of cpList=" + cpList.size()); for (CarProduct pc : cpList) { System.out.println("productService.updateProductStock(pc.getProductId()):"+pc.getProductId()); partStock=productService.getProductStock(pc.getProductId()); System.out.println("partStock="+partStock+", for part "+pc.getProductId()+", which is "+productService.findById(pc.getProductId())); partStock--; System.out.println("partStock="+partStock); productService.updateStockMinOne(pc.getProductId()); } } public boolean checkPartsAvailable(Integer carId) { Map<Integer, Integer> cpMap = new HashMap<Integer, Integer>(); List<CarProduct> cpList = cpService.findAllById(carId); System.out.println("carId=" + carId + ", size of cpList=" + cpList.size()); if (cpList.size() == 0) { System.out.println("We cannot produce a car with id " + carId + "."); isCarCreationPossible = false; } else { // for (CarProduct pc : cpList) { pcgetProductId = pc.getProductId(); System.out.println(pcgetProductId); partStock = productService.findById(pcgetProductId).getStock(); cpMap.put(pcgetProductId, partStock); switch (partStock) { case 0: // part not available System.out .println("part <" + productService.findById(pcgetProductId).getName() + "> not available"); System.out.println("Need to order this part..."); // create SupplierOrder // Order this part supplierorderService.createSupplierOrderViaPartId(pcgetProductId); isCarCreationPossible = false; break; default: System.out.println("available!"); isCarCreationPossible = true; } } // check if at least one part is missing to set isCarCreationPossible=false; for (Map.Entry<Integer, Integer> entry : cpMap.entrySet()) { if (entry.getValue() == 0) { isCarCreationPossible = false; } } } System.out.println("isCarCreationPossible=" + isCarCreationPossible); return isCarCreationPossible; } public Double calculateCarOrderPrice(Integer carId) { System.out.println("carService - calculateCarOrderPrice"); carPrice=0.0; Map<Integer, Double> cpMap = new HashMap<Integer, Double>(); List<CarProduct> cpList = cpService.findAllById(carId); System.out.println("carId=" + carId + ", size of cpList=" + cpList.size()); if (cpList.size() == 0) { System.out.println("We cannot calculate a price for car with id " + carId + "."); } else { for (CarProduct cp : cpList) { pcgetProductId = cp.getProductId(); partPrice = productService.findById(pcgetProductId).getConsumerPrice(); System.out.println(pcgetProductId+ " costs " +partPrice); carPrice+=partPrice; } } System.out.println("carPrice=" + carPrice); return carPrice; } @Override public Car findById(Integer key) { return carMapper.findById(key); } @Override public List<Car> findAll() { return carMapper.findAll(); } @Override public void deleteById(Integer key) { carMapper.deleteById(key); } @Override public void update(Car entity) { carMapper.update(entity); } public Integer getCarStock(Integer key) { return carMapper.getCarStock(key); } public void updateStockMinOne(Car entity) { carStock=carMapper.getCarStock(entity.getId()); System.out.println("carStock="+carStock); carStock--; System.out.println("carStock="+carStock); entity.setStock(carStock); carMapper.updateStock(entity); } public void updateStockPlusOne(Car entity) { carStock=carMapper.getCarStock(entity.getId()); System.out.println("updateStockPlusOne carStock for Car "+entity.getId()+"="+carStock); carStock++; System.out.println("updateStockPlusOne carStock for Car "+entity.getId()+"="+carStock); entity.setStock(carStock); carMapper.updateStock(entity); } public Integer getProductStock(int carProductId) { // TODO Auto-generated method stub return this.findById(carProductId).getStock(); } }
cpjjpeters/javafx1
src/main/java/be/ipeters/brol/cpbelcar/services/CarService.java
1,861
/* * bij een nieuwe wagen van een bepaald type dient de stock +1 te worden * tegelijk 4 parts -1 */
block_comment
nl
package be.ipeters.brol.cpbelcar.services; import java.time.LocalDate; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.apache.ibatis.javassist.bytecode.Descriptor.Iterator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import be.ipeters.brol.cpbelcar.domain.Car; import be.ipeters.brol.cpbelcar.domain.CarProduct; import be.ipeters.brol.cpbelcar.domain.Production; import be.ipeters.brol.cpbelcar.mappers.CarMapper; @Service public class CarService implements CrudService<Car, Integer> { private boolean isCarCreationPossible = false; private Integer pcgetProductId; private Integer partStock = 0; private Integer carStock = 0; private Double partPrice=0.0; private Double carPrice = 0.0; private Integer partId = 0; private Production production; @Autowired private CarMapper carMapper; @Autowired private SupplierOrderService supplierorderService; @Autowired private CarProductService cpService; @Autowired private ProductService productService; @Autowired private ProductionService productionService; public CarService() { super(); } public CarService(CarMapper carMock) { this.carMapper = carMock; } @Override public void save(Car entity) { /* * bij een nieuwe<SUF>*/ checkPartsAvailable(entity.getId()); if (isCarCreationPossible) { // verminder de stock van elk onderdeel partId=entity.getId(); adaptPartStock( partId); // carMapper.insert(entity); // not creating a new line in the table, so update the stock this.updateStockPlusOne(entity); filloutProduction(); productionService.save(production); System.out.println("We have: "+production.getDescription()); } else { System.out.println("Not all parts are available..."); } } protected void filloutProduction() { // fill out the fields orderId, orderlineId, description, lastUpdate production=new Production(1, 1, 1, "created car of type "+partId, LocalDate.now()); } protected void adaptPartStock(Integer carId) { // verminder stock van elk van de 4 parts met id=partID List<CarProduct> cpList = cpService.findAllById(carId); System.out.println("carId=" + carId + ", size of cpList=" + cpList.size()); for (CarProduct pc : cpList) { System.out.println("productService.updateProductStock(pc.getProductId()):"+pc.getProductId()); partStock=productService.getProductStock(pc.getProductId()); System.out.println("partStock="+partStock+", for part "+pc.getProductId()+", which is "+productService.findById(pc.getProductId())); partStock--; System.out.println("partStock="+partStock); productService.updateStockMinOne(pc.getProductId()); } } public boolean checkPartsAvailable(Integer carId) { Map<Integer, Integer> cpMap = new HashMap<Integer, Integer>(); List<CarProduct> cpList = cpService.findAllById(carId); System.out.println("carId=" + carId + ", size of cpList=" + cpList.size()); if (cpList.size() == 0) { System.out.println("We cannot produce a car with id " + carId + "."); isCarCreationPossible = false; } else { // for (CarProduct pc : cpList) { pcgetProductId = pc.getProductId(); System.out.println(pcgetProductId); partStock = productService.findById(pcgetProductId).getStock(); cpMap.put(pcgetProductId, partStock); switch (partStock) { case 0: // part not available System.out .println("part <" + productService.findById(pcgetProductId).getName() + "> not available"); System.out.println("Need to order this part..."); // create SupplierOrder // Order this part supplierorderService.createSupplierOrderViaPartId(pcgetProductId); isCarCreationPossible = false; break; default: System.out.println("available!"); isCarCreationPossible = true; } } // check if at least one part is missing to set isCarCreationPossible=false; for (Map.Entry<Integer, Integer> entry : cpMap.entrySet()) { if (entry.getValue() == 0) { isCarCreationPossible = false; } } } System.out.println("isCarCreationPossible=" + isCarCreationPossible); return isCarCreationPossible; } public Double calculateCarOrderPrice(Integer carId) { System.out.println("carService - calculateCarOrderPrice"); carPrice=0.0; Map<Integer, Double> cpMap = new HashMap<Integer, Double>(); List<CarProduct> cpList = cpService.findAllById(carId); System.out.println("carId=" + carId + ", size of cpList=" + cpList.size()); if (cpList.size() == 0) { System.out.println("We cannot calculate a price for car with id " + carId + "."); } else { for (CarProduct cp : cpList) { pcgetProductId = cp.getProductId(); partPrice = productService.findById(pcgetProductId).getConsumerPrice(); System.out.println(pcgetProductId+ " costs " +partPrice); carPrice+=partPrice; } } System.out.println("carPrice=" + carPrice); return carPrice; } @Override public Car findById(Integer key) { return carMapper.findById(key); } @Override public List<Car> findAll() { return carMapper.findAll(); } @Override public void deleteById(Integer key) { carMapper.deleteById(key); } @Override public void update(Car entity) { carMapper.update(entity); } public Integer getCarStock(Integer key) { return carMapper.getCarStock(key); } public void updateStockMinOne(Car entity) { carStock=carMapper.getCarStock(entity.getId()); System.out.println("carStock="+carStock); carStock--; System.out.println("carStock="+carStock); entity.setStock(carStock); carMapper.updateStock(entity); } public void updateStockPlusOne(Car entity) { carStock=carMapper.getCarStock(entity.getId()); System.out.println("updateStockPlusOne carStock for Car "+entity.getId()+"="+carStock); carStock++; System.out.println("updateStockPlusOne carStock for Car "+entity.getId()+"="+carStock); entity.setStock(carStock); carMapper.updateStock(entity); } public Integer getProductStock(int carProductId) { // TODO Auto-generated method stub return this.findById(carProductId).getStock(); } }
70649_19
package view.MenuPanes; import java.util.ArrayList; import controller.LoginController; import controller.MenuController; import databeest.DataBaseApplication; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ScrollPane; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundFill; import javafx.scene.layout.FlowPane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.FontWeight; public class MenuPlayersPane extends VBox {// door joery private ScrollPane playersList; private VBox listInput; private MenuController menuController; private boolean loadbutton; private boolean turnOn; private ArrayList<MenuDropdown> menuItems; private Button cancel; private Button invitePlayer; private Label title; private FlowPane btnPane; private DataBaseApplication databeest; private ArrayList<String> players; private ArrayList<String> selectedPlayers; private Label message; private Button createGame; private LoginController loginController; private MenuWaitingPane menuWaitingPane; public MenuPlayersPane(MenuController menuController, LoginController loginController, MenuWaitingPane menuWaitingPane) { this.menuController = menuController; this.loginController = loginController; this.menuWaitingPane = menuWaitingPane; databeest = menuController.getDataBaseApplication(); players = databeest.getPlayers(); setPaneSize(); createPlayersList(false); setBackground(new Background(new BackgroundFill(Color.rgb(208, 215, 206), null, null))); // tijdelijk } private void createPlayersList(boolean turnon) { selectedPlayers = new ArrayList<String>(); // heeft de invited players in zich selectedPlayers.add(loginController.getCurrentAccount()); this.turnOn = turnon; // title title = new Label(); title.setText("Spelers"); title.setFont(Font.font("Verdana", FontWeight.BOLD, 30)); title.setTextFill(Color.GREEN); // buttons btnPane = new FlowPane(); btnPane.setPrefSize(200, 40); btnPane.setAlignment(Pos.CENTER); invitePlayer = new Button("Daag uit"); invitePlayer.setPrefSize(100, 30); invitePlayer.setOnAction(e -> turnOn()); btnPane.getChildren().add(invitePlayer); // update message message = new Label(); // the list with buttons playersList = new ScrollPane(); playersList.setMinSize(MenuPane.paneWidth - 60, (MenuPane.windowMaxHeight - (MenuPane.windowMaxHeight / 3)) - 150); playersList.setMaxSize(MenuPane.paneWidth - 60, (MenuPane.windowMaxHeight - (MenuPane.windowMaxHeight / 3)) - 150); playersList.setFitToWidth(true); playersList.setFitToHeight(true); listInput = new VBox(); listInput.setMinWidth(MenuPane.paneWidth - 80); // binding of listner. listInput.setMaxWidth(MenuPane.paneWidth - 80); playersList.setContent(listInput); menuItems = new ArrayList<MenuDropdown>(); databeest.getPlayers(); for (int i = 0; i < players.size(); i++) {// check of eigen gebruikersnaam er tussen staat if (players.get(i).equals(loginController.getCurrentAccount())) { players.remove(i); } } for (int i = 0; i < players.size(); i++) {// vult verzameling met alle knoppen met bijbehorende username menuItems.add(new MenuDropdown(menuController, false, players.get(i), false, this, false, false, null, loginController, null, null)); // spelersnaam moet uit } for (int x = 0; x < menuItems.size(); x++) { // voegt alle knoppen toe aan de lijst listInput.getChildren().add(menuItems.get(x)); } setAlignment(Pos.TOP_CENTER); getChildren().addAll(title, btnPane, message, playersList); } private void turnOn() { // verandert zicht om te inviten getChildren().clear(); cancel = new Button("afbreken"); cancel.setPrefSize(100, 30); cancel.setOnAction(e -> turnOff()); createGame = new Button("Uitnodigen"); createGame.setPrefSize(100, 30); createGame.setOnAction(e -> getUsernames()); btnPane.getChildren().clear(); btnPane.getChildren().addAll(cancel, createGame); btnPane.setAlignment(Pos.CENTER); getChildren().addAll(title, btnPane, message, playersList); menuItems.clear(); listInput.getChildren().clear(); message.setText(" "); for (int i = 0; i < players.size(); i++) {// vult verzameling met alle knoppen menuItems.add(new MenuDropdown(menuController, false, players.get(i), true, this, false, false, null, loginController, null, null)); // spelersnaam moet uit // database worden getrokken } for (int x = 0; x < menuItems.size(); x++) { // voegt alle knoppen toe aan de lijst listInput.getChildren().add(menuItems.get(x)); } } private void getUsernames() { // checkt of er niet te weinig of te veel spelers zijn geselecteerd. if (selectedPlayers.size() == 1) { message.setText("Je hebt geen spelers geselecteerd."); message.setTextFill(Color.RED); } else if (selectedPlayers.size() > 0 && selectedPlayers.size() <= 4) { if (selectedPlayers.size() == 2) { message.setText("Uitnodiging is verzonden!"); message.setTextFill(Color.GREEN); } else { message.setText("Uitnodigingen zijn verzonden!"); message.setTextFill(Color.GREEN); } menuController.newGame(selectedPlayers); // [START] testing in console // System.out.println("send invite to:"); // // for (int i = 0; i < selectedPlayers.size(); i++) { // System.out.println("- " + selectedPlayers.get(i)); // } // [END] testing in console turnOff(); } else if (selectedPlayers.size() > 4) { message.setText("Je hebt te veel spelers geselecteerd."); message.setTextFill(Color.RED); } // de array 'selectedPlayers' is nu gevuld met de uitgenodigde spelers. menuWaitingPane.updateWaitingPane(); } private void turnOff() { // na 'uitnodigen' of 'afbreken' wordt de normale spelerslijst weergegeven. getChildren().clear(); btnPane.getChildren().clear(); btnPane.getChildren().add(invitePlayer); getChildren().addAll(title, btnPane, message, playersList); menuItems.clear(); listInput.getChildren().clear(); for (int i = 0; i < players.size(); i++) {// vult verzameling met alle knoppen menuItems.add(new MenuDropdown(menuController, false, players.get(i), false, this, false, false, null, loginController, null, null)); } for (int x = 0; x < menuItems.size(); x++) { // voegt alle knoppen toe aan de lijst listInput.getChildren().add(menuItems.get(x)); } selectedPlayers.clear(); selectedPlayers.add(loginController.getCurrentAccount()); } public final void addPlayer(String username) { // voegt speler toe in arraylist selectedPlayers.add(username); // System.out.println("added " + username); if (selectedPlayers.size() > 4) { message.setText("Je kunt niet meer dan 3 spelers uitnodigen"); message.setTextFill(Color.RED); } } public final void removePlayer(String username) { // verwijderd speler uit arraylist for (int i = 0; i < selectedPlayers.size(); i++) { if (selectedPlayers.get(i).equals(username)) { // System.out.println("removed " + selectedPlayers.get(i)); selectedPlayers.remove(i); if (selectedPlayers.size() <= 4) { message.setText(" "); } } } } private void setPaneSize() { setMinSize(MenuPane.paneWidth - 40, MenuPane.windowMaxHeight - (MenuPane.windowMaxHeight / 3) - 40); setMaxSize(MenuPane.paneWidth - 40, MenuPane.windowMaxHeight - (MenuPane.windowMaxHeight / 3) - 40); } }
stefkattenvriend/Sagrada2019
code/src/view/MenuPanes/MenuPlayersPane.java
2,239
// na 'uitnodigen' of 'afbreken' wordt de normale spelerslijst weergegeven.
line_comment
nl
package view.MenuPanes; import java.util.ArrayList; import controller.LoginController; import controller.MenuController; import databeest.DataBaseApplication; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ScrollPane; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundFill; import javafx.scene.layout.FlowPane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.FontWeight; public class MenuPlayersPane extends VBox {// door joery private ScrollPane playersList; private VBox listInput; private MenuController menuController; private boolean loadbutton; private boolean turnOn; private ArrayList<MenuDropdown> menuItems; private Button cancel; private Button invitePlayer; private Label title; private FlowPane btnPane; private DataBaseApplication databeest; private ArrayList<String> players; private ArrayList<String> selectedPlayers; private Label message; private Button createGame; private LoginController loginController; private MenuWaitingPane menuWaitingPane; public MenuPlayersPane(MenuController menuController, LoginController loginController, MenuWaitingPane menuWaitingPane) { this.menuController = menuController; this.loginController = loginController; this.menuWaitingPane = menuWaitingPane; databeest = menuController.getDataBaseApplication(); players = databeest.getPlayers(); setPaneSize(); createPlayersList(false); setBackground(new Background(new BackgroundFill(Color.rgb(208, 215, 206), null, null))); // tijdelijk } private void createPlayersList(boolean turnon) { selectedPlayers = new ArrayList<String>(); // heeft de invited players in zich selectedPlayers.add(loginController.getCurrentAccount()); this.turnOn = turnon; // title title = new Label(); title.setText("Spelers"); title.setFont(Font.font("Verdana", FontWeight.BOLD, 30)); title.setTextFill(Color.GREEN); // buttons btnPane = new FlowPane(); btnPane.setPrefSize(200, 40); btnPane.setAlignment(Pos.CENTER); invitePlayer = new Button("Daag uit"); invitePlayer.setPrefSize(100, 30); invitePlayer.setOnAction(e -> turnOn()); btnPane.getChildren().add(invitePlayer); // update message message = new Label(); // the list with buttons playersList = new ScrollPane(); playersList.setMinSize(MenuPane.paneWidth - 60, (MenuPane.windowMaxHeight - (MenuPane.windowMaxHeight / 3)) - 150); playersList.setMaxSize(MenuPane.paneWidth - 60, (MenuPane.windowMaxHeight - (MenuPane.windowMaxHeight / 3)) - 150); playersList.setFitToWidth(true); playersList.setFitToHeight(true); listInput = new VBox(); listInput.setMinWidth(MenuPane.paneWidth - 80); // binding of listner. listInput.setMaxWidth(MenuPane.paneWidth - 80); playersList.setContent(listInput); menuItems = new ArrayList<MenuDropdown>(); databeest.getPlayers(); for (int i = 0; i < players.size(); i++) {// check of eigen gebruikersnaam er tussen staat if (players.get(i).equals(loginController.getCurrentAccount())) { players.remove(i); } } for (int i = 0; i < players.size(); i++) {// vult verzameling met alle knoppen met bijbehorende username menuItems.add(new MenuDropdown(menuController, false, players.get(i), false, this, false, false, null, loginController, null, null)); // spelersnaam moet uit } for (int x = 0; x < menuItems.size(); x++) { // voegt alle knoppen toe aan de lijst listInput.getChildren().add(menuItems.get(x)); } setAlignment(Pos.TOP_CENTER); getChildren().addAll(title, btnPane, message, playersList); } private void turnOn() { // verandert zicht om te inviten getChildren().clear(); cancel = new Button("afbreken"); cancel.setPrefSize(100, 30); cancel.setOnAction(e -> turnOff()); createGame = new Button("Uitnodigen"); createGame.setPrefSize(100, 30); createGame.setOnAction(e -> getUsernames()); btnPane.getChildren().clear(); btnPane.getChildren().addAll(cancel, createGame); btnPane.setAlignment(Pos.CENTER); getChildren().addAll(title, btnPane, message, playersList); menuItems.clear(); listInput.getChildren().clear(); message.setText(" "); for (int i = 0; i < players.size(); i++) {// vult verzameling met alle knoppen menuItems.add(new MenuDropdown(menuController, false, players.get(i), true, this, false, false, null, loginController, null, null)); // spelersnaam moet uit // database worden getrokken } for (int x = 0; x < menuItems.size(); x++) { // voegt alle knoppen toe aan de lijst listInput.getChildren().add(menuItems.get(x)); } } private void getUsernames() { // checkt of er niet te weinig of te veel spelers zijn geselecteerd. if (selectedPlayers.size() == 1) { message.setText("Je hebt geen spelers geselecteerd."); message.setTextFill(Color.RED); } else if (selectedPlayers.size() > 0 && selectedPlayers.size() <= 4) { if (selectedPlayers.size() == 2) { message.setText("Uitnodiging is verzonden!"); message.setTextFill(Color.GREEN); } else { message.setText("Uitnodigingen zijn verzonden!"); message.setTextFill(Color.GREEN); } menuController.newGame(selectedPlayers); // [START] testing in console // System.out.println("send invite to:"); // // for (int i = 0; i < selectedPlayers.size(); i++) { // System.out.println("- " + selectedPlayers.get(i)); // } // [END] testing in console turnOff(); } else if (selectedPlayers.size() > 4) { message.setText("Je hebt te veel spelers geselecteerd."); message.setTextFill(Color.RED); } // de array 'selectedPlayers' is nu gevuld met de uitgenodigde spelers. menuWaitingPane.updateWaitingPane(); } private void turnOff() { // na 'uitnodigen'<SUF> getChildren().clear(); btnPane.getChildren().clear(); btnPane.getChildren().add(invitePlayer); getChildren().addAll(title, btnPane, message, playersList); menuItems.clear(); listInput.getChildren().clear(); for (int i = 0; i < players.size(); i++) {// vult verzameling met alle knoppen menuItems.add(new MenuDropdown(menuController, false, players.get(i), false, this, false, false, null, loginController, null, null)); } for (int x = 0; x < menuItems.size(); x++) { // voegt alle knoppen toe aan de lijst listInput.getChildren().add(menuItems.get(x)); } selectedPlayers.clear(); selectedPlayers.add(loginController.getCurrentAccount()); } public final void addPlayer(String username) { // voegt speler toe in arraylist selectedPlayers.add(username); // System.out.println("added " + username); if (selectedPlayers.size() > 4) { message.setText("Je kunt niet meer dan 3 spelers uitnodigen"); message.setTextFill(Color.RED); } } public final void removePlayer(String username) { // verwijderd speler uit arraylist for (int i = 0; i < selectedPlayers.size(); i++) { if (selectedPlayers.get(i).equals(username)) { // System.out.println("removed " + selectedPlayers.get(i)); selectedPlayers.remove(i); if (selectedPlayers.size() <= 4) { message.setText(" "); } } } } private void setPaneSize() { setMinSize(MenuPane.paneWidth - 40, MenuPane.windowMaxHeight - (MenuPane.windowMaxHeight / 3) - 40); setMaxSize(MenuPane.paneWidth - 40, MenuPane.windowMaxHeight - (MenuPane.windowMaxHeight / 3) - 40); } }
72828_24
package apollo.gui.detailviewers.exonviewer; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import java.util.*; import apollo.datamodel.*; import apollo.editor.AnnotationChangeEvent; import apollo.editor.AnnotationChangeListener; import apollo.gui.event.*; import apollo.dataadapter.DataLoadEvent; import apollo.dataadapter.DataLoadListener; import apollo.gui.ControlledObjectI; import apollo.gui.Controller; import apollo.gui.Transformer; import apollo.gui.genomemap.StrandedZoomableApolloPanel; import apollo.gui.SelectionManager; import apollo.gui.synteny.CurationManager; import apollo.gui.synteny.GuiCurationState; public class BaseFineEditor extends JFrame implements FeatureSelectionListener, ControlledObjectI, AnnotationChangeListener { private static final Color [] colorList = { new Color(0,0,0), new Color(255,255,0), new Color(0,255,255), new Color(255,0,255), new Color(255,0,0), new Color(0,255,0), new Color(0,0,255)}; private static int colorIndex = 0; private static ArrayList baseEditorInstanceList = new ArrayList(5); protected BaseEditorPanel editorPanel = null; private TranslationViewer translationViewer; private JViewport viewport; protected JLabel lengthLabel; private JComboBox transcriptComboBox; StrandedZoomableApolloPanel szap; Transformer transformer; private FineEditorScrollListener scrollListener; Color indicatorColor; JPanel colorSwatch; SelectionManager selection_manager; protected JButton findButton; protected JButton clearFindsButton; protected JButton goToButton; protected JCheckBox showIntronBox; // Need? private JCheckBox followSelectionCheckBox; protected JButton upstream_button; protected JButton downstream_button; private AnnotatedFeatureI currentAnnot;//Transcript protected Transcript neighbor_up; protected Transcript neighbor_down; private GuiCurationState curationState; public static void showBaseEditor(AnnotatedFeatureI editMe,GuiCurationState curationState, SeqFeatureI geneHolder) { BaseFineEditor bfe = new BaseFineEditor(editMe,curationState,geneHolder); baseEditorInstanceList.add(bfe); } private BaseFineEditor(AnnotatedFeatureI editMe,GuiCurationState curationState, SeqFeatureI geneHolder) { super((editMe.isForwardStrand() ? "Forward" : "Reverse") + " Strand Exon Editor"); this.curationState = curationState; curationState.getController().addListener(this); curationState.getController().addListener(new BaseEditorDataListener()); szap = curationState.getSZAP(); transformer = szap.getScaleView().getTransform(); int seqStart = curationState.getCurationSet().getLow(); int seqEnd = curationState.getCurationSet().getHigh(); //FeatureSetI annFeatSet=((DrawableFeatureSet)view.getDrawableSet()).getFeatureSet(); editorPanel = new BaseEditorPanel(curationState, this, !editMe.isForwardStrand(), seqStart, seqEnd, geneHolder); initGui(editMe); // cant do til after editorPanel made // cant do this til after initGui (editorPanel needs to know size) editorPanel.displayAnnot(editMe); attachListeners(); showEditRegion(); displayAnnot(getTransOrOneLevelAnn(editMe)); translationViewer.repaint(); setVisible(true); // Might just be linux, but bofe gets iconified on close if (getState()==Frame.ICONIFIED) setState(Frame.NORMAL); } /** ControlledObjectI interface - but controller now comes from curationState */ public void setController(Controller controller) { //this.controller = controller; //controller.addListener (this); } public Controller getController() { return curationState.getController(); } public Object getControllerWindow() { return this; } // Although they are removed we need to remove from hash in controller public boolean needsAutoRemoval() { return true; } public void setSelectionManager (SelectionManager sm) { this.selection_manager = sm; } public SelectionManager getSelectionManager () { return curationState.getSelectionManager();//this.selection_manager; } private void removeComponents(Container cont) { Component[] components = cont.getComponents(); Component comp; for (int i = 0; i < components.length; i++) { comp = components[i]; if (comp != null) { cont.remove(comp); if (comp instanceof Container) removeComponents((Container) comp); } } } public boolean handleAnnotationChangeEvent(AnnotationChangeEvent evt) { if (this.isVisible() && evt.getSource() != this) { if (evt.isCompound()) { for (int i = 0; i < evt.getNumberOfChildren(); ++i) { handleAnnotationChangeEvent(evt.getChildChangeEvent(i)); } return true; } if (evt.isEndOfEditSession()) { // Dont want scrolling on ann change, also sf for redraw is the // gene, so it just goes to 1st trans which is problematic. displayAnnot(currentAnnot); repaint(); // this is the needed repaint after the changes return true; } /* AnnotatedFeatureI gene = evt.getChangedAnnot(); for (Object o : szap.getAnnotations().getFeatures()) { AnnotatedFeatureI feat = (AnnotatedFeatureI)o; if (feat.getId().equals(gene.getId())) { //gene = feat; break; } } */ if (evt.isAdd()) { AnnotatedFeatureI annotToDisplay = null; AnnotatedFeatureI gene = evt.getChangedAnnot(); int trans_count = gene.size(); for (int i = 0; i < trans_count; ++i) { if (evt.isUndo()) { Transcript t = (Transcript) gene.getFeatureAt (i); //System.out.printf("Attaching %s(%d)\n", t, t.hashCode()); editorPanel.attachAnnot(t); if (currentAnnot != null && t.getName().equals(currentAnnot.getName())) { annotToDisplay = t; } } } if (annotToDisplay == null) { annotToDisplay = (AnnotatedFeatureI)evt.getChangedAnnot().getFeatureAt(0); } displayAnnot(annotToDisplay); return true; } if (evt.isDelete()) { AnnotatedFeatureI gene = evt.getChangedAnnot(); int trans_count = gene.size(); for (int i = 0; i < trans_count; ++i) { if (evt.isUndo()) { Transcript t = (Transcript) gene.getFeatureAt (i); //System.out.printf("Detaching %s(%d)\n", t, t.hashCode()); editorPanel.detachTranscript(t); } } return true; } /* // getAnnotation() can be null after a delete - return if null? SeqFeatureI sf = evt.getAnnotTop(); // If the annotation event is not for the editors strand then return boolean is_reverse = (sf.getStrand() == -1); if (editorPanel.getReverseStrand() != is_reverse) return false; if (evt.isDelete() && evt.isRootAnnotChange()) { AnnotatedFeatureI gene = evt.getChangedAnnot(); int trans_count = gene.size(); for (int i = 0; i < trans_count; i++) { Transcript t = (Transcript) gene.getFeatureAt (i); editorPanel.detachTranscript (t); if (t == currentAnnot) currentAnnot = null; } } else if (evt.isDelete() && evt.isTranscriptChange()) { Transcript t = (Transcript) evt.getChangedAnnot(); editorPanel.detachTranscript (t); if (t == currentAnnot) currentAnnot = null; } else if ((evt.isAdd() || evt.isSplit() || evt.isMerge()) && evt.isRootAnnotChange()) { AnnotatedFeatureI gene = evt.getChangedAnnot(); int trans_count = gene.size(); for (int i = 0; i < trans_count; i++) { Transcript t = (Transcript) gene.getFeatureAt (i); int tier = editorPanel.attachAnnot (t); } } else if (evt.isAdd() && evt.isTranscriptChange()) { Transcript t = (Transcript) evt.getChangedAnnot(); int tier = editorPanel.attachAnnot (t); } // Exon split or intron made - same thing isnt it? else if (evt.isAdd() && evt.isExonChange()) { Transcript t = (Transcript) evt.getParentFeature(); // removing and adding transcript will force editorPanel // to pick up new exon editorPanel.detachTranscript(t); editorPanel.attachAnnot(t); } else if (evt.isDelete() && evt.isExonChange()) { Transcript t = (Transcript) evt.getParentFeature(); // removing and adding transcript will force editorPanel to remove exon editorPanel.detachTranscript(t); editorPanel.attachAnnot(t); // or editorPanel.removeFeature((Exon)evt.getSecondFeature()); } // else if (evt.isReplace()) { //&&evt.isTopAnnotChange - always true of replace // AnnotatedFeatureI old_gene = evt.getReplacedFeature(); // AnnotatedFeatureI new_gene = (AnnotatedFeatureI)evt.getChangedFeature(); // int trans_count = old_gene.size(); // /* This does assume that there are no changes in the number // of transcripts between the old and the new. Might be safer // to separate the 2 loops */ // for (int i = 0; i < trans_count; i++) { // Transcript t; // t = (Transcript) old_gene.getFeatureAt (i); // editorPanel.detachTranscript (t); // t = (Transcript) new_gene.getFeatureAt (i); // int tier = editorPanel.attachTranscript (t); // } // // This is so that we don't select a different transcript // AnnotatedFeatureI current_gene = (current_transcript != null ? // current_transcript.getGene() : null); // if (current_gene != null && current_gene == old_gene) { // int index = current_gene.getFeatureIndex(current_transcript); // current_transcript = (Transcript) new_gene.getFeatureAt(index); // } // } // this isnt possible - all replaces are for top annots // else if (evt.isReplace() && evt.isTranscriptChange()) { // Transcript old_trans = (Transcript)evt.getReplacedFeature(); // Transcript new_trans = (Transcript)evt.getChangedFeature(); // editorPanel.detachTranscript (old_trans); // int tier = editorPanel.attachTranscript (new_trans); // // This is so that we don't select a different transcript // if (current_transcript != null && current_transcript == old_trans) { // current_transcript = new_trans; // } // } } return true; } /** Handle the selection event (feature was selected in another window--select it here) This is also where selections from BaseFineEditor come in which are really internal selections. Only handle external selection if followSelection is checked */ public boolean handleFeatureSelectionEvent (FeatureSelectionEvent evt) { if (!canHandleSelection(evt,this)) return false; // now we do something, canHanSel filters for GenAnnIs AnnotatedFeatureI gai = (AnnotatedFeatureI)evt.getFeatures().getFeature(0); displayAnnot(getTransOrOneLevelAnn(gai)); translationViewer.repaint(); return true; } /** Does all the handle selection checks for BaseFineEditor and BaseEditorPanel */ boolean canHandleSelection(FeatureSelectionEvent evt,Object self) { if ((noExternalSelection() && isExternalSelection(evt)) && !evt.forceSelection()) return false; if (evt.getSource() == self) return false; if (!this.isVisible()) return false; if (evt.getFeatures().size() == 0) return false; SeqFeatureI sf = evt.getFeatures().getFeature(0); // if strand of selection is not our strand return boolean is_reverse = (sf.getStrand() == -1); if (is_reverse != editorPanel.getReverseStrand()) return false; if ( ! (sf instanceof AnnotatedFeatureI)) return false;//repaint transVw? else return true; } /** True if the selection comes from outside world. false if from this OR editorPanel */ private boolean isExternalSelection(FeatureSelectionEvent e) { if (e.getSource() == this || e.getSource() == editorPanel) return false; return true; } private boolean noExternalSelection() { return !followSelectionCheckBox.isSelected(); } public Color getIndicatorColor() { return indicatorColor; } /** puts up vertical lines in szap(main window) indicating the region EDE is * displaying - make private? */ private void showEditRegion() { colorIndex = (colorIndex + 1) % colorList.length; indicatorColor = colorList[colorIndex]; colorSwatch.setBackground(indicatorColor); szap.addHighlightRegion(editorPanel, indicatorColor, editorPanel.getReverseStrand()); } public void attachListeners() { // changeListener = new AnnotationChangeDoodad(); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { szap.removeHighlightRegion(editorPanel); szap.repaint(); BaseFineEditor.this.setVisible(false); } } ); clearFindsButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { editorPanel.setShowHitZones(false); clearFindsButton.setEnabled(false); } } ); findButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { editorPanel.showFindDialog(); } } ); goToButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { editorPanel.showGoToDialog(); } } ); showIntronBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { translationViewer. setDrawIntrons(showIntronBox.isSelected()); } } ); upstream_button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { selectAnnot(neighbor_up); } } ); downstream_button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { selectAnnot(neighbor_down); } } ); } private class FineEditorScrollListener implements ChangeListener { int oldstart = -1; int oldwidth = -1; public void stateChanged(ChangeEvent e) { szap.repaint(); translationViewer.repaint(); } } /** Dispose all editors currently in existence. Keeps track of all instances for this purpose */ public static void disposeAllEditors() { for (Iterator it = baseEditorInstanceList.iterator(); it.hasNext(); ) ((BaseFineEditor)it.next()).dispose(); baseEditorInstanceList.clear(); } private class BaseEditorDataListener implements DataLoadListener { public boolean handleDataLoadEvent(DataLoadEvent e) { if (!e.dataRetrievalBeginning()) return false; disposeAllEditors(); curationState.getController().removeListener(this); return true; } } public void dispose() { removeComponents(this); editorPanel.cleanup(); // 1.3.1 popup mem leak & remove listener szap.removeHighlightRegion(editorPanel); editorPanel = null; translationViewer = null; viewport.removeChangeListener(scrollListener); viewport = null; lengthLabel = null; //featureNameLabel = null; transcriptComboBox = null; szap = null; transformer = null; scrollListener = null; indicatorColor = null; colorSwatch = null; // changeListener = null; // removeWindowListener(windowListener); // windowListener = null; getController().removeListener(this); //getController() = null; //view = null; findButton = null; clearFindsButton = null; goToButton = null; upstream_button = null; downstream_button = null; super.dispose(); } private void initGui(AnnotatedFeatureI annot) { translationViewer = new TranslationViewer(editorPanel); translationViewer.setBackground(Color.black); transcriptComboBox = new JComboBox(); lengthLabel = new JLabel("Translation length: <no feature selected>"); lengthLabel.setForeground(Color.black); findButton = new JButton("Find sequence..."); // clearFindsBox = new JCheckBox("Show search hits"); clearFindsButton = new JButton("Clear search hits"); // Disable until we actually get search results clearFindsButton.setEnabled(false); goToButton = new JButton("GoTo..."); showIntronBox = new JCheckBox("Show introns in translation viewer", true); showIntronBox.setBackground (Color.white); followSelectionCheckBox = new JCheckBox("Follow external selection",false); followSelectionCheckBox.setBackground(Color.white); upstream_button = new JButton (); downstream_button = new JButton (); colorSwatch = new JPanel(); setSize(824,500); JScrollPane pane = new JScrollPane(editorPanel); pane.setHorizontalScrollBarPolicy( JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); pane.setRowHeaderView(new BaseFineEditorRowHeader(editorPanel)); viewport = pane.getViewport(); colorSwatch.setPreferredSize(new Dimension(10,10)); getContentPane().setBackground (Color.white); getContentPane().setLayout(new BorderLayout()); getContentPane().add(colorSwatch, "North"); getContentPane().add(pane, "Center"); Box transcriptListBox = new Box(BoxLayout.X_AXIS); JLabel tranLabel; // 1 LEVEL ANNOT if (annot.isAnnotTop()) tranLabel = new JLabel("Annotation: "); else // 3-level tranLabel = new JLabel("Transcript: "); tranLabel.setForeground(Color.black); transcriptListBox.add(Box.createHorizontalStrut(5)); transcriptListBox.add(tranLabel); transcriptListBox.setBackground(Color.white); transcriptComboBox.setMaximumSize(new Dimension(300,30)); transcriptListBox.add(transcriptComboBox); transcriptListBox.add(Box.createHorizontalGlue()); transcriptListBox.add(Box.createHorizontalStrut(5)); transcriptListBox.add(lengthLabel); transcriptListBox.add(Box.createHorizontalGlue()); Box checkboxesTop = new Box(BoxLayout.X_AXIS); checkboxesTop.setBackground (Color.white); checkboxesTop.add(Box.createHorizontalStrut(5)); checkboxesTop.add(findButton); checkboxesTop.add(Box.createHorizontalStrut(10)); checkboxesTop.add(clearFindsButton); checkboxesTop.add(Box.createHorizontalStrut(15)); checkboxesTop.add(goToButton); checkboxesTop.add(Box.createHorizontalGlue()); Box checkboxesBottom = new Box(BoxLayout.X_AXIS); checkboxesBottom.add(showIntronBox); checkboxesBottom.add(Box.createHorizontalGlue()); checkboxesBottom.add(Box.createHorizontalStrut(10)); checkboxesBottom.add(followSelectionCheckBox); Box checkboxes = new Box(BoxLayout.Y_AXIS); checkboxes.add(checkboxesTop); checkboxes.add(checkboxesBottom); Box labelPanel = new Box(BoxLayout.Y_AXIS); labelPanel.setBackground(Color.white); labelPanel.add(transcriptListBox); labelPanel.add(Box.createVerticalStrut(5)); labelPanel.add(checkboxes); Box navPanel = new Box(BoxLayout.Y_AXIS); navPanel.setBackground (Color.white); navPanel.add(upstream_button); navPanel.add(Box.createVerticalStrut(10)); navPanel.add(downstream_button); navPanel.add(Box.createVerticalGlue()); Box textBoxes = new Box(BoxLayout.X_AXIS); textBoxes.setBackground (Color.white); textBoxes.add(labelPanel); textBoxes.add(navPanel); Box detailPanel = new Box(BoxLayout.Y_AXIS); detailPanel.setBackground(Color.white); detailPanel.add(translationViewer); detailPanel.add(textBoxes); getContentPane().add(detailPanel, "South"); validateTree(); scrollListener = new FineEditorScrollListener(); viewport.addChangeListener(scrollListener); transcriptComboBox.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_U && (e.getModifiers() & KeyEvent.CTRL_MASK) != 0) { CurationManager.getActiveCurationState().getTransactionManager().undo(this); } } }); } /** Both fires off selection event and displays annot */ private void selectAnnot(AnnotatedFeatureI annot) { displayAnnot(getTransOrOneLevelAnn(annot)); translationViewer.repaint(); BaseFocusEvent evt = new BaseFocusEvent(this, annot.getStart(), annot); getController().handleBaseFocusEvent(evt); getSelectionManager().select(annot,this); // sends off selection } /** Display AnnotatedFeatureI feature. * Exon, Transcript, and Gene are all GenericAnnotationI. * No selection event is fired. (selectAnnot fires and displays) */ private void displayAnnot(AnnotatedFeatureI annot) { currentAnnot = annot; if (currentAnnot == null) { transcriptComboBox.removeAllItems(); transcriptComboBox.addItem("<no feature selected>"); lengthLabel.setText("Translation length: <no feature selected>"); upstream_button.setLabel(""); downstream_button.setLabel(""); translationViewer.setTranscript(null,editorPanel.getSelectedTier()); // ?? return; } //else { setupTranscriptComboBox(currentAnnot); SeqFeatureI topAnnot = currentAnnot; if (topAnnot.isTranscript()) topAnnot = currentAnnot.getRefFeature(); if (topAnnot.isProteinCodingGene()) { String translation = currentAnnot.translate(); if (translation == null) { lengthLabel.setText("Translation length: <no start selected>"); } else { lengthLabel.setText("Translation length: " + currentAnnot.translate().length()); } } else { lengthLabel.setText(topAnnot.getFeatureType() + " annotation"); } FeatureSetI holder = (FeatureSetI) topAnnot.getRefFeature(); neighbor_up = null; neighbor_down = null; if (holder != null) { int index = holder.getFeatureIndex(topAnnot); // get next neighbor up that has whole sequence for (int i = index-1; i >= 0 && neighbor_up==null; i--) { FeatureSetI gene_sib = (FeatureSetI) holder.getFeatureAt(i); if (gene_sib.getFeatureAt(0) instanceof Transcript) { Transcript trans = (Transcript) gene_sib.getFeatureAt(0); if (trans.haveWholeSequence())//szap.getCurationSet())) neighbor_up = trans; } } // get next neighbor down that has whole sequence for (int i = index+1; i < holder.size() && neighbor_down==null; i++) { FeatureSetI gene_sib = (FeatureSetI) holder.getFeatureAt(i); if (gene_sib.getFeatureAt(0) instanceof Transcript) { Transcript trans = (Transcript) gene_sib.getFeatureAt(0); if (trans.haveWholeSequence())//szap.getCurationSet())) neighbor_down = trans; } } } upstream_button.setLabel (neighbor_up == null ? "" : "Go to next 5' annotation (" + neighbor_up.getParent().getName()+")"); upstream_button.setVisible (neighbor_up != null); downstream_button.setLabel (neighbor_down == null ? "" : "Go to next 3' annotation (" + neighbor_down.getParent().getName()+")"); downstream_button.setVisible (neighbor_down != null); //} // todo - translationViewer take in 1 level annot if (currentAnnot.isTranscript()) translationViewer.setTranscript((Transcript)currentAnnot, editorPanel.getSelectedTier()); } /** Sets up transcriptComboBox (pulldown list) with transcript and * its parent gene's other transcripts, with transcript selected */ private void setupTranscriptComboBox(AnnotatedFeatureI annot) { // could also check for gene change before doing a removeAll if (transcriptComboBox.getSelectedItem() == annot) return; // adding and removing items causes item events to fire so need to remove // listener here - is there any other way to supress firing? transcriptComboBox.removeItemListener(transItemListener); transcriptComboBox.removeAllItems(); if (annot==null) { transcriptComboBox.addItem("<no feature selected>"); return; } // 1 LEVEL ANNOT if (annot.isAnnotTop()) { transcriptComboBox.addItem(annot); return; } // TRANSCRIPT SeqFeatureI gene = annot.getRefFeature(); Vector transcripts = gene.getFeatures(); for (int i=0; i<transcripts.size(); i++) transcriptComboBox.addItem(transcripts.elementAt(i)); transcriptComboBox.setSelectedItem(annot); // transcript transcriptComboBox.addItemListener(transItemListener); } private TranscriptComboBoxItemListener transItemListener = new TranscriptComboBoxItemListener(); private class TranscriptComboBoxItemListener implements ItemListener { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED && e.getItem() instanceof Transcript) selectAnnot((Transcript)e.getItem()); } } /** AssemblyFeature is the only GAI at the moment that has no relation to // a transcript. Dont think they can end up in ede (??). // Would be nice to have an interface that was solely for the exon // trans gene heirarchy? Should we actively make sure AssemblyFeatures dont // get into ede? (filter in AnnotationMenu?) returns null if no transcript can be found. */ private AnnotatedFeatureI getTransOrOneLevelAnn(AnnotatedFeatureI af) { if (af != null) { if (af.isTranscript()) return af; if (af.isExon()) return af.getRefFeature().getAnnotatedFeature(); if (af.isAnnotTop()) { if (af.hasKids()) return af.getFeatureAt(0).getAnnotatedFeature(); // transcript else // 1 level annot return af; } } return null; } }
seqflow/BatchAmpTargetSeqSearch
src/main/java/apollo/gui/detailviewers/exonviewer/BaseFineEditor.java
6,892
// else if (evt.isReplace() && evt.isTranscriptChange()) {
line_comment
nl
package apollo.gui.detailviewers.exonviewer; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import java.util.*; import apollo.datamodel.*; import apollo.editor.AnnotationChangeEvent; import apollo.editor.AnnotationChangeListener; import apollo.gui.event.*; import apollo.dataadapter.DataLoadEvent; import apollo.dataadapter.DataLoadListener; import apollo.gui.ControlledObjectI; import apollo.gui.Controller; import apollo.gui.Transformer; import apollo.gui.genomemap.StrandedZoomableApolloPanel; import apollo.gui.SelectionManager; import apollo.gui.synteny.CurationManager; import apollo.gui.synteny.GuiCurationState; public class BaseFineEditor extends JFrame implements FeatureSelectionListener, ControlledObjectI, AnnotationChangeListener { private static final Color [] colorList = { new Color(0,0,0), new Color(255,255,0), new Color(0,255,255), new Color(255,0,255), new Color(255,0,0), new Color(0,255,0), new Color(0,0,255)}; private static int colorIndex = 0; private static ArrayList baseEditorInstanceList = new ArrayList(5); protected BaseEditorPanel editorPanel = null; private TranslationViewer translationViewer; private JViewport viewport; protected JLabel lengthLabel; private JComboBox transcriptComboBox; StrandedZoomableApolloPanel szap; Transformer transformer; private FineEditorScrollListener scrollListener; Color indicatorColor; JPanel colorSwatch; SelectionManager selection_manager; protected JButton findButton; protected JButton clearFindsButton; protected JButton goToButton; protected JCheckBox showIntronBox; // Need? private JCheckBox followSelectionCheckBox; protected JButton upstream_button; protected JButton downstream_button; private AnnotatedFeatureI currentAnnot;//Transcript protected Transcript neighbor_up; protected Transcript neighbor_down; private GuiCurationState curationState; public static void showBaseEditor(AnnotatedFeatureI editMe,GuiCurationState curationState, SeqFeatureI geneHolder) { BaseFineEditor bfe = new BaseFineEditor(editMe,curationState,geneHolder); baseEditorInstanceList.add(bfe); } private BaseFineEditor(AnnotatedFeatureI editMe,GuiCurationState curationState, SeqFeatureI geneHolder) { super((editMe.isForwardStrand() ? "Forward" : "Reverse") + " Strand Exon Editor"); this.curationState = curationState; curationState.getController().addListener(this); curationState.getController().addListener(new BaseEditorDataListener()); szap = curationState.getSZAP(); transformer = szap.getScaleView().getTransform(); int seqStart = curationState.getCurationSet().getLow(); int seqEnd = curationState.getCurationSet().getHigh(); //FeatureSetI annFeatSet=((DrawableFeatureSet)view.getDrawableSet()).getFeatureSet(); editorPanel = new BaseEditorPanel(curationState, this, !editMe.isForwardStrand(), seqStart, seqEnd, geneHolder); initGui(editMe); // cant do til after editorPanel made // cant do this til after initGui (editorPanel needs to know size) editorPanel.displayAnnot(editMe); attachListeners(); showEditRegion(); displayAnnot(getTransOrOneLevelAnn(editMe)); translationViewer.repaint(); setVisible(true); // Might just be linux, but bofe gets iconified on close if (getState()==Frame.ICONIFIED) setState(Frame.NORMAL); } /** ControlledObjectI interface - but controller now comes from curationState */ public void setController(Controller controller) { //this.controller = controller; //controller.addListener (this); } public Controller getController() { return curationState.getController(); } public Object getControllerWindow() { return this; } // Although they are removed we need to remove from hash in controller public boolean needsAutoRemoval() { return true; } public void setSelectionManager (SelectionManager sm) { this.selection_manager = sm; } public SelectionManager getSelectionManager () { return curationState.getSelectionManager();//this.selection_manager; } private void removeComponents(Container cont) { Component[] components = cont.getComponents(); Component comp; for (int i = 0; i < components.length; i++) { comp = components[i]; if (comp != null) { cont.remove(comp); if (comp instanceof Container) removeComponents((Container) comp); } } } public boolean handleAnnotationChangeEvent(AnnotationChangeEvent evt) { if (this.isVisible() && evt.getSource() != this) { if (evt.isCompound()) { for (int i = 0; i < evt.getNumberOfChildren(); ++i) { handleAnnotationChangeEvent(evt.getChildChangeEvent(i)); } return true; } if (evt.isEndOfEditSession()) { // Dont want scrolling on ann change, also sf for redraw is the // gene, so it just goes to 1st trans which is problematic. displayAnnot(currentAnnot); repaint(); // this is the needed repaint after the changes return true; } /* AnnotatedFeatureI gene = evt.getChangedAnnot(); for (Object o : szap.getAnnotations().getFeatures()) { AnnotatedFeatureI feat = (AnnotatedFeatureI)o; if (feat.getId().equals(gene.getId())) { //gene = feat; break; } } */ if (evt.isAdd()) { AnnotatedFeatureI annotToDisplay = null; AnnotatedFeatureI gene = evt.getChangedAnnot(); int trans_count = gene.size(); for (int i = 0; i < trans_count; ++i) { if (evt.isUndo()) { Transcript t = (Transcript) gene.getFeatureAt (i); //System.out.printf("Attaching %s(%d)\n", t, t.hashCode()); editorPanel.attachAnnot(t); if (currentAnnot != null && t.getName().equals(currentAnnot.getName())) { annotToDisplay = t; } } } if (annotToDisplay == null) { annotToDisplay = (AnnotatedFeatureI)evt.getChangedAnnot().getFeatureAt(0); } displayAnnot(annotToDisplay); return true; } if (evt.isDelete()) { AnnotatedFeatureI gene = evt.getChangedAnnot(); int trans_count = gene.size(); for (int i = 0; i < trans_count; ++i) { if (evt.isUndo()) { Transcript t = (Transcript) gene.getFeatureAt (i); //System.out.printf("Detaching %s(%d)\n", t, t.hashCode()); editorPanel.detachTranscript(t); } } return true; } /* // getAnnotation() can be null after a delete - return if null? SeqFeatureI sf = evt.getAnnotTop(); // If the annotation event is not for the editors strand then return boolean is_reverse = (sf.getStrand() == -1); if (editorPanel.getReverseStrand() != is_reverse) return false; if (evt.isDelete() && evt.isRootAnnotChange()) { AnnotatedFeatureI gene = evt.getChangedAnnot(); int trans_count = gene.size(); for (int i = 0; i < trans_count; i++) { Transcript t = (Transcript) gene.getFeatureAt (i); editorPanel.detachTranscript (t); if (t == currentAnnot) currentAnnot = null; } } else if (evt.isDelete() && evt.isTranscriptChange()) { Transcript t = (Transcript) evt.getChangedAnnot(); editorPanel.detachTranscript (t); if (t == currentAnnot) currentAnnot = null; } else if ((evt.isAdd() || evt.isSplit() || evt.isMerge()) && evt.isRootAnnotChange()) { AnnotatedFeatureI gene = evt.getChangedAnnot(); int trans_count = gene.size(); for (int i = 0; i < trans_count; i++) { Transcript t = (Transcript) gene.getFeatureAt (i); int tier = editorPanel.attachAnnot (t); } } else if (evt.isAdd() && evt.isTranscriptChange()) { Transcript t = (Transcript) evt.getChangedAnnot(); int tier = editorPanel.attachAnnot (t); } // Exon split or intron made - same thing isnt it? else if (evt.isAdd() && evt.isExonChange()) { Transcript t = (Transcript) evt.getParentFeature(); // removing and adding transcript will force editorPanel // to pick up new exon editorPanel.detachTranscript(t); editorPanel.attachAnnot(t); } else if (evt.isDelete() && evt.isExonChange()) { Transcript t = (Transcript) evt.getParentFeature(); // removing and adding transcript will force editorPanel to remove exon editorPanel.detachTranscript(t); editorPanel.attachAnnot(t); // or editorPanel.removeFeature((Exon)evt.getSecondFeature()); } // else if (evt.isReplace()) { //&&evt.isTopAnnotChange - always true of replace // AnnotatedFeatureI old_gene = evt.getReplacedFeature(); // AnnotatedFeatureI new_gene = (AnnotatedFeatureI)evt.getChangedFeature(); // int trans_count = old_gene.size(); // /* This does assume that there are no changes in the number // of transcripts between the old and the new. Might be safer // to separate the 2 loops */ // for (int i = 0; i < trans_count; i++) { // Transcript t; // t = (Transcript) old_gene.getFeatureAt (i); // editorPanel.detachTranscript (t); // t = (Transcript) new_gene.getFeatureAt (i); // int tier = editorPanel.attachTranscript (t); // } // // This is so that we don't select a different transcript // AnnotatedFeatureI current_gene = (current_transcript != null ? // current_transcript.getGene() : null); // if (current_gene != null && current_gene == old_gene) { // int index = current_gene.getFeatureIndex(current_transcript); // current_transcript = (Transcript) new_gene.getFeatureAt(index); // } // } // this isnt possible - all replaces are for top annots // else if<SUF> // Transcript old_trans = (Transcript)evt.getReplacedFeature(); // Transcript new_trans = (Transcript)evt.getChangedFeature(); // editorPanel.detachTranscript (old_trans); // int tier = editorPanel.attachTranscript (new_trans); // // This is so that we don't select a different transcript // if (current_transcript != null && current_transcript == old_trans) { // current_transcript = new_trans; // } // } } return true; } /** Handle the selection event (feature was selected in another window--select it here) This is also where selections from BaseFineEditor come in which are really internal selections. Only handle external selection if followSelection is checked */ public boolean handleFeatureSelectionEvent (FeatureSelectionEvent evt) { if (!canHandleSelection(evt,this)) return false; // now we do something, canHanSel filters for GenAnnIs AnnotatedFeatureI gai = (AnnotatedFeatureI)evt.getFeatures().getFeature(0); displayAnnot(getTransOrOneLevelAnn(gai)); translationViewer.repaint(); return true; } /** Does all the handle selection checks for BaseFineEditor and BaseEditorPanel */ boolean canHandleSelection(FeatureSelectionEvent evt,Object self) { if ((noExternalSelection() && isExternalSelection(evt)) && !evt.forceSelection()) return false; if (evt.getSource() == self) return false; if (!this.isVisible()) return false; if (evt.getFeatures().size() == 0) return false; SeqFeatureI sf = evt.getFeatures().getFeature(0); // if strand of selection is not our strand return boolean is_reverse = (sf.getStrand() == -1); if (is_reverse != editorPanel.getReverseStrand()) return false; if ( ! (sf instanceof AnnotatedFeatureI)) return false;//repaint transVw? else return true; } /** True if the selection comes from outside world. false if from this OR editorPanel */ private boolean isExternalSelection(FeatureSelectionEvent e) { if (e.getSource() == this || e.getSource() == editorPanel) return false; return true; } private boolean noExternalSelection() { return !followSelectionCheckBox.isSelected(); } public Color getIndicatorColor() { return indicatorColor; } /** puts up vertical lines in szap(main window) indicating the region EDE is * displaying - make private? */ private void showEditRegion() { colorIndex = (colorIndex + 1) % colorList.length; indicatorColor = colorList[colorIndex]; colorSwatch.setBackground(indicatorColor); szap.addHighlightRegion(editorPanel, indicatorColor, editorPanel.getReverseStrand()); } public void attachListeners() { // changeListener = new AnnotationChangeDoodad(); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { szap.removeHighlightRegion(editorPanel); szap.repaint(); BaseFineEditor.this.setVisible(false); } } ); clearFindsButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { editorPanel.setShowHitZones(false); clearFindsButton.setEnabled(false); } } ); findButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { editorPanel.showFindDialog(); } } ); goToButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { editorPanel.showGoToDialog(); } } ); showIntronBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { translationViewer. setDrawIntrons(showIntronBox.isSelected()); } } ); upstream_button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { selectAnnot(neighbor_up); } } ); downstream_button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { selectAnnot(neighbor_down); } } ); } private class FineEditorScrollListener implements ChangeListener { int oldstart = -1; int oldwidth = -1; public void stateChanged(ChangeEvent e) { szap.repaint(); translationViewer.repaint(); } } /** Dispose all editors currently in existence. Keeps track of all instances for this purpose */ public static void disposeAllEditors() { for (Iterator it = baseEditorInstanceList.iterator(); it.hasNext(); ) ((BaseFineEditor)it.next()).dispose(); baseEditorInstanceList.clear(); } private class BaseEditorDataListener implements DataLoadListener { public boolean handleDataLoadEvent(DataLoadEvent e) { if (!e.dataRetrievalBeginning()) return false; disposeAllEditors(); curationState.getController().removeListener(this); return true; } } public void dispose() { removeComponents(this); editorPanel.cleanup(); // 1.3.1 popup mem leak & remove listener szap.removeHighlightRegion(editorPanel); editorPanel = null; translationViewer = null; viewport.removeChangeListener(scrollListener); viewport = null; lengthLabel = null; //featureNameLabel = null; transcriptComboBox = null; szap = null; transformer = null; scrollListener = null; indicatorColor = null; colorSwatch = null; // changeListener = null; // removeWindowListener(windowListener); // windowListener = null; getController().removeListener(this); //getController() = null; //view = null; findButton = null; clearFindsButton = null; goToButton = null; upstream_button = null; downstream_button = null; super.dispose(); } private void initGui(AnnotatedFeatureI annot) { translationViewer = new TranslationViewer(editorPanel); translationViewer.setBackground(Color.black); transcriptComboBox = new JComboBox(); lengthLabel = new JLabel("Translation length: <no feature selected>"); lengthLabel.setForeground(Color.black); findButton = new JButton("Find sequence..."); // clearFindsBox = new JCheckBox("Show search hits"); clearFindsButton = new JButton("Clear search hits"); // Disable until we actually get search results clearFindsButton.setEnabled(false); goToButton = new JButton("GoTo..."); showIntronBox = new JCheckBox("Show introns in translation viewer", true); showIntronBox.setBackground (Color.white); followSelectionCheckBox = new JCheckBox("Follow external selection",false); followSelectionCheckBox.setBackground(Color.white); upstream_button = new JButton (); downstream_button = new JButton (); colorSwatch = new JPanel(); setSize(824,500); JScrollPane pane = new JScrollPane(editorPanel); pane.setHorizontalScrollBarPolicy( JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); pane.setRowHeaderView(new BaseFineEditorRowHeader(editorPanel)); viewport = pane.getViewport(); colorSwatch.setPreferredSize(new Dimension(10,10)); getContentPane().setBackground (Color.white); getContentPane().setLayout(new BorderLayout()); getContentPane().add(colorSwatch, "North"); getContentPane().add(pane, "Center"); Box transcriptListBox = new Box(BoxLayout.X_AXIS); JLabel tranLabel; // 1 LEVEL ANNOT if (annot.isAnnotTop()) tranLabel = new JLabel("Annotation: "); else // 3-level tranLabel = new JLabel("Transcript: "); tranLabel.setForeground(Color.black); transcriptListBox.add(Box.createHorizontalStrut(5)); transcriptListBox.add(tranLabel); transcriptListBox.setBackground(Color.white); transcriptComboBox.setMaximumSize(new Dimension(300,30)); transcriptListBox.add(transcriptComboBox); transcriptListBox.add(Box.createHorizontalGlue()); transcriptListBox.add(Box.createHorizontalStrut(5)); transcriptListBox.add(lengthLabel); transcriptListBox.add(Box.createHorizontalGlue()); Box checkboxesTop = new Box(BoxLayout.X_AXIS); checkboxesTop.setBackground (Color.white); checkboxesTop.add(Box.createHorizontalStrut(5)); checkboxesTop.add(findButton); checkboxesTop.add(Box.createHorizontalStrut(10)); checkboxesTop.add(clearFindsButton); checkboxesTop.add(Box.createHorizontalStrut(15)); checkboxesTop.add(goToButton); checkboxesTop.add(Box.createHorizontalGlue()); Box checkboxesBottom = new Box(BoxLayout.X_AXIS); checkboxesBottom.add(showIntronBox); checkboxesBottom.add(Box.createHorizontalGlue()); checkboxesBottom.add(Box.createHorizontalStrut(10)); checkboxesBottom.add(followSelectionCheckBox); Box checkboxes = new Box(BoxLayout.Y_AXIS); checkboxes.add(checkboxesTop); checkboxes.add(checkboxesBottom); Box labelPanel = new Box(BoxLayout.Y_AXIS); labelPanel.setBackground(Color.white); labelPanel.add(transcriptListBox); labelPanel.add(Box.createVerticalStrut(5)); labelPanel.add(checkboxes); Box navPanel = new Box(BoxLayout.Y_AXIS); navPanel.setBackground (Color.white); navPanel.add(upstream_button); navPanel.add(Box.createVerticalStrut(10)); navPanel.add(downstream_button); navPanel.add(Box.createVerticalGlue()); Box textBoxes = new Box(BoxLayout.X_AXIS); textBoxes.setBackground (Color.white); textBoxes.add(labelPanel); textBoxes.add(navPanel); Box detailPanel = new Box(BoxLayout.Y_AXIS); detailPanel.setBackground(Color.white); detailPanel.add(translationViewer); detailPanel.add(textBoxes); getContentPane().add(detailPanel, "South"); validateTree(); scrollListener = new FineEditorScrollListener(); viewport.addChangeListener(scrollListener); transcriptComboBox.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_U && (e.getModifiers() & KeyEvent.CTRL_MASK) != 0) { CurationManager.getActiveCurationState().getTransactionManager().undo(this); } } }); } /** Both fires off selection event and displays annot */ private void selectAnnot(AnnotatedFeatureI annot) { displayAnnot(getTransOrOneLevelAnn(annot)); translationViewer.repaint(); BaseFocusEvent evt = new BaseFocusEvent(this, annot.getStart(), annot); getController().handleBaseFocusEvent(evt); getSelectionManager().select(annot,this); // sends off selection } /** Display AnnotatedFeatureI feature. * Exon, Transcript, and Gene are all GenericAnnotationI. * No selection event is fired. (selectAnnot fires and displays) */ private void displayAnnot(AnnotatedFeatureI annot) { currentAnnot = annot; if (currentAnnot == null) { transcriptComboBox.removeAllItems(); transcriptComboBox.addItem("<no feature selected>"); lengthLabel.setText("Translation length: <no feature selected>"); upstream_button.setLabel(""); downstream_button.setLabel(""); translationViewer.setTranscript(null,editorPanel.getSelectedTier()); // ?? return; } //else { setupTranscriptComboBox(currentAnnot); SeqFeatureI topAnnot = currentAnnot; if (topAnnot.isTranscript()) topAnnot = currentAnnot.getRefFeature(); if (topAnnot.isProteinCodingGene()) { String translation = currentAnnot.translate(); if (translation == null) { lengthLabel.setText("Translation length: <no start selected>"); } else { lengthLabel.setText("Translation length: " + currentAnnot.translate().length()); } } else { lengthLabel.setText(topAnnot.getFeatureType() + " annotation"); } FeatureSetI holder = (FeatureSetI) topAnnot.getRefFeature(); neighbor_up = null; neighbor_down = null; if (holder != null) { int index = holder.getFeatureIndex(topAnnot); // get next neighbor up that has whole sequence for (int i = index-1; i >= 0 && neighbor_up==null; i--) { FeatureSetI gene_sib = (FeatureSetI) holder.getFeatureAt(i); if (gene_sib.getFeatureAt(0) instanceof Transcript) { Transcript trans = (Transcript) gene_sib.getFeatureAt(0); if (trans.haveWholeSequence())//szap.getCurationSet())) neighbor_up = trans; } } // get next neighbor down that has whole sequence for (int i = index+1; i < holder.size() && neighbor_down==null; i++) { FeatureSetI gene_sib = (FeatureSetI) holder.getFeatureAt(i); if (gene_sib.getFeatureAt(0) instanceof Transcript) { Transcript trans = (Transcript) gene_sib.getFeatureAt(0); if (trans.haveWholeSequence())//szap.getCurationSet())) neighbor_down = trans; } } } upstream_button.setLabel (neighbor_up == null ? "" : "Go to next 5' annotation (" + neighbor_up.getParent().getName()+")"); upstream_button.setVisible (neighbor_up != null); downstream_button.setLabel (neighbor_down == null ? "" : "Go to next 3' annotation (" + neighbor_down.getParent().getName()+")"); downstream_button.setVisible (neighbor_down != null); //} // todo - translationViewer take in 1 level annot if (currentAnnot.isTranscript()) translationViewer.setTranscript((Transcript)currentAnnot, editorPanel.getSelectedTier()); } /** Sets up transcriptComboBox (pulldown list) with transcript and * its parent gene's other transcripts, with transcript selected */ private void setupTranscriptComboBox(AnnotatedFeatureI annot) { // could also check for gene change before doing a removeAll if (transcriptComboBox.getSelectedItem() == annot) return; // adding and removing items causes item events to fire so need to remove // listener here - is there any other way to supress firing? transcriptComboBox.removeItemListener(transItemListener); transcriptComboBox.removeAllItems(); if (annot==null) { transcriptComboBox.addItem("<no feature selected>"); return; } // 1 LEVEL ANNOT if (annot.isAnnotTop()) { transcriptComboBox.addItem(annot); return; } // TRANSCRIPT SeqFeatureI gene = annot.getRefFeature(); Vector transcripts = gene.getFeatures(); for (int i=0; i<transcripts.size(); i++) transcriptComboBox.addItem(transcripts.elementAt(i)); transcriptComboBox.setSelectedItem(annot); // transcript transcriptComboBox.addItemListener(transItemListener); } private TranscriptComboBoxItemListener transItemListener = new TranscriptComboBoxItemListener(); private class TranscriptComboBoxItemListener implements ItemListener { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED && e.getItem() instanceof Transcript) selectAnnot((Transcript)e.getItem()); } } /** AssemblyFeature is the only GAI at the moment that has no relation to // a transcript. Dont think they can end up in ede (??). // Would be nice to have an interface that was solely for the exon // trans gene heirarchy? Should we actively make sure AssemblyFeatures dont // get into ede? (filter in AnnotationMenu?) returns null if no transcript can be found. */ private AnnotatedFeatureI getTransOrOneLevelAnn(AnnotatedFeatureI af) { if (af != null) { if (af.isTranscript()) return af; if (af.isExon()) return af.getRefFeature().getAnnotatedFeature(); if (af.isAnnotTop()) { if (af.hasKids()) return af.getFeatureAt(0).getAnnotatedFeature(); // transcript else // 1 level annot return af; } } return null; } }
44449_4
/** */ package de.urszeidler.eclipse.shr5.impl; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.ENotificationImpl; import de.urszeidler.eclipse.shr5.Schutzgeist; import de.urszeidler.eclipse.shr5.Shr5Package; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Schutzgeist</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link de.urszeidler.eclipse.shr5.impl.SchutzgeistImpl#getVorteile <em>Vorteile</em>}</li> * <li>{@link de.urszeidler.eclipse.shr5.impl.SchutzgeistImpl#getNachteile <em>Nachteile</em>}</li> * </ul> * </p> * * @generated */ public class SchutzgeistImpl extends MagischeModsImpl implements Schutzgeist { /** * The default value of the '{@link #getVorteile() <em>Vorteile</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getVorteile() * @generated * @ordered */ protected static final String VORTEILE_EDEFAULT = null; /** * The cached value of the '{@link #getVorteile() <em>Vorteile</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getVorteile() * @generated * @ordered */ protected String vorteile = VORTEILE_EDEFAULT; /** * The default value of the '{@link #getNachteile() <em>Nachteile</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getNachteile() * @generated * @ordered */ protected static final String NACHTEILE_EDEFAULT = null; /** * The cached value of the '{@link #getNachteile() <em>Nachteile</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getNachteile() * @generated * @ordered */ protected String nachteile = NACHTEILE_EDEFAULT; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected SchutzgeistImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return Shr5Package.Literals.SCHUTZGEIST; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getVorteile() { return vorteile; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setVorteile(String newVorteile) { String oldVorteile = vorteile; vorteile = newVorteile; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Shr5Package.SCHUTZGEIST__VORTEILE, oldVorteile, vorteile)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getNachteile() { return nachteile; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setNachteile(String newNachteile) { String oldNachteile = nachteile; nachteile = newNachteile; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Shr5Package.SCHUTZGEIST__NACHTEILE, oldNachteile, nachteile)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case Shr5Package.SCHUTZGEIST__VORTEILE: return getVorteile(); case Shr5Package.SCHUTZGEIST__NACHTEILE: return getNachteile(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case Shr5Package.SCHUTZGEIST__VORTEILE: setVorteile((String)newValue); return; case Shr5Package.SCHUTZGEIST__NACHTEILE: setNachteile((String)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case Shr5Package.SCHUTZGEIST__VORTEILE: setVorteile(VORTEILE_EDEFAULT); return; case Shr5Package.SCHUTZGEIST__NACHTEILE: setNachteile(NACHTEILE_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case Shr5Package.SCHUTZGEIST__VORTEILE: return VORTEILE_EDEFAULT == null ? vorteile != null : !VORTEILE_EDEFAULT.equals(vorteile); case Shr5Package.SCHUTZGEIST__NACHTEILE: return NACHTEILE_EDEFAULT == null ? nachteile != null : !NACHTEILE_EDEFAULT.equals(nachteile); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (vorteile: "); result.append(vorteile); result.append(", nachteile: "); result.append(nachteile); result.append(')'); return result.toString(); } } //SchutzgeistImpl
UrsZeidler/shr5rcp
de.urszeidler.shr5.model/src/de/urszeidler/eclipse/shr5/impl/SchutzgeistImpl.java
1,679
/** * The cached value of the '{@link #getNachteile() <em>Nachteile</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getNachteile() * @generated * @ordered */
block_comment
nl
/** */ package de.urszeidler.eclipse.shr5.impl; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.ENotificationImpl; import de.urszeidler.eclipse.shr5.Schutzgeist; import de.urszeidler.eclipse.shr5.Shr5Package; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Schutzgeist</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link de.urszeidler.eclipse.shr5.impl.SchutzgeistImpl#getVorteile <em>Vorteile</em>}</li> * <li>{@link de.urszeidler.eclipse.shr5.impl.SchutzgeistImpl#getNachteile <em>Nachteile</em>}</li> * </ul> * </p> * * @generated */ public class SchutzgeistImpl extends MagischeModsImpl implements Schutzgeist { /** * The default value of the '{@link #getVorteile() <em>Vorteile</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getVorteile() * @generated * @ordered */ protected static final String VORTEILE_EDEFAULT = null; /** * The cached value of the '{@link #getVorteile() <em>Vorteile</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getVorteile() * @generated * @ordered */ protected String vorteile = VORTEILE_EDEFAULT; /** * The default value of the '{@link #getNachteile() <em>Nachteile</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getNachteile() * @generated * @ordered */ protected static final String NACHTEILE_EDEFAULT = null; /** * The cached value<SUF>*/ protected String nachteile = NACHTEILE_EDEFAULT; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected SchutzgeistImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return Shr5Package.Literals.SCHUTZGEIST; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getVorteile() { return vorteile; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setVorteile(String newVorteile) { String oldVorteile = vorteile; vorteile = newVorteile; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Shr5Package.SCHUTZGEIST__VORTEILE, oldVorteile, vorteile)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getNachteile() { return nachteile; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setNachteile(String newNachteile) { String oldNachteile = nachteile; nachteile = newNachteile; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Shr5Package.SCHUTZGEIST__NACHTEILE, oldNachteile, nachteile)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case Shr5Package.SCHUTZGEIST__VORTEILE: return getVorteile(); case Shr5Package.SCHUTZGEIST__NACHTEILE: return getNachteile(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case Shr5Package.SCHUTZGEIST__VORTEILE: setVorteile((String)newValue); return; case Shr5Package.SCHUTZGEIST__NACHTEILE: setNachteile((String)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case Shr5Package.SCHUTZGEIST__VORTEILE: setVorteile(VORTEILE_EDEFAULT); return; case Shr5Package.SCHUTZGEIST__NACHTEILE: setNachteile(NACHTEILE_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case Shr5Package.SCHUTZGEIST__VORTEILE: return VORTEILE_EDEFAULT == null ? vorteile != null : !VORTEILE_EDEFAULT.equals(vorteile); case Shr5Package.SCHUTZGEIST__NACHTEILE: return NACHTEILE_EDEFAULT == null ? nachteile != null : !NACHTEILE_EDEFAULT.equals(nachteile); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (vorteile: "); result.append(vorteile); result.append(", nachteile: "); result.append(nachteile); result.append(')'); return result.toString(); } } //SchutzgeistImpl
22324_16
/* * Copyright (c) 2015-2017 Privacy Vandaag / Privacy Barometer * * Copyright (c) 2015 Arnaud Renaud-Goud * Copyright (c) 2012-2015 Frederic Julian * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package nl.privacybarometer.privacyvandaag.utils; import android.content.Context; import android.content.Intent; import android.text.TextUtils; import nl.privacybarometer.privacyvandaag.Constants; import nl.privacybarometer.privacyvandaag.MainApplication; import nl.privacybarometer.privacyvandaag.service.FetcherService; import org.jsoup.Jsoup; import org.jsoup.safety.Whitelist; import java.io.File; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; public class HtmlUtils { private static final String TAG = HtmlUtils.class.getSimpleName() + " ~> "; private static final Whitelist JSOUP_WHITELIST = Whitelist.relaxed().addTags("iframe", "video", "audio", "source", "track") .addAttributes("iframe", "src", "frameborder", "height", "width") .addAttributes("video", "src", "controls", "height", "width", "poster") .addAttributes("audio", "src", "controls") .addAttributes("source", "src", "type") .addAttributes("track", "src", "kind", "srclang", "label"); private static final String URL_SPACE = "%20"; private static final Pattern IMG_PATTERN = Pattern.compile("<img\\s+[^>]*src=\\s*['\"]([^'\"]+)['\"][^>]*>", Pattern.CASE_INSENSITIVE); private static final Pattern ADS_PATTERN = Pattern.compile("<div class=('|\")mf-viral('|\")><table border=('|\")0('|\")>.*", Pattern.CASE_INSENSITIVE); private static final Pattern LAZY_LOADING_PATTERN = Pattern.compile("\\s+src=[^>]+\\s+original[-]*src=(\"|')", Pattern.CASE_INSENSITIVE); private static final Pattern EMPTY_IMAGE_PATTERN = Pattern.compile("<img\\s+(height=['\"]1['\"]\\s+width=['\"]1['\"]|width=['\"]1['\"]\\s+height=['\"]1['\"])\\s+[^>]*src=\\s*['\"]([^'\"]+)['\"][^>]*>", Pattern.CASE_INSENSITIVE); private static final Pattern NON_HTTP_IMAGE_PATTERN = Pattern.compile("\\s+(href|src)=(\"|')//", Pattern.CASE_INSENSITIVE); private static final Pattern BAD_IMAGE_PATTERN = Pattern.compile("<img\\s+[^>]*src=\\s*['\"]([^'\"]+)\\.img['\"][^>]*>", Pattern.CASE_INSENSITIVE); private static final Pattern START_BR_PATTERN = Pattern.compile("^(\\s*<br\\s*[/]*>\\s*)*", Pattern.CASE_INSENSITIVE); private static final Pattern END_BR_PATTERN = Pattern.compile("(\\s*<br\\s*[/]*>\\s*)*$", Pattern.CASE_INSENSITIVE); private static final Pattern MULTIPLE_BR_PATTERN = Pattern.compile("(\\s*<br\\s*[/]*>\\s*){3,}", Pattern.CASE_INSENSITIVE); private static final Pattern EMPTY_LINK_PATTERN = Pattern.compile("<a\\s+[^>]*></a>", Pattern.CASE_INSENSITIVE); private static final Pattern REMOVE_BEFORE_H1_PATTERN = Pattern.compile("<p>(.+?)</h1>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE ); private static final Pattern REMOVE_H1_PATTERN = Pattern.compile("<h1>(.+?)</h1>", Pattern.CASE_INSENSITIVE); public static String improveHtmlContent(String content, String baseUri) { content = ADS_PATTERN.matcher(content).replaceAll(""); if (content != null) { // remove some ads content = ADS_PATTERN.matcher(content).replaceAll(""); // remove lazy loading images stuff content = LAZY_LOADING_PATTERN.matcher(content).replaceAll(" src=$1"); // clean by JSoup. Remove all non-whitelisted tags. Return safe HTML // This removes also all the classes and id's within the html-tags content = Jsoup.clean(content, baseUri, JSOUP_WHITELIST); // Log.e(TAG, "De opgeschoonde inhoud ziet er nu zo uit: " + content); // remove empty or bad images content = EMPTY_IMAGE_PATTERN.matcher(content).replaceAll(""); content = BAD_IMAGE_PATTERN.matcher(content).replaceAll(""); // remove empty links content = EMPTY_LINK_PATTERN.matcher(content).replaceAll(""); // fix non http image paths content = NON_HTTP_IMAGE_PATTERN.matcher(content).replaceAll(" $1=$2http://"); // remove trailing BR & too much BR content = START_BR_PATTERN.matcher(content).replaceAll(""); // TODO: quick (and dirty) fix for #11. I HAVE TO FIND ANOTHER SOLUTION !! //content = END_BR_PATTERN.matcher(content).replaceAll(""); // TODO: end of fix for #11 content = MULTIPLE_BR_PATTERN.matcher(content).replaceAll("<br><br>"); // remove all text before the <h1>. Sometimes there is a subtitel or date content = REMOVE_BEFORE_H1_PATTERN.matcher(content).replaceAll(""); // remove <h1> from document, because title is given seperately in rss feed. // TODO: If former match is made, this match is superfluous content = REMOVE_H1_PATTERN.matcher(content).replaceAll(""); // Log.e (TAG, "De gecorrigeerde inhoud ziet er nu zo uit: " + content); } return content; } public static ArrayList<String> getImageURLs(String content) { ArrayList<String> images = new ArrayList<>(); if (!TextUtils.isEmpty(content)) { Matcher matcher = IMG_PATTERN.matcher(content); while (matcher.find()) { images.add(matcher.group(1).replace(" ", URL_SPACE)); } } return images; } public static String replaceImageURLs(String content, final long entryId) { if (!TextUtils.isEmpty(content)) { // Check settings if we should display and/or download images. boolean needDownloadPictures = NetworkUtils.needDownloadPictures(); final ArrayList<String> imagesToDl = new ArrayList<>(); // Regex to match the img tags in the HTML web content Matcher matcher = IMG_PATTERN.matcher(content); while (matcher.find()) { // find a match with the regex and store the image source in 'match'. String match = matcher.group(1).replace(" ", URL_SPACE); String imgPath = NetworkUtils.getDownloadedImagePath(entryId, match); if (new File(imgPath).exists()) { content = content.replace(match, Constants.FILE_SCHEME + imgPath); } else if (needDownloadPictures) { imagesToDl.add(match); } } // Download the images if needed if (!imagesToDl.isEmpty()) { new Thread(new Runnable() { @Override public void run() { FetcherService.addImagesToDownload(String.valueOf(entryId), imagesToDl); Context context = MainApplication.getContext(); context.startService(new Intent(context, FetcherService.class).setAction(FetcherService.ACTION_DOWNLOAD_IMAGES)); } }).start(); } } return content; } public static String getMainImageURL(String content) { if (!TextUtils.isEmpty(content)) { Matcher matcher = IMG_PATTERN.matcher(content); while (matcher.find()) { String imgUrl = matcher.group(1).replace(" ", URL_SPACE); if (isCorrectImage(imgUrl)) { return imgUrl; } } } return null; } public static String getMainImageURL(ArrayList<String> imgUrls) { for (String imgUrl : imgUrls) { if (isCorrectImage(imgUrl)) { return imgUrl; } } return null; } // Some image types cannot be shown. private static boolean isCorrectImage(String imgUrl) { return (( ! imgUrl.endsWith(".gif")) && ( ! imgUrl.endsWith(".GIF")) && ( ! imgUrl.endsWith(".img")) && ( ! imgUrl.endsWith(".IMG")) ); } }
PrivacyVandaag/PrivacyVandaag
mobile/src/main/java/nl/privacybarometer/privacyvandaag/utils/HtmlUtils.java
2,226
// Log.e (TAG, "De gecorrigeerde inhoud ziet er nu zo uit: " + content);
line_comment
nl
/* * Copyright (c) 2015-2017 Privacy Vandaag / Privacy Barometer * * Copyright (c) 2015 Arnaud Renaud-Goud * Copyright (c) 2012-2015 Frederic Julian * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package nl.privacybarometer.privacyvandaag.utils; import android.content.Context; import android.content.Intent; import android.text.TextUtils; import nl.privacybarometer.privacyvandaag.Constants; import nl.privacybarometer.privacyvandaag.MainApplication; import nl.privacybarometer.privacyvandaag.service.FetcherService; import org.jsoup.Jsoup; import org.jsoup.safety.Whitelist; import java.io.File; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; public class HtmlUtils { private static final String TAG = HtmlUtils.class.getSimpleName() + " ~> "; private static final Whitelist JSOUP_WHITELIST = Whitelist.relaxed().addTags("iframe", "video", "audio", "source", "track") .addAttributes("iframe", "src", "frameborder", "height", "width") .addAttributes("video", "src", "controls", "height", "width", "poster") .addAttributes("audio", "src", "controls") .addAttributes("source", "src", "type") .addAttributes("track", "src", "kind", "srclang", "label"); private static final String URL_SPACE = "%20"; private static final Pattern IMG_PATTERN = Pattern.compile("<img\\s+[^>]*src=\\s*['\"]([^'\"]+)['\"][^>]*>", Pattern.CASE_INSENSITIVE); private static final Pattern ADS_PATTERN = Pattern.compile("<div class=('|\")mf-viral('|\")><table border=('|\")0('|\")>.*", Pattern.CASE_INSENSITIVE); private static final Pattern LAZY_LOADING_PATTERN = Pattern.compile("\\s+src=[^>]+\\s+original[-]*src=(\"|')", Pattern.CASE_INSENSITIVE); private static final Pattern EMPTY_IMAGE_PATTERN = Pattern.compile("<img\\s+(height=['\"]1['\"]\\s+width=['\"]1['\"]|width=['\"]1['\"]\\s+height=['\"]1['\"])\\s+[^>]*src=\\s*['\"]([^'\"]+)['\"][^>]*>", Pattern.CASE_INSENSITIVE); private static final Pattern NON_HTTP_IMAGE_PATTERN = Pattern.compile("\\s+(href|src)=(\"|')//", Pattern.CASE_INSENSITIVE); private static final Pattern BAD_IMAGE_PATTERN = Pattern.compile("<img\\s+[^>]*src=\\s*['\"]([^'\"]+)\\.img['\"][^>]*>", Pattern.CASE_INSENSITIVE); private static final Pattern START_BR_PATTERN = Pattern.compile("^(\\s*<br\\s*[/]*>\\s*)*", Pattern.CASE_INSENSITIVE); private static final Pattern END_BR_PATTERN = Pattern.compile("(\\s*<br\\s*[/]*>\\s*)*$", Pattern.CASE_INSENSITIVE); private static final Pattern MULTIPLE_BR_PATTERN = Pattern.compile("(\\s*<br\\s*[/]*>\\s*){3,}", Pattern.CASE_INSENSITIVE); private static final Pattern EMPTY_LINK_PATTERN = Pattern.compile("<a\\s+[^>]*></a>", Pattern.CASE_INSENSITIVE); private static final Pattern REMOVE_BEFORE_H1_PATTERN = Pattern.compile("<p>(.+?)</h1>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE ); private static final Pattern REMOVE_H1_PATTERN = Pattern.compile("<h1>(.+?)</h1>", Pattern.CASE_INSENSITIVE); public static String improveHtmlContent(String content, String baseUri) { content = ADS_PATTERN.matcher(content).replaceAll(""); if (content != null) { // remove some ads content = ADS_PATTERN.matcher(content).replaceAll(""); // remove lazy loading images stuff content = LAZY_LOADING_PATTERN.matcher(content).replaceAll(" src=$1"); // clean by JSoup. Remove all non-whitelisted tags. Return safe HTML // This removes also all the classes and id's within the html-tags content = Jsoup.clean(content, baseUri, JSOUP_WHITELIST); // Log.e(TAG, "De opgeschoonde inhoud ziet er nu zo uit: " + content); // remove empty or bad images content = EMPTY_IMAGE_PATTERN.matcher(content).replaceAll(""); content = BAD_IMAGE_PATTERN.matcher(content).replaceAll(""); // remove empty links content = EMPTY_LINK_PATTERN.matcher(content).replaceAll(""); // fix non http image paths content = NON_HTTP_IMAGE_PATTERN.matcher(content).replaceAll(" $1=$2http://"); // remove trailing BR & too much BR content = START_BR_PATTERN.matcher(content).replaceAll(""); // TODO: quick (and dirty) fix for #11. I HAVE TO FIND ANOTHER SOLUTION !! //content = END_BR_PATTERN.matcher(content).replaceAll(""); // TODO: end of fix for #11 content = MULTIPLE_BR_PATTERN.matcher(content).replaceAll("<br><br>"); // remove all text before the <h1>. Sometimes there is a subtitel or date content = REMOVE_BEFORE_H1_PATTERN.matcher(content).replaceAll(""); // remove <h1> from document, because title is given seperately in rss feed. // TODO: If former match is made, this match is superfluous content = REMOVE_H1_PATTERN.matcher(content).replaceAll(""); // Log.e (TAG,<SUF> } return content; } public static ArrayList<String> getImageURLs(String content) { ArrayList<String> images = new ArrayList<>(); if (!TextUtils.isEmpty(content)) { Matcher matcher = IMG_PATTERN.matcher(content); while (matcher.find()) { images.add(matcher.group(1).replace(" ", URL_SPACE)); } } return images; } public static String replaceImageURLs(String content, final long entryId) { if (!TextUtils.isEmpty(content)) { // Check settings if we should display and/or download images. boolean needDownloadPictures = NetworkUtils.needDownloadPictures(); final ArrayList<String> imagesToDl = new ArrayList<>(); // Regex to match the img tags in the HTML web content Matcher matcher = IMG_PATTERN.matcher(content); while (matcher.find()) { // find a match with the regex and store the image source in 'match'. String match = matcher.group(1).replace(" ", URL_SPACE); String imgPath = NetworkUtils.getDownloadedImagePath(entryId, match); if (new File(imgPath).exists()) { content = content.replace(match, Constants.FILE_SCHEME + imgPath); } else if (needDownloadPictures) { imagesToDl.add(match); } } // Download the images if needed if (!imagesToDl.isEmpty()) { new Thread(new Runnable() { @Override public void run() { FetcherService.addImagesToDownload(String.valueOf(entryId), imagesToDl); Context context = MainApplication.getContext(); context.startService(new Intent(context, FetcherService.class).setAction(FetcherService.ACTION_DOWNLOAD_IMAGES)); } }).start(); } } return content; } public static String getMainImageURL(String content) { if (!TextUtils.isEmpty(content)) { Matcher matcher = IMG_PATTERN.matcher(content); while (matcher.find()) { String imgUrl = matcher.group(1).replace(" ", URL_SPACE); if (isCorrectImage(imgUrl)) { return imgUrl; } } } return null; } public static String getMainImageURL(ArrayList<String> imgUrls) { for (String imgUrl : imgUrls) { if (isCorrectImage(imgUrl)) { return imgUrl; } } return null; } // Some image types cannot be shown. private static boolean isCorrectImage(String imgUrl) { return (( ! imgUrl.endsWith(".gif")) && ( ! imgUrl.endsWith(".GIF")) && ( ! imgUrl.endsWith(".img")) && ( ! imgUrl.endsWith(".IMG")) ); } }
88976_2
/*- * #%L * WollMux * %% * Copyright (C) 2005 - 2023 Landeshauptstadt München and LibreOffice contributors * %% * Licensed under the EUPL, Version 1.1 or – as soon they will be * approved by the European Commission - subsequent versions of the * EUPL (the "Licence"); * * You may not use this work except in compliance with the Licence. * You may obtain a copy of the Licence at: * * http://ec.europa.eu/idabc/eupl5 * * Unless required by applicable law or agreed to in writing, software * distributed under the Licence is distributed on an "AS IS" basis, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Licence for the specific language governing permissions and * limitations under the Licence. * #L% */ package org.libreoffice.lots.former; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.InputMap; import javax.swing.KeyStroke; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultHighlighter; import javax.swing.text.Highlighter; import javax.swing.text.JTextComponent; import org.libreoffice.lots.config.ConfigThingy; import org.libreoffice.lots.util.L; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Erweiterte eine JTextComponent um die Fähigkeit, Tags, die als * &quot;&lt;tag&gt;&quot; angezeigt werden, wie atomare Elemente zu behandeln. */ public class TextComponentTags { private static final Logger LOGGER = LoggerFactory.getLogger(TextComponentTags.class); /** * Syntax für {@link #getContent(int)}: CAT(... VALUE "&lt;tagname&gt;" ... VALUE * "&lt;tagname"&gt; ...) */ public static final int CAT_VALUE_SYNTAX = 0; /** * Präfix, mit dem Tags in der Anzeige der Zuordnung angezeigt werden. Die * Zuordnung beginnt mit einem zero width space (nicht sichtbar, aber zur * Unterscheidung des Präfix von den Benutzereingaben) und dem "<"-Zeichen. */ private static final String TAG_PREFIX = "" + Character.toChars(0x200B)[0] + "<"; /** * Suffix, mit dem Tags in der Anzeige der Zuordnung angezeigt werden. Die * Zuordnung beginnt mit einem zero width space (nicht sichtbar, aber zur * Unterscheidung des Präfix von den Benutzereingaben) und dem ">"-Zeichen. */ private static final String TAG_SUFFIX = "" + Character.toChars(0x200B)[0] + ">"; /** * Beschreibt einen regulären Ausdruck, mit dem nach Tags im Text gesucht * werden kann. Ein Match liefert in Gruppe 1 den Text des Tags. */ private static final Pattern TAG_PATTERN = Pattern.compile("(" + TAG_PREFIX + "(.*?)" + TAG_SUFFIX + ")"); /** * Farbe, mit dem der Hintergund eines Textfeldes im Dialog "Felder anpassen" * eingefärbt wird, wenn ein ungültiger Inhalt enthalten ist. */ private static final Color invalidEntryBGColor = Color.PINK; /** * Die JTextComponent, die durch diese Wrapperklasse erweitert wird. */ private JTextComponent compo; /** * Enthält das tag das beim Erzeugen des Extra-Highlights zurückgeliefert * wurde und das Highlight-Objekt auszeichnet. */ private Object extraHighlightTag = null; /** * Erzeugt den Wrapper und nimmt die notwendigen Änderungen am * Standardverhalten der JTextComponent component vor. */ public TextComponentTags(JTextComponent component) { this.compo = component; changeInputMap(); changeCaretHandling(); changeFocusLostHandling(); changeDocumentUpdateHandling(); } /** * Fügt an der aktuellen Cursorposition ein neues Tag tag ein, das * anschließend mit der Darstellung &quot;&lt;tag&gt;&quot; angezeigt wird und * bezüglich der Editierung wie ein atomares Element behandelt wird. * * @param tag * Der Name des tags, das in dieser JTextComponent an der * Cursorposition eingefügt und angezeigt werden soll. */ public void insertTag(String tag) { String t = compo.getText(); int inspos = compo.getCaretPosition(); String p1 = (inspos > 0) ? t.substring(0, inspos) : ""; String p2 = (inspos < t.length()) ? t.substring(inspos, t.length()) : ""; // ACHTUNG! Änderungen hier müssen auch in setContent() gemacht werden t = TAG_PREFIX + tag + TAG_SUFFIX; compo.setText(p1 + t + p2); compo.getCaret().setDot(inspos + t.length()); extraHighlight(inspos, inspos + t.length()); } /** * Liefert die JTextComponent, die durch diesen Wrapper erweitert wird. */ public JTextComponent getJTextComponent() { return compo; } /** * Liefert eine Liste von {@link ContentElement}-Objekten, die den aktuellen * Inhalt der JTextComponent repräsentiert und dabei enthaltenen Text und * evtl. enthaltene Tags als eigene Objekte kapselt. */ public List<ContentElement> getContent() { List<ContentElement> list = new ArrayList<>(); String t = compo.getText(); Matcher m = TAG_PATTERN.matcher(t); int lastEndPos = 0; int startPos = 0; while (m.find()) { startPos = m.start(); String tag = m.group(2); list.add(new ContentElement(t.substring(lastEndPos, startPos), false)); if (tag.length() > 0) { list.add(new ContentElement(tag, true)); } lastEndPos = m.end(); } String text = t.substring(lastEndPos); if (text.length() > 0) { list.add(new ContentElement(text, false)); } return list; } /** * Liefert den Inhalt der Textkomponente in der durch syntaxType * spezifizierten Syntax. * * @see #CAT_VALUE_SYNTAX * @throws IllegalArgumentException * falls der syntaxType nicht existiert. */ public ConfigThingy getContent(int syntaxType) { if (syntaxType != CAT_VALUE_SYNTAX) throw new IllegalArgumentException(L.m("Unknown syntaxType: {0}", "" + syntaxType)); ConfigThingy conf = new ConfigThingy("CAT"); List<ContentElement> content = getContent(); if (content.isEmpty()) { conf.add(""); } else { Iterator<ContentElement> iter = content.iterator(); while (iter.hasNext()) { ContentElement ele = iter.next(); if (ele.isTag()) conf.add("VALUE").add(ele.toString()); else conf.add(ele.toString()); } } return conf; } /** * Liefert den Inhalt der TextComponentTag als String mit aufgelösten Tags, * wobei an Stelle jedes Tags der entsprechende Inhalt eingesetzt wird, der in * mapTagToValue unter dem Schlüssel des Tagnamens gefunden wird oder der * String "&lt;tagname&gt;", wenn das Tag nicht aufgelöst werden kann. * * @param mapTagToValue * Map mit Schlüssel-/Wertpaaren, die die entsprechenden Werte für * die Tags enthält. * @return Inhalt der TextComponentTag als String mit aufgelösten Tags (soweit * möglich). */ public String getContent(Map<String, String> mapTagToValue) { StringBuilder buf = new StringBuilder(); for (ContentElement el : getContent()) { if (el.isTag()) { String key = el.toString(); String value = mapTagToValue.get(key); if (value != null) buf.append(mapTagToValue.get(key)); else buf.append("<" + key + ">"); } else { buf.append(el.toString()); } } return buf.toString(); } /** * Das Gegenstück zu {@link #getContent(int)}. * * @throws IllegalArgumentException * wenn syntaxType illegal oder ein Fehler in conf ist. */ public void setContent(int syntaxType, ConfigThingy conf) { if (syntaxType != CAT_VALUE_SYNTAX) throw new IllegalArgumentException(L.m("Unknown syntaxType: {0}", "" + syntaxType)); if (!"CAT".equals(conf.getName())) throw new IllegalArgumentException(L.m("Topmost node must be \"CAT\"")); StringBuilder buffy = new StringBuilder(); Iterator<ConfigThingy> iter = conf.iterator(); while (iter.hasNext()) { ConfigThingy subConf = iter.next(); if ("VALUE".equals(subConf.getName()) && subConf.count() == 1) { // ACHTUNG! Änderungen hier müssen auch in insertTag() gemacht werden buffy.append(TAG_PREFIX); buffy.append(subConf.toString()); buffy.append(TAG_SUFFIX); } else { buffy.append(subConf.toString()); } } extraHighlightOff(); compo.setText(buffy.toString()); } /** * Liefert zur String-Liste fieldNames eine Liste von Actions, die die * entsprechenden Strings in text einfügen. */ public static List<Action> makeInsertFieldActions(List<String> fieldNames, final TextComponentTags text) { List<Action> actions = new ArrayList<>(); Iterator<String> iter = fieldNames.iterator(); while (iter.hasNext()) { final String name = iter.next(); Action action = new AbstractAction(name) { private static final long serialVersionUID = -9123184290299840565L; @Override public void actionPerformed(ActionEvent e) { text.insertTag(name); } }; actions.add(action); } return actions; } /** * Kann überschrieben werden um eine Logik zu hinterlegen, die berechnet, ob * das Feld einen gültigen Inhalt besitzt. Ist der Inhalt nicht gültig, dann * wird das Feld mit einem roten Hintergrund hinterlegt. * * @return true, wenn der Inhalt gültig ist und false, wenn der Inhalt nicht * gültig ist. */ public boolean isContentValid() { return true; } /** * Beschreibt ein Element des Inhalts dieser JTextComponent und kann entweder * ein eingefügtes Tag oder ein normaler String sein. Auskunft über den Typ * des Elements erteilt die Methode isTag(), auf den String-Wert kann über die * toString()-Methode zugegriffen werden. */ public static class ContentElement { private String value; private boolean isTag; private ContentElement(String value, boolean isTag) { this.value = value; this.isTag = isTag; } @Override public String toString() { return value; } /** * Liefert true, wenn dieses Element ein Tag ist oder false, wenn es sich um * normalen Text handelt. */ public boolean isTag() { return isTag; } } /** * Immer wenn der Cursor mit der Maus in einen Bereich innerhalb eines Tags * gesetzt wird, sorgt der hier registrierte caret Listener dafür, dass der * Bereich auf das gesamte Tag ausgedehnt wird. */ private void changeCaretHandling() { compo.addCaretListener(event -> { extraHighlightOff(); int dot = compo.getCaret().getDot(); int mark = compo.getCaret().getMark(); for (TagPos fp : getTagPos()) { if (dot > fp.start && dot < fp.end) { if (dot < mark) { caretMoveDot(fp.start); } else if (dot > mark) { caretMoveDot(fp.end); } else { caretSetDot(fp.end); extraHighlight(fp.start, fp.end); } } } }); } /** * Der FocusLostListener wird hier registriert, damit nach einem FocusLost ein * evtl. gesetztes Extra-Highlight aufgehoben werden kann. */ private void changeFocusLostHandling() { compo.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { extraHighlightOff(); } }); } /** * Implementiert die Aktionen für die Tastendrücke Cursor-links, * Cursor-rechts, Delete und Backspace neu und berücksichtigt dabei die * atomaren Tags. */ private void changeInputMap() { String goLeftKeyStroke = "goLeft"; String goRightKeyStroke = "goRight"; String expandLeftKeyStroke = "expandLeft"; String expandRightKeyStroke = "expandRight"; String deleteLeftKeyStroke = "deleteLeft"; String deleteRightKeyStroke = "deleteRight"; InputMap m = compo.getInputMap(); m.put(KeyStroke.getKeyStroke("LEFT"), goLeftKeyStroke); m.put(KeyStroke.getKeyStroke("RIGHT"), goRightKeyStroke); m.put(KeyStroke.getKeyStroke("shift LEFT"), expandLeftKeyStroke); m.put(KeyStroke.getKeyStroke("shift RIGHT"), expandRightKeyStroke); m.put(KeyStroke.getKeyStroke("DELETE"), deleteRightKeyStroke); m.put(KeyStroke.getKeyStroke("BACK_SPACE"), deleteLeftKeyStroke); compo.getActionMap().put(goLeftKeyStroke, new GoAction(goLeftKeyStroke, true)); compo.getActionMap().put(goRightKeyStroke, new GoAction(goRightKeyStroke, false)); compo.getActionMap().put(expandLeftKeyStroke, new ExpandAction(expandLeftKeyStroke, true)); compo.getActionMap().put(expandRightKeyStroke, new ExpandAction(expandRightKeyStroke, false)); compo.getActionMap().put(deleteRightKeyStroke, new DeleteAction(deleteRightKeyStroke, false)); compo.getActionMap().put(deleteLeftKeyStroke, new DeleteAction(deleteLeftKeyStroke, true)); } /** * Der hier registrierte DocumentListener sorgt dafür, dass nach jeder * Textänderung geprüft wird, ob der Inhalt der JTextComponent noch gültig ist * und im Fehlerfall mit der Hintergrundfarbe invalidEntryBGColor eingefärbt * wird. */ private void changeDocumentUpdateHandling() { compo.getDocument().addDocumentListener(new DocumentListener() { private Color oldColor = null; @Override public void changedUpdate(DocumentEvent e) { update(); } @Override public void removeUpdate(DocumentEvent e) { update(); } @Override public void insertUpdate(DocumentEvent e) { update(); } private void update() { if (isContentValid()) { if (oldColor != null) { compo.setBackground(oldColor); } } else { if (oldColor == null) { oldColor = compo.getBackground(); } compo.setBackground(invalidEntryBGColor); } } }); } /** * Macht das selbe wie getCaret().setDot(pos), aber nur wenn pos >= 0 und pos * <= getText().length() gilt. */ private void caretSetDot(int pos) { if (pos >= 0 && pos <= compo.getText().length()) { compo.getCaret().setDot(pos); } } /** * Macht das selbe wie getCaret().setDot(pos), aber nur wenn pos >= 0 und pos * <= getText().length() gilt. */ private void caretMoveDot(int pos) { if (pos >= 0 && pos <= compo.getText().length()) { compo.getCaret().moveDot(pos); } } /** * Diese Klasse beschreibt die Position eines Tags innerhalb des Textes der * JTextComponent. */ static class TagPos { public final String name; public final int start; public final int end; TagPos(int start, int end, String name) { this.start = start; this.end = end; this.name = name; } } /** * Liefert einen Iterator von TagPos-Elementen, die beschreiben an welcher * Position im aktuellen Text Tags gefunden werden. */ private List<TagPos> getTagPos() { List<TagPos> results = new ArrayList<>(); Matcher m = TAG_PATTERN.matcher(compo.getText()); while (m.find()) { results.add(new TagPos(m.start(1), m.end(1), m.group(2))); } return results; } /** * Deaktiviert die Anzeige des Extra-Highlights. */ private void extraHighlightOff() { if (extraHighlightTag != null) { Highlighter hl = compo.getHighlighter(); hl.removeHighlight(extraHighlightTag); extraHighlightTag = null; } } /** * Highlightet den Textbereich zwischen pos1 und pos2 * * @param pos1 * @param pos2 */ private void extraHighlight(int pos1, int pos2) { Highlighter hl = compo.getHighlighter(); try { if (extraHighlightTag == null) { Highlighter.HighlightPainter hp = new DefaultHighlighter.DefaultHighlightPainter(new Color(0xddddff)); extraHighlightTag = hl.addHighlight(pos1, pos2, hp); } else { hl.changeHighlight(extraHighlightTag, pos1, pos2); } } catch (BadLocationException e1) { LOGGER.trace("", e1); } } private class GoAction extends AbstractAction { private static final long serialVersionUID = 2098288193497911628L; boolean isGoLeft; public GoAction(String name, boolean isGoLeft) { super(name); this.isGoLeft = isGoLeft; } @Override public void actionPerformed(ActionEvent evt) { extraHighlightOff(); int dot = compo.getCaret().getDot(); // evtl. vorhandenes Tag überspringen for (TagPos fp : getTagPos()) { int end = fp.end; int start = fp.start; if (!isGoLeft) { end = fp.start; start = fp.end; } if (dot == end) { caretSetDot(start); extraHighlight(fp.start, fp.end); return; } } if (isGoLeft) { caretSetDot(dot - 1); } else { caretSetDot(dot + 1); } } } private class ExpandAction extends AbstractAction { private static final long serialVersionUID = -947661984555078391L; boolean isExpandLeft; public ExpandAction(String name, boolean isExpandLeft) { super(name); this.isExpandLeft = isExpandLeft; } @Override public void actionPerformed(ActionEvent evt) { extraHighlightOff(); int dot = compo.getCaret().getDot(); // evtl. vorhandenes Tag überspringen for (TagPos fp : getTagPos()) { int end = fp.end; int start = fp.start; if (!isExpandLeft) { end = fp.start; start = fp.end; } if (dot == end) { caretMoveDot(start); return; } } if (isExpandLeft) { caretSetDot(dot - 1); } else { caretSetDot(dot + 1); } } } private class DeleteAction extends AbstractAction { private static final long serialVersionUID = 6955626055766864569L; boolean isDeleteLeft; public DeleteAction(String name, boolean isDeleteLeft) { super(name); this.isDeleteLeft = isDeleteLeft; } @Override public void actionPerformed(ActionEvent evt) { extraHighlightOff(); int dot = compo.getCaret().getDot(); int mark = compo.getCaret().getMark(); // evtl. vorhandene Selektion löschen if (dot != mark) { deleteAPartOfTheText(dot, mark); return; } // Endposition des zu löschenden Bereichs bestimmen int pos2 = dot - 1; if (!isDeleteLeft) { pos2 = dot + 1; } for (TagPos fp : getTagPos()) { int end = fp.end; int start = fp.start; if (!isDeleteLeft) { end = fp.start; start = fp.end; } if (dot == end) { pos2 = start; } } deleteAPartOfTheText(dot, pos2); } /** * Löscht einen Teil des aktuellen Texts zwischen den zwei Positionen pos1 * und pos2. pos1 kann größer, kleiner oder gleich pos2 sein. */ private void deleteAPartOfTheText(int pos1, int pos2) { // sicherstellen dass pos1 <= pos2 if (pos1 > pos2) { int tmp = pos2; pos2 = pos1; pos1 = tmp; } String t = compo.getText(); String part1 = (pos1 > 0) ? t.substring(0, pos1) : ""; String part2 = (pos2 < t.length()) ? t.substring(pos2) : ""; compo.setText(part1 + part2); compo.getCaret().setDot(pos1); } } }
LibreOffice/lots
core/src/main/java/org/libreoffice/lots/former/TextComponentTags.java
5,821
/** * Syntax für {@link #getContent(int)}: CAT(... VALUE "&lt;tagname&gt;" ... VALUE * "&lt;tagname"&gt; ...) */
block_comment
nl
/*- * #%L * WollMux * %% * Copyright (C) 2005 - 2023 Landeshauptstadt München and LibreOffice contributors * %% * Licensed under the EUPL, Version 1.1 or – as soon they will be * approved by the European Commission - subsequent versions of the * EUPL (the "Licence"); * * You may not use this work except in compliance with the Licence. * You may obtain a copy of the Licence at: * * http://ec.europa.eu/idabc/eupl5 * * Unless required by applicable law or agreed to in writing, software * distributed under the Licence is distributed on an "AS IS" basis, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Licence for the specific language governing permissions and * limitations under the Licence. * #L% */ package org.libreoffice.lots.former; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.InputMap; import javax.swing.KeyStroke; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultHighlighter; import javax.swing.text.Highlighter; import javax.swing.text.JTextComponent; import org.libreoffice.lots.config.ConfigThingy; import org.libreoffice.lots.util.L; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Erweiterte eine JTextComponent um die Fähigkeit, Tags, die als * &quot;&lt;tag&gt;&quot; angezeigt werden, wie atomare Elemente zu behandeln. */ public class TextComponentTags { private static final Logger LOGGER = LoggerFactory.getLogger(TextComponentTags.class); /** * Syntax für {@link<SUF>*/ public static final int CAT_VALUE_SYNTAX = 0; /** * Präfix, mit dem Tags in der Anzeige der Zuordnung angezeigt werden. Die * Zuordnung beginnt mit einem zero width space (nicht sichtbar, aber zur * Unterscheidung des Präfix von den Benutzereingaben) und dem "<"-Zeichen. */ private static final String TAG_PREFIX = "" + Character.toChars(0x200B)[0] + "<"; /** * Suffix, mit dem Tags in der Anzeige der Zuordnung angezeigt werden. Die * Zuordnung beginnt mit einem zero width space (nicht sichtbar, aber zur * Unterscheidung des Präfix von den Benutzereingaben) und dem ">"-Zeichen. */ private static final String TAG_SUFFIX = "" + Character.toChars(0x200B)[0] + ">"; /** * Beschreibt einen regulären Ausdruck, mit dem nach Tags im Text gesucht * werden kann. Ein Match liefert in Gruppe 1 den Text des Tags. */ private static final Pattern TAG_PATTERN = Pattern.compile("(" + TAG_PREFIX + "(.*?)" + TAG_SUFFIX + ")"); /** * Farbe, mit dem der Hintergund eines Textfeldes im Dialog "Felder anpassen" * eingefärbt wird, wenn ein ungültiger Inhalt enthalten ist. */ private static final Color invalidEntryBGColor = Color.PINK; /** * Die JTextComponent, die durch diese Wrapperklasse erweitert wird. */ private JTextComponent compo; /** * Enthält das tag das beim Erzeugen des Extra-Highlights zurückgeliefert * wurde und das Highlight-Objekt auszeichnet. */ private Object extraHighlightTag = null; /** * Erzeugt den Wrapper und nimmt die notwendigen Änderungen am * Standardverhalten der JTextComponent component vor. */ public TextComponentTags(JTextComponent component) { this.compo = component; changeInputMap(); changeCaretHandling(); changeFocusLostHandling(); changeDocumentUpdateHandling(); } /** * Fügt an der aktuellen Cursorposition ein neues Tag tag ein, das * anschließend mit der Darstellung &quot;&lt;tag&gt;&quot; angezeigt wird und * bezüglich der Editierung wie ein atomares Element behandelt wird. * * @param tag * Der Name des tags, das in dieser JTextComponent an der * Cursorposition eingefügt und angezeigt werden soll. */ public void insertTag(String tag) { String t = compo.getText(); int inspos = compo.getCaretPosition(); String p1 = (inspos > 0) ? t.substring(0, inspos) : ""; String p2 = (inspos < t.length()) ? t.substring(inspos, t.length()) : ""; // ACHTUNG! Änderungen hier müssen auch in setContent() gemacht werden t = TAG_PREFIX + tag + TAG_SUFFIX; compo.setText(p1 + t + p2); compo.getCaret().setDot(inspos + t.length()); extraHighlight(inspos, inspos + t.length()); } /** * Liefert die JTextComponent, die durch diesen Wrapper erweitert wird. */ public JTextComponent getJTextComponent() { return compo; } /** * Liefert eine Liste von {@link ContentElement}-Objekten, die den aktuellen * Inhalt der JTextComponent repräsentiert und dabei enthaltenen Text und * evtl. enthaltene Tags als eigene Objekte kapselt. */ public List<ContentElement> getContent() { List<ContentElement> list = new ArrayList<>(); String t = compo.getText(); Matcher m = TAG_PATTERN.matcher(t); int lastEndPos = 0; int startPos = 0; while (m.find()) { startPos = m.start(); String tag = m.group(2); list.add(new ContentElement(t.substring(lastEndPos, startPos), false)); if (tag.length() > 0) { list.add(new ContentElement(tag, true)); } lastEndPos = m.end(); } String text = t.substring(lastEndPos); if (text.length() > 0) { list.add(new ContentElement(text, false)); } return list; } /** * Liefert den Inhalt der Textkomponente in der durch syntaxType * spezifizierten Syntax. * * @see #CAT_VALUE_SYNTAX * @throws IllegalArgumentException * falls der syntaxType nicht existiert. */ public ConfigThingy getContent(int syntaxType) { if (syntaxType != CAT_VALUE_SYNTAX) throw new IllegalArgumentException(L.m("Unknown syntaxType: {0}", "" + syntaxType)); ConfigThingy conf = new ConfigThingy("CAT"); List<ContentElement> content = getContent(); if (content.isEmpty()) { conf.add(""); } else { Iterator<ContentElement> iter = content.iterator(); while (iter.hasNext()) { ContentElement ele = iter.next(); if (ele.isTag()) conf.add("VALUE").add(ele.toString()); else conf.add(ele.toString()); } } return conf; } /** * Liefert den Inhalt der TextComponentTag als String mit aufgelösten Tags, * wobei an Stelle jedes Tags der entsprechende Inhalt eingesetzt wird, der in * mapTagToValue unter dem Schlüssel des Tagnamens gefunden wird oder der * String "&lt;tagname&gt;", wenn das Tag nicht aufgelöst werden kann. * * @param mapTagToValue * Map mit Schlüssel-/Wertpaaren, die die entsprechenden Werte für * die Tags enthält. * @return Inhalt der TextComponentTag als String mit aufgelösten Tags (soweit * möglich). */ public String getContent(Map<String, String> mapTagToValue) { StringBuilder buf = new StringBuilder(); for (ContentElement el : getContent()) { if (el.isTag()) { String key = el.toString(); String value = mapTagToValue.get(key); if (value != null) buf.append(mapTagToValue.get(key)); else buf.append("<" + key + ">"); } else { buf.append(el.toString()); } } return buf.toString(); } /** * Das Gegenstück zu {@link #getContent(int)}. * * @throws IllegalArgumentException * wenn syntaxType illegal oder ein Fehler in conf ist. */ public void setContent(int syntaxType, ConfigThingy conf) { if (syntaxType != CAT_VALUE_SYNTAX) throw new IllegalArgumentException(L.m("Unknown syntaxType: {0}", "" + syntaxType)); if (!"CAT".equals(conf.getName())) throw new IllegalArgumentException(L.m("Topmost node must be \"CAT\"")); StringBuilder buffy = new StringBuilder(); Iterator<ConfigThingy> iter = conf.iterator(); while (iter.hasNext()) { ConfigThingy subConf = iter.next(); if ("VALUE".equals(subConf.getName()) && subConf.count() == 1) { // ACHTUNG! Änderungen hier müssen auch in insertTag() gemacht werden buffy.append(TAG_PREFIX); buffy.append(subConf.toString()); buffy.append(TAG_SUFFIX); } else { buffy.append(subConf.toString()); } } extraHighlightOff(); compo.setText(buffy.toString()); } /** * Liefert zur String-Liste fieldNames eine Liste von Actions, die die * entsprechenden Strings in text einfügen. */ public static List<Action> makeInsertFieldActions(List<String> fieldNames, final TextComponentTags text) { List<Action> actions = new ArrayList<>(); Iterator<String> iter = fieldNames.iterator(); while (iter.hasNext()) { final String name = iter.next(); Action action = new AbstractAction(name) { private static final long serialVersionUID = -9123184290299840565L; @Override public void actionPerformed(ActionEvent e) { text.insertTag(name); } }; actions.add(action); } return actions; } /** * Kann überschrieben werden um eine Logik zu hinterlegen, die berechnet, ob * das Feld einen gültigen Inhalt besitzt. Ist der Inhalt nicht gültig, dann * wird das Feld mit einem roten Hintergrund hinterlegt. * * @return true, wenn der Inhalt gültig ist und false, wenn der Inhalt nicht * gültig ist. */ public boolean isContentValid() { return true; } /** * Beschreibt ein Element des Inhalts dieser JTextComponent und kann entweder * ein eingefügtes Tag oder ein normaler String sein. Auskunft über den Typ * des Elements erteilt die Methode isTag(), auf den String-Wert kann über die * toString()-Methode zugegriffen werden. */ public static class ContentElement { private String value; private boolean isTag; private ContentElement(String value, boolean isTag) { this.value = value; this.isTag = isTag; } @Override public String toString() { return value; } /** * Liefert true, wenn dieses Element ein Tag ist oder false, wenn es sich um * normalen Text handelt. */ public boolean isTag() { return isTag; } } /** * Immer wenn der Cursor mit der Maus in einen Bereich innerhalb eines Tags * gesetzt wird, sorgt der hier registrierte caret Listener dafür, dass der * Bereich auf das gesamte Tag ausgedehnt wird. */ private void changeCaretHandling() { compo.addCaretListener(event -> { extraHighlightOff(); int dot = compo.getCaret().getDot(); int mark = compo.getCaret().getMark(); for (TagPos fp : getTagPos()) { if (dot > fp.start && dot < fp.end) { if (dot < mark) { caretMoveDot(fp.start); } else if (dot > mark) { caretMoveDot(fp.end); } else { caretSetDot(fp.end); extraHighlight(fp.start, fp.end); } } } }); } /** * Der FocusLostListener wird hier registriert, damit nach einem FocusLost ein * evtl. gesetztes Extra-Highlight aufgehoben werden kann. */ private void changeFocusLostHandling() { compo.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { extraHighlightOff(); } }); } /** * Implementiert die Aktionen für die Tastendrücke Cursor-links, * Cursor-rechts, Delete und Backspace neu und berücksichtigt dabei die * atomaren Tags. */ private void changeInputMap() { String goLeftKeyStroke = "goLeft"; String goRightKeyStroke = "goRight"; String expandLeftKeyStroke = "expandLeft"; String expandRightKeyStroke = "expandRight"; String deleteLeftKeyStroke = "deleteLeft"; String deleteRightKeyStroke = "deleteRight"; InputMap m = compo.getInputMap(); m.put(KeyStroke.getKeyStroke("LEFT"), goLeftKeyStroke); m.put(KeyStroke.getKeyStroke("RIGHT"), goRightKeyStroke); m.put(KeyStroke.getKeyStroke("shift LEFT"), expandLeftKeyStroke); m.put(KeyStroke.getKeyStroke("shift RIGHT"), expandRightKeyStroke); m.put(KeyStroke.getKeyStroke("DELETE"), deleteRightKeyStroke); m.put(KeyStroke.getKeyStroke("BACK_SPACE"), deleteLeftKeyStroke); compo.getActionMap().put(goLeftKeyStroke, new GoAction(goLeftKeyStroke, true)); compo.getActionMap().put(goRightKeyStroke, new GoAction(goRightKeyStroke, false)); compo.getActionMap().put(expandLeftKeyStroke, new ExpandAction(expandLeftKeyStroke, true)); compo.getActionMap().put(expandRightKeyStroke, new ExpandAction(expandRightKeyStroke, false)); compo.getActionMap().put(deleteRightKeyStroke, new DeleteAction(deleteRightKeyStroke, false)); compo.getActionMap().put(deleteLeftKeyStroke, new DeleteAction(deleteLeftKeyStroke, true)); } /** * Der hier registrierte DocumentListener sorgt dafür, dass nach jeder * Textänderung geprüft wird, ob der Inhalt der JTextComponent noch gültig ist * und im Fehlerfall mit der Hintergrundfarbe invalidEntryBGColor eingefärbt * wird. */ private void changeDocumentUpdateHandling() { compo.getDocument().addDocumentListener(new DocumentListener() { private Color oldColor = null; @Override public void changedUpdate(DocumentEvent e) { update(); } @Override public void removeUpdate(DocumentEvent e) { update(); } @Override public void insertUpdate(DocumentEvent e) { update(); } private void update() { if (isContentValid()) { if (oldColor != null) { compo.setBackground(oldColor); } } else { if (oldColor == null) { oldColor = compo.getBackground(); } compo.setBackground(invalidEntryBGColor); } } }); } /** * Macht das selbe wie getCaret().setDot(pos), aber nur wenn pos >= 0 und pos * <= getText().length() gilt. */ private void caretSetDot(int pos) { if (pos >= 0 && pos <= compo.getText().length()) { compo.getCaret().setDot(pos); } } /** * Macht das selbe wie getCaret().setDot(pos), aber nur wenn pos >= 0 und pos * <= getText().length() gilt. */ private void caretMoveDot(int pos) { if (pos >= 0 && pos <= compo.getText().length()) { compo.getCaret().moveDot(pos); } } /** * Diese Klasse beschreibt die Position eines Tags innerhalb des Textes der * JTextComponent. */ static class TagPos { public final String name; public final int start; public final int end; TagPos(int start, int end, String name) { this.start = start; this.end = end; this.name = name; } } /** * Liefert einen Iterator von TagPos-Elementen, die beschreiben an welcher * Position im aktuellen Text Tags gefunden werden. */ private List<TagPos> getTagPos() { List<TagPos> results = new ArrayList<>(); Matcher m = TAG_PATTERN.matcher(compo.getText()); while (m.find()) { results.add(new TagPos(m.start(1), m.end(1), m.group(2))); } return results; } /** * Deaktiviert die Anzeige des Extra-Highlights. */ private void extraHighlightOff() { if (extraHighlightTag != null) { Highlighter hl = compo.getHighlighter(); hl.removeHighlight(extraHighlightTag); extraHighlightTag = null; } } /** * Highlightet den Textbereich zwischen pos1 und pos2 * * @param pos1 * @param pos2 */ private void extraHighlight(int pos1, int pos2) { Highlighter hl = compo.getHighlighter(); try { if (extraHighlightTag == null) { Highlighter.HighlightPainter hp = new DefaultHighlighter.DefaultHighlightPainter(new Color(0xddddff)); extraHighlightTag = hl.addHighlight(pos1, pos2, hp); } else { hl.changeHighlight(extraHighlightTag, pos1, pos2); } } catch (BadLocationException e1) { LOGGER.trace("", e1); } } private class GoAction extends AbstractAction { private static final long serialVersionUID = 2098288193497911628L; boolean isGoLeft; public GoAction(String name, boolean isGoLeft) { super(name); this.isGoLeft = isGoLeft; } @Override public void actionPerformed(ActionEvent evt) { extraHighlightOff(); int dot = compo.getCaret().getDot(); // evtl. vorhandenes Tag überspringen for (TagPos fp : getTagPos()) { int end = fp.end; int start = fp.start; if (!isGoLeft) { end = fp.start; start = fp.end; } if (dot == end) { caretSetDot(start); extraHighlight(fp.start, fp.end); return; } } if (isGoLeft) { caretSetDot(dot - 1); } else { caretSetDot(dot + 1); } } } private class ExpandAction extends AbstractAction { private static final long serialVersionUID = -947661984555078391L; boolean isExpandLeft; public ExpandAction(String name, boolean isExpandLeft) { super(name); this.isExpandLeft = isExpandLeft; } @Override public void actionPerformed(ActionEvent evt) { extraHighlightOff(); int dot = compo.getCaret().getDot(); // evtl. vorhandenes Tag überspringen for (TagPos fp : getTagPos()) { int end = fp.end; int start = fp.start; if (!isExpandLeft) { end = fp.start; start = fp.end; } if (dot == end) { caretMoveDot(start); return; } } if (isExpandLeft) { caretSetDot(dot - 1); } else { caretSetDot(dot + 1); } } } private class DeleteAction extends AbstractAction { private static final long serialVersionUID = 6955626055766864569L; boolean isDeleteLeft; public DeleteAction(String name, boolean isDeleteLeft) { super(name); this.isDeleteLeft = isDeleteLeft; } @Override public void actionPerformed(ActionEvent evt) { extraHighlightOff(); int dot = compo.getCaret().getDot(); int mark = compo.getCaret().getMark(); // evtl. vorhandene Selektion löschen if (dot != mark) { deleteAPartOfTheText(dot, mark); return; } // Endposition des zu löschenden Bereichs bestimmen int pos2 = dot - 1; if (!isDeleteLeft) { pos2 = dot + 1; } for (TagPos fp : getTagPos()) { int end = fp.end; int start = fp.start; if (!isDeleteLeft) { end = fp.start; start = fp.end; } if (dot == end) { pos2 = start; } } deleteAPartOfTheText(dot, pos2); } /** * Löscht einen Teil des aktuellen Texts zwischen den zwei Positionen pos1 * und pos2. pos1 kann größer, kleiner oder gleich pos2 sein. */ private void deleteAPartOfTheText(int pos1, int pos2) { // sicherstellen dass pos1 <= pos2 if (pos1 > pos2) { int tmp = pos2; pos2 = pos1; pos1 = tmp; } String t = compo.getText(); String part1 = (pos1 > 0) ? t.substring(0, pos1) : ""; String part2 = (pos2 < t.length()) ? t.substring(pos2) : ""; compo.setText(part1 + part2); compo.getCaret().setDot(pos1); } } }
90919_0
package h5; import java.applet.Applet; import java.awt.*; public class opdracht5_1 extends Applet{ //declaratie. Color opvulkleur; Color lijnkleur; int breedte; int hoogte; public void init() { //initialisatie. opvulkleur = Color.MAGENTA; lijnkleur = Color.BLACK; breedte = 200; hoogte = 100; } public void paint(Graphics g) { //teken lijn g.drawLine( 100, 50, 297, 50); //teken rechthoek g.drawRect(100, 100, breedte, hoogte); //teken afgeronde rechthoek g.drawRoundRect(100, 225, breedte, hoogte, 30, 30); //teken gevulde rechthoek g.setColor(opvulkleur); g.fillRect(315, 100, breedte, hoogte); //teken ovaal g.setColor(lijnkleur); g.drawOval(315, 100, breedte, hoogte); //teken gevulde ovaal g.setColor(opvulkleur); g.fillOval(315, 225, breedte, hoogte); //begin Taartpunt met ovaal eromheen g.setColor(lijnkleur); g.drawArc(530, 102, breedte, hoogte, 90, 360); g.setColor(opvulkleur); g.fillArc(530,102,breedte,hoogte,0,45); g.setColor(lijnkleur); g.drawArc(570, 220, 120, 120, 720, 360); } }
robincreebsburg/inleiding-java
src/h5/opdracht5_1.java
486
//teken afgeronde rechthoek
line_comment
nl
package h5; import java.applet.Applet; import java.awt.*; public class opdracht5_1 extends Applet{ //declaratie. Color opvulkleur; Color lijnkleur; int breedte; int hoogte; public void init() { //initialisatie. opvulkleur = Color.MAGENTA; lijnkleur = Color.BLACK; breedte = 200; hoogte = 100; } public void paint(Graphics g) { //teken lijn g.drawLine( 100, 50, 297, 50); //teken rechthoek g.drawRect(100, 100, breedte, hoogte); //teken afgeronde<SUF> g.drawRoundRect(100, 225, breedte, hoogte, 30, 30); //teken gevulde rechthoek g.setColor(opvulkleur); g.fillRect(315, 100, breedte, hoogte); //teken ovaal g.setColor(lijnkleur); g.drawOval(315, 100, breedte, hoogte); //teken gevulde ovaal g.setColor(opvulkleur); g.fillOval(315, 225, breedte, hoogte); //begin Taartpunt met ovaal eromheen g.setColor(lijnkleur); g.drawArc(530, 102, breedte, hoogte, 90, 360); g.setColor(opvulkleur); g.fillArc(530,102,breedte,hoogte,0,45); g.setColor(lijnkleur); g.drawArc(570, 220, 120, 120, 720, 360); } }
205905_0
package be.ehb.koalaexpress.Tasks; import android.os.AsyncTask; import android.util.Log; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import be.ehb.koalaexpress.ConnectionInfo; import be.ehb.koalaexpress.JSONhelper; import be.ehb.koalaexpress.KoalaDataRepository; import be.ehb.koalaexpress.models.CustomerList; import be.ehb.koalaexpress.models.ProductList; import be.ehb.koalaexpress.returnMessage; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class Task_FetchCustomers extends AsyncTask<KoalaDataRepository, Object, CustomerList> { private String TAG = "Task_FetchCustomers"; private KoalaDataRepository mRepository; @Override protected CustomerList doInBackground(KoalaDataRepository... koalaDataZwembaden) { mRepository = koalaDataZwembaden[0]; OkHttpClient client = new OkHttpClient(); String url= ConnectionInfo.ServerUrl() + "/customers?action=listCustomers"; final Request request = new Request.Builder() .url(url) .build(); String s=""; CustomerList myList = null; try { // nu doen we de eigenlijke servlet call Response response = client.newCall(request).execute(); if (!response.isSuccessful()) return null; s = (response.body().string()); // now process return message from URL call of try { returnMessage msg = JSONhelper.extractmsgFromJSONAnswer(s); // objectmapper zet string om in object via json (jackson library) ObjectMapper objmap = new ObjectMapper(); objmap.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false); // zet content om in object using json myList = objmap.readValue(msg.m_Content, CustomerList.class); /*for (ProductCategory g: myList.mList) { Log.d(TAG, g.toString()); }*/ } catch (JsonProcessingException e) { Log.d(TAG, e.toString()); } } catch (Exception e){ s = e.getMessage().toString(); } return myList; } @Override protected void onPostExecute(CustomerList l){ super.onPostExecute(l); mRepository.koalaCustomers= l; } }
MRoeland/KoalaExpress
app/src/main/java/be/ehb/koalaexpress/Tasks/Task_FetchCustomers.java
603
// nu doen we de eigenlijke servlet call
line_comment
nl
package be.ehb.koalaexpress.Tasks; import android.os.AsyncTask; import android.util.Log; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import be.ehb.koalaexpress.ConnectionInfo; import be.ehb.koalaexpress.JSONhelper; import be.ehb.koalaexpress.KoalaDataRepository; import be.ehb.koalaexpress.models.CustomerList; import be.ehb.koalaexpress.models.ProductList; import be.ehb.koalaexpress.returnMessage; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class Task_FetchCustomers extends AsyncTask<KoalaDataRepository, Object, CustomerList> { private String TAG = "Task_FetchCustomers"; private KoalaDataRepository mRepository; @Override protected CustomerList doInBackground(KoalaDataRepository... koalaDataZwembaden) { mRepository = koalaDataZwembaden[0]; OkHttpClient client = new OkHttpClient(); String url= ConnectionInfo.ServerUrl() + "/customers?action=listCustomers"; final Request request = new Request.Builder() .url(url) .build(); String s=""; CustomerList myList = null; try { // nu doen<SUF> Response response = client.newCall(request).execute(); if (!response.isSuccessful()) return null; s = (response.body().string()); // now process return message from URL call of try { returnMessage msg = JSONhelper.extractmsgFromJSONAnswer(s); // objectmapper zet string om in object via json (jackson library) ObjectMapper objmap = new ObjectMapper(); objmap.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false); // zet content om in object using json myList = objmap.readValue(msg.m_Content, CustomerList.class); /*for (ProductCategory g: myList.mList) { Log.d(TAG, g.toString()); }*/ } catch (JsonProcessingException e) { Log.d(TAG, e.toString()); } } catch (Exception e){ s = e.getMessage().toString(); } return myList; } @Override protected void onPostExecute(CustomerList l){ super.onPostExecute(l); mRepository.koalaCustomers= l; } }
187199_99
package com.itwillbs.mvc_board.controller; import java.util.List; import java.util.Map; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.itwillbs.mvc_board.service.BankService; import com.itwillbs.mvc_board.service.MemberService; import com.itwillbs.mvc_board.service.SendMailService; import com.itwillbs.mvc_board.vo.MailAuthInfoVO; import com.itwillbs.mvc_board.vo.MemberVO; import com.itwillbs.mvc_board.vo.ResponseTokenVO; @Controller public class MemberController { // MemberService 객체 자동 주입 @Autowired private MemberService memberService; // SendMailService 객체 자동 주입 @Autowired private SendMailService mailService; @Autowired private BankService bankService; // [ 회원 가입 ] // "MemberJoinForm" 요청 joinForm() 메서드 정의(GET) // => "member/member_join_form.jsp" 페이지 포워딩 @GetMapping("MemberJoinForm") public String joinForm() { return "member/member_join_form"; } // "MemberJoinPro" 요청에 대한 비즈니스 로직 처리 수행할 joinPro() 메서드 정의(POST) // => 폼 파라미터를 통해 전달받은 회원정보를 MemberVO 타입으로 전달받기 // => 데이터 공유 객체 Model 타입 파라미터 추가 @PostMapping("MemberJoinPro") public String joinPro(MemberVO member, Model model) { // System.out.println(member); // ------------------------------------------------------------------------ // BCryptPasswordEncoder 를 활용한 패스워드 암호화 // 입력받은 패스워드는 암호화 필요 => 복호화가 불가능하도록 단방향 암호화(해싱) 수행 // => 평문(Clear Text, Plain Text) 을 해싱 후 MemberVO 객체의 passwd 에 덮어쓰기 // => org.springframework.security.crypto.bcrypt 패키지의 BCryptPasswordEncoder 클래스 활용 // (spring-security-crypto 또는 spring-security-web 라이브러리 추가) // 주의! JDK 11 일 때 5.x.x 버전 필요 // => BCryptPasswordEncoder 활용한 해싱은 솔팅(Salting) 기법을 통해 // 동일한 평문(원본 암호)이더라도 매번 다른 결과(암호문)를 얻을 수 있다! // 1. BCryptPasswordEncoder 클래스 인스턴스 생성 BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); // 2. BCryptPasswordEncoder 객체의 encode() 메서드를 호출하여 // 원문(평문) 패스워드에 대한 해싱(= 암호화) 수행 후 결과값 저장 // => 파라미터 : MemberVO 객체의 패스워드(평문 암호) 리턴타입 : String(암호문) String securePasswd = passwordEncoder.encode(member.getPasswd()); // System.out.println("평문 패스워드 : " + member.getPasswd()); // 1234 // System.out.println("암호화 된 패스워드 : " + securePasswd); // $2a$10$wvO.wV.ZHbRFVr9q4ayFbeGGCRs7XKxsN8wmll/.5YFlA/N7hFYl2(매번 다름) // 3. 암호화 된 패스워드를 MemberVO 객체에 저장 member.setPasswd(securePasswd); // ------------------------------------------------------------------------------------- // MemberService - registMember() 메서드 호출하여 회원가입 작업 요청 // => 파라미터 : MemberVO 객체 리턴타입 : int(insertCount) int insertCount = memberService.registMember(member); // 회원가입 성공/실패에 따른 페이징 처리 // => 성공 시 "MemberJoinSuccess" 서블릿 주소 리다이렉트 // => 실패 시 "fail_back.jsp" 페이지 포워딩("msg" 속성값으로 "회원 가입 실패!" 저장) if(insertCount > 0) { // 12-29 추가내용 // -------- 인증메일 발송 작업 추가 -------- // SendMailService - sendAuthMail() 메서드 호출하여 인증 메일 발송 요청 // => 파라미터 : 아이디, 이메일(= 회원 가입 시 입력한 정보) // 리턴타입 : String(auth_code = 인증코드) member.setEmail(member.getEmail1() + "@" + member.getEmail2()); // 이메일 결합 String auth_code = mailService.sendAuthMail(member); // System.out.println("인증코드 : " + auth_code); // MemberService - registAuthInfo() 메서드 호출하여 인증 정보 등록 요청 // => 파라미터 : 아이디, 인증코드 memberService.registMailAuthInfo(member.getId(), auth_code); return "redirect:/MemberJoinSuccess"; } else { // 실패 시 메세지 출력 및 이전페이지로 돌아가는 기능을 모듈화 한 fail_back.jsp 페이지 model.addAttribute("msg", "회원 가입 실패!"); return "fail_back"; } } // "MemberCheckDupId" 요청에 대한 아이디 중복 검사 비즈니스 로직 처리 // 응답데이터를 디스패치 또는 리다이렉트 용도가 아닌 응답 데이터 body 로 그대로 활용하려면 // @ResponseBody 어노테이션을 적용해야한다! => 응답 데이터를 직접 전송하도록 지정한다. // => 이 어노테이션은 AJAX 와 상관없이 적용 가능하지만 AJAX 일 때는 대부분 사용한다. @ResponseBody @GetMapping("MemberCheckDupId") public String checkDupId(MemberVO member) { System.out.println(member.getId()); // MemberService - getMember() 메서드 호출하여 아이디 조회(기존 메서드 재사용) // (MemberService - getMemberId() 메서드 호출하여 아이디 조회 메서드 정의 가능) // => 파라미터 : MemberVO 객체 리턴타입 : MemberVO(dbMember) MemberVO dbMember = memberService.getMember(member); // 조회 결과 판별 // => MemberVO 객체가 존재할 경우 아이디 중복, 아니면 사용 가능한 아이디 if(dbMember == null) { // 사용 가능한 아이디 return "false"; // 중복이 아니라는 의미로 "false" 값 전달 } else { // 아이디 중복 return "true"; // 중복이라는 의미로 "true" 값 전달 } } // -------------------------------------- // 인증 메일 발송 테스트를 위한 서블릿 매핑 // => URL 을 통해 강제로 회원 아이디와 수신자 이메일 주소 전달받아 사용 @GetMapping("TestAuthMail") public String testAuthMail(MemberVO member) { String auth_code = mailService.sendAuthMail(member); // System.out.println("인증코드 : " + auth_code); // MemberService - registAuthInfo() 메서드 호출하여 인증 정보 등록 요청 // => 파라미터 : 아이디, 인증코드 memberService.registMailAuthInfo(member.getId(), auth_code); // return "member/member_join_success"; return "redirect:/MemberJoinSuccess"; } // ----------------- // "MemberEmailAuth" 서블릿 요청에 대한 메일 인증 작업 비즈니스 로직 처리 @GetMapping("MemberEmailAuth") public String emailAuth(MailAuthInfoVO authInfo, Model model) { System.out.println("인증정보 : " + authInfo); // MemberService - requestEmailAuth() 메서드 호출하여 인증 요청 // => 파라미터 : MailAuthInfoVO 객체 리턴타입 : boolean(isAuthSuccess) boolean isAuthSuccess = memberService.requestEmailAuth(authInfo); // 인증 요청 결과 판별 if(isAuthSuccess) { // 성공 model.addAttribute("msg", "인증 성공! 로그인 페이지로 이동합니다!"); model.addAttribute("targetURL", "MemberLoginForm"); return "forward"; } else { model.addAttribute("msg", "인증 실패!"); return "fail_back"; } } // ================================================================================ // [ 로그인 ] // "MemberJoinSuccess" 요청에 대해 "member/member_join_success" 페이지 포워딩(GET) @GetMapping("MemberJoinSuccess") public String joinSuccess() { // 아이디 : hong, 비번 : 1111 return "member/member_join_success"; } // "MemberLoginForm" 요청에 대해 "member/login_form" 페이지 포워딩(GET) @GetMapping("MemberLoginForm") public String loginForm() { return "member/member_login_form"; } // "MemberLoginPro" 요청에 대한 비즈니스 로직 처리 수행할 loginPro() 메서드 정의(POST) // => 폼 파라미터를 통해 전달받은 회원정보를 MemberVO 타입으로 전달받기 // => 세션 활용을 위해 HttpSession 타입 파라미터 추가 // => 데이터 공유 객체 Model 타입 파라미터 추가 @PostMapping("MemberLoginPro") public String loginPro(MemberVO member, HttpSession session, Model model) { System.out.println(member); // MemberService - getMember() 메서드 호출하여 회원 정보 조회 요청 // => 파라미터 : MemberVO 객체 리턴타입 : MemberVO(dbMember) MemberVO dbMember = memberService.getMember(member); // System.out.println(dbMember); // 만약, 회원 상태(member_status)값이 3일 경우 // "fail_back" 포워딩 처리("탈퇴한 회원입니다!") if(dbMember.getMember_status() == 3) { model.addAttribute("msg", "탈퇴한 회원입니다!"); return "fail_back"; } // BCryptPasswordEncoder 객체를 활용한 패스워드 비교 // => 입력받은 패스워드(평문)와 DB 에 저장된 패스워드(암호문)는 직접적인 문자열 비교 불가 // => 일반적인 경우 전달받은 평문과 DB 에 저장된 암호문을 복호화하여 비교하면 되지만 // 단방향 암호화가 된 패스워드의 경우 평문을 암호화(해싱)하여 결과값을 비교해야함 // (단, 솔팅값이 서로 다르므로 직접적인 비교(String 의 equals())가 불가능) // => BCryptPasswordEncoder 객체의 matches() 메서드를 통한 비교 필수! BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); // => 단, 아이디가 일치하지 않을 경우(null 값 리턴됨) 또는 패스워드 불일치 시 // fail_back.jsp 페이지 포워딩("로그인 실패!") // null 값을 먼저 비교하지 않으면 NullPointException 발생 if(dbMember == null || !passwordEncoder.matches(member.getPasswd(), dbMember.getPasswd())) { // 로그인 실패 처리 model.addAttribute("msg", "로그인 실패!"); return "fail_back"; } else { // 12-29 추가내용 // 이메일 인증 여부 확인 // => 회원정보조회를 통해 MemberVO 객체에 저장된 // 이메일 인증 정보(mail_auth_status) 값이 "N" 일 경우 이메일 미인증 회원이므로 // "이메일 인증 후 로그인이 가능합니다" 출력 후 이전페이지로 돌아가기 if(dbMember.getMail_auth_status().equals("N")) { model.addAttribute("msg","이메일 인증 후 로그인이 가능합니다"); return "fail_back"; } // 세션 객체에 로그인 성공한 아이디를 "sId" 속성으로 추가 session.setAttribute("sId", member.getId()); // 1-22 추가내용 // -------------------------------------------------------------------- // BankService - getBankUserInfo() 메서드 호출하여 엑세스 토큰 조회 요청 // => 파라미터 : 아이디 리턴타입 : Map<String, String> Map<String, String> token = bankService.getBankUserInfo(member.getId()); // System.out.println(token); // -------------------------------------------------------------------- // 조회된 엑세스 토큰을 "access_token", 사용자 번호를 "user_seq_no" 로 세션에 추가 // => 단, Map객체(token)이 null 이 아닐 경우에만 수행 if(token != null ) { session.setAttribute("access_token", token.get("access_token")); session.setAttribute("user_seq_no", token.get("user_seq_no")); } // 메인페이지로 리다이렉트 return "redirect:/"; } } // "MemberLogout" 요청에 대한 로그아웃 비즈니스 로직 처리 @GetMapping("MemberLogout") public String logout(HttpSession session) { session.invalidate(); return "redirect:/"; } // =============================================================== // [ 회원 상세정보 조회 ] // "MemberInfo" 서블릿 요청 시 회원 상세정보 조회 비즈니스 로직 처리 // 회원 정보 조회 @GetMapping("MemberInfo") public String info(MemberVO member, HttpSession session, Model model) { // 세션 아이디가 없을 경우 "fail_back" 페이지를 통해 "잘못된 접근입니다" 출력 처리 String sId = (String)session.getAttribute("sId"); if(sId == null) { model.addAttribute("msg", "잘못된 접근입니다!"); return "fail_back"; } // 12-19 추가내용 // 관리자 계정일 경우 회원 조회시 해당 회원의 정보가 출력되어야한다. // 만약, 현재 세션이 관리자가 아니거나 // 관리자이면서 id 파라미터가 없을 경우(null 또는 널스트링) // MemberVO 객체의 id 값을 세션 아이디로 교체(덮어쓰기) // 파라미터가 없을 경우는 null, 파라미터는 있지만 데이터가 없으면 "" // 두가지 경우를 고려해서 null과 "" 둘 다 판별한다. if(!sId.equals("admin") || sId.equals("admin") && (member.getId() == null || member.getId().equals(""))) { member.setId(sId); } // MemberService - getMember() 메서드 호출하여 회원 상세정보 조회 요청 // => 파라미터 : MemberVO 객체 리턴타입 : MemberVO(dbMember) MemberVO dbMember = memberService.getMember(member); // 조회 결과 Model 객체에 저장 model.addAttribute("member", dbMember); // 주민번호(MemberVO - jumin는 뒷자리 첫번째 숫자를 제외한 나머지 * 처리(마스킹) // => 처리된 주민번호를 jumin 멤버변수에 저장 // => 주민번호 앞자리 6자리와 뒷자리 1자리까지 추출하여 뒷부분에 * 기호 6개 결합 dbMember.setJumin(dbMember.getJumin().substring(0, 8) + "******"); // 0 ~ 8-1 인덱스까지 추출 // 회원 상세정보 조회 페이지 포워딩 return "member/member_info"; } // =============================================================== // [ 회원 정보 수정 ] // "MemberModifyForm" 서블릿 요청 시 회원 정보 수정 폼 표시 @GetMapping("MemberModifyForm") public String modifyForm(MemberVO member, HttpSession session, Model model) { String sId = (String)session.getAttribute("sId"); if(sId == null) { model.addAttribute("msg", "잘못된 접근입니다!"); return "fail_back"; } // 만약, 현재 세션이 관리자가 아니거나 // 관리자이면서 id 파라미터가 없을 경우(null 또는 널스트링) // MemberVO 객체의 id 값을 세션 아이디로 교체(덮어쓰기) if(!sId.equals("admin") || sId.equals("admin") && (member.getId() == null || member.getId().equals(""))) { member.setId(sId); } // MemberService - getMember() 메서드 호출하여 회원 상세정보 조회 요청 // => 파라미터 : MemberVO 객체 리턴타입 : MemberVO(dbMember) MemberVO dbMember = memberService.getMember(member); // 주민번호(MemberVO - jumin는 뒷자리 첫번째 숫자를 제외한 나머지 * 처리(마스킹) // => 처리된 주민번호를 jumin 멤버변수에 저장 // => 주민번호 앞자리 6자리와 뒷자리 1자리까지 추출하여 뒷부분에 * 기호 6개 결합 dbMember.setJumin(dbMember.getJumin().substring(0, 8) + "******"); // 0 ~ 8-1 인덱스까지 추출 // 조회 결과 Model 객체에 저장 model.addAttribute("member", dbMember); return "member/member_modify_form"; } // "MemberModifyPro" 서블릿 요청에 대한 회원 정보 수정 비즈니스 로직 처리 // => 추가로 전달되는 새 패스워드(newPasswd) 값을 전달받을 파라미터 변수 1개 추가(Map 사용 가능) @PostMapping("MemberModifyPro") public String modifyPro(MemberVO member, String newPasswd, HttpSession session, Model model) { String sId = (String)session.getAttribute("sId"); if(sId == null) { model.addAttribute("msg", "잘못된 접근입니다!"); return "fail_back"; } // 만약, 현재 세션이 관리자가 아니거나 // 관리자이면서 id 파라미터가 없을 경우(null 또는 널스트링) // MemberVO 객체의 id 값을 세션 아이디로 교체(덮어쓰기) if(!sId.equals("admin") || sId.equals("admin") && (member.getId() == null || member.getId().equals(""))) { member.setId(sId); } // MemberService - getMember() 메서드 호출하여 회원 정보 조회 요청(패스워드 비교용) // => 파라미터 : MemberVO 객체 리턴타입 : MemberVO(dbMember) MemberVO dbMember = memberService.getMember(member); // BCryptPasswordEncoder 클래스를 활용하여 입력받은 기존 패스워드와 DB 패스워드 비교 BCryptPasswordEncoder passwoedEncoder = new BCryptPasswordEncoder(); // 만약, 현재 세션이 관리자가 아니거나 // 관리자이면서 id 파라미터가 없을 경우(null 또는 널스트링) // MemberVO 객체의 id 값을 세션 아이디로 교체(덮어쓰기) if(!sId.equals("admin") || sId.equals("admin") && (member.getId() == null || member.getId().equals(""))) { // 이 때, 동일한 조건에서 패스워드 검증도 추가로 수행 // => 관리자가 다른 회원의 정보를 수정할 경우에는 패스워드 검증 수행 생략됨 if(!passwoedEncoder.matches(member.getPasswd(), dbMember.getPasswd())) { model.addAttribute("msg", "수정 권한이 없습니다!"); return "fail_back"; } } // 새 패스워드를 입력받았을 경우 BCryptPasswordEncoder 클래스를 활요하여 암호화 처리 // 파라미터로는 newPasswd 자체는 있기에 입력값이 없을 경우 ""으로 넘어오지만 // 만일의 경우를 대비해서 null값도 비교한다. if(newPasswd != null && !newPasswd.equals("")) { newPasswd = passwoedEncoder.encode(newPasswd); } // MemberService - modifyMember() 메서드 호출하여 회원 정보 수정 요청 // => 파라미터 : MemberVO 객체, 새 패스워드(newPasswd) 리턴타입 : int(updateCount) int updateCount = memberService.modifyMember(member, newPasswd); // 회원 정보 수정 요청 결과 판별 // => 실패 시 "fail_back" 페이지 포워딩 처리("회원정보 수정 실패!") // => 성공 시 "MemberInfo" 서블릿 리다이렉트 if(updateCount > 0) { // 관리자가 다른 회원 정보 수정 시 MemberInfo 서블릿 주소에 아이디 파라미터 결합 if(!sId.equals("admin") || sId.equals("admin") && (member.getId() == null || member.getId().equals(""))) { // 본인 정보를 조회할 경우 return "redirect:/MemberInfo"; } else { return "redirect:/MemberInfo?id=" + member.getId(); } } else { model.addAttribute("msg", "회원정보 수정 실패!"); return "fail_back"; } } // =============================================================== // [ 회원 탈퇴 ] // "MemberWithdrawForm" 서블릿 요청 시 회원 정보 탈퇴 폼 표시 @GetMapping("MemberWithdrawForm") public String withdrawForm(HttpSession session, Model model) { String sId = (String)session.getAttribute("sId"); if(sId == null) { model.addAttribute("msg", "잘못된 접근입니다!"); return "fail_back"; } return "member/member_withdraw_form"; } // "MemberWithdrawPro" 서블릿 요청 시 회원 탈퇴 비즈니스 로직 처리 @PostMapping("MemberWithdrawPro") public String withdrawPro(MemberVO member, HttpSession session, Model model) { String sId = (String)session.getAttribute("sId"); if(sId == null) { model.addAttribute("msg", "잘못된 접근입니다!"); return "fail_back"; } member.setId(sId); // MemberService - getMember() 메서드 호출하여 회원 정보 조회 요청(패스워드 비교용) // => 파라미터 : MemberVO 객체 리턴타입 : MemberVO(dbMember) MemberVO dbMember = memberService.getMember(member); // BCryptPasswordEncoder 클래스를 활용하여 입력받은 기존 패스워드와 DB 패스워드 비교 BCryptPasswordEncoder passwoedEncoder = new BCryptPasswordEncoder(); if(!passwoedEncoder.matches(member.getPasswd(), dbMember.getPasswd())) { model.addAttribute("msg", "수정 권한이 없습니다!"); return "fail_back"; } // MemberService - withdrawMember() 메서드 호출하여 회원 탈퇴 처리 요청 // => 파라미터 : MemberVO 객체 리턴타입 : int(updateCount) int updateCount = memberService.withdrawMember(member); // 탈퇴 처리 결과 판별 // => 실패 시 "fail_back" 포워딩 처리("회원 탈퇴 실패!") // => 성공 시 세션 초기화 후 메인페이지 리다이렉트 if(updateCount > 0) { session.invalidate(); return "redirect:/"; } else { model.addAttribute("msg", "회원 탈퇴 실패!"); return "fail_back"; } } // ======================================================================= // [ 관리자 페이지 ] @GetMapping("MemberAdminMain") public String adminMain(HttpSession session, Model model) { // 세션 아이디가 null 이거나 "admin" 이 아닐 경우 String sId = (String)session.getAttribute("sId"); if(sId == null || !sId.equals("admin")) { model.addAttribute("msg", "잘못된 접근입니다!"); return "fail_back"; } return "admin/admin_main"; } // [ 회원 목록 조회 ] @GetMapping("AdminMemberList") public String memberList(HttpSession session, Model model) { // 세션 아이디가 null 이거나 "admin" 이 아닐 경우 String sId = (String)session.getAttribute("sId"); if(sId == null || !sId.equals("admin")) { model.addAttribute("msg", "잘못된 접근입니다!"); return "fail_back"; } // MemberService - getMemberList() 메서드 호출하여 회원 목록 조회 요청 // => 파라미터 : 없음 리턴타입 : List<MemberVO>(memberList) List<MemberVO> memberList = memberService.getMemberList(); System.out.println(memberList); // Model 객체에 회원 목록 조회 결과 저장 model.addAttribute("memberList", memberList); // 회원 목록 조회 페이지(admin/member_list.jsp)로 포워딩 return "admin/member_list"; } }
penguKim/Spring_study
Spring_MVC_Board/src/main/java/com/itwillbs/mvc_board/controller/MemberController.java
6,501
// MemberService - getMember() 메서드 호출하여 회원 상세정보 조회 요청
line_comment
nl
package com.itwillbs.mvc_board.controller; import java.util.List; import java.util.Map; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.itwillbs.mvc_board.service.BankService; import com.itwillbs.mvc_board.service.MemberService; import com.itwillbs.mvc_board.service.SendMailService; import com.itwillbs.mvc_board.vo.MailAuthInfoVO; import com.itwillbs.mvc_board.vo.MemberVO; import com.itwillbs.mvc_board.vo.ResponseTokenVO; @Controller public class MemberController { // MemberService 객체 자동 주입 @Autowired private MemberService memberService; // SendMailService 객체 자동 주입 @Autowired private SendMailService mailService; @Autowired private BankService bankService; // [ 회원 가입 ] // "MemberJoinForm" 요청 joinForm() 메서드 정의(GET) // => "member/member_join_form.jsp" 페이지 포워딩 @GetMapping("MemberJoinForm") public String joinForm() { return "member/member_join_form"; } // "MemberJoinPro" 요청에 대한 비즈니스 로직 처리 수행할 joinPro() 메서드 정의(POST) // => 폼 파라미터를 통해 전달받은 회원정보를 MemberVO 타입으로 전달받기 // => 데이터 공유 객체 Model 타입 파라미터 추가 @PostMapping("MemberJoinPro") public String joinPro(MemberVO member, Model model) { // System.out.println(member); // ------------------------------------------------------------------------ // BCryptPasswordEncoder 를 활용한 패스워드 암호화 // 입력받은 패스워드는 암호화 필요 => 복호화가 불가능하도록 단방향 암호화(해싱) 수행 // => 평문(Clear Text, Plain Text) 을 해싱 후 MemberVO 객체의 passwd 에 덮어쓰기 // => org.springframework.security.crypto.bcrypt 패키지의 BCryptPasswordEncoder 클래스 활용 // (spring-security-crypto 또는 spring-security-web 라이브러리 추가) // 주의! JDK 11 일 때 5.x.x 버전 필요 // => BCryptPasswordEncoder 활용한 해싱은 솔팅(Salting) 기법을 통해 // 동일한 평문(원본 암호)이더라도 매번 다른 결과(암호문)를 얻을 수 있다! // 1. BCryptPasswordEncoder 클래스 인스턴스 생성 BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); // 2. BCryptPasswordEncoder 객체의 encode() 메서드를 호출하여 // 원문(평문) 패스워드에 대한 해싱(= 암호화) 수행 후 결과값 저장 // => 파라미터 : MemberVO 객체의 패스워드(평문 암호) 리턴타입 : String(암호문) String securePasswd = passwordEncoder.encode(member.getPasswd()); // System.out.println("평문 패스워드 : " + member.getPasswd()); // 1234 // System.out.println("암호화 된 패스워드 : " + securePasswd); // $2a$10$wvO.wV.ZHbRFVr9q4ayFbeGGCRs7XKxsN8wmll/.5YFlA/N7hFYl2(매번 다름) // 3. 암호화 된 패스워드를 MemberVO 객체에 저장 member.setPasswd(securePasswd); // ------------------------------------------------------------------------------------- // MemberService - registMember() 메서드 호출하여 회원가입 작업 요청 // => 파라미터 : MemberVO 객체 리턴타입 : int(insertCount) int insertCount = memberService.registMember(member); // 회원가입 성공/실패에 따른 페이징 처리 // => 성공 시 "MemberJoinSuccess" 서블릿 주소 리다이렉트 // => 실패 시 "fail_back.jsp" 페이지 포워딩("msg" 속성값으로 "회원 가입 실패!" 저장) if(insertCount > 0) { // 12-29 추가내용 // -------- 인증메일 발송 작업 추가 -------- // SendMailService - sendAuthMail() 메서드 호출하여 인증 메일 발송 요청 // => 파라미터 : 아이디, 이메일(= 회원 가입 시 입력한 정보) // 리턴타입 : String(auth_code = 인증코드) member.setEmail(member.getEmail1() + "@" + member.getEmail2()); // 이메일 결합 String auth_code = mailService.sendAuthMail(member); // System.out.println("인증코드 : " + auth_code); // MemberService - registAuthInfo() 메서드 호출하여 인증 정보 등록 요청 // => 파라미터 : 아이디, 인증코드 memberService.registMailAuthInfo(member.getId(), auth_code); return "redirect:/MemberJoinSuccess"; } else { // 실패 시 메세지 출력 및 이전페이지로 돌아가는 기능을 모듈화 한 fail_back.jsp 페이지 model.addAttribute("msg", "회원 가입 실패!"); return "fail_back"; } } // "MemberCheckDupId" 요청에 대한 아이디 중복 검사 비즈니스 로직 처리 // 응답데이터를 디스패치 또는 리다이렉트 용도가 아닌 응답 데이터 body 로 그대로 활용하려면 // @ResponseBody 어노테이션을 적용해야한다! => 응답 데이터를 직접 전송하도록 지정한다. // => 이 어노테이션은 AJAX 와 상관없이 적용 가능하지만 AJAX 일 때는 대부분 사용한다. @ResponseBody @GetMapping("MemberCheckDupId") public String checkDupId(MemberVO member) { System.out.println(member.getId()); // MemberService - getMember() 메서드 호출하여 아이디 조회(기존 메서드 재사용) // (MemberService - getMemberId() 메서드 호출하여 아이디 조회 메서드 정의 가능) // => 파라미터 : MemberVO 객체 리턴타입 : MemberVO(dbMember) MemberVO dbMember = memberService.getMember(member); // 조회 결과 판별 // => MemberVO 객체가 존재할 경우 아이디 중복, 아니면 사용 가능한 아이디 if(dbMember == null) { // 사용 가능한 아이디 return "false"; // 중복이 아니라는 의미로 "false" 값 전달 } else { // 아이디 중복 return "true"; // 중복이라는 의미로 "true" 값 전달 } } // -------------------------------------- // 인증 메일 발송 테스트를 위한 서블릿 매핑 // => URL 을 통해 강제로 회원 아이디와 수신자 이메일 주소 전달받아 사용 @GetMapping("TestAuthMail") public String testAuthMail(MemberVO member) { String auth_code = mailService.sendAuthMail(member); // System.out.println("인증코드 : " + auth_code); // MemberService - registAuthInfo() 메서드 호출하여 인증 정보 등록 요청 // => 파라미터 : 아이디, 인증코드 memberService.registMailAuthInfo(member.getId(), auth_code); // return "member/member_join_success"; return "redirect:/MemberJoinSuccess"; } // ----------------- // "MemberEmailAuth" 서블릿 요청에 대한 메일 인증 작업 비즈니스 로직 처리 @GetMapping("MemberEmailAuth") public String emailAuth(MailAuthInfoVO authInfo, Model model) { System.out.println("인증정보 : " + authInfo); // MemberService - requestEmailAuth() 메서드 호출하여 인증 요청 // => 파라미터 : MailAuthInfoVO 객체 리턴타입 : boolean(isAuthSuccess) boolean isAuthSuccess = memberService.requestEmailAuth(authInfo); // 인증 요청 결과 판별 if(isAuthSuccess) { // 성공 model.addAttribute("msg", "인증 성공! 로그인 페이지로 이동합니다!"); model.addAttribute("targetURL", "MemberLoginForm"); return "forward"; } else { model.addAttribute("msg", "인증 실패!"); return "fail_back"; } } // ================================================================================ // [ 로그인 ] // "MemberJoinSuccess" 요청에 대해 "member/member_join_success" 페이지 포워딩(GET) @GetMapping("MemberJoinSuccess") public String joinSuccess() { // 아이디 : hong, 비번 : 1111 return "member/member_join_success"; } // "MemberLoginForm" 요청에 대해 "member/login_form" 페이지 포워딩(GET) @GetMapping("MemberLoginForm") public String loginForm() { return "member/member_login_form"; } // "MemberLoginPro" 요청에 대한 비즈니스 로직 처리 수행할 loginPro() 메서드 정의(POST) // => 폼 파라미터를 통해 전달받은 회원정보를 MemberVO 타입으로 전달받기 // => 세션 활용을 위해 HttpSession 타입 파라미터 추가 // => 데이터 공유 객체 Model 타입 파라미터 추가 @PostMapping("MemberLoginPro") public String loginPro(MemberVO member, HttpSession session, Model model) { System.out.println(member); // MemberService - getMember() 메서드 호출하여 회원 정보 조회 요청 // => 파라미터 : MemberVO 객체 리턴타입 : MemberVO(dbMember) MemberVO dbMember = memberService.getMember(member); // System.out.println(dbMember); // 만약, 회원 상태(member_status)값이 3일 경우 // "fail_back" 포워딩 처리("탈퇴한 회원입니다!") if(dbMember.getMember_status() == 3) { model.addAttribute("msg", "탈퇴한 회원입니다!"); return "fail_back"; } // BCryptPasswordEncoder 객체를 활용한 패스워드 비교 // => 입력받은 패스워드(평문)와 DB 에 저장된 패스워드(암호문)는 직접적인 문자열 비교 불가 // => 일반적인 경우 전달받은 평문과 DB 에 저장된 암호문을 복호화하여 비교하면 되지만 // 단방향 암호화가 된 패스워드의 경우 평문을 암호화(해싱)하여 결과값을 비교해야함 // (단, 솔팅값이 서로 다르므로 직접적인 비교(String 의 equals())가 불가능) // => BCryptPasswordEncoder 객체의 matches() 메서드를 통한 비교 필수! BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); // => 단, 아이디가 일치하지 않을 경우(null 값 리턴됨) 또는 패스워드 불일치 시 // fail_back.jsp 페이지 포워딩("로그인 실패!") // null 값을 먼저 비교하지 않으면 NullPointException 발생 if(dbMember == null || !passwordEncoder.matches(member.getPasswd(), dbMember.getPasswd())) { // 로그인 실패 처리 model.addAttribute("msg", "로그인 실패!"); return "fail_back"; } else { // 12-29 추가내용 // 이메일 인증 여부 확인 // => 회원정보조회를 통해 MemberVO 객체에 저장된 // 이메일 인증 정보(mail_auth_status) 값이 "N" 일 경우 이메일 미인증 회원이므로 // "이메일 인증 후 로그인이 가능합니다" 출력 후 이전페이지로 돌아가기 if(dbMember.getMail_auth_status().equals("N")) { model.addAttribute("msg","이메일 인증 후 로그인이 가능합니다"); return "fail_back"; } // 세션 객체에 로그인 성공한 아이디를 "sId" 속성으로 추가 session.setAttribute("sId", member.getId()); // 1-22 추가내용 // -------------------------------------------------------------------- // BankService - getBankUserInfo() 메서드 호출하여 엑세스 토큰 조회 요청 // => 파라미터 : 아이디 리턴타입 : Map<String, String> Map<String, String> token = bankService.getBankUserInfo(member.getId()); // System.out.println(token); // -------------------------------------------------------------------- // 조회된 엑세스 토큰을 "access_token", 사용자 번호를 "user_seq_no" 로 세션에 추가 // => 단, Map객체(token)이 null 이 아닐 경우에만 수행 if(token != null ) { session.setAttribute("access_token", token.get("access_token")); session.setAttribute("user_seq_no", token.get("user_seq_no")); } // 메인페이지로 리다이렉트 return "redirect:/"; } } // "MemberLogout" 요청에 대한 로그아웃 비즈니스 로직 처리 @GetMapping("MemberLogout") public String logout(HttpSession session) { session.invalidate(); return "redirect:/"; } // =============================================================== // [ 회원 상세정보 조회 ] // "MemberInfo" 서블릿 요청 시 회원 상세정보 조회 비즈니스 로직 처리 // 회원 정보 조회 @GetMapping("MemberInfo") public String info(MemberVO member, HttpSession session, Model model) { // 세션 아이디가 없을 경우 "fail_back" 페이지를 통해 "잘못된 접근입니다" 출력 처리 String sId = (String)session.getAttribute("sId"); if(sId == null) { model.addAttribute("msg", "잘못된 접근입니다!"); return "fail_back"; } // 12-19 추가내용 // 관리자 계정일 경우 회원 조회시 해당 회원의 정보가 출력되어야한다. // 만약, 현재 세션이 관리자가 아니거나 // 관리자이면서 id 파라미터가 없을 경우(null 또는 널스트링) // MemberVO 객체의 id 값을 세션 아이디로 교체(덮어쓰기) // 파라미터가 없을 경우는 null, 파라미터는 있지만 데이터가 없으면 "" // 두가지 경우를 고려해서 null과 "" 둘 다 판별한다. if(!sId.equals("admin") || sId.equals("admin") && (member.getId() == null || member.getId().equals(""))) { member.setId(sId); } // MemberService -<SUF> // => 파라미터 : MemberVO 객체 리턴타입 : MemberVO(dbMember) MemberVO dbMember = memberService.getMember(member); // 조회 결과 Model 객체에 저장 model.addAttribute("member", dbMember); // 주민번호(MemberVO - jumin는 뒷자리 첫번째 숫자를 제외한 나머지 * 처리(마스킹) // => 처리된 주민번호를 jumin 멤버변수에 저장 // => 주민번호 앞자리 6자리와 뒷자리 1자리까지 추출하여 뒷부분에 * 기호 6개 결합 dbMember.setJumin(dbMember.getJumin().substring(0, 8) + "******"); // 0 ~ 8-1 인덱스까지 추출 // 회원 상세정보 조회 페이지 포워딩 return "member/member_info"; } // =============================================================== // [ 회원 정보 수정 ] // "MemberModifyForm" 서블릿 요청 시 회원 정보 수정 폼 표시 @GetMapping("MemberModifyForm") public String modifyForm(MemberVO member, HttpSession session, Model model) { String sId = (String)session.getAttribute("sId"); if(sId == null) { model.addAttribute("msg", "잘못된 접근입니다!"); return "fail_back"; } // 만약, 현재 세션이 관리자가 아니거나 // 관리자이면서 id 파라미터가 없을 경우(null 또는 널스트링) // MemberVO 객체의 id 값을 세션 아이디로 교체(덮어쓰기) if(!sId.equals("admin") || sId.equals("admin") && (member.getId() == null || member.getId().equals(""))) { member.setId(sId); } // MemberService - getMember() 메서드 호출하여 회원 상세정보 조회 요청 // => 파라미터 : MemberVO 객체 리턴타입 : MemberVO(dbMember) MemberVO dbMember = memberService.getMember(member); // 주민번호(MemberVO - jumin는 뒷자리 첫번째 숫자를 제외한 나머지 * 처리(마스킹) // => 처리된 주민번호를 jumin 멤버변수에 저장 // => 주민번호 앞자리 6자리와 뒷자리 1자리까지 추출하여 뒷부분에 * 기호 6개 결합 dbMember.setJumin(dbMember.getJumin().substring(0, 8) + "******"); // 0 ~ 8-1 인덱스까지 추출 // 조회 결과 Model 객체에 저장 model.addAttribute("member", dbMember); return "member/member_modify_form"; } // "MemberModifyPro" 서블릿 요청에 대한 회원 정보 수정 비즈니스 로직 처리 // => 추가로 전달되는 새 패스워드(newPasswd) 값을 전달받을 파라미터 변수 1개 추가(Map 사용 가능) @PostMapping("MemberModifyPro") public String modifyPro(MemberVO member, String newPasswd, HttpSession session, Model model) { String sId = (String)session.getAttribute("sId"); if(sId == null) { model.addAttribute("msg", "잘못된 접근입니다!"); return "fail_back"; } // 만약, 현재 세션이 관리자가 아니거나 // 관리자이면서 id 파라미터가 없을 경우(null 또는 널스트링) // MemberVO 객체의 id 값을 세션 아이디로 교체(덮어쓰기) if(!sId.equals("admin") || sId.equals("admin") && (member.getId() == null || member.getId().equals(""))) { member.setId(sId); } // MemberService - getMember() 메서드 호출하여 회원 정보 조회 요청(패스워드 비교용) // => 파라미터 : MemberVO 객체 리턴타입 : MemberVO(dbMember) MemberVO dbMember = memberService.getMember(member); // BCryptPasswordEncoder 클래스를 활용하여 입력받은 기존 패스워드와 DB 패스워드 비교 BCryptPasswordEncoder passwoedEncoder = new BCryptPasswordEncoder(); // 만약, 현재 세션이 관리자가 아니거나 // 관리자이면서 id 파라미터가 없을 경우(null 또는 널스트링) // MemberVO 객체의 id 값을 세션 아이디로 교체(덮어쓰기) if(!sId.equals("admin") || sId.equals("admin") && (member.getId() == null || member.getId().equals(""))) { // 이 때, 동일한 조건에서 패스워드 검증도 추가로 수행 // => 관리자가 다른 회원의 정보를 수정할 경우에는 패스워드 검증 수행 생략됨 if(!passwoedEncoder.matches(member.getPasswd(), dbMember.getPasswd())) { model.addAttribute("msg", "수정 권한이 없습니다!"); return "fail_back"; } } // 새 패스워드를 입력받았을 경우 BCryptPasswordEncoder 클래스를 활요하여 암호화 처리 // 파라미터로는 newPasswd 자체는 있기에 입력값이 없을 경우 ""으로 넘어오지만 // 만일의 경우를 대비해서 null값도 비교한다. if(newPasswd != null && !newPasswd.equals("")) { newPasswd = passwoedEncoder.encode(newPasswd); } // MemberService - modifyMember() 메서드 호출하여 회원 정보 수정 요청 // => 파라미터 : MemberVO 객체, 새 패스워드(newPasswd) 리턴타입 : int(updateCount) int updateCount = memberService.modifyMember(member, newPasswd); // 회원 정보 수정 요청 결과 판별 // => 실패 시 "fail_back" 페이지 포워딩 처리("회원정보 수정 실패!") // => 성공 시 "MemberInfo" 서블릿 리다이렉트 if(updateCount > 0) { // 관리자가 다른 회원 정보 수정 시 MemberInfo 서블릿 주소에 아이디 파라미터 결합 if(!sId.equals("admin") || sId.equals("admin") && (member.getId() == null || member.getId().equals(""))) { // 본인 정보를 조회할 경우 return "redirect:/MemberInfo"; } else { return "redirect:/MemberInfo?id=" + member.getId(); } } else { model.addAttribute("msg", "회원정보 수정 실패!"); return "fail_back"; } } // =============================================================== // [ 회원 탈퇴 ] // "MemberWithdrawForm" 서블릿 요청 시 회원 정보 탈퇴 폼 표시 @GetMapping("MemberWithdrawForm") public String withdrawForm(HttpSession session, Model model) { String sId = (String)session.getAttribute("sId"); if(sId == null) { model.addAttribute("msg", "잘못된 접근입니다!"); return "fail_back"; } return "member/member_withdraw_form"; } // "MemberWithdrawPro" 서블릿 요청 시 회원 탈퇴 비즈니스 로직 처리 @PostMapping("MemberWithdrawPro") public String withdrawPro(MemberVO member, HttpSession session, Model model) { String sId = (String)session.getAttribute("sId"); if(sId == null) { model.addAttribute("msg", "잘못된 접근입니다!"); return "fail_back"; } member.setId(sId); // MemberService - getMember() 메서드 호출하여 회원 정보 조회 요청(패스워드 비교용) // => 파라미터 : MemberVO 객체 리턴타입 : MemberVO(dbMember) MemberVO dbMember = memberService.getMember(member); // BCryptPasswordEncoder 클래스를 활용하여 입력받은 기존 패스워드와 DB 패스워드 비교 BCryptPasswordEncoder passwoedEncoder = new BCryptPasswordEncoder(); if(!passwoedEncoder.matches(member.getPasswd(), dbMember.getPasswd())) { model.addAttribute("msg", "수정 권한이 없습니다!"); return "fail_back"; } // MemberService - withdrawMember() 메서드 호출하여 회원 탈퇴 처리 요청 // => 파라미터 : MemberVO 객체 리턴타입 : int(updateCount) int updateCount = memberService.withdrawMember(member); // 탈퇴 처리 결과 판별 // => 실패 시 "fail_back" 포워딩 처리("회원 탈퇴 실패!") // => 성공 시 세션 초기화 후 메인페이지 리다이렉트 if(updateCount > 0) { session.invalidate(); return "redirect:/"; } else { model.addAttribute("msg", "회원 탈퇴 실패!"); return "fail_back"; } } // ======================================================================= // [ 관리자 페이지 ] @GetMapping("MemberAdminMain") public String adminMain(HttpSession session, Model model) { // 세션 아이디가 null 이거나 "admin" 이 아닐 경우 String sId = (String)session.getAttribute("sId"); if(sId == null || !sId.equals("admin")) { model.addAttribute("msg", "잘못된 접근입니다!"); return "fail_back"; } return "admin/admin_main"; } // [ 회원 목록 조회 ] @GetMapping("AdminMemberList") public String memberList(HttpSession session, Model model) { // 세션 아이디가 null 이거나 "admin" 이 아닐 경우 String sId = (String)session.getAttribute("sId"); if(sId == null || !sId.equals("admin")) { model.addAttribute("msg", "잘못된 접근입니다!"); return "fail_back"; } // MemberService - getMemberList() 메서드 호출하여 회원 목록 조회 요청 // => 파라미터 : 없음 리턴타입 : List<MemberVO>(memberList) List<MemberVO> memberList = memberService.getMemberList(); System.out.println(memberList); // Model 객체에 회원 목록 조회 결과 저장 model.addAttribute("memberList", memberList); // 회원 목록 조회 페이지(admin/member_list.jsp)로 포워딩 return "admin/member_list"; } }
26167_3
package main.view.start; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import javafx.stage.WindowEvent; import main.Log; import main.model.MainModel; public class StartPresenter { private StartView startView; public StartPresenter( MainModel model, StartView startView ) { this.startView = startView; this.addEventHandlers(); this.updateView(); Log.debug("StartView is initialized."); } 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. addMenuEventHandlers(); } private void updateView() { // Vult de view met data uit model // splash-screen } public void addWindowEventHandlers() { // Window event handlers (anon. inner klassen) // Koppeling via view.getScene().getWindow() startView.getScene().getWindow().setOnCloseRequest(new EventHandler<WindowEvent>() { @Override public void handle(WindowEvent event) { Alert alert = new Alert(Alert.AlertType.WARNING); alert.setHeaderText("Are you sure?"); alert.setContentText("Are you sure you want to close the application?"); alert.setTitle("Warning!"); alert.getButtonTypes().clear(); ButtonType no = new ButtonType("No"); ButtonType yes = new ButtonType("Yes"); alert.getButtonTypes().addAll(no, yes); alert.showAndWait(); if (alert.getResult().equals(no)) { event.consume(); } } }); } private void addMenuEventHandlers() { startView.getMiExit().setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { Alert alert = new Alert(Alert.AlertType.WARNING); alert.setHeaderText("Are you sure?"); alert.setContentText("Are you sure you want to close the application?"); alert.setTitle("Warning!"); alert.getButtonTypes().clear(); ButtonType no = new ButtonType("No"); ButtonType yes = new ButtonType("Yes"); alert.getButtonTypes().addAll(no, yes); alert.showAndWait(); if (alert.getResult().equals(no)) { event.consume(); } else { Platform.exit(); } } }); } }
LeventHAN/JavaFX-MVP-Pattern-Boilerplate
src/main/view/start/StartPresenter.java
645
// model en zorgen voor een update van de view.
line_comment
nl
package main.view.start; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import javafx.stage.WindowEvent; import main.Log; import main.model.MainModel; public class StartPresenter { private StartView startView; public StartPresenter( MainModel model, StartView startView ) { this.startView = startView; this.addEventHandlers(); this.updateView(); Log.debug("StartView is initialized."); } 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> addMenuEventHandlers(); } private void updateView() { // Vult de view met data uit model // splash-screen } public void addWindowEventHandlers() { // Window event handlers (anon. inner klassen) // Koppeling via view.getScene().getWindow() startView.getScene().getWindow().setOnCloseRequest(new EventHandler<WindowEvent>() { @Override public void handle(WindowEvent event) { Alert alert = new Alert(Alert.AlertType.WARNING); alert.setHeaderText("Are you sure?"); alert.setContentText("Are you sure you want to close the application?"); alert.setTitle("Warning!"); alert.getButtonTypes().clear(); ButtonType no = new ButtonType("No"); ButtonType yes = new ButtonType("Yes"); alert.getButtonTypes().addAll(no, yes); alert.showAndWait(); if (alert.getResult().equals(no)) { event.consume(); } } }); } private void addMenuEventHandlers() { startView.getMiExit().setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { Alert alert = new Alert(Alert.AlertType.WARNING); alert.setHeaderText("Are you sure?"); alert.setContentText("Are you sure you want to close the application?"); alert.setTitle("Warning!"); alert.getButtonTypes().clear(); ButtonType no = new ButtonType("No"); ButtonType yes = new ButtonType("Yes"); alert.getButtonTypes().addAll(no, yes); alert.showAndWait(); if (alert.getResult().equals(no)) { event.consume(); } else { Platform.exit(); } } }); } }
121873_11
/* Copyright (c) 2017 FIRST. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted (subject to the limitations in the disclaimer below) provided that * the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * Neither the name of FIRST nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS * LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.firstinspires.ftc.teamcode; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import com.disnodeteam.dogecv.CameraViewDisplay; import com.disnodeteam.dogecv.detectors.*; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.eventloop.opmode.OpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.qualcomm.robotcore.util.ElapsedTime; import java.io.IOException; /** * This file contains an minimal example of a Linear "OpMode". An OpMode is a 'program' that runs in either * the autonomous or the teleop period of an FTC match. The names of OpModes appear on the menu * of the FTC Driver Station. When an selection is made from the menu, the corresponding OpMode * class is instantiated on the Robot Controller and executed. * * This particular OpMode just executes a basic Tank Drive Teleop for a two wheeled robot * It includes all the skeletal structure that all linear OpModes contain. * * Use Android Studios to Copy this Class, and Paste it into your team's code folder with a new name. * Remove or comment out the @Disabled line to add this opmode to the Driver Station OpMode list */ @Autonomous(name="Autonomous Period", group="Linear Opmode") //@Disabled public class AutonomousPeriod extends LinearOpMode { // Declare OpMode members. HardwareVar r = new HardwareVar(); @Override public void runOpMode() { r.init(hardwareMap); r.grijp.setPosition(0.68); waitForStart(); // run until the end of the match (driver presses STOP) while (opModeIsActive()) { r.powerAll(0.4); sleep(1100); r.powerAll(0); r.grijp.setPosition(1); r.powerAll(-0.2); sleep(200); r.powerAll(0); break; //Lees kleur //Bal omgooien //Terug draaien //90 graden draaien //0.76 meter naar voren // 90 graden terug draaien //iets naar voren //blok neerzetten //ietsje pietsje naar achter // if(r.colorSensor.red() > r.colorSensor.blue() && r.colorSensor.red() >= 5 ) { // // } // // // if(r.colorSensor.blue() > r.colorSensor.red() && r.colorSensor.blue() >= 5 ) { // telemetry.addData("kleur:", "Waarschijnlijk blauw"); // // } // telemetry.addData("Clear", r.colorSensor.alpha()); // telemetry.addData("Red ", r.colorSensor.red()); // telemetry.addData("Green", r.colorSensor.green()); // telemetry.addData("Blue ", r.colorSensor.blue()); // // // telemetry.update(); } } }
ArjanB2001/FTC_Robot
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/AutonomousPeriod.java
1,173
// telemetry.addData("kleur:", "Waarschijnlijk blauw");
line_comment
nl
/* Copyright (c) 2017 FIRST. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted (subject to the limitations in the disclaimer below) provided that * the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * Neither the name of FIRST nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS * LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.firstinspires.ftc.teamcode; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import com.disnodeteam.dogecv.CameraViewDisplay; import com.disnodeteam.dogecv.detectors.*; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.eventloop.opmode.OpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.qualcomm.robotcore.util.ElapsedTime; import java.io.IOException; /** * This file contains an minimal example of a Linear "OpMode". An OpMode is a 'program' that runs in either * the autonomous or the teleop period of an FTC match. The names of OpModes appear on the menu * of the FTC Driver Station. When an selection is made from the menu, the corresponding OpMode * class is instantiated on the Robot Controller and executed. * * This particular OpMode just executes a basic Tank Drive Teleop for a two wheeled robot * It includes all the skeletal structure that all linear OpModes contain. * * Use Android Studios to Copy this Class, and Paste it into your team's code folder with a new name. * Remove or comment out the @Disabled line to add this opmode to the Driver Station OpMode list */ @Autonomous(name="Autonomous Period", group="Linear Opmode") //@Disabled public class AutonomousPeriod extends LinearOpMode { // Declare OpMode members. HardwareVar r = new HardwareVar(); @Override public void runOpMode() { r.init(hardwareMap); r.grijp.setPosition(0.68); waitForStart(); // run until the end of the match (driver presses STOP) while (opModeIsActive()) { r.powerAll(0.4); sleep(1100); r.powerAll(0); r.grijp.setPosition(1); r.powerAll(-0.2); sleep(200); r.powerAll(0); break; //Lees kleur //Bal omgooien //Terug draaien //90 graden draaien //0.76 meter naar voren // 90 graden terug draaien //iets naar voren //blok neerzetten //ietsje pietsje naar achter // if(r.colorSensor.red() > r.colorSensor.blue() && r.colorSensor.red() >= 5 ) { // // } // // // if(r.colorSensor.blue() > r.colorSensor.red() && r.colorSensor.blue() >= 5 ) { // telemetry.addData("kleur:", "Waarschijnlijk<SUF> // // } // telemetry.addData("Clear", r.colorSensor.alpha()); // telemetry.addData("Red ", r.colorSensor.red()); // telemetry.addData("Green", r.colorSensor.green()); // telemetry.addData("Blue ", r.colorSensor.blue()); // // // telemetry.update(); } } }
122953_4
package be.kdg.fill.views.gamemenu.addworld; import be.kdg.fill.FillApplication; import be.kdg.fill.models.core.Level; import be.kdg.fill.models.core.World; import be.kdg.fill.models.helpers.WorldLoader; import be.kdg.fill.views.Presenter; import be.kdg.fill.views.gamemenu.GameMenuPresenter; import be.kdg.fill.views.gamemenu.addworld.helpers.CheckBoxes; import be.kdg.fill.views.gamemenu.addworld.helpers.LevelCreationBox; import be.kdg.fill.views.gamemenu.worldselect.WorldSelectPresenter; import be.kdg.fill.views.gamemenu.worldselect.WorldSelectView; import javafx.event.ActionEvent; import javafx.scene.control.ButtonBar; import javafx.scene.control.ButtonType; import javafx.scene.control.Dialog; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.GridPane; import javafx.scene.layout.VBox; import javafx.stage.Stage; import java.util.ArrayList; import java.util.List; public class AddWorldPresenter implements Presenter { private AddWorldView view; private GameMenuPresenter parent; private List<LevelCreationBox> levelCreationBoxes; private List<CheckBoxes> checkBoxesList; private List<Level> levels; private int nextId = 1; public static final String SCREEN_NAME = "addworld"; public AddWorldPresenter(AddWorldView addWorldView, GameMenuPresenter parent) { this.view = addWorldView; this.parent = parent; this.levelCreationBoxes = new ArrayList<>(); this.checkBoxesList = new ArrayList<>(); this.levels = new ArrayList<>(); addEventHandlers(); } private void addEventHandlers() { view.getBackButton().setOnAction(this::handleBackButton); view.getAddButton().setOnAction(this::handleAddButton); view.getConfirmationButton().setOnAction(this::handleConfirmationButton); view.getSavingButton().setOnAction(this::handleSavingButton); } private void handleBackButton(ActionEvent event) { parent.getSubScreenManager().switchBack(); resetTheListsAndView(); } private void handleAddButton(ActionEvent actionEvent) { try { AddWorldInputControl(); addLevelInputInfo(); view.getErrorLabel().setText(""); } catch (Exception e) { view.getErrorLabel().setText(e.getMessage()); } } private void handleConfirmationButton(ActionEvent actionEvent) { boolean firstStepControled; try { AddWorldInputControl(); view.getErrorLabel().setText(""); firstStepControled = true; } catch (Exception e) { view.getErrorLabel().setText(e.getMessage()); firstStepControled = false; } for (LevelCreationBox box : levelCreationBoxes) { try { box.getErrorsLabelLevelCreationBox().setText(""); levelCreationBoxInputControl(box); addCheckBoxes(); } catch (Exception e) { box.getErrorsLabelLevelCreationBox().setText(e.getMessage()); } } if (firstStepControled && levelCreationBoxes.isEmpty()) { view.getErrorLabel().setText("This action can be taken after you add some levels to this world!"); } } private void handleSavingButton(ActionEvent actionEvent) { boolean firstStepControled = false; boolean secondStepControled = false; boolean worldAddedSuccesfully = false; //input eerste stap checken try { AddWorldInputControl(); view.getErrorLabel().setText(""); firstStepControled = true; } catch (Exception e) { view.getErrorLabel().setText(e.getMessage()); } //input 2e stap checken if (firstStepControled) { for (LevelCreationBox box : levelCreationBoxes) { try { box.getErrorsLabelLevelCreationBox().setText(""); levelCreationBoxInputControl(box); checkBoxesListControl(); secondStepControled = true; } catch (Exception e) { box.getErrorsLabelLevelCreationBox().setText(e.getMessage()); } } } //3e stap opslaan van de world if (secondStepControled) { try { for (LevelCreationBox box : levelCreationBoxes) { box.getErrorsLabelLevelCreationBox().setText(""); levelCreationBoxInputControl(box); checkBoxesListControl(); } AddWorldInputControl(); view.getErrorLabel().setText(""); //nagaan of de positie 1 is addLevels(); //alle opgeslagen data van de levels wissen levels.clear(); //wanneer de exceptions zijn opgevangen //dan met deze boolean alle levels opslaan in de world //en deze operatie beeindigen worldAddedSuccesfully = true; } catch (Exception e) { for (LevelCreationBox box : levelCreationBoxes) { box.getErrorsLabelLevelCreationBox().setText(e.getMessage()); } } } if (!worldAddedSuccesfully) { if (firstStepControled && levelCreationBoxes.isEmpty()) { view.getErrorLabel().setText("This action can be taken after you add some levels to this world!"); } } if (worldAddedSuccesfully) { addLevels(); addWorld(); resetTheListsAndView(); lastDialog(); } if (worldAddedSuccesfully) { boolean worldLoaded = false; while (!worldLoaded) { try { WorldSelectPresenter worldSelectPresenter = new WorldSelectPresenter(new WorldSelectView(), parent); worldSelectPresenter.reload(); parent.getWorldLoader().loadWorlds(); worldLoaded = true; } catch (Exception e) { e.printStackTrace(); } } } } public void addLevelInputInfo() { LevelCreationBox levelCreationBox = new LevelCreationBox(); levelCreationBox.setId(nextId++); levelCreationBoxes.add(levelCreationBox); view.getvBox().getChildren().addAll(levelCreationBox); } public void addCheckBoxes() { VBox vBox = new VBox(20); checkBoxesList.clear(); for (LevelCreationBox box : levelCreationBoxes) { int rows = box.getRows(); int cols = box.getCols(); GridPane gridPane = new GridPane(); gridPane.add(box, 0, 0); CheckBoxes checkBoxes = new CheckBoxes(rows, cols); checkBoxesList.add(checkBoxes); gridPane.add(checkBoxes, 1, 0); vBox.getChildren().addAll(gridPane); } view.getvBox().getChildren().clear(); view.getvBox().getChildren().add(vBox); } public void addLevels() { List<int[][]> checkBoxesStatusMatrix = new ArrayList<>(); for (CheckBoxes checkBoxes : checkBoxesList) { int[][] checkBoxStatus = checkBoxes.getCheckBoxStatus(); checkBoxesStatusMatrix.add(checkBoxStatus); } int idJsonLevel = 0; for (LevelCreationBox levelCreationBox : levelCreationBoxes) { int[] startPos = levelCreationBox.startPosCoordination(); if (checkBoxesStatusMatrix.get(idJsonLevel)[startPos[0]][startPos[1]] == 0) { levels.clear(); throw new IllegalStateException("Checkbox value at start position cannot be 0!"); } levels.add(new Level(idJsonLevel + 1, checkBoxesStatusMatrix.get(idJsonLevel), startPos)); idJsonLevel++; } } private void addWorld() { String worldName = String.valueOf(view.getWorldName().getField().getText()); String difficultyName = String.valueOf(view.getDifficultyName().getField().getText()); World world = new World(worldName, "images/admin-foto.jpg", difficultyName); WorldLoader worldLoader = parent.getWorldLoader(); for (Level level : levels) { world.addLevel(level); } worldLoader.addWorld(world); worldLoader.saveWorld(world.getId()); } private void AddWorldInputControl() { String worldName = String.valueOf(view.getWorldName().getField().getText()); String difficultyName = String.valueOf(view.getDifficultyName().getField().getText()); if (worldName == null || worldName.length() < 4 || worldName.length() > 15) { throw new IllegalArgumentException("World name must be between 4 and 15 characters long"); } else if (difficultyName == null || difficultyName.length() < 4 || difficultyName.length() > 15) { throw new IllegalArgumentException("Difficulty name must be between 4 and 15 characters long"); } } private void checkBoxesListControl() { if (checkBoxesList.isEmpty()) { throw new ArrayIndexOutOfBoundsException("First you need to get checkboxes!"); } } private void levelCreationBoxInputControl(LevelCreationBox box) { int rows = box.getRows(); int cols = box.getCols(); if (rows > 20 || rows < 1) { throw new IllegalArgumentException("Rows value must be between 1 and 20!"); } else if (cols > 20 || cols < 1) { throw new IllegalArgumentException("Columns value must be between 1 and 20!"); } int[] positionCheck = box.startPosCoordination(); if (positionCheck[0] >= rows || positionCheck[0] < 0) { throw new IllegalArgumentException("The X-coordinate must be within the range of 0 to (row - 1)"); } else if (positionCheck[1] >= cols || positionCheck[1] < 0) { throw new IllegalArgumentException("The Y-coordinate must be within the range of 0 to (column - 1)"); } } private void resetTheListsAndView() { view.getWorldName().getField().clear(); view.getDifficultyName().getField().clear(); levelCreationBoxes.clear(); checkBoxesList.clear(); levels.clear(); this.nextId = 1; view.getErrorLabel().setText(""); view.getvBox().getChildren().clear(); } private void lastDialog() { Dialog<ButtonType> dialog = new Dialog<>(); dialog.setTitle("World succesfully added!"); dialog.setHeaderText("What's next?"); ImageView imageView = new ImageView(new Image(FillApplication.class.getResourceAsStream("images/fill-icon.png"))); dialog.setGraphic(imageView); dialog.setContentText("You can leave this page or add some more levels."); ((Stage) dialog.getDialogPane().getScene().getWindow()).getIcons().add(new Image(FillApplication.class.getResourceAsStream("images/fill-icon.png"))); ButtonType backButton = new ButtonType("Leave", ButtonBar.ButtonData.OK_DONE); ButtonType addAnotherWorldButton = new ButtonType("Add another world", ButtonBar.ButtonData.OK_DONE); dialog.getDialogPane().getButtonTypes().addAll(backButton, addAnotherWorldButton); dialog.getDialogPane().getScene().getWindow().setOnCloseRequest(event -> dialog.close()); dialog.showAndWait().ifPresent(choice -> { if (choice == backButton) { parent.getSubScreenManager().switchScreen("worldselect"); } else if (choice == addAnotherWorldButton) { parent.getSubScreenManager().getCurrentScreen(); } }); } @Override public AddWorldView getView() { return this.view; } @Override public String getScreenName() { return SCREEN_NAME; } }
Luciffffer/FILL
src/main/java/be/kdg/fill/views/gamemenu/addworld/AddWorldPresenter.java
2,961
//alle opgeslagen data van de levels wissen
line_comment
nl
package be.kdg.fill.views.gamemenu.addworld; import be.kdg.fill.FillApplication; import be.kdg.fill.models.core.Level; import be.kdg.fill.models.core.World; import be.kdg.fill.models.helpers.WorldLoader; import be.kdg.fill.views.Presenter; import be.kdg.fill.views.gamemenu.GameMenuPresenter; import be.kdg.fill.views.gamemenu.addworld.helpers.CheckBoxes; import be.kdg.fill.views.gamemenu.addworld.helpers.LevelCreationBox; import be.kdg.fill.views.gamemenu.worldselect.WorldSelectPresenter; import be.kdg.fill.views.gamemenu.worldselect.WorldSelectView; import javafx.event.ActionEvent; import javafx.scene.control.ButtonBar; import javafx.scene.control.ButtonType; import javafx.scene.control.Dialog; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.GridPane; import javafx.scene.layout.VBox; import javafx.stage.Stage; import java.util.ArrayList; import java.util.List; public class AddWorldPresenter implements Presenter { private AddWorldView view; private GameMenuPresenter parent; private List<LevelCreationBox> levelCreationBoxes; private List<CheckBoxes> checkBoxesList; private List<Level> levels; private int nextId = 1; public static final String SCREEN_NAME = "addworld"; public AddWorldPresenter(AddWorldView addWorldView, GameMenuPresenter parent) { this.view = addWorldView; this.parent = parent; this.levelCreationBoxes = new ArrayList<>(); this.checkBoxesList = new ArrayList<>(); this.levels = new ArrayList<>(); addEventHandlers(); } private void addEventHandlers() { view.getBackButton().setOnAction(this::handleBackButton); view.getAddButton().setOnAction(this::handleAddButton); view.getConfirmationButton().setOnAction(this::handleConfirmationButton); view.getSavingButton().setOnAction(this::handleSavingButton); } private void handleBackButton(ActionEvent event) { parent.getSubScreenManager().switchBack(); resetTheListsAndView(); } private void handleAddButton(ActionEvent actionEvent) { try { AddWorldInputControl(); addLevelInputInfo(); view.getErrorLabel().setText(""); } catch (Exception e) { view.getErrorLabel().setText(e.getMessage()); } } private void handleConfirmationButton(ActionEvent actionEvent) { boolean firstStepControled; try { AddWorldInputControl(); view.getErrorLabel().setText(""); firstStepControled = true; } catch (Exception e) { view.getErrorLabel().setText(e.getMessage()); firstStepControled = false; } for (LevelCreationBox box : levelCreationBoxes) { try { box.getErrorsLabelLevelCreationBox().setText(""); levelCreationBoxInputControl(box); addCheckBoxes(); } catch (Exception e) { box.getErrorsLabelLevelCreationBox().setText(e.getMessage()); } } if (firstStepControled && levelCreationBoxes.isEmpty()) { view.getErrorLabel().setText("This action can be taken after you add some levels to this world!"); } } private void handleSavingButton(ActionEvent actionEvent) { boolean firstStepControled = false; boolean secondStepControled = false; boolean worldAddedSuccesfully = false; //input eerste stap checken try { AddWorldInputControl(); view.getErrorLabel().setText(""); firstStepControled = true; } catch (Exception e) { view.getErrorLabel().setText(e.getMessage()); } //input 2e stap checken if (firstStepControled) { for (LevelCreationBox box : levelCreationBoxes) { try { box.getErrorsLabelLevelCreationBox().setText(""); levelCreationBoxInputControl(box); checkBoxesListControl(); secondStepControled = true; } catch (Exception e) { box.getErrorsLabelLevelCreationBox().setText(e.getMessage()); } } } //3e stap opslaan van de world if (secondStepControled) { try { for (LevelCreationBox box : levelCreationBoxes) { box.getErrorsLabelLevelCreationBox().setText(""); levelCreationBoxInputControl(box); checkBoxesListControl(); } AddWorldInputControl(); view.getErrorLabel().setText(""); //nagaan of de positie 1 is addLevels(); //alle opgeslagen<SUF> levels.clear(); //wanneer de exceptions zijn opgevangen //dan met deze boolean alle levels opslaan in de world //en deze operatie beeindigen worldAddedSuccesfully = true; } catch (Exception e) { for (LevelCreationBox box : levelCreationBoxes) { box.getErrorsLabelLevelCreationBox().setText(e.getMessage()); } } } if (!worldAddedSuccesfully) { if (firstStepControled && levelCreationBoxes.isEmpty()) { view.getErrorLabel().setText("This action can be taken after you add some levels to this world!"); } } if (worldAddedSuccesfully) { addLevels(); addWorld(); resetTheListsAndView(); lastDialog(); } if (worldAddedSuccesfully) { boolean worldLoaded = false; while (!worldLoaded) { try { WorldSelectPresenter worldSelectPresenter = new WorldSelectPresenter(new WorldSelectView(), parent); worldSelectPresenter.reload(); parent.getWorldLoader().loadWorlds(); worldLoaded = true; } catch (Exception e) { e.printStackTrace(); } } } } public void addLevelInputInfo() { LevelCreationBox levelCreationBox = new LevelCreationBox(); levelCreationBox.setId(nextId++); levelCreationBoxes.add(levelCreationBox); view.getvBox().getChildren().addAll(levelCreationBox); } public void addCheckBoxes() { VBox vBox = new VBox(20); checkBoxesList.clear(); for (LevelCreationBox box : levelCreationBoxes) { int rows = box.getRows(); int cols = box.getCols(); GridPane gridPane = new GridPane(); gridPane.add(box, 0, 0); CheckBoxes checkBoxes = new CheckBoxes(rows, cols); checkBoxesList.add(checkBoxes); gridPane.add(checkBoxes, 1, 0); vBox.getChildren().addAll(gridPane); } view.getvBox().getChildren().clear(); view.getvBox().getChildren().add(vBox); } public void addLevels() { List<int[][]> checkBoxesStatusMatrix = new ArrayList<>(); for (CheckBoxes checkBoxes : checkBoxesList) { int[][] checkBoxStatus = checkBoxes.getCheckBoxStatus(); checkBoxesStatusMatrix.add(checkBoxStatus); } int idJsonLevel = 0; for (LevelCreationBox levelCreationBox : levelCreationBoxes) { int[] startPos = levelCreationBox.startPosCoordination(); if (checkBoxesStatusMatrix.get(idJsonLevel)[startPos[0]][startPos[1]] == 0) { levels.clear(); throw new IllegalStateException("Checkbox value at start position cannot be 0!"); } levels.add(new Level(idJsonLevel + 1, checkBoxesStatusMatrix.get(idJsonLevel), startPos)); idJsonLevel++; } } private void addWorld() { String worldName = String.valueOf(view.getWorldName().getField().getText()); String difficultyName = String.valueOf(view.getDifficultyName().getField().getText()); World world = new World(worldName, "images/admin-foto.jpg", difficultyName); WorldLoader worldLoader = parent.getWorldLoader(); for (Level level : levels) { world.addLevel(level); } worldLoader.addWorld(world); worldLoader.saveWorld(world.getId()); } private void AddWorldInputControl() { String worldName = String.valueOf(view.getWorldName().getField().getText()); String difficultyName = String.valueOf(view.getDifficultyName().getField().getText()); if (worldName == null || worldName.length() < 4 || worldName.length() > 15) { throw new IllegalArgumentException("World name must be between 4 and 15 characters long"); } else if (difficultyName == null || difficultyName.length() < 4 || difficultyName.length() > 15) { throw new IllegalArgumentException("Difficulty name must be between 4 and 15 characters long"); } } private void checkBoxesListControl() { if (checkBoxesList.isEmpty()) { throw new ArrayIndexOutOfBoundsException("First you need to get checkboxes!"); } } private void levelCreationBoxInputControl(LevelCreationBox box) { int rows = box.getRows(); int cols = box.getCols(); if (rows > 20 || rows < 1) { throw new IllegalArgumentException("Rows value must be between 1 and 20!"); } else if (cols > 20 || cols < 1) { throw new IllegalArgumentException("Columns value must be between 1 and 20!"); } int[] positionCheck = box.startPosCoordination(); if (positionCheck[0] >= rows || positionCheck[0] < 0) { throw new IllegalArgumentException("The X-coordinate must be within the range of 0 to (row - 1)"); } else if (positionCheck[1] >= cols || positionCheck[1] < 0) { throw new IllegalArgumentException("The Y-coordinate must be within the range of 0 to (column - 1)"); } } private void resetTheListsAndView() { view.getWorldName().getField().clear(); view.getDifficultyName().getField().clear(); levelCreationBoxes.clear(); checkBoxesList.clear(); levels.clear(); this.nextId = 1; view.getErrorLabel().setText(""); view.getvBox().getChildren().clear(); } private void lastDialog() { Dialog<ButtonType> dialog = new Dialog<>(); dialog.setTitle("World succesfully added!"); dialog.setHeaderText("What's next?"); ImageView imageView = new ImageView(new Image(FillApplication.class.getResourceAsStream("images/fill-icon.png"))); dialog.setGraphic(imageView); dialog.setContentText("You can leave this page or add some more levels."); ((Stage) dialog.getDialogPane().getScene().getWindow()).getIcons().add(new Image(FillApplication.class.getResourceAsStream("images/fill-icon.png"))); ButtonType backButton = new ButtonType("Leave", ButtonBar.ButtonData.OK_DONE); ButtonType addAnotherWorldButton = new ButtonType("Add another world", ButtonBar.ButtonData.OK_DONE); dialog.getDialogPane().getButtonTypes().addAll(backButton, addAnotherWorldButton); dialog.getDialogPane().getScene().getWindow().setOnCloseRequest(event -> dialog.close()); dialog.showAndWait().ifPresent(choice -> { if (choice == backButton) { parent.getSubScreenManager().switchScreen("worldselect"); } else if (choice == addAnotherWorldButton) { parent.getSubScreenManager().getCurrentScreen(); } }); } @Override public AddWorldView getView() { return this.view; } @Override public String getScreenName() { return SCREEN_NAME; } }
71980_3
package be.kuleuven.candycrush.model; import be.kuleuven.candycrush.model.candys.*; import java.util.ArrayList; import java.util.Random; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.*; public class CandyCrushModel { private int circleRadius; private int score; private String playerName; private Board<Candy> grid; private BoardSize size; private Position previousClicked; public CandyCrushModel(int veldBreedte, int veldHooghte) { playerName = "Default Player"; this.circleRadius = 30; this.score = 0; size = new BoardSize(veldBreedte, veldHooghte); this.grid = new Board<>(size); resetGame(); } public Candy generateRandomCandy(){ Random rndGen = new Random(); int random = rndGen.nextInt(1,8); switch (random){ case 1: return new NormalCandy(0); case 2: return new NormalCandy(1); case 3: return new NormalCandy(2); case 4: return new NormalCandy(3); case 5: return new Stheefje(); case 6: return new bolleke(); case 7: return new petoterke(); case 8: return new haaariebooo(); default: return null; } } public void generateGrid(){ for (Position pos : size.positions()) { grid.replaceCellAt(pos, generateRandomCandy()); } } public void onCircleClick(double x, double y){ //index to check wordt hieronder uigerekend double xCoordInArray = x / circleRadius; double yCoordInArray = y / circleRadius; int row = (int) Math.floor(yCoordInArray); int col = (int) Math.floor(xCoordInArray); System.out.println("row: " + row + " col: " + col); Position pos = new Position(row, col, size); if(previousClicked == null){ previousClicked = pos; } if(!pos.equals(previousClicked)){ //swap these positions Swap swap = new Swap(previousClicked, pos); doSwap(swap, grid); score += countMatches(grid); updateBoard(grid, findAllMatches(grid)); previousClicked = null; ArrayList<Swap> swaps = possibleSwaps(grid); System.out.println("possble swaps: " + swaps.size()); } } //opdracht 12 functies public boolean firstTwoHaveCandy(Candy candy, Stream<Position> positions, Board<Candy> bord) { //neemt de eerste 2 elementen van de lijst List<Position> positionList = positions.limit(2).toList(); if(positionList.size() < 2) return false; //geeft alle matches terug met die candy return positionList.stream() .allMatch(pos -> bord.getCellAt(pos) != null && bord.getCellAt(pos).equals(candy)); } //geen idee of dit een probleem is maar momenteel als je een lengte langer als 2 hebt dan heb je meerdere posities voor dezelfde candy groep public Stream<Position> horizontalStartingPositions(Board<Candy> bord) { return size.positions().stream().filter(pos -> !firstTwoHaveCandy(bord.getCellAt(pos), pos.walkLeft(), bord)).filter(pos -> bord.getCellAt(pos) != null); } public Stream<Position> verticalStartingPositions(Board<Candy> bord) { return size.positions().stream().filter(pos -> !firstTwoHaveCandy(bord.getCellAt(pos), pos.walkUp(), bord)).filter(pos -> bord.getCellAt(pos) != null); } public List<Position> longestMatchToRight(Position pos, Board<Candy> bord) { Candy candy = bord.getCellAt(pos); return pos.walkRight().takeWhile(p -> bord.getCellAt(p) != null && bord.getCellAt(p).equals(candy)).collect(Collectors.toList()); } public List<Position> longestMatchDown(Position pos, Board<Candy> bord) { Candy candy = bord.getCellAt(pos); return pos.walkDown().takeWhile(p -> bord.getCellAt(p) != null && bord.getCellAt(p).equals(candy)).collect(Collectors.toList()); } public Set<List<Position>> findAllMatches(Board<Candy> bord) { Set<List<Position>> matches = new HashSet<>(); Stream.concat(horizontalStartingPositions(bord), verticalStartingPositions(bord)) .forEach(pos -> { List<Position> matchRight = longestMatchToRight(pos, bord); if (matchRight.size() >= 3) { matches.add(matchRight); } List<Position> matchDown = longestMatchDown(pos, bord); if (matchDown.size() >= 3) { matches.add(matchDown); } }); //sorteer zodat de langste match als eerste staat return matches.stream().filter(match -> matches.stream() .noneMatch(longerMatch -> longerMatch.size() > match.size() && longerMatch.containsAll(match))) .collect(Collectors.toSet()); } //opdracht 13 functies public void clearMatch(List<Position> match, Board<Candy> bord){ if (match.isEmpty()) { return; } Position pos = match.get(0); bord.replaceCellAt(pos, null); // Verwijder het snoepje op de positie match.remove(0); // Verwijder het eerste element uit de lijst clearMatch(match, bord); // Roep de methode opnieuw aan met de bijgewerkte lijst } public void fallDownTo(Position pos, Board<Candy> bord){ if (pos.row() == 0) { return; } Position bovenPos = new Position(pos.row() - 1, pos.col(), pos.bord()); if(bord.getCellAt(pos) == null){ if (bord.getCellAt(bovenPos) == null) { fallDownTo(bovenPos, bord); } if(bord.getCellAt(bovenPos) != null){ bord.replaceCellAt(pos, bord.getCellAt(bovenPos)); bord.replaceCellAt(bovenPos, null); fallDownTo(bovenPos, bord); } }else{ fallDownTo(bovenPos, bord); } } public boolean updateBoard(Board<Candy> bord, Set<List<Position>> matches){ if (matches.isEmpty()) { return false; } Iterator<List<Position>> iterator = matches.iterator(); List<Position> match = iterator.next(); // Haal de eerste match op iterator.remove(); // Verwijder de eerste match List<Position> copyMatch = new ArrayList<>(match); clearMatch(copyMatch, bord); updateBoard(bord, matches); //hierna alles matches laten vallen for (Position pos : match) { fallDownTo(pos, bord); } Set<List<Position>> newMatches = findAllMatches(bord); updateBoard(bord, newMatches); return true; } //opdracht 14 functies boolean matchAfterSwitch(Swap swap, Board<Candy> bord) { if(swap.getPos1() == null || swap.getPos2() == null){ return false; } if(bord.getCellAt(swap.getPos1()) == null || bord.getCellAt(swap.getPos2()) == null){ return false; } //switch match simpleSwap(swap, bord); Set<List<Position>> matches = findAllMatches(bord); simpleSwap(swap, bord); return !matches.isEmpty(); } private void doSwap(Swap swap, Board<Candy> bord) { if(!matchAfterSwitch(swap, bord)){ return; } if (swap.getPos1().isRightNextTo(swap.getPos2())) { simpleSwap(swap, bord); } } private void simpleSwap(Swap swap, Board<Candy> bord) { Candy temp = bord.getCellAt(swap.getPos1()); bord.replaceCellAt(swap.getPos1(), bord.getCellAt(swap.getPos2())); bord.replaceCellAt(swap.getPos2(), temp); } public ArrayList<Swap> possibleSwaps(Board<Candy> bord){ ArrayList<Swap> swaps = new ArrayList<>(); for (Position pos : bord.getSize().positions()) { for(Position p : pos.neighborPositions()){ Swap swap = new Swap(pos, p); if(swaps.stream().noneMatch(s -> s.getPos1().equals(p) && s.getPos2().equals(pos))){ if(pos.isRightNextTo(p) && matchAfterSwitch(swap, bord)){ swaps.add(swap); } } } } return swaps; } public Solution maximizeScore() { Board<Candy> bord = new Board<>(grid.getSize()); grid.copyTo(bord); Solution solution = new Solution(0, new ArrayList<>(), bord); Solution optimalsolution = GetOptimalSolutions(solution, null); return optimalsolution; } private Solution GetOptimalSolutions(Solution current, Solution bestSoFar){ Board<Candy> oldboard = current.getBord(); ArrayList<Swap> swaps = possibleSwaps(oldboard); //we zijn aan het einde als deze swaps empty is. if(swaps.isEmpty()) { if(bestSoFar == null || current.isBetterThan(bestSoFar)){ return current; }else{ return bestSoFar; } } for(Swap swap : swaps){ Board<Candy> bord = new Board<>(current.getBord().getSize()); oldboard.copyTo(bord); doSwap(swap, bord); updateBoard(bord, findAllMatches(bord)); int newScore = bord.getCells().entrySet().stream().filter(entry -> entry.getValue() == null).mapToInt(entry -> 1).sum(); ArrayList<Swap> newSwaps = new ArrayList<>(current.getSwaps()); newSwaps.add(swap); Solution newSolution = new Solution(newScore, newSwaps, bord); bestSoFar = GetOptimalSolutions(newSolution, bestSoFar); } return bestSoFar; } private int countMatches(Board<Candy> bord) { return findAllMatches(bord).stream().mapToInt(List::size).sum(); } public void addScore(int waarde){ score+= waarde; } public void resetGame(){ score = 0; generateGrid(); updateBoard(grid, findAllMatches(grid)); } public BoardSize getSize() { return size; } public Board<Candy> getGrid() { return grid; } public int getCircleRadius() { return circleRadius; } public int getScore() { return score; } public void setPlayerName(String playerName) { this.playerName = playerName; } public String getPlayerName() { return playerName; } }
Vicxke/SES_Opdracht_deel1
candycrush/src/main/java/be/kuleuven/candycrush/model/CandyCrushModel.java
2,802
//neemt de eerste 2 elementen van de lijst
line_comment
nl
package be.kuleuven.candycrush.model; import be.kuleuven.candycrush.model.candys.*; import java.util.ArrayList; import java.util.Random; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.*; public class CandyCrushModel { private int circleRadius; private int score; private String playerName; private Board<Candy> grid; private BoardSize size; private Position previousClicked; public CandyCrushModel(int veldBreedte, int veldHooghte) { playerName = "Default Player"; this.circleRadius = 30; this.score = 0; size = new BoardSize(veldBreedte, veldHooghte); this.grid = new Board<>(size); resetGame(); } public Candy generateRandomCandy(){ Random rndGen = new Random(); int random = rndGen.nextInt(1,8); switch (random){ case 1: return new NormalCandy(0); case 2: return new NormalCandy(1); case 3: return new NormalCandy(2); case 4: return new NormalCandy(3); case 5: return new Stheefje(); case 6: return new bolleke(); case 7: return new petoterke(); case 8: return new haaariebooo(); default: return null; } } public void generateGrid(){ for (Position pos : size.positions()) { grid.replaceCellAt(pos, generateRandomCandy()); } } public void onCircleClick(double x, double y){ //index to check wordt hieronder uigerekend double xCoordInArray = x / circleRadius; double yCoordInArray = y / circleRadius; int row = (int) Math.floor(yCoordInArray); int col = (int) Math.floor(xCoordInArray); System.out.println("row: " + row + " col: " + col); Position pos = new Position(row, col, size); if(previousClicked == null){ previousClicked = pos; } if(!pos.equals(previousClicked)){ //swap these positions Swap swap = new Swap(previousClicked, pos); doSwap(swap, grid); score += countMatches(grid); updateBoard(grid, findAllMatches(grid)); previousClicked = null; ArrayList<Swap> swaps = possibleSwaps(grid); System.out.println("possble swaps: " + swaps.size()); } } //opdracht 12 functies public boolean firstTwoHaveCandy(Candy candy, Stream<Position> positions, Board<Candy> bord) { //neemt de<SUF> List<Position> positionList = positions.limit(2).toList(); if(positionList.size() < 2) return false; //geeft alle matches terug met die candy return positionList.stream() .allMatch(pos -> bord.getCellAt(pos) != null && bord.getCellAt(pos).equals(candy)); } //geen idee of dit een probleem is maar momenteel als je een lengte langer als 2 hebt dan heb je meerdere posities voor dezelfde candy groep public Stream<Position> horizontalStartingPositions(Board<Candy> bord) { return size.positions().stream().filter(pos -> !firstTwoHaveCandy(bord.getCellAt(pos), pos.walkLeft(), bord)).filter(pos -> bord.getCellAt(pos) != null); } public Stream<Position> verticalStartingPositions(Board<Candy> bord) { return size.positions().stream().filter(pos -> !firstTwoHaveCandy(bord.getCellAt(pos), pos.walkUp(), bord)).filter(pos -> bord.getCellAt(pos) != null); } public List<Position> longestMatchToRight(Position pos, Board<Candy> bord) { Candy candy = bord.getCellAt(pos); return pos.walkRight().takeWhile(p -> bord.getCellAt(p) != null && bord.getCellAt(p).equals(candy)).collect(Collectors.toList()); } public List<Position> longestMatchDown(Position pos, Board<Candy> bord) { Candy candy = bord.getCellAt(pos); return pos.walkDown().takeWhile(p -> bord.getCellAt(p) != null && bord.getCellAt(p).equals(candy)).collect(Collectors.toList()); } public Set<List<Position>> findAllMatches(Board<Candy> bord) { Set<List<Position>> matches = new HashSet<>(); Stream.concat(horizontalStartingPositions(bord), verticalStartingPositions(bord)) .forEach(pos -> { List<Position> matchRight = longestMatchToRight(pos, bord); if (matchRight.size() >= 3) { matches.add(matchRight); } List<Position> matchDown = longestMatchDown(pos, bord); if (matchDown.size() >= 3) { matches.add(matchDown); } }); //sorteer zodat de langste match als eerste staat return matches.stream().filter(match -> matches.stream() .noneMatch(longerMatch -> longerMatch.size() > match.size() && longerMatch.containsAll(match))) .collect(Collectors.toSet()); } //opdracht 13 functies public void clearMatch(List<Position> match, Board<Candy> bord){ if (match.isEmpty()) { return; } Position pos = match.get(0); bord.replaceCellAt(pos, null); // Verwijder het snoepje op de positie match.remove(0); // Verwijder het eerste element uit de lijst clearMatch(match, bord); // Roep de methode opnieuw aan met de bijgewerkte lijst } public void fallDownTo(Position pos, Board<Candy> bord){ if (pos.row() == 0) { return; } Position bovenPos = new Position(pos.row() - 1, pos.col(), pos.bord()); if(bord.getCellAt(pos) == null){ if (bord.getCellAt(bovenPos) == null) { fallDownTo(bovenPos, bord); } if(bord.getCellAt(bovenPos) != null){ bord.replaceCellAt(pos, bord.getCellAt(bovenPos)); bord.replaceCellAt(bovenPos, null); fallDownTo(bovenPos, bord); } }else{ fallDownTo(bovenPos, bord); } } public boolean updateBoard(Board<Candy> bord, Set<List<Position>> matches){ if (matches.isEmpty()) { return false; } Iterator<List<Position>> iterator = matches.iterator(); List<Position> match = iterator.next(); // Haal de eerste match op iterator.remove(); // Verwijder de eerste match List<Position> copyMatch = new ArrayList<>(match); clearMatch(copyMatch, bord); updateBoard(bord, matches); //hierna alles matches laten vallen for (Position pos : match) { fallDownTo(pos, bord); } Set<List<Position>> newMatches = findAllMatches(bord); updateBoard(bord, newMatches); return true; } //opdracht 14 functies boolean matchAfterSwitch(Swap swap, Board<Candy> bord) { if(swap.getPos1() == null || swap.getPos2() == null){ return false; } if(bord.getCellAt(swap.getPos1()) == null || bord.getCellAt(swap.getPos2()) == null){ return false; } //switch match simpleSwap(swap, bord); Set<List<Position>> matches = findAllMatches(bord); simpleSwap(swap, bord); return !matches.isEmpty(); } private void doSwap(Swap swap, Board<Candy> bord) { if(!matchAfterSwitch(swap, bord)){ return; } if (swap.getPos1().isRightNextTo(swap.getPos2())) { simpleSwap(swap, bord); } } private void simpleSwap(Swap swap, Board<Candy> bord) { Candy temp = bord.getCellAt(swap.getPos1()); bord.replaceCellAt(swap.getPos1(), bord.getCellAt(swap.getPos2())); bord.replaceCellAt(swap.getPos2(), temp); } public ArrayList<Swap> possibleSwaps(Board<Candy> bord){ ArrayList<Swap> swaps = new ArrayList<>(); for (Position pos : bord.getSize().positions()) { for(Position p : pos.neighborPositions()){ Swap swap = new Swap(pos, p); if(swaps.stream().noneMatch(s -> s.getPos1().equals(p) && s.getPos2().equals(pos))){ if(pos.isRightNextTo(p) && matchAfterSwitch(swap, bord)){ swaps.add(swap); } } } } return swaps; } public Solution maximizeScore() { Board<Candy> bord = new Board<>(grid.getSize()); grid.copyTo(bord); Solution solution = new Solution(0, new ArrayList<>(), bord); Solution optimalsolution = GetOptimalSolutions(solution, null); return optimalsolution; } private Solution GetOptimalSolutions(Solution current, Solution bestSoFar){ Board<Candy> oldboard = current.getBord(); ArrayList<Swap> swaps = possibleSwaps(oldboard); //we zijn aan het einde als deze swaps empty is. if(swaps.isEmpty()) { if(bestSoFar == null || current.isBetterThan(bestSoFar)){ return current; }else{ return bestSoFar; } } for(Swap swap : swaps){ Board<Candy> bord = new Board<>(current.getBord().getSize()); oldboard.copyTo(bord); doSwap(swap, bord); updateBoard(bord, findAllMatches(bord)); int newScore = bord.getCells().entrySet().stream().filter(entry -> entry.getValue() == null).mapToInt(entry -> 1).sum(); ArrayList<Swap> newSwaps = new ArrayList<>(current.getSwaps()); newSwaps.add(swap); Solution newSolution = new Solution(newScore, newSwaps, bord); bestSoFar = GetOptimalSolutions(newSolution, bestSoFar); } return bestSoFar; } private int countMatches(Board<Candy> bord) { return findAllMatches(bord).stream().mapToInt(List::size).sum(); } public void addScore(int waarde){ score+= waarde; } public void resetGame(){ score = 0; generateGrid(); updateBoard(grid, findAllMatches(grid)); } public BoardSize getSize() { return size; } public Board<Candy> getGrid() { return grid; } public int getCircleRadius() { return circleRadius; } public int getScore() { return score; } public void setPlayerName(String playerName) { this.playerName = playerName; } public String getPlayerName() { return playerName; } }
83394_3
package nl.hsleiden.service; import java.util.Collection; import javax.inject.Inject; import javax.inject.Singleton; import nl.hsleiden.model.User; import nl.hsleiden.persistence.UserDAO; /** * * @author Peter van Vliet */ @Singleton public class UserService extends BaseService<User> { private final UserDAO dao; @Inject public UserService(UserDAO dao) { this.dao = dao; } public Collection<User> getAll() { return dao.getAll(); } public User get(int id) { return requireResult(dao.get(id)); } public void add(User user) { user.setRoles(new String[] { "GUEST" }); dao.add(user); } public void update(User authenticator, int id, User user) { // Controleren of deze gebruiker wel bestaat User oldUser = get(id); if (!authenticator.hasRole("ADMIN")) { // Vaststellen dat de geauthenticeerde gebruiker // zichzelf aan het aanpassen is assertSelf(authenticator, oldUser); } dao.update(id, user); } public void delete(int id) { // Controleren of deze gebruiker wel bestaat User user = get(id); dao.delete(id); } }
pvvliet/workshop-api
src/main/java/nl/hsleiden/service/UserService.java
401
// zichzelf aan het aanpassen is
line_comment
nl
package nl.hsleiden.service; import java.util.Collection; import javax.inject.Inject; import javax.inject.Singleton; import nl.hsleiden.model.User; import nl.hsleiden.persistence.UserDAO; /** * * @author Peter van Vliet */ @Singleton public class UserService extends BaseService<User> { private final UserDAO dao; @Inject public UserService(UserDAO dao) { this.dao = dao; } public Collection<User> getAll() { return dao.getAll(); } public User get(int id) { return requireResult(dao.get(id)); } public void add(User user) { user.setRoles(new String[] { "GUEST" }); dao.add(user); } public void update(User authenticator, int id, User user) { // Controleren of deze gebruiker wel bestaat User oldUser = get(id); if (!authenticator.hasRole("ADMIN")) { // Vaststellen dat de geauthenticeerde gebruiker // zichzelf aan<SUF> assertSelf(authenticator, oldUser); } dao.update(id, user); } public void delete(int id) { // Controleren of deze gebruiker wel bestaat User user = get(id); dao.delete(id); } }
133318_0
import java.util.*; public class BetCards { private List<Stack<BetCard>> betCardList; private boolean successful; public BetCards(){ betCardList = new ArrayList<>(Game.CAMEL_COLORS.length); successful = false; resetBetCardList(); // damit man kein duplicate Code hat } public BetCard drawBetCard(String color){ for (int i = 0; i < betCardList.size(); i++){ if (!betCardList.get(i).isEmpty()){ if (betCardList.get(i).peek().getColor().equals(color)){ return betCardList.get(i).pop(); } } else { System.out.println("Der " + color + " Stack ist leider schon leer."); return null; } } return null; } public void resetBetCardList(){ betCardList.clear(); HashMap<Integer, Integer> punkteMap = new HashMap<>(); punkteMap.put(2, 1); // zuerst die Stacks für jede Farbe erstellen for (String color : Game.CAMEL_COLORS) { Stack<BetCard> stack = new Stack<>(); punkteMap.put(1, 2); stack.push(new BetCard(color, new HashMap<>(punkteMap))); punkteMap.put(1, 3); stack.push(new BetCard(color, new HashMap<>(punkteMap))); punkteMap.put(1, 5); stack.push(new BetCard(color, new HashMap<>(punkteMap))); betCardList.add(stack); // den Stack zur Liste hinzufügen } } public boolean getSuccessful(){ return successful; } public void printBetCardsInBetCardsClass(){ System.out.println(betCardList); // dafür @Override ^^ } }
tillreichardt/Camel-Up
BetCards.java
452
// damit man kein duplicate Code hat
line_comment
nl
import java.util.*; public class BetCards { private List<Stack<BetCard>> betCardList; private boolean successful; public BetCards(){ betCardList = new ArrayList<>(Game.CAMEL_COLORS.length); successful = false; resetBetCardList(); // damit man<SUF> } public BetCard drawBetCard(String color){ for (int i = 0; i < betCardList.size(); i++){ if (!betCardList.get(i).isEmpty()){ if (betCardList.get(i).peek().getColor().equals(color)){ return betCardList.get(i).pop(); } } else { System.out.println("Der " + color + " Stack ist leider schon leer."); return null; } } return null; } public void resetBetCardList(){ betCardList.clear(); HashMap<Integer, Integer> punkteMap = new HashMap<>(); punkteMap.put(2, 1); // zuerst die Stacks für jede Farbe erstellen for (String color : Game.CAMEL_COLORS) { Stack<BetCard> stack = new Stack<>(); punkteMap.put(1, 2); stack.push(new BetCard(color, new HashMap<>(punkteMap))); punkteMap.put(1, 3); stack.push(new BetCard(color, new HashMap<>(punkteMap))); punkteMap.put(1, 5); stack.push(new BetCard(color, new HashMap<>(punkteMap))); betCardList.add(stack); // den Stack zur Liste hinzufügen } } public boolean getSuccessful(){ return successful; } public void printBetCardsInBetCardsClass(){ System.out.println(betCardList); // dafür @Override ^^ } }
34914_0
package oefening1; /** * @author Ruben Dejonckheere * */ public abstract class Spons extends OngewerveldDier implements OnderWaterLevend { /** * @param naam * @param kleur */ public Spons(String naam, Kleur kleur) { super(naam, kleur); } @Override public String maakGeluid() { // alle sponzen maken een vergelijkbaar geluid return "..."; } public int geefTijdOnderWater() { // alle sponzen kunnen even lang onder water blijven return 0; } }
EHB-TI/Programming-Essentials-2
Werkcollege4/src/oefening1/Spons.java
150
/** * @author Ruben Dejonckheere * */
block_comment
nl
package oefening1; /** * @author Ruben Dejonckheere<SUF>*/ public abstract class Spons extends OngewerveldDier implements OnderWaterLevend { /** * @param naam * @param kleur */ public Spons(String naam, Kleur kleur) { super(naam, kleur); } @Override public String maakGeluid() { // alle sponzen maken een vergelijkbaar geluid return "..."; } public int geefTijdOnderWater() { // alle sponzen kunnen even lang onder water blijven return 0; } }
81932_17
package javax.rtcbench; import javax.rtc.RTC; import javax.rtc.Lightweight; /* Author : Shay Gal-On, EEMBC This file is part of EEMBC(R) and CoreMark(TM), which are Copyright (C) 2009 All rights reserved. EEMBC CoreMark Software is a product of EEMBC and is provided under the terms of the CoreMark License that is distributed with the official EEMBC COREMARK Software release. If you received this EEMBC CoreMark Software without the accompanying CoreMark License, you must discontinue use and download the official release from www.coremark.org. Also, if you are publicly displaying scores generated from the EEMBC CoreMark software, make sure that you are in compliance with Run and Reporting rules specified in the accompanying readme.txt file. EEMBC 4354 Town Center Blvd. Suite 114-200 El Dorado Hills, CA, 95762 */ /* Topic: Description Simple state machines like this one are used in many embedded products. For more complex state machines, sometimes a state transition table implementation is used instead, trading speed of direct coding for ease of maintenance. Since the main goal of using a state machine in CoreMark is to excercise the switch/if behaviour, we are using a small moore machine. In particular, this machine tests type of string input, trying to determine whether the input is a number or something else. (see core_state.png). */ public class CoreState { public static final byte CORE_STATE_START = 0; public static final byte CORE_STATE_INVALID = 1; public static final byte CORE_STATE_S1 = 2; public static final byte CORE_STATE_S2 = 3; public static final byte CORE_STATE_INT = 4; public static final byte CORE_STATE_FLOAT = 5; public static final byte CORE_STATE_EXPONENT = 6; public static final byte CORE_STATE_SCIENTIFIC = 7; public static final byte NUM_CORE_STATES = 8; /* Function: core_bench_state Benchmark function Go over the input twice, once direct, and once after introducing some corruption. */ static short core_bench_state(int blksize, byte[] memblock, short seed1, short seed2, short step, short crc, CoreMain.TmpData tmpData) { int[] final_counts = tmpData.final_counts; int[] track_counts = tmpData.track_counts; ShortWrapper p = tmpData.p; short pValue; // Within this method we use this so the local variable can be pinned by markloop. p.value=0; // We use this to pass to core_state_transition since it needs to be able to modify the index (it's a double pointer in C). int i; for (i=0; i<NUM_CORE_STATES; i++) { final_counts[i]=track_counts[i]=0; } /* run the state machine over the input */ while (memblock[p.value]!=0) { byte fstate=core_state_transition(p,memblock,track_counts); final_counts[fstate]++; } // p=memblock; pValue=0; // Stays within this method, so use pValue while (pValue < blksize) { /* insert some corruption */ if (memblock[pValue]!=',') memblock[pValue]^=(byte)seed1; pValue+=step; } // p=memblock; p.value=0; /* run the state machine over the input again */ while (memblock[p.value]!=0) { byte fstate=core_state_transition(p,memblock,track_counts); final_counts[fstate]++; } // p=memblock; pValue=0; // Stays within this method, so use pValue while (pValue < blksize) { /* undo corruption if seed1 and seed2 are equal */ if (memblock[pValue]!=',') memblock[pValue]^=(byte)seed2; pValue+=step; } /* end timing */ for (i=0; i<NUM_CORE_STATES; i++) { crc=CoreUtil.crcu32(final_counts[i],crc); crc=CoreUtil.crcu32(track_counts[i],crc); } return crc; } // NOT STANDARD COREMARK CODE: make this into functions to prevent them taking up memory at runtime. // not used during the benchmark so this won't influence the results. /* Default initialization patterns */ // private static Object[] intpat ={ "5012".getBytes(), "1234".getBytes(), "-874".getBytes(), "+122".getBytes()}; // private static Object[] floatpat={"35.54400".getBytes(),".1234500".getBytes(),"-110.700".getBytes(),"+0.64400".getBytes()}; // private static Object[] scipat ={"5.500e+3".getBytes(),"-.123e-2".getBytes(),"-87e+832".getBytes(),"+0.6e-12".getBytes()}; // private static Object[] errpat ={"T0.3e-1F".getBytes(),"-T.T++Tq".getBytes(),"1T3.4e4z".getBytes(),"34.0e-T^".getBytes()}; private static byte[] intpat(int i) { if (i==0) return "5012".getBytes(); else if (i==1) return "1234".getBytes(); else if (i==2) return "-874".getBytes(); else return "+122".getBytes(); } private static byte[] floatpat(int i) { if (i==0) return "35.54400".getBytes(); else if (i==1) return ".1234500".getBytes(); else if (i==2) return "-110.700".getBytes(); else return "+0.64400".getBytes(); } private static byte[] scipat(int i) { if (i==0) return "5.500e+3".getBytes(); else if (i==1) return "-.123e-2".getBytes(); else if (i==2) return "-87e+832".getBytes(); else return "+0.6e-12".getBytes(); } private static byte[] errpat(int i) { if (i==0) return "T0.3e-1F".getBytes(); else if (i==1) return "-T.T++Tq".getBytes(); else if (i==2) return "1T3.4e4z".getBytes(); else return "34.0e-T^".getBytes(); } // TODO: This is a very ugly hack to prevent ProGuard from inlining core_bench_state, which causes other problems when it happens. // It would be nice to have more direct control over what gets inlined or not. private static byte vliegtuig = 1; /* Function: core_init_state Initialize the input data for the state machine. Populate the input with several predetermined strings, interspersed. Actual patterns chosen depend on the seed parameter. Note: The seed parameter MUST be supplied from a source that cannot be determined at compile time */ static byte[] core_init_state(int size, short seed) { byte[] p=new byte[size]; int total=0,next=0,i; byte[] buf=null; size--; next=0; while ((total+next+1)<size) { if (next>0) { for(i=0;i<next;i++) p[total+i]=buf[i]; p[total+i]=','; total+=next+1; } seed++; switch (seed & 0x7) { case 0: /* int */ case 1: /* int */ case 2: /* int */ buf=intpat((seed>>3) & 0x3); next=4; break; case 3: /* float */ case 4: /* float */ buf=floatpat((seed>>3) & 0x3); next=8; break; case 5: /* scientific */ case 6: /* scientific */ buf=scipat((seed>>3) & 0x3); next=8; break; case 7: /* invalid */ buf=errpat((seed>>3) & 0x3); next=8; break; default: /* Never happen, just to make some compilers happy */ break; } } size++; while (total<size) { /* fill the rest with 0 */ p[total]=0; total++; } return p; } // static boolean ee_isdigit(byte c) { // boolean retval; // retval = ((c>='0') & (c<='9')) ? true : false; // return retval; // } /* Function: core_state_transition Actual state machine. The state machine will continue scanning until either: 1 - an invalid input is detected. 2 - a valid number has been detected. The input pointer is updated to point to the end of the token, and the end state is returned (either specific format determined or invalid). */ private static class CoreStateTransitionParam { public byte[] instr; public short index; } // State core_state_transition( ee_u8 **instr , int[] transition_count) { @Lightweight static byte core_state_transition(ShortWrapper indexWrapper, byte[] str, int[] transition_count) { short index = indexWrapper.value; byte NEXT_SYMBOL; byte state=CORE_STATE_START; // for( ; *str && state != CORE_INVALID; str++ ) { for( ; (NEXT_SYMBOL = str[index])!=0 && state != CORE_STATE_INVALID; index++ ) { if (NEXT_SYMBOL==',') /* end of this input */ { index++; break; } switch(state) { case CORE_STATE_START: if((NEXT_SYMBOL>='0') && (NEXT_SYMBOL<='9')) { state = CORE_STATE_INT; } else if( NEXT_SYMBOL == '+' || NEXT_SYMBOL == '-' ) { state = CORE_STATE_S1; } else if( NEXT_SYMBOL == '.' ) { state = CORE_STATE_FLOAT; } else { state = CORE_STATE_INVALID; transition_count[CORE_STATE_INVALID]++; } transition_count[CORE_STATE_START]++; break; case CORE_STATE_S1: if((NEXT_SYMBOL>='0') && (NEXT_SYMBOL<='9')) { state = CORE_STATE_INT; transition_count[CORE_STATE_S1]++; } else if( NEXT_SYMBOL == '.' ) { state = CORE_STATE_FLOAT; transition_count[CORE_STATE_S1]++; } else { state = CORE_STATE_INVALID; transition_count[CORE_STATE_S1]++; } break; case CORE_STATE_INT: if( NEXT_SYMBOL == '.' ) { state = CORE_STATE_FLOAT; transition_count[CORE_STATE_INT]++; } else if(!((NEXT_SYMBOL>='0') && (NEXT_SYMBOL<='9'))) { state = CORE_STATE_INVALID; transition_count[CORE_STATE_INT]++; } break; case CORE_STATE_FLOAT: if( NEXT_SYMBOL == 'E' || NEXT_SYMBOL == 'e' ) { state = CORE_STATE_S2; transition_count[CORE_STATE_FLOAT]++; } else if(!((NEXT_SYMBOL>='0') && (NEXT_SYMBOL<='9'))) { state = CORE_STATE_INVALID; transition_count[CORE_STATE_FLOAT]++; } break; case CORE_STATE_S2: if( NEXT_SYMBOL == '+' || NEXT_SYMBOL == '-' ) { state = CORE_STATE_EXPONENT; transition_count[CORE_STATE_S2]++; } else { state = CORE_STATE_INVALID; transition_count[CORE_STATE_S2]++; } break; case CORE_STATE_EXPONENT: if((NEXT_SYMBOL>='0') && (NEXT_SYMBOL<='9')) { state = CORE_STATE_SCIENTIFIC; transition_count[CORE_STATE_EXPONENT]++; } else { state = CORE_STATE_INVALID; transition_count[CORE_STATE_EXPONENT]++; } break; case CORE_STATE_SCIENTIFIC: if(!((NEXT_SYMBOL>='0') && (NEXT_SYMBOL<='9'))) { state = CORE_STATE_INVALID; transition_count[CORE_STATE_INVALID]++; } break; default: break; } } // *instr=str; indexWrapper.value = index; return state; } }
NEWSLabNTU/capevm
src/lib/bm_coremk/java/javax/rtcbench/CoreState.java
3,367
// private static Object[] errpat ={"T0.3e-1F".getBytes(),"-T.T++Tq".getBytes(),"1T3.4e4z".getBytes(),"34.0e-T^".getBytes()};
line_comment
nl
package javax.rtcbench; import javax.rtc.RTC; import javax.rtc.Lightweight; /* Author : Shay Gal-On, EEMBC This file is part of EEMBC(R) and CoreMark(TM), which are Copyright (C) 2009 All rights reserved. EEMBC CoreMark Software is a product of EEMBC and is provided under the terms of the CoreMark License that is distributed with the official EEMBC COREMARK Software release. If you received this EEMBC CoreMark Software without the accompanying CoreMark License, you must discontinue use and download the official release from www.coremark.org. Also, if you are publicly displaying scores generated from the EEMBC CoreMark software, make sure that you are in compliance with Run and Reporting rules specified in the accompanying readme.txt file. EEMBC 4354 Town Center Blvd. Suite 114-200 El Dorado Hills, CA, 95762 */ /* Topic: Description Simple state machines like this one are used in many embedded products. For more complex state machines, sometimes a state transition table implementation is used instead, trading speed of direct coding for ease of maintenance. Since the main goal of using a state machine in CoreMark is to excercise the switch/if behaviour, we are using a small moore machine. In particular, this machine tests type of string input, trying to determine whether the input is a number or something else. (see core_state.png). */ public class CoreState { public static final byte CORE_STATE_START = 0; public static final byte CORE_STATE_INVALID = 1; public static final byte CORE_STATE_S1 = 2; public static final byte CORE_STATE_S2 = 3; public static final byte CORE_STATE_INT = 4; public static final byte CORE_STATE_FLOAT = 5; public static final byte CORE_STATE_EXPONENT = 6; public static final byte CORE_STATE_SCIENTIFIC = 7; public static final byte NUM_CORE_STATES = 8; /* Function: core_bench_state Benchmark function Go over the input twice, once direct, and once after introducing some corruption. */ static short core_bench_state(int blksize, byte[] memblock, short seed1, short seed2, short step, short crc, CoreMain.TmpData tmpData) { int[] final_counts = tmpData.final_counts; int[] track_counts = tmpData.track_counts; ShortWrapper p = tmpData.p; short pValue; // Within this method we use this so the local variable can be pinned by markloop. p.value=0; // We use this to pass to core_state_transition since it needs to be able to modify the index (it's a double pointer in C). int i; for (i=0; i<NUM_CORE_STATES; i++) { final_counts[i]=track_counts[i]=0; } /* run the state machine over the input */ while (memblock[p.value]!=0) { byte fstate=core_state_transition(p,memblock,track_counts); final_counts[fstate]++; } // p=memblock; pValue=0; // Stays within this method, so use pValue while (pValue < blksize) { /* insert some corruption */ if (memblock[pValue]!=',') memblock[pValue]^=(byte)seed1; pValue+=step; } // p=memblock; p.value=0; /* run the state machine over the input again */ while (memblock[p.value]!=0) { byte fstate=core_state_transition(p,memblock,track_counts); final_counts[fstate]++; } // p=memblock; pValue=0; // Stays within this method, so use pValue while (pValue < blksize) { /* undo corruption if seed1 and seed2 are equal */ if (memblock[pValue]!=',') memblock[pValue]^=(byte)seed2; pValue+=step; } /* end timing */ for (i=0; i<NUM_CORE_STATES; i++) { crc=CoreUtil.crcu32(final_counts[i],crc); crc=CoreUtil.crcu32(track_counts[i],crc); } return crc; } // NOT STANDARD COREMARK CODE: make this into functions to prevent them taking up memory at runtime. // not used during the benchmark so this won't influence the results. /* Default initialization patterns */ // private static Object[] intpat ={ "5012".getBytes(), "1234".getBytes(), "-874".getBytes(), "+122".getBytes()}; // private static Object[] floatpat={"35.54400".getBytes(),".1234500".getBytes(),"-110.700".getBytes(),"+0.64400".getBytes()}; // private static Object[] scipat ={"5.500e+3".getBytes(),"-.123e-2".getBytes(),"-87e+832".getBytes(),"+0.6e-12".getBytes()}; // private static<SUF> private static byte[] intpat(int i) { if (i==0) return "5012".getBytes(); else if (i==1) return "1234".getBytes(); else if (i==2) return "-874".getBytes(); else return "+122".getBytes(); } private static byte[] floatpat(int i) { if (i==0) return "35.54400".getBytes(); else if (i==1) return ".1234500".getBytes(); else if (i==2) return "-110.700".getBytes(); else return "+0.64400".getBytes(); } private static byte[] scipat(int i) { if (i==0) return "5.500e+3".getBytes(); else if (i==1) return "-.123e-2".getBytes(); else if (i==2) return "-87e+832".getBytes(); else return "+0.6e-12".getBytes(); } private static byte[] errpat(int i) { if (i==0) return "T0.3e-1F".getBytes(); else if (i==1) return "-T.T++Tq".getBytes(); else if (i==2) return "1T3.4e4z".getBytes(); else return "34.0e-T^".getBytes(); } // TODO: This is a very ugly hack to prevent ProGuard from inlining core_bench_state, which causes other problems when it happens. // It would be nice to have more direct control over what gets inlined or not. private static byte vliegtuig = 1; /* Function: core_init_state Initialize the input data for the state machine. Populate the input with several predetermined strings, interspersed. Actual patterns chosen depend on the seed parameter. Note: The seed parameter MUST be supplied from a source that cannot be determined at compile time */ static byte[] core_init_state(int size, short seed) { byte[] p=new byte[size]; int total=0,next=0,i; byte[] buf=null; size--; next=0; while ((total+next+1)<size) { if (next>0) { for(i=0;i<next;i++) p[total+i]=buf[i]; p[total+i]=','; total+=next+1; } seed++; switch (seed & 0x7) { case 0: /* int */ case 1: /* int */ case 2: /* int */ buf=intpat((seed>>3) & 0x3); next=4; break; case 3: /* float */ case 4: /* float */ buf=floatpat((seed>>3) & 0x3); next=8; break; case 5: /* scientific */ case 6: /* scientific */ buf=scipat((seed>>3) & 0x3); next=8; break; case 7: /* invalid */ buf=errpat((seed>>3) & 0x3); next=8; break; default: /* Never happen, just to make some compilers happy */ break; } } size++; while (total<size) { /* fill the rest with 0 */ p[total]=0; total++; } return p; } // static boolean ee_isdigit(byte c) { // boolean retval; // retval = ((c>='0') & (c<='9')) ? true : false; // return retval; // } /* Function: core_state_transition Actual state machine. The state machine will continue scanning until either: 1 - an invalid input is detected. 2 - a valid number has been detected. The input pointer is updated to point to the end of the token, and the end state is returned (either specific format determined or invalid). */ private static class CoreStateTransitionParam { public byte[] instr; public short index; } // State core_state_transition( ee_u8 **instr , int[] transition_count) { @Lightweight static byte core_state_transition(ShortWrapper indexWrapper, byte[] str, int[] transition_count) { short index = indexWrapper.value; byte NEXT_SYMBOL; byte state=CORE_STATE_START; // for( ; *str && state != CORE_INVALID; str++ ) { for( ; (NEXT_SYMBOL = str[index])!=0 && state != CORE_STATE_INVALID; index++ ) { if (NEXT_SYMBOL==',') /* end of this input */ { index++; break; } switch(state) { case CORE_STATE_START: if((NEXT_SYMBOL>='0') && (NEXT_SYMBOL<='9')) { state = CORE_STATE_INT; } else if( NEXT_SYMBOL == '+' || NEXT_SYMBOL == '-' ) { state = CORE_STATE_S1; } else if( NEXT_SYMBOL == '.' ) { state = CORE_STATE_FLOAT; } else { state = CORE_STATE_INVALID; transition_count[CORE_STATE_INVALID]++; } transition_count[CORE_STATE_START]++; break; case CORE_STATE_S1: if((NEXT_SYMBOL>='0') && (NEXT_SYMBOL<='9')) { state = CORE_STATE_INT; transition_count[CORE_STATE_S1]++; } else if( NEXT_SYMBOL == '.' ) { state = CORE_STATE_FLOAT; transition_count[CORE_STATE_S1]++; } else { state = CORE_STATE_INVALID; transition_count[CORE_STATE_S1]++; } break; case CORE_STATE_INT: if( NEXT_SYMBOL == '.' ) { state = CORE_STATE_FLOAT; transition_count[CORE_STATE_INT]++; } else if(!((NEXT_SYMBOL>='0') && (NEXT_SYMBOL<='9'))) { state = CORE_STATE_INVALID; transition_count[CORE_STATE_INT]++; } break; case CORE_STATE_FLOAT: if( NEXT_SYMBOL == 'E' || NEXT_SYMBOL == 'e' ) { state = CORE_STATE_S2; transition_count[CORE_STATE_FLOAT]++; } else if(!((NEXT_SYMBOL>='0') && (NEXT_SYMBOL<='9'))) { state = CORE_STATE_INVALID; transition_count[CORE_STATE_FLOAT]++; } break; case CORE_STATE_S2: if( NEXT_SYMBOL == '+' || NEXT_SYMBOL == '-' ) { state = CORE_STATE_EXPONENT; transition_count[CORE_STATE_S2]++; } else { state = CORE_STATE_INVALID; transition_count[CORE_STATE_S2]++; } break; case CORE_STATE_EXPONENT: if((NEXT_SYMBOL>='0') && (NEXT_SYMBOL<='9')) { state = CORE_STATE_SCIENTIFIC; transition_count[CORE_STATE_EXPONENT]++; } else { state = CORE_STATE_INVALID; transition_count[CORE_STATE_EXPONENT]++; } break; case CORE_STATE_SCIENTIFIC: if(!((NEXT_SYMBOL>='0') && (NEXT_SYMBOL<='9'))) { state = CORE_STATE_INVALID; transition_count[CORE_STATE_INVALID]++; } break; default: break; } } // *instr=str; indexWrapper.value = index; return state; } }
46128_10
package BKE.Game.Variants; import BKE.ApplicationState; import BKE.Framework; import BKE.Game.Board; import BKE.Game.IBoard; import BKE.Game.IGame; import BKE.Game.Player.IPlayer; import BKE.Helper.MatchStats; import BKE.Helper.Vector2D; import BKE.Network.Message.GameResultMessage; import BKE.Network.Message.MoveMessage; import java.io.IOException; import java.util.Arrays; import java.util.Random; public class Zeeslag implements IGame { private final String _name = "ZEESLAG"; private ApplicationState _state; private IPlayer _playerOne; private IPlayer _playerTwo; private String _nextTurn; private IBoard _playerOneBoard; private IBoard _playerTwoBoard; private MatchStats _stats; private IPlayer _winner; private boolean _networked; private static Vector2D[] _boatOffsetChecks = { new Vector2D(-1, 0), new Vector2D(1, 0), new Vector2D(0, -1), new Vector2D(0, 1) }; private boolean _playerOneTurn; private int _rowSelection; private int _columnSelection; private Thread _thread; public enum FieldValues { // This is some bullshit, Java! EMPTY(0), HIT(1), MISS(2), SHIP(3), GEZONKEN(4), MASKED(5); private final int value; private FieldValues(int val){ this.value = val; } public int getValue() { return value; } } private void startLocalThread(){ if (_thread != null){ _thread.interrupt(); _thread = null; } _thread = new Thread(() -> { // Schepen voor speler plaatsen plaatsSchepen(_playerOneBoard); // Schepen voor tegenstander plaatsen plaatsSchepen(_playerTwoBoard); _nextTurn = _playerOne.getName(); IPlayer nextPlayer; // Spelronde while (!isGameOver()) { nextPlayer = _nextTurn.equals(_playerOne.getName()) ? _playerOne : _playerTwo; nextPlayer.doMove(); _stats.turns++; _nextTurn = nextPlayer == _playerOne ? _playerTwo.getName() : _playerOne.getName(); if (!Framework.isRunningBenchmarks()){ Framework.UpdateUI(_playerOne, _playerTwo); } _nextTurn = nextPlayer == _playerOne ? _playerTwo.getName() : _playerOne.getName(); // Controleer of het spel voorbij is if (isGameOver()) { break; } } // System.out.println("Winner is " + _winner.getName()); _state = ApplicationState.HALTED; // Toon het resultaat resultaat(); }); _thread.start(); } @Override public void start(String playerStarting) { if (!getIsNetworked()){ startLocalThread(); } } @Override public void initialize(IPlayer playerOne, IPlayer playerTwo, boolean isNetworked) { // System.out.println("Initializing Zeeslag"); _networked = isNetworked; // zet bord op _playerOneBoard = new Board(8, 8); _playerTwoBoard = new Board(8, 8); _playerOne = playerOne; _playerTwo = playerTwo; _playerOne.setBoard(_playerOneBoard); _playerTwo.setBoard(_playerTwoBoard); _state = ApplicationState.RUNNING; _stats = new MatchStats(); _stats.playerOne = playerOne.getName(); _stats.playerTwo = playerTwo.getName(); } @Override public void HandleInput(String input) { // Hier komt the user-input binnen // ongeldige input negeren if (_nextTurn != _playerOne.getName() || input == null || input.isEmpty()) return; if (input.length() != 2) return; _rowSelection = Integer.parseInt(String.valueOf(input.charAt(0))); _columnSelection = input.charAt(1) - 'A'; _playerOne.setNextMove(_columnSelection, _rowSelection); } @Override public ApplicationState GetState() { return _state; } @Override public void SetState(ApplicationState state) { _state = state; } @Override public IBoard GetPlayerBoard() { return _playerOneBoard; } public IBoard GetOpponentBoard(){ return _playerTwoBoard; } public void RequestUpdate() { Framework.UpdateUI(_playerOne, _playerTwo); } @Override public boolean getIsNetworked() { return _networked; } @Override public String GetGameName() { return _name; } @Override public IPlayer getPlayer(String name) { return _playerOne.getName().equals(name) ? _playerOne : _playerTwo; } @Override public void doTurn(String playerName) { IPlayer player = getPlayer(playerName); if (player == null) throw new RuntimeException("Player " + playerName + " does not exist"); player.doMove(); } @Override public void move(MoveMessage msg) { // IPlayer playerMakingMove = _playerOne.getName().equals(msg.getPlayerName()) ? _playerOne : _playerTwo; IBoard affectedBoard = _playerOne.getName().equals(msg.getPlayerName()) ? _playerTwoBoard : _playerOneBoard; Vector2D position = affectedBoard.getFromNetworked(msg.getLocation()); affectedBoard.setValue(position.X, position.Y, msg.getValue().getValue()); Framework.UpdateUI(_playerOne, _playerTwo); } @Override public void setGameResult(GameResultMessage gsm) { Framework.UpdateUI(gsm); } @Override public IPlayer getPlayerOne() { return _playerOne; } @Override public IPlayer getPlayerTwo() { return _playerTwo; } @Override public MatchStats getMatchStats() { return _stats; } @Override public void close() throws IOException { if (_thread != null){ _thread.interrupt(); _thread = null; } _state = ApplicationState.HALTED; } private void zetSpeler() throws InterruptedException { // De speler kan een vak kiezen om op de schieten // Dit doet de speler door het nummer en de letter // van de bij behorende row en col aan te geven _playerOneTurn = true; _columnSelection = -1; _rowSelection = 0; Framework.SendMessageToUser("Jouw beurt:"); Framework.SendMessageToUser("Voer coordinaten in:(1-8 + A-H) (1A, 4D, 8B)"); while(_rowSelection == 0 && _columnSelection < 0){ Thread.sleep(100); } // Voer het schot uit op het bord van de tegenstander boolean hit = schiet(_playerTwoBoard, _rowSelection - 1, _columnSelection); // Toon de resultaten van het schot aan de speler if (hit) { Framework.SendMessageToUser("Gefeliciteerd! Je hebt een schip geraakt op positie " + _playerTwoBoard.locatie(_rowSelection - 1, _columnSelection)); } else { Framework.SendMessageToUser("Helaas, je hebt gemist op positie " + _playerTwoBoard.locatie(_rowSelection - 1, _columnSelection)); } // Reset de selecties voor de volgende beurt _columnSelection = -1; _rowSelection = 0; } private void zetTegenstander() { _playerOneTurn = false; Random random = new Random(); int row, col; do { row = random.nextInt(8); col = random.nextInt(8); } while (!_playerOneBoard.isValidPosition(row, col)); // Voer het schot uit op het bord van de speler boolean hit = schiet(_playerOneBoard, row, col); // Toon de resultaten van het schot aan de speler if (hit) { Framework.SendMessageToUser("De tegenstander heeft een schip geraakt op positie " + _playerOneBoard.locatie(row, col)); } else { Framework.SendMessageToUser("De tegenstander heeft gemist op positie " + _playerOneBoard.locatie(row, col)); } } private boolean isGameOver() { if (schepenGezonken(_playerOneBoard)){ _winner = _playerTwo; _stats.winner = _playerTwo.getName(); } else if (schepenGezonken(_playerTwoBoard)){ _winner = _playerOne; _stats.winner = _playerOne.getName(); } return _winner != null; } private void resultaat() { Framework.SendMessageToUser("Het spel is voorbij!"); if (schepenGezonken(_playerOneBoard)) { Framework.SendMessageToUser("De tegenstander heeft gewonnen!"); } else { Framework.SendMessageToUser("Je hebt gewonnen!"); } } public void plaatsSchepen(IBoard board) { Random random = new Random(); // Hier worden de schip sizes gedefineerd // Dit kan eventueel ook later gelinked worden aan namen int[] shipSizes = {2, 2, 3, 4, 5}; int totalsquares = Arrays.stream(shipSizes).sum(); // get a sum of all the items in the array. int attempts = 0; boolean valid = false; do { attempts ++; int placedSquares = 0; for (int grootte : shipSizes) { int row, col; boolean horizontaal = random.nextBoolean(); // Random ligging van ship int cycles = 0; // Hier checked hij of het ship juist geplaatst wordt do { row = random.nextInt(board.getHeight()); col = random.nextInt(board.getWidth()); cycles ++; } while (!isValidPositionForShip(board, row, col, grootte, horizontaal) && cycles < 100); // Will attempt 100 times... After that, probably impossible... if (cycles > 99){ // Invalid break; } plaatsSchipOpBord(board, row, col, grootte, horizontaal); placedSquares += grootte; } // The combination is invalid, start over. if (totalsquares != placedSquares){ board.clear(); // System.out.println("Invalid config, attempt " + attempts); continue; } valid = true; } while (!valid); } public static void plaatsSchipOpBord(IBoard board, int row, int col, int grootte, boolean horizontaal) { // Hier gaat het ship horizontaal via col if (horizontaal) { for (int i = 0; i < grootte; i++) { board.setValue(row, col + i, FieldValues.SHIP.getValue()); } } // Hier gaat het ship verticaal via row else { for (int i = 0; i < grootte; i++) { board.setValue(row + i, col, FieldValues.SHIP.getValue()); } } } public static boolean isValidPositionForShip(IBoard board,int row, int col, int size, boolean horizontal){ if (!board.isValidPosition(row, col)){ return false; } // If the boat is left-to-right, make sure that the column coordinate plus the length of it does not exceed the // width of the playing board. if(horizontal) { if (!board.isValidPosition(row, col + size) ) { return false; } for (int i = 0; i < size; i ++){ if (board.getValue(row, col + i) != FieldValues.EMPTY.getValue()){ return false; } if (HasNeighbors(board, row, col + i)) return false; } return true; } // Do the same for up-to-down if (row + size < board.getHeight()){ if (!board.isValidPosition(row + size, col) ) { return false; } for (int i = 0; i < size; i ++){ if (board.getValue(row + i, col) != FieldValues.EMPTY.getValue()){ return false; } if (HasNeighbors(board, row + i, col)) return false; } return true; } return false; } private static boolean HasNeighbors(IBoard board, int row, int col){ // Check left, right, up and down of this coordinate to see if there is a ship there. for(Vector2D offset : _boatOffsetChecks){ int x = row + offset.X; int y = col + offset.Y; // If the coordinate to check is outside of bounds, we don't have to check it. if (!board.isValidPosition(x, y)) continue; if (board.getValue(x, y) != FieldValues.EMPTY.getValue()){ return true; } } return false; } private boolean schepenGezonken(IBoard board) { int[][] boardData = board.getValues(); // Loop door het bord en controleer of er nog 'O' (schepen) aanwezig zijn for (int i = 0; i < board.getWidth(); i++) { for (int j = 0; j < board.getHeight(); j++) { if (boardData[i][j] == Zeeslag.FieldValues.SHIP.getValue()) { // Er is nog minstens één schip aanwezig return false; } } } // Alle schepen zijn gezonken return true; } public void plaatsSchip(IBoard board, int row, int col) { // Hier wordt er gecontroleerd of de posiitie juist is. // Zo ja krijgt de speler een melding dat het plaatsen gelukt is. if (canPlacePiece(board, row, col)) { board.setValue(row, col, Zeeslag.FieldValues.SHIP.getValue()); System.out.println("Schip geplaatst op positie " + board.locatie(row, col)); } else { System.out.println("je kan hier geen schip plaatsen"); } } private boolean canPlacePiece(IBoard board, int row, int col) { // Hier wordt er gekeken of de positie juist is die gekozen werd op het veld return board.isValidPosition(row, col) && board.getValue(row, col) == Zeeslag.FieldValues.EMPTY.getValue(); } public boolean schiet(IBoard board, int row, int col) { // Controleer of de zet binnen het bord valt if (!board.isValidPosition(row, col)) { System.out.println(row + " -> " + col); System.out.println("Ongeldige positie. Probeer opnieuw."); return false; } // Controleer of er een schip op de opgegeven positie is if (board.getValue(row, col) == Zeeslag.FieldValues.SHIP.getValue()) { board.setValue(row, col,Zeeslag.FieldValues.HIT.getValue()); // Markeer het getroffen schip // System.out.println("Gefeliciteerd! Je hebt een schip geraakt op positie " + board.locatie(row, col)); // Controleert of het schip is gezonken if (isSchipGezonken(board, row, col)) { // System.out.println("Helaas, je schip is gezonken op positie " + board.locatie(row, col)); } return true; } else if (board.getValue(row, col) == Zeeslag.FieldValues.EMPTY.getValue()) { board.setValue(row, col, Zeeslag.FieldValues.MISS.getValue()); // Markeer de gemiste schoten // System.out.println("Helaas, je hebt gemist op positie " + board.locatie(row, col)); } else { System.out.println("Je hebt hier al geschoten. Probeer een andere positie."); } return false; } private boolean isSchipGezonken(IBoard board, int row, int col) { // Controleer horizontaal int countHorizontaal = 0; for (int j = 0; j < 8; j++) { if (board.getValue(row, j) == Zeeslag.FieldValues.HIT.getValue()) { countHorizontaal++; } } // Controleer verticaal int countVerticaal = 0; for (int i = 0; i < 8; i++) { if (board.getValue(i, col) == Zeeslag.FieldValues.HIT.getValue()) { countVerticaal++; } } // Als alle vakjes van het schip zijn geraakt, is het schip gezonken // TODO This needs to be different return countHorizontaal == 5 || countVerticaal == 5; } }
klankhuizen/Zeeslag
src/BKE/Game/Variants/Zeeslag.java
4,339
// De speler kan een vak kiezen om op de schieten
line_comment
nl
package BKE.Game.Variants; import BKE.ApplicationState; import BKE.Framework; import BKE.Game.Board; import BKE.Game.IBoard; import BKE.Game.IGame; import BKE.Game.Player.IPlayer; import BKE.Helper.MatchStats; import BKE.Helper.Vector2D; import BKE.Network.Message.GameResultMessage; import BKE.Network.Message.MoveMessage; import java.io.IOException; import java.util.Arrays; import java.util.Random; public class Zeeslag implements IGame { private final String _name = "ZEESLAG"; private ApplicationState _state; private IPlayer _playerOne; private IPlayer _playerTwo; private String _nextTurn; private IBoard _playerOneBoard; private IBoard _playerTwoBoard; private MatchStats _stats; private IPlayer _winner; private boolean _networked; private static Vector2D[] _boatOffsetChecks = { new Vector2D(-1, 0), new Vector2D(1, 0), new Vector2D(0, -1), new Vector2D(0, 1) }; private boolean _playerOneTurn; private int _rowSelection; private int _columnSelection; private Thread _thread; public enum FieldValues { // This is some bullshit, Java! EMPTY(0), HIT(1), MISS(2), SHIP(3), GEZONKEN(4), MASKED(5); private final int value; private FieldValues(int val){ this.value = val; } public int getValue() { return value; } } private void startLocalThread(){ if (_thread != null){ _thread.interrupt(); _thread = null; } _thread = new Thread(() -> { // Schepen voor speler plaatsen plaatsSchepen(_playerOneBoard); // Schepen voor tegenstander plaatsen plaatsSchepen(_playerTwoBoard); _nextTurn = _playerOne.getName(); IPlayer nextPlayer; // Spelronde while (!isGameOver()) { nextPlayer = _nextTurn.equals(_playerOne.getName()) ? _playerOne : _playerTwo; nextPlayer.doMove(); _stats.turns++; _nextTurn = nextPlayer == _playerOne ? _playerTwo.getName() : _playerOne.getName(); if (!Framework.isRunningBenchmarks()){ Framework.UpdateUI(_playerOne, _playerTwo); } _nextTurn = nextPlayer == _playerOne ? _playerTwo.getName() : _playerOne.getName(); // Controleer of het spel voorbij is if (isGameOver()) { break; } } // System.out.println("Winner is " + _winner.getName()); _state = ApplicationState.HALTED; // Toon het resultaat resultaat(); }); _thread.start(); } @Override public void start(String playerStarting) { if (!getIsNetworked()){ startLocalThread(); } } @Override public void initialize(IPlayer playerOne, IPlayer playerTwo, boolean isNetworked) { // System.out.println("Initializing Zeeslag"); _networked = isNetworked; // zet bord op _playerOneBoard = new Board(8, 8); _playerTwoBoard = new Board(8, 8); _playerOne = playerOne; _playerTwo = playerTwo; _playerOne.setBoard(_playerOneBoard); _playerTwo.setBoard(_playerTwoBoard); _state = ApplicationState.RUNNING; _stats = new MatchStats(); _stats.playerOne = playerOne.getName(); _stats.playerTwo = playerTwo.getName(); } @Override public void HandleInput(String input) { // Hier komt the user-input binnen // ongeldige input negeren if (_nextTurn != _playerOne.getName() || input == null || input.isEmpty()) return; if (input.length() != 2) return; _rowSelection = Integer.parseInt(String.valueOf(input.charAt(0))); _columnSelection = input.charAt(1) - 'A'; _playerOne.setNextMove(_columnSelection, _rowSelection); } @Override public ApplicationState GetState() { return _state; } @Override public void SetState(ApplicationState state) { _state = state; } @Override public IBoard GetPlayerBoard() { return _playerOneBoard; } public IBoard GetOpponentBoard(){ return _playerTwoBoard; } public void RequestUpdate() { Framework.UpdateUI(_playerOne, _playerTwo); } @Override public boolean getIsNetworked() { return _networked; } @Override public String GetGameName() { return _name; } @Override public IPlayer getPlayer(String name) { return _playerOne.getName().equals(name) ? _playerOne : _playerTwo; } @Override public void doTurn(String playerName) { IPlayer player = getPlayer(playerName); if (player == null) throw new RuntimeException("Player " + playerName + " does not exist"); player.doMove(); } @Override public void move(MoveMessage msg) { // IPlayer playerMakingMove = _playerOne.getName().equals(msg.getPlayerName()) ? _playerOne : _playerTwo; IBoard affectedBoard = _playerOne.getName().equals(msg.getPlayerName()) ? _playerTwoBoard : _playerOneBoard; Vector2D position = affectedBoard.getFromNetworked(msg.getLocation()); affectedBoard.setValue(position.X, position.Y, msg.getValue().getValue()); Framework.UpdateUI(_playerOne, _playerTwo); } @Override public void setGameResult(GameResultMessage gsm) { Framework.UpdateUI(gsm); } @Override public IPlayer getPlayerOne() { return _playerOne; } @Override public IPlayer getPlayerTwo() { return _playerTwo; } @Override public MatchStats getMatchStats() { return _stats; } @Override public void close() throws IOException { if (_thread != null){ _thread.interrupt(); _thread = null; } _state = ApplicationState.HALTED; } private void zetSpeler() throws InterruptedException { // De speler<SUF> // Dit doet de speler door het nummer en de letter // van de bij behorende row en col aan te geven _playerOneTurn = true; _columnSelection = -1; _rowSelection = 0; Framework.SendMessageToUser("Jouw beurt:"); Framework.SendMessageToUser("Voer coordinaten in:(1-8 + A-H) (1A, 4D, 8B)"); while(_rowSelection == 0 && _columnSelection < 0){ Thread.sleep(100); } // Voer het schot uit op het bord van de tegenstander boolean hit = schiet(_playerTwoBoard, _rowSelection - 1, _columnSelection); // Toon de resultaten van het schot aan de speler if (hit) { Framework.SendMessageToUser("Gefeliciteerd! Je hebt een schip geraakt op positie " + _playerTwoBoard.locatie(_rowSelection - 1, _columnSelection)); } else { Framework.SendMessageToUser("Helaas, je hebt gemist op positie " + _playerTwoBoard.locatie(_rowSelection - 1, _columnSelection)); } // Reset de selecties voor de volgende beurt _columnSelection = -1; _rowSelection = 0; } private void zetTegenstander() { _playerOneTurn = false; Random random = new Random(); int row, col; do { row = random.nextInt(8); col = random.nextInt(8); } while (!_playerOneBoard.isValidPosition(row, col)); // Voer het schot uit op het bord van de speler boolean hit = schiet(_playerOneBoard, row, col); // Toon de resultaten van het schot aan de speler if (hit) { Framework.SendMessageToUser("De tegenstander heeft een schip geraakt op positie " + _playerOneBoard.locatie(row, col)); } else { Framework.SendMessageToUser("De tegenstander heeft gemist op positie " + _playerOneBoard.locatie(row, col)); } } private boolean isGameOver() { if (schepenGezonken(_playerOneBoard)){ _winner = _playerTwo; _stats.winner = _playerTwo.getName(); } else if (schepenGezonken(_playerTwoBoard)){ _winner = _playerOne; _stats.winner = _playerOne.getName(); } return _winner != null; } private void resultaat() { Framework.SendMessageToUser("Het spel is voorbij!"); if (schepenGezonken(_playerOneBoard)) { Framework.SendMessageToUser("De tegenstander heeft gewonnen!"); } else { Framework.SendMessageToUser("Je hebt gewonnen!"); } } public void plaatsSchepen(IBoard board) { Random random = new Random(); // Hier worden de schip sizes gedefineerd // Dit kan eventueel ook later gelinked worden aan namen int[] shipSizes = {2, 2, 3, 4, 5}; int totalsquares = Arrays.stream(shipSizes).sum(); // get a sum of all the items in the array. int attempts = 0; boolean valid = false; do { attempts ++; int placedSquares = 0; for (int grootte : shipSizes) { int row, col; boolean horizontaal = random.nextBoolean(); // Random ligging van ship int cycles = 0; // Hier checked hij of het ship juist geplaatst wordt do { row = random.nextInt(board.getHeight()); col = random.nextInt(board.getWidth()); cycles ++; } while (!isValidPositionForShip(board, row, col, grootte, horizontaal) && cycles < 100); // Will attempt 100 times... After that, probably impossible... if (cycles > 99){ // Invalid break; } plaatsSchipOpBord(board, row, col, grootte, horizontaal); placedSquares += grootte; } // The combination is invalid, start over. if (totalsquares != placedSquares){ board.clear(); // System.out.println("Invalid config, attempt " + attempts); continue; } valid = true; } while (!valid); } public static void plaatsSchipOpBord(IBoard board, int row, int col, int grootte, boolean horizontaal) { // Hier gaat het ship horizontaal via col if (horizontaal) { for (int i = 0; i < grootte; i++) { board.setValue(row, col + i, FieldValues.SHIP.getValue()); } } // Hier gaat het ship verticaal via row else { for (int i = 0; i < grootte; i++) { board.setValue(row + i, col, FieldValues.SHIP.getValue()); } } } public static boolean isValidPositionForShip(IBoard board,int row, int col, int size, boolean horizontal){ if (!board.isValidPosition(row, col)){ return false; } // If the boat is left-to-right, make sure that the column coordinate plus the length of it does not exceed the // width of the playing board. if(horizontal) { if (!board.isValidPosition(row, col + size) ) { return false; } for (int i = 0; i < size; i ++){ if (board.getValue(row, col + i) != FieldValues.EMPTY.getValue()){ return false; } if (HasNeighbors(board, row, col + i)) return false; } return true; } // Do the same for up-to-down if (row + size < board.getHeight()){ if (!board.isValidPosition(row + size, col) ) { return false; } for (int i = 0; i < size; i ++){ if (board.getValue(row + i, col) != FieldValues.EMPTY.getValue()){ return false; } if (HasNeighbors(board, row + i, col)) return false; } return true; } return false; } private static boolean HasNeighbors(IBoard board, int row, int col){ // Check left, right, up and down of this coordinate to see if there is a ship there. for(Vector2D offset : _boatOffsetChecks){ int x = row + offset.X; int y = col + offset.Y; // If the coordinate to check is outside of bounds, we don't have to check it. if (!board.isValidPosition(x, y)) continue; if (board.getValue(x, y) != FieldValues.EMPTY.getValue()){ return true; } } return false; } private boolean schepenGezonken(IBoard board) { int[][] boardData = board.getValues(); // Loop door het bord en controleer of er nog 'O' (schepen) aanwezig zijn for (int i = 0; i < board.getWidth(); i++) { for (int j = 0; j < board.getHeight(); j++) { if (boardData[i][j] == Zeeslag.FieldValues.SHIP.getValue()) { // Er is nog minstens één schip aanwezig return false; } } } // Alle schepen zijn gezonken return true; } public void plaatsSchip(IBoard board, int row, int col) { // Hier wordt er gecontroleerd of de posiitie juist is. // Zo ja krijgt de speler een melding dat het plaatsen gelukt is. if (canPlacePiece(board, row, col)) { board.setValue(row, col, Zeeslag.FieldValues.SHIP.getValue()); System.out.println("Schip geplaatst op positie " + board.locatie(row, col)); } else { System.out.println("je kan hier geen schip plaatsen"); } } private boolean canPlacePiece(IBoard board, int row, int col) { // Hier wordt er gekeken of de positie juist is die gekozen werd op het veld return board.isValidPosition(row, col) && board.getValue(row, col) == Zeeslag.FieldValues.EMPTY.getValue(); } public boolean schiet(IBoard board, int row, int col) { // Controleer of de zet binnen het bord valt if (!board.isValidPosition(row, col)) { System.out.println(row + " -> " + col); System.out.println("Ongeldige positie. Probeer opnieuw."); return false; } // Controleer of er een schip op de opgegeven positie is if (board.getValue(row, col) == Zeeslag.FieldValues.SHIP.getValue()) { board.setValue(row, col,Zeeslag.FieldValues.HIT.getValue()); // Markeer het getroffen schip // System.out.println("Gefeliciteerd! Je hebt een schip geraakt op positie " + board.locatie(row, col)); // Controleert of het schip is gezonken if (isSchipGezonken(board, row, col)) { // System.out.println("Helaas, je schip is gezonken op positie " + board.locatie(row, col)); } return true; } else if (board.getValue(row, col) == Zeeslag.FieldValues.EMPTY.getValue()) { board.setValue(row, col, Zeeslag.FieldValues.MISS.getValue()); // Markeer de gemiste schoten // System.out.println("Helaas, je hebt gemist op positie " + board.locatie(row, col)); } else { System.out.println("Je hebt hier al geschoten. Probeer een andere positie."); } return false; } private boolean isSchipGezonken(IBoard board, int row, int col) { // Controleer horizontaal int countHorizontaal = 0; for (int j = 0; j < 8; j++) { if (board.getValue(row, j) == Zeeslag.FieldValues.HIT.getValue()) { countHorizontaal++; } } // Controleer verticaal int countVerticaal = 0; for (int i = 0; i < 8; i++) { if (board.getValue(i, col) == Zeeslag.FieldValues.HIT.getValue()) { countVerticaal++; } } // Als alle vakjes van het schip zijn geraakt, is het schip gezonken // TODO This needs to be different return countHorizontaal == 5 || countVerticaal == 5; } }
136031_55
/****************************************************************************** * Compilation: javac StdRandom.java * Execution: java StdRandom * Dependencies: StdOut.java * * A library of static methods to generate pseudo-random numbers from * different distributions (bernoulli, uniform, gaussian, discrete, * and exponential). Also includes a method for shuffling an array. * * * % java StdRandom 5 * seed = 1316600602069 * 59 16.81826 true 8.83954 0 * 32 91.32098 true 9.11026 0 * 35 10.11874 true 8.95396 3 * 92 32.88401 true 8.87089 0 * 72 92.55791 true 9.46241 0 * * % java StdRandom 5 * seed = 1316600616575 * 96 60.17070 true 8.72821 0 * 79 32.01607 true 8.58159 0 * 81 59.49065 true 9.10423 1 * 96 51.65818 true 9.02102 0 * 99 17.55771 true 8.99762 0 * * % java StdRandom 5 1316600616575 * seed = 1316600616575 * 96 60.17070 true 8.72821 0 * 79 32.01607 true 8.58159 0 * 81 59.49065 true 9.10423 1 * 96 51.65818 true 9.02102 0 * 99 17.55771 true 8.99762 0 * * * Remark * ------ * - Relies on randomness of nextDouble() method in java.util.Random * to generate pseudo-random numbers in [0, 1). * * - This library allows you to set and get the pseudo-random number seed. * * - See http://www.honeylocust.com/RngPack/ for an industrial * strength random number generator in Java. * ******************************************************************************/ package edu.princeton.cs.algs4; import java.util.Random; /** * The {@code StdRandom} class provides static methods for generating * random number from various discrete and continuous distributions, * including uniform, Bernoulli, geometric, Gaussian, exponential, Pareto, * Poisson, and Cauchy. It also provides method for shuffling an * array or subarray and generating random permutations. * * <p><b>Conventions.</b> * By convention, all intervals are half open. For example, * <code>uniformDouble(-1.0, 1.0)</code> returns a random number between * <code>-1.0</code> (inclusive) and <code>1.0</code> (exclusive). * Similarly, <code>shuffle(a, lo, hi)</code> shuffles the <code>hi - lo</code> * elements in the array <code>a[]</code>, starting at index <code>lo</code> * (inclusive) and ending at index <code>hi</code> (exclusive). * * <p><b>Performance.</b> * The methods all take constant expected time, except those that involve arrays. * The <em>shuffle</em> method takes time linear in the subarray to be shuffled; * the <em>discrete</em> methods take time linear in the length of the argument * array. * * <p><b>Additional information.</b> * For additional documentation, * see <a href="https://introcs.cs.princeton.edu/22library">Section 2.2</a> of * <i>Computer Science: An Interdisciplinary Approach</i> * by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public final class StdRandom { private static Random random; // pseudo-random number generator private static long seed; // pseudo-random number generator seed // static initializer static { // this is how the seed was set in Java 1.4 seed = System.currentTimeMillis(); random = new Random(seed); } // don't instantiate private StdRandom() { } /** * Sets the seed of the pseudo-random number generator. * This method enables you to produce the same sequence of "random" * number for each execution of the program. * Ordinarily, you should call this method at most once per program. * * @param s the seed */ public static void setSeed(long s) { seed = s; random = new Random(seed); } /** * Returns the seed of the pseudo-random number generator. * * @return the seed */ public static long getSeed() { return seed; } /** * Returns a random real number uniformly in [0, 1). * * @return a random real number uniformly in [0, 1) * @deprecated Replaced by {@link #uniformDouble()}. */ @Deprecated public static double uniform() { return uniformDouble(); } /** * Returns a random real number uniformly in [0, 1). * * @return a random real number uniformly in [0, 1) */ public static double uniformDouble() { return random.nextDouble(); } /** * Returns a random integer uniformly in [0, n). * * @param n number of possible integers * @return a random integer uniformly between 0 (inclusive) and {@code n} (exclusive) * @throws IllegalArgumentException if {@code n <= 0} * @deprecated Replaced by {@link #uniformInt(int n)}. */ @Deprecated public static int uniform(int n) { return uniformInt(n); } /** * Returns a random integer uniformly in [0, n). * * @param n number of possible integers * @return a random integer uniformly between 0 (inclusive) and {@code n} (exclusive) * @throws IllegalArgumentException if {@code n <= 0} */ public static int uniformInt(int n) { if (n <= 0) throw new IllegalArgumentException("argument must be positive: " + n); return random.nextInt(n); } /** * Returns a random long integer uniformly in [0, n). * * @param n number of possible {@code long} integers * @return a random long integer uniformly between 0 (inclusive) and {@code n} (exclusive) * @throws IllegalArgumentException if {@code n <= 0} * @deprecated Replaced by {@link #uniformLong(long n)}. */ @Deprecated public static long uniform(long n) { return uniformLong(n); } /** * Returns a random long integer uniformly in [0, n). * * @param n number of possible {@code long} integers * @return a random long integer uniformly between 0 (inclusive) and {@code n} (exclusive) * @throws IllegalArgumentException if {@code n <= 0} */ public static long uniformLong(long n) { if (n <= 0L) throw new IllegalArgumentException("argument must be positive: " + n); // https://docs.oracle.com/javase/8/docs/api/java/util/Random.html#longs-long-long-long- long r = random.nextLong(); long m = n - 1; // power of two if ((n & m) == 0L) { return r & m; } // reject over-represented candidates long u = r >>> 1; while (u + m - (r = u % n) < 0L) { u = random.nextLong() >>> 1; } return r; } /////////////////////////////////////////////////////////////////////////// // STATIC METHODS BELOW RELY ON JAVA.UTIL.RANDOM ONLY INDIRECTLY VIA // THE STATIC METHODS ABOVE. /////////////////////////////////////////////////////////////////////////// /** * Returns a random real number uniformly in [0, 1). * * @return a random real number uniformly in [0, 1) * @deprecated Replaced by {@link #uniformDouble()}. */ @Deprecated public static double random() { return uniformDouble(); } /** * Returns a random integer uniformly in [a, b). * * @param a the left endpoint * @param b the right endpoint * @return a random integer uniformly in [a, b) * @throws IllegalArgumentException if {@code b <= a} * @throws IllegalArgumentException if {@code b - a >= Integer.MAX_VALUE} * @deprecated Replaced by {@link #uniformInt(int a, int b)}. */ @Deprecated public static int uniform(int a, int b) { return uniformInt(a, b); } /** * Returns a random integer uniformly in [a, b). * * @param a the left endpoint * @param b the right endpoint * @return a random integer uniformly in [a, b) * @throws IllegalArgumentException if {@code b <= a} * @throws IllegalArgumentException if {@code b - a >= Integer.MAX_VALUE} */ public static int uniformInt(int a, int b) { if ((b <= a) || ((long) b - a >= Integer.MAX_VALUE)) { throw new IllegalArgumentException("invalid range: [" + a + ", " + b + ")"); } return a + uniform(b - a); } /** * Returns a random real number uniformly in [a, b). * * @param a the left endpoint * @param b the right endpoint * @return a random real number uniformly in [a, b) * @throws IllegalArgumentException unless {@code a < b} * @deprecated Replaced by {@link #uniformDouble(double a, double b)}. */ @Deprecated public static double uniform(double a, double b) { return uniformDouble(a, b); } /** * Returns a random real number uniformly in [a, b). * * @param a the left endpoint * @param b the right endpoint * @return a random real number uniformly in [a, b) * @throws IllegalArgumentException unless {@code a < b} */ public static double uniformDouble(double a, double b) { if (!(a < b)) { throw new IllegalArgumentException("invalid range: [" + a + ", " + b + ")"); } return a + uniform() * (b-a); } /** * Returns a random boolean from a Bernoulli distribution with success * probability <em>p</em>. * * @param p the probability of returning {@code true} * @return {@code true} with probability {@code p} and * {@code false} with probability {@code 1 - p} * @throws IllegalArgumentException unless {@code 0} &le; {@code p} &le; {@code 1.0} */ public static boolean bernoulli(double p) { if (!(p >= 0.0 && p <= 1.0)) throw new IllegalArgumentException("probability p must be between 0.0 and 1.0: " + p); return uniformDouble() < p; } /** * Returns a random boolean from a Bernoulli distribution with success * probability 1/2. * * @return {@code true} with probability 1/2 and * {@code false} with probability 1/2 */ public static boolean bernoulli() { return bernoulli(0.5); } /** * Returns a random real number from a standard Gaussian distribution. * * @return a random real number from a standard Gaussian distribution * (mean 0 and standard deviation 1). */ public static double gaussian() { // use the polar form of the Box-Muller transform double r, x, y; do { x = uniformDouble(-1.0, 1.0); y = uniformDouble(-1.0, 1.0); r = x*x + y*y; } while (r >= 1 || r == 0); return x * Math.sqrt(-2 * Math.log(r) / r); // Remark: y * Math.sqrt(-2 * Math.log(r) / r) // is an independent random gaussian } /** * Returns a random real number from a Gaussian distribution with mean &mu; * and standard deviation &sigma;. * * @param mu the mean * @param sigma the standard deviation * @return a real number distributed according to the Gaussian distribution * with mean {@code mu} and standard deviation {@code sigma} */ public static double gaussian(double mu, double sigma) { return mu + sigma * gaussian(); } /** * Returns a random integer from a geometric distribution with success * probability <em>p</em>. * The integer represents the number of independent trials * before the first success. * * @param p the parameter of the geometric distribution * @return a random integer from a geometric distribution with success * probability {@code p}; or {@code Integer.MAX_VALUE} if * {@code p} is (nearly) equal to {@code 1.0}. * @throws IllegalArgumentException unless {@code p >= 0.0} and {@code p <= 1.0} */ public static int geometric(double p) { if (!(p >= 0)) { throw new IllegalArgumentException("probability p must be greater than 0: " + p); } if (!(p <= 1.0)) { throw new IllegalArgumentException("probability p must not be larger than 1: " + p); } // using algorithm given by Knuth return (int) Math.ceil(Math.log(uniformDouble()) / Math.log(1.0 - p)); } /** * Returns a random integer from a Poisson distribution with mean &lambda;. * * @param lambda the mean of the Poisson distribution * @return a random integer from a Poisson distribution with mean {@code lambda} * @throws IllegalArgumentException unless {@code lambda > 0.0} and not infinite */ public static int poisson(double lambda) { if (!(lambda > 0.0)) throw new IllegalArgumentException("lambda must be positive: " + lambda); if (Double.isInfinite(lambda)) throw new IllegalArgumentException("lambda must not be infinite: " + lambda); // using algorithm given by Knuth // see http://en.wikipedia.org/wiki/Poisson_distribution int k = 0; double p = 1.0; double expLambda = Math.exp(-lambda); do { k++; p *= uniformDouble(); } while (p >= expLambda); return k-1; } /** * Returns a random real number from the standard Pareto distribution. * * @return a random real number from the standard Pareto distribution */ public static double pareto() { return pareto(1.0); } /** * Returns a random real number from a Pareto distribution with * shape parameter &alpha;. * * @param alpha shape parameter * @return a random real number from a Pareto distribution with shape * parameter {@code alpha} * @throws IllegalArgumentException unless {@code alpha > 0.0} */ public static double pareto(double alpha) { if (!(alpha > 0.0)) throw new IllegalArgumentException("alpha must be positive: " + alpha); return Math.pow(1 - uniformDouble(), -1.0 / alpha) - 1.0; } /** * Returns a random real number from the Cauchy distribution. * * @return a random real number from the Cauchy distribution. */ public static double cauchy() { return Math.tan(Math.PI * (uniformDouble() - 0.5)); } /** * Returns a random integer from the specified discrete distribution. * * @param probabilities the probability of occurrence of each integer * @return a random integer from a discrete distribution: * {@code i} with probability {@code probabilities[i]} * @throws IllegalArgumentException if {@code probabilities} is {@code null} * @throws IllegalArgumentException if sum of array entries is not (very nearly) equal to {@code 1.0} * @throws IllegalArgumentException unless {@code probabilities[i] >= 0.0} for each index {@code i} */ public static int discrete(double[] probabilities) { if (probabilities == null) throw new IllegalArgumentException("argument array must not be null"); double EPSILON = 1.0E-14; double sum = 0.0; for (int i = 0; i < probabilities.length; i++) { if (!(probabilities[i] >= 0.0)) throw new IllegalArgumentException("array entry " + i + " must be non-negative: " + probabilities[i]); sum += probabilities[i]; } if (sum > 1.0 + EPSILON || sum < 1.0 - EPSILON) throw new IllegalArgumentException("sum of array entries does not approximately equal 1.0: " + sum); // the for loop may not return a value when both r is (nearly) 1.0 and when the // cumulative sum is less than 1.0 (as a result of floating-point roundoff error) while (true) { double r = uniformDouble(); sum = 0.0; for (int i = 0; i < probabilities.length; i++) { sum = sum + probabilities[i]; if (sum > r) return i; } } } /** * Returns a random integer from the specified discrete distribution. * * @param frequencies the frequency of occurrence of each integer * @return a random integer from a discrete distribution: * {@code i} with probability proportional to {@code frequencies[i]} * @throws IllegalArgumentException if {@code frequencies} is {@code null} * @throws IllegalArgumentException if all array entries are {@code 0} * @throws IllegalArgumentException if {@code frequencies[i]} is negative for any index {@code i} * @throws IllegalArgumentException if sum of frequencies exceeds {@code Integer.MAX_VALUE} (2<sup>31</sup> - 1) */ public static int discrete(int[] frequencies) { if (frequencies == null) throw new IllegalArgumentException("argument array must not be null"); long sum = 0; for (int i = 0; i < frequencies.length; i++) { if (frequencies[i] < 0) throw new IllegalArgumentException("array entry " + i + " must be non-negative: " + frequencies[i]); sum += frequencies[i]; } if (sum == 0) throw new IllegalArgumentException("at least one array entry must be positive"); if (sum >= Integer.MAX_VALUE) throw new IllegalArgumentException("sum of frequencies overflows an int"); // pick index i with probability proportional to frequency double r = uniformInt((int) sum); sum = 0; for (int i = 0; i < frequencies.length; i++) { sum += frequencies[i]; if (sum > r) return i; } // can't reach here assert false; return -1; } /** * Returns a random real number from an exponential distribution * with rate &lambda;. * * @param lambda the rate of the exponential distribution * @return a random real number from an exponential distribution with * rate {@code lambda} * @throws IllegalArgumentException unless {@code lambda > 0.0} */ public static double exponential(double lambda) { if (!(lambda > 0.0)) throw new IllegalArgumentException("lambda must be positive: " + lambda); return -Math.log(1 - uniformDouble()) / lambda; } /** * Returns a random real number from an exponential distribution * with rate &lambda;. * * @param lambda the rate of the exponential distribution * @return a random real number from an exponential distribution with * rate {@code lambda} * @throws IllegalArgumentException unless {@code lambda > 0.0} * @deprecated Replaced by {@link #exponential(double)}. */ @Deprecated public static double exp(double lambda) { return exponential(lambda); } /** * Rearranges the elements of the specified array in uniformly random order. * * @param a the array to shuffle * @throws IllegalArgumentException if {@code a} is {@code null} */ public static void shuffle(Object[] a) { validateNotNull(a); int n = a.length; for (int i = 0; i < n; i++) { int r = i + uniformInt(n-i); // between i and n-1 Object temp = a[i]; a[i] = a[r]; a[r] = temp; } } /** * Rearranges the elements of the specified array in uniformly random order. * * @param a the array to shuffle * @throws IllegalArgumentException if {@code a} is {@code null} */ public static void shuffle(double[] a) { validateNotNull(a); int n = a.length; for (int i = 0; i < n; i++) { int r = i + uniformInt(n-i); // between i and n-1 double temp = a[i]; a[i] = a[r]; a[r] = temp; } } /** * Rearranges the elements of the specified array in uniformly random order. * * @param a the array to shuffle * @throws IllegalArgumentException if {@code a} is {@code null} */ public static void shuffle(int[] a) { validateNotNull(a); int n = a.length; for (int i = 0; i < n; i++) { int r = i + uniformInt(n-i); // between i and n-1 int temp = a[i]; a[i] = a[r]; a[r] = temp; } } /** * Rearranges the elements of the specified array in uniformly random order. * * @param a the array to shuffle * @throws IllegalArgumentException if {@code a} is {@code null} */ public static void shuffle(char[] a) { validateNotNull(a); int n = a.length; for (int i = 0; i < n; i++) { int r = i + uniformInt(n-i); // between i and n-1 char temp = a[i]; a[i] = a[r]; a[r] = temp; } } /** * Rearranges the elements of the specified subarray in uniformly random order. * * @param a the array to shuffle * @param lo the left endpoint (inclusive) * @param hi the right endpoint (exclusive) * @throws IllegalArgumentException if {@code a} is {@code null} * @throws IllegalArgumentException unless {@code (0 <= lo) && (lo < hi) && (hi <= a.length)} * */ public static void shuffle(Object[] a, int lo, int hi) { validateNotNull(a); validateSubarrayIndices(lo, hi, a.length); for (int i = lo; i < hi; i++) { int r = i + uniformInt(hi-i); // between i and hi-1 Object temp = a[i]; a[i] = a[r]; a[r] = temp; } } /** * Rearranges the elements of the specified subarray in uniformly random order. * * @param a the array to shuffle * @param lo the left endpoint (inclusive) * @param hi the right endpoint (exclusive) * @throws IllegalArgumentException if {@code a} is {@code null} * @throws IllegalArgumentException unless {@code (0 <= lo) && (lo < hi) && (hi <= a.length)} */ public static void shuffle(double[] a, int lo, int hi) { validateNotNull(a); validateSubarrayIndices(lo, hi, a.length); for (int i = lo; i < hi; i++) { int r = i + uniformInt(hi-i); // between i and hi-1 double temp = a[i]; a[i] = a[r]; a[r] = temp; } } /** * Rearranges the elements of the specified subarray in uniformly random order. * * @param a the array to shuffle * @param lo the left endpoint (inclusive) * @param hi the right endpoint (exclusive) * @throws IllegalArgumentException if {@code a} is {@code null} * @throws IllegalArgumentException unless {@code (0 <= lo) && (lo < hi) && (hi <= a.length)} */ public static void shuffle(int[] a, int lo, int hi) { validateNotNull(a); validateSubarrayIndices(lo, hi, a.length); for (int i = lo; i < hi; i++) { int r = i + uniformInt(hi-i); // between i and hi-1 int temp = a[i]; a[i] = a[r]; a[r] = temp; } } /** * Returns a uniformly random permutation of <em>n</em> elements. * * @param n number of elements * @throws IllegalArgumentException if {@code n} is negative * @return an array of length {@code n} that is a uniformly random permutation * of {@code 0}, {@code 1}, ..., {@code n-1} */ public static int[] permutation(int n) { if (n < 0) throw new IllegalArgumentException("n must be non-negative: " + n); int[] perm = new int[n]; for (int i = 0; i < n; i++) perm[i] = i; shuffle(perm); return perm; } /** * Returns a uniformly random permutation of <em>k</em> of <em>n</em> elements. * * @param n number of elements * @param k number of elements to select * @throws IllegalArgumentException if {@code n} is negative * @throws IllegalArgumentException unless {@code 0 <= k <= n} * @return an array of length {@code k} that is a uniformly random permutation * of {@code k} of the elements from {@code 0}, {@code 1}, ..., {@code n-1} */ public static int[] permutation(int n, int k) { if (n < 0) throw new IllegalArgumentException("n must be non-negative: " + n); if (k < 0 || k > n) throw new IllegalArgumentException("k must be between 0 and n: " + k); int[] perm = new int[k]; for (int i = 0; i < k; i++) { int r = uniformInt(i+1); // between 0 and i perm[i] = perm[r]; perm[r] = i; } for (int i = k; i < n; i++) { int r = uniformInt(i+1); // between 0 and i if (r < k) perm[r] = i; } return perm; } // throw an IllegalArgumentException if x is null // (x can be of type Object[], double[], int[], ...) private static void validateNotNull(Object x) { if (x == null) { throw new IllegalArgumentException("argument must not be null"); } } // throw an exception unless 0 <= lo <= hi <= length private static void validateSubarrayIndices(int lo, int hi, int length) { if (lo < 0 || hi > length || lo > hi) { throw new IllegalArgumentException("subarray indices out of bounds: [" + lo + ", " + hi + ")"); } } /** * Unit tests the methods in this class. * * @param args the command-line arguments */ public static void main(String[] args) { int n = Integer.parseInt(args[0]); if (args.length == 2) StdRandom.setSeed(Long.parseLong(args[1])); double[] probabilities = { 0.5, 0.3, 0.1, 0.1 }; int[] frequencies = { 5, 3, 1, 1 }; String[] a = "A B C D E F G".split(" "); StdOut.println("seed = " + StdRandom.getSeed()); for (int i = 0; i < n; i++) { StdOut.printf("%2d ", uniformInt(100)); StdOut.printf("%8.5f ", uniformDouble(10.0, 99.0)); StdOut.printf("%5b ", bernoulli(0.5)); StdOut.printf("%7.5f ", gaussian(9.0, 0.2)); StdOut.printf("%1d ", discrete(probabilities)); StdOut.printf("%1d ", discrete(frequencies)); StdOut.printf("%11d ", uniformLong(100000000000L)); StdRandom.shuffle(a); for (String s : a) StdOut.print(s); StdOut.println(); } } } /****************************************************************************** * Copyright 2002-2022, Robert Sedgewick and Kevin Wayne. * * This file is part of algs4.jar, which accompanies the textbook * * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. * http://algs4.cs.princeton.edu * * * algs4.jar 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. * * algs4.jar 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 algs4.jar. If not, see http://www.gnu.org/licenses. ******************************************************************************/
kevin-wayne/algs4
src/main/java/edu/princeton/cs/algs4/StdRandom.java
7,833
// between i and hi-1
line_comment
nl
/****************************************************************************** * Compilation: javac StdRandom.java * Execution: java StdRandom * Dependencies: StdOut.java * * A library of static methods to generate pseudo-random numbers from * different distributions (bernoulli, uniform, gaussian, discrete, * and exponential). Also includes a method for shuffling an array. * * * % java StdRandom 5 * seed = 1316600602069 * 59 16.81826 true 8.83954 0 * 32 91.32098 true 9.11026 0 * 35 10.11874 true 8.95396 3 * 92 32.88401 true 8.87089 0 * 72 92.55791 true 9.46241 0 * * % java StdRandom 5 * seed = 1316600616575 * 96 60.17070 true 8.72821 0 * 79 32.01607 true 8.58159 0 * 81 59.49065 true 9.10423 1 * 96 51.65818 true 9.02102 0 * 99 17.55771 true 8.99762 0 * * % java StdRandom 5 1316600616575 * seed = 1316600616575 * 96 60.17070 true 8.72821 0 * 79 32.01607 true 8.58159 0 * 81 59.49065 true 9.10423 1 * 96 51.65818 true 9.02102 0 * 99 17.55771 true 8.99762 0 * * * Remark * ------ * - Relies on randomness of nextDouble() method in java.util.Random * to generate pseudo-random numbers in [0, 1). * * - This library allows you to set and get the pseudo-random number seed. * * - See http://www.honeylocust.com/RngPack/ for an industrial * strength random number generator in Java. * ******************************************************************************/ package edu.princeton.cs.algs4; import java.util.Random; /** * The {@code StdRandom} class provides static methods for generating * random number from various discrete and continuous distributions, * including uniform, Bernoulli, geometric, Gaussian, exponential, Pareto, * Poisson, and Cauchy. It also provides method for shuffling an * array or subarray and generating random permutations. * * <p><b>Conventions.</b> * By convention, all intervals are half open. For example, * <code>uniformDouble(-1.0, 1.0)</code> returns a random number between * <code>-1.0</code> (inclusive) and <code>1.0</code> (exclusive). * Similarly, <code>shuffle(a, lo, hi)</code> shuffles the <code>hi - lo</code> * elements in the array <code>a[]</code>, starting at index <code>lo</code> * (inclusive) and ending at index <code>hi</code> (exclusive). * * <p><b>Performance.</b> * The methods all take constant expected time, except those that involve arrays. * The <em>shuffle</em> method takes time linear in the subarray to be shuffled; * the <em>discrete</em> methods take time linear in the length of the argument * array. * * <p><b>Additional information.</b> * For additional documentation, * see <a href="https://introcs.cs.princeton.edu/22library">Section 2.2</a> of * <i>Computer Science: An Interdisciplinary Approach</i> * by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public final class StdRandom { private static Random random; // pseudo-random number generator private static long seed; // pseudo-random number generator seed // static initializer static { // this is how the seed was set in Java 1.4 seed = System.currentTimeMillis(); random = new Random(seed); } // don't instantiate private StdRandom() { } /** * Sets the seed of the pseudo-random number generator. * This method enables you to produce the same sequence of "random" * number for each execution of the program. * Ordinarily, you should call this method at most once per program. * * @param s the seed */ public static void setSeed(long s) { seed = s; random = new Random(seed); } /** * Returns the seed of the pseudo-random number generator. * * @return the seed */ public static long getSeed() { return seed; } /** * Returns a random real number uniformly in [0, 1). * * @return a random real number uniformly in [0, 1) * @deprecated Replaced by {@link #uniformDouble()}. */ @Deprecated public static double uniform() { return uniformDouble(); } /** * Returns a random real number uniformly in [0, 1). * * @return a random real number uniformly in [0, 1) */ public static double uniformDouble() { return random.nextDouble(); } /** * Returns a random integer uniformly in [0, n). * * @param n number of possible integers * @return a random integer uniformly between 0 (inclusive) and {@code n} (exclusive) * @throws IllegalArgumentException if {@code n <= 0} * @deprecated Replaced by {@link #uniformInt(int n)}. */ @Deprecated public static int uniform(int n) { return uniformInt(n); } /** * Returns a random integer uniformly in [0, n). * * @param n number of possible integers * @return a random integer uniformly between 0 (inclusive) and {@code n} (exclusive) * @throws IllegalArgumentException if {@code n <= 0} */ public static int uniformInt(int n) { if (n <= 0) throw new IllegalArgumentException("argument must be positive: " + n); return random.nextInt(n); } /** * Returns a random long integer uniformly in [0, n). * * @param n number of possible {@code long} integers * @return a random long integer uniformly between 0 (inclusive) and {@code n} (exclusive) * @throws IllegalArgumentException if {@code n <= 0} * @deprecated Replaced by {@link #uniformLong(long n)}. */ @Deprecated public static long uniform(long n) { return uniformLong(n); } /** * Returns a random long integer uniformly in [0, n). * * @param n number of possible {@code long} integers * @return a random long integer uniformly between 0 (inclusive) and {@code n} (exclusive) * @throws IllegalArgumentException if {@code n <= 0} */ public static long uniformLong(long n) { if (n <= 0L) throw new IllegalArgumentException("argument must be positive: " + n); // https://docs.oracle.com/javase/8/docs/api/java/util/Random.html#longs-long-long-long- long r = random.nextLong(); long m = n - 1; // power of two if ((n & m) == 0L) { return r & m; } // reject over-represented candidates long u = r >>> 1; while (u + m - (r = u % n) < 0L) { u = random.nextLong() >>> 1; } return r; } /////////////////////////////////////////////////////////////////////////// // STATIC METHODS BELOW RELY ON JAVA.UTIL.RANDOM ONLY INDIRECTLY VIA // THE STATIC METHODS ABOVE. /////////////////////////////////////////////////////////////////////////// /** * Returns a random real number uniformly in [0, 1). * * @return a random real number uniformly in [0, 1) * @deprecated Replaced by {@link #uniformDouble()}. */ @Deprecated public static double random() { return uniformDouble(); } /** * Returns a random integer uniformly in [a, b). * * @param a the left endpoint * @param b the right endpoint * @return a random integer uniformly in [a, b) * @throws IllegalArgumentException if {@code b <= a} * @throws IllegalArgumentException if {@code b - a >= Integer.MAX_VALUE} * @deprecated Replaced by {@link #uniformInt(int a, int b)}. */ @Deprecated public static int uniform(int a, int b) { return uniformInt(a, b); } /** * Returns a random integer uniformly in [a, b). * * @param a the left endpoint * @param b the right endpoint * @return a random integer uniformly in [a, b) * @throws IllegalArgumentException if {@code b <= a} * @throws IllegalArgumentException if {@code b - a >= Integer.MAX_VALUE} */ public static int uniformInt(int a, int b) { if ((b <= a) || ((long) b - a >= Integer.MAX_VALUE)) { throw new IllegalArgumentException("invalid range: [" + a + ", " + b + ")"); } return a + uniform(b - a); } /** * Returns a random real number uniformly in [a, b). * * @param a the left endpoint * @param b the right endpoint * @return a random real number uniformly in [a, b) * @throws IllegalArgumentException unless {@code a < b} * @deprecated Replaced by {@link #uniformDouble(double a, double b)}. */ @Deprecated public static double uniform(double a, double b) { return uniformDouble(a, b); } /** * Returns a random real number uniformly in [a, b). * * @param a the left endpoint * @param b the right endpoint * @return a random real number uniformly in [a, b) * @throws IllegalArgumentException unless {@code a < b} */ public static double uniformDouble(double a, double b) { if (!(a < b)) { throw new IllegalArgumentException("invalid range: [" + a + ", " + b + ")"); } return a + uniform() * (b-a); } /** * Returns a random boolean from a Bernoulli distribution with success * probability <em>p</em>. * * @param p the probability of returning {@code true} * @return {@code true} with probability {@code p} and * {@code false} with probability {@code 1 - p} * @throws IllegalArgumentException unless {@code 0} &le; {@code p} &le; {@code 1.0} */ public static boolean bernoulli(double p) { if (!(p >= 0.0 && p <= 1.0)) throw new IllegalArgumentException("probability p must be between 0.0 and 1.0: " + p); return uniformDouble() < p; } /** * Returns a random boolean from a Bernoulli distribution with success * probability 1/2. * * @return {@code true} with probability 1/2 and * {@code false} with probability 1/2 */ public static boolean bernoulli() { return bernoulli(0.5); } /** * Returns a random real number from a standard Gaussian distribution. * * @return a random real number from a standard Gaussian distribution * (mean 0 and standard deviation 1). */ public static double gaussian() { // use the polar form of the Box-Muller transform double r, x, y; do { x = uniformDouble(-1.0, 1.0); y = uniformDouble(-1.0, 1.0); r = x*x + y*y; } while (r >= 1 || r == 0); return x * Math.sqrt(-2 * Math.log(r) / r); // Remark: y * Math.sqrt(-2 * Math.log(r) / r) // is an independent random gaussian } /** * Returns a random real number from a Gaussian distribution with mean &mu; * and standard deviation &sigma;. * * @param mu the mean * @param sigma the standard deviation * @return a real number distributed according to the Gaussian distribution * with mean {@code mu} and standard deviation {@code sigma} */ public static double gaussian(double mu, double sigma) { return mu + sigma * gaussian(); } /** * Returns a random integer from a geometric distribution with success * probability <em>p</em>. * The integer represents the number of independent trials * before the first success. * * @param p the parameter of the geometric distribution * @return a random integer from a geometric distribution with success * probability {@code p}; or {@code Integer.MAX_VALUE} if * {@code p} is (nearly) equal to {@code 1.0}. * @throws IllegalArgumentException unless {@code p >= 0.0} and {@code p <= 1.0} */ public static int geometric(double p) { if (!(p >= 0)) { throw new IllegalArgumentException("probability p must be greater than 0: " + p); } if (!(p <= 1.0)) { throw new IllegalArgumentException("probability p must not be larger than 1: " + p); } // using algorithm given by Knuth return (int) Math.ceil(Math.log(uniformDouble()) / Math.log(1.0 - p)); } /** * Returns a random integer from a Poisson distribution with mean &lambda;. * * @param lambda the mean of the Poisson distribution * @return a random integer from a Poisson distribution with mean {@code lambda} * @throws IllegalArgumentException unless {@code lambda > 0.0} and not infinite */ public static int poisson(double lambda) { if (!(lambda > 0.0)) throw new IllegalArgumentException("lambda must be positive: " + lambda); if (Double.isInfinite(lambda)) throw new IllegalArgumentException("lambda must not be infinite: " + lambda); // using algorithm given by Knuth // see http://en.wikipedia.org/wiki/Poisson_distribution int k = 0; double p = 1.0; double expLambda = Math.exp(-lambda); do { k++; p *= uniformDouble(); } while (p >= expLambda); return k-1; } /** * Returns a random real number from the standard Pareto distribution. * * @return a random real number from the standard Pareto distribution */ public static double pareto() { return pareto(1.0); } /** * Returns a random real number from a Pareto distribution with * shape parameter &alpha;. * * @param alpha shape parameter * @return a random real number from a Pareto distribution with shape * parameter {@code alpha} * @throws IllegalArgumentException unless {@code alpha > 0.0} */ public static double pareto(double alpha) { if (!(alpha > 0.0)) throw new IllegalArgumentException("alpha must be positive: " + alpha); return Math.pow(1 - uniformDouble(), -1.0 / alpha) - 1.0; } /** * Returns a random real number from the Cauchy distribution. * * @return a random real number from the Cauchy distribution. */ public static double cauchy() { return Math.tan(Math.PI * (uniformDouble() - 0.5)); } /** * Returns a random integer from the specified discrete distribution. * * @param probabilities the probability of occurrence of each integer * @return a random integer from a discrete distribution: * {@code i} with probability {@code probabilities[i]} * @throws IllegalArgumentException if {@code probabilities} is {@code null} * @throws IllegalArgumentException if sum of array entries is not (very nearly) equal to {@code 1.0} * @throws IllegalArgumentException unless {@code probabilities[i] >= 0.0} for each index {@code i} */ public static int discrete(double[] probabilities) { if (probabilities == null) throw new IllegalArgumentException("argument array must not be null"); double EPSILON = 1.0E-14; double sum = 0.0; for (int i = 0; i < probabilities.length; i++) { if (!(probabilities[i] >= 0.0)) throw new IllegalArgumentException("array entry " + i + " must be non-negative: " + probabilities[i]); sum += probabilities[i]; } if (sum > 1.0 + EPSILON || sum < 1.0 - EPSILON) throw new IllegalArgumentException("sum of array entries does not approximately equal 1.0: " + sum); // the for loop may not return a value when both r is (nearly) 1.0 and when the // cumulative sum is less than 1.0 (as a result of floating-point roundoff error) while (true) { double r = uniformDouble(); sum = 0.0; for (int i = 0; i < probabilities.length; i++) { sum = sum + probabilities[i]; if (sum > r) return i; } } } /** * Returns a random integer from the specified discrete distribution. * * @param frequencies the frequency of occurrence of each integer * @return a random integer from a discrete distribution: * {@code i} with probability proportional to {@code frequencies[i]} * @throws IllegalArgumentException if {@code frequencies} is {@code null} * @throws IllegalArgumentException if all array entries are {@code 0} * @throws IllegalArgumentException if {@code frequencies[i]} is negative for any index {@code i} * @throws IllegalArgumentException if sum of frequencies exceeds {@code Integer.MAX_VALUE} (2<sup>31</sup> - 1) */ public static int discrete(int[] frequencies) { if (frequencies == null) throw new IllegalArgumentException("argument array must not be null"); long sum = 0; for (int i = 0; i < frequencies.length; i++) { if (frequencies[i] < 0) throw new IllegalArgumentException("array entry " + i + " must be non-negative: " + frequencies[i]); sum += frequencies[i]; } if (sum == 0) throw new IllegalArgumentException("at least one array entry must be positive"); if (sum >= Integer.MAX_VALUE) throw new IllegalArgumentException("sum of frequencies overflows an int"); // pick index i with probability proportional to frequency double r = uniformInt((int) sum); sum = 0; for (int i = 0; i < frequencies.length; i++) { sum += frequencies[i]; if (sum > r) return i; } // can't reach here assert false; return -1; } /** * Returns a random real number from an exponential distribution * with rate &lambda;. * * @param lambda the rate of the exponential distribution * @return a random real number from an exponential distribution with * rate {@code lambda} * @throws IllegalArgumentException unless {@code lambda > 0.0} */ public static double exponential(double lambda) { if (!(lambda > 0.0)) throw new IllegalArgumentException("lambda must be positive: " + lambda); return -Math.log(1 - uniformDouble()) / lambda; } /** * Returns a random real number from an exponential distribution * with rate &lambda;. * * @param lambda the rate of the exponential distribution * @return a random real number from an exponential distribution with * rate {@code lambda} * @throws IllegalArgumentException unless {@code lambda > 0.0} * @deprecated Replaced by {@link #exponential(double)}. */ @Deprecated public static double exp(double lambda) { return exponential(lambda); } /** * Rearranges the elements of the specified array in uniformly random order. * * @param a the array to shuffle * @throws IllegalArgumentException if {@code a} is {@code null} */ public static void shuffle(Object[] a) { validateNotNull(a); int n = a.length; for (int i = 0; i < n; i++) { int r = i + uniformInt(n-i); // between i and n-1 Object temp = a[i]; a[i] = a[r]; a[r] = temp; } } /** * Rearranges the elements of the specified array in uniformly random order. * * @param a the array to shuffle * @throws IllegalArgumentException if {@code a} is {@code null} */ public static void shuffle(double[] a) { validateNotNull(a); int n = a.length; for (int i = 0; i < n; i++) { int r = i + uniformInt(n-i); // between i and n-1 double temp = a[i]; a[i] = a[r]; a[r] = temp; } } /** * Rearranges the elements of the specified array in uniformly random order. * * @param a the array to shuffle * @throws IllegalArgumentException if {@code a} is {@code null} */ public static void shuffle(int[] a) { validateNotNull(a); int n = a.length; for (int i = 0; i < n; i++) { int r = i + uniformInt(n-i); // between i and n-1 int temp = a[i]; a[i] = a[r]; a[r] = temp; } } /** * Rearranges the elements of the specified array in uniformly random order. * * @param a the array to shuffle * @throws IllegalArgumentException if {@code a} is {@code null} */ public static void shuffle(char[] a) { validateNotNull(a); int n = a.length; for (int i = 0; i < n; i++) { int r = i + uniformInt(n-i); // between i and n-1 char temp = a[i]; a[i] = a[r]; a[r] = temp; } } /** * Rearranges the elements of the specified subarray in uniformly random order. * * @param a the array to shuffle * @param lo the left endpoint (inclusive) * @param hi the right endpoint (exclusive) * @throws IllegalArgumentException if {@code a} is {@code null} * @throws IllegalArgumentException unless {@code (0 <= lo) && (lo < hi) && (hi <= a.length)} * */ public static void shuffle(Object[] a, int lo, int hi) { validateNotNull(a); validateSubarrayIndices(lo, hi, a.length); for (int i = lo; i < hi; i++) { int r = i + uniformInt(hi-i); // between i and hi-1 Object temp = a[i]; a[i] = a[r]; a[r] = temp; } } /** * Rearranges the elements of the specified subarray in uniformly random order. * * @param a the array to shuffle * @param lo the left endpoint (inclusive) * @param hi the right endpoint (exclusive) * @throws IllegalArgumentException if {@code a} is {@code null} * @throws IllegalArgumentException unless {@code (0 <= lo) && (lo < hi) && (hi <= a.length)} */ public static void shuffle(double[] a, int lo, int hi) { validateNotNull(a); validateSubarrayIndices(lo, hi, a.length); for (int i = lo; i < hi; i++) { int r = i + uniformInt(hi-i); // between i<SUF> double temp = a[i]; a[i] = a[r]; a[r] = temp; } } /** * Rearranges the elements of the specified subarray in uniformly random order. * * @param a the array to shuffle * @param lo the left endpoint (inclusive) * @param hi the right endpoint (exclusive) * @throws IllegalArgumentException if {@code a} is {@code null} * @throws IllegalArgumentException unless {@code (0 <= lo) && (lo < hi) && (hi <= a.length)} */ public static void shuffle(int[] a, int lo, int hi) { validateNotNull(a); validateSubarrayIndices(lo, hi, a.length); for (int i = lo; i < hi; i++) { int r = i + uniformInt(hi-i); // between i and hi-1 int temp = a[i]; a[i] = a[r]; a[r] = temp; } } /** * Returns a uniformly random permutation of <em>n</em> elements. * * @param n number of elements * @throws IllegalArgumentException if {@code n} is negative * @return an array of length {@code n} that is a uniformly random permutation * of {@code 0}, {@code 1}, ..., {@code n-1} */ public static int[] permutation(int n) { if (n < 0) throw new IllegalArgumentException("n must be non-negative: " + n); int[] perm = new int[n]; for (int i = 0; i < n; i++) perm[i] = i; shuffle(perm); return perm; } /** * Returns a uniformly random permutation of <em>k</em> of <em>n</em> elements. * * @param n number of elements * @param k number of elements to select * @throws IllegalArgumentException if {@code n} is negative * @throws IllegalArgumentException unless {@code 0 <= k <= n} * @return an array of length {@code k} that is a uniformly random permutation * of {@code k} of the elements from {@code 0}, {@code 1}, ..., {@code n-1} */ public static int[] permutation(int n, int k) { if (n < 0) throw new IllegalArgumentException("n must be non-negative: " + n); if (k < 0 || k > n) throw new IllegalArgumentException("k must be between 0 and n: " + k); int[] perm = new int[k]; for (int i = 0; i < k; i++) { int r = uniformInt(i+1); // between 0 and i perm[i] = perm[r]; perm[r] = i; } for (int i = k; i < n; i++) { int r = uniformInt(i+1); // between 0 and i if (r < k) perm[r] = i; } return perm; } // throw an IllegalArgumentException if x is null // (x can be of type Object[], double[], int[], ...) private static void validateNotNull(Object x) { if (x == null) { throw new IllegalArgumentException("argument must not be null"); } } // throw an exception unless 0 <= lo <= hi <= length private static void validateSubarrayIndices(int lo, int hi, int length) { if (lo < 0 || hi > length || lo > hi) { throw new IllegalArgumentException("subarray indices out of bounds: [" + lo + ", " + hi + ")"); } } /** * Unit tests the methods in this class. * * @param args the command-line arguments */ public static void main(String[] args) { int n = Integer.parseInt(args[0]); if (args.length == 2) StdRandom.setSeed(Long.parseLong(args[1])); double[] probabilities = { 0.5, 0.3, 0.1, 0.1 }; int[] frequencies = { 5, 3, 1, 1 }; String[] a = "A B C D E F G".split(" "); StdOut.println("seed = " + StdRandom.getSeed()); for (int i = 0; i < n; i++) { StdOut.printf("%2d ", uniformInt(100)); StdOut.printf("%8.5f ", uniformDouble(10.0, 99.0)); StdOut.printf("%5b ", bernoulli(0.5)); StdOut.printf("%7.5f ", gaussian(9.0, 0.2)); StdOut.printf("%1d ", discrete(probabilities)); StdOut.printf("%1d ", discrete(frequencies)); StdOut.printf("%11d ", uniformLong(100000000000L)); StdRandom.shuffle(a); for (String s : a) StdOut.print(s); StdOut.println(); } } } /****************************************************************************** * Copyright 2002-2022, Robert Sedgewick and Kevin Wayne. * * This file is part of algs4.jar, which accompanies the textbook * * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. * http://algs4.cs.princeton.edu * * * algs4.jar 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. * * algs4.jar 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 algs4.jar. If not, see http://www.gnu.org/licenses. ******************************************************************************/
134441_3
package com.awesome.excelpp.gui; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.image.BufferedImage; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JColorChooser; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JButton; import javax.swing.JTextField; import javax.swing.JTabbedPane; import javax.swing.JComboBox; import javax.swing.ImageIcon; import javax.swing.KeyStroke; import javax.swing.SwingConstants; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.undo.UndoManager; import javax.xml.parsers.ParserConfigurationException; import javax.imageio.ImageIO; import org.w3c.dom.Document; import org.xml.sax.SAXException; import com.awesome.excelpp.models.Cell; import com.awesome.excelpp.models.SpreadSheet; import com.awesome.excelpp.readers.XML; import com.awesome.excelpp.writers.XMLWriter; /** * Class that constructs the main window of the GUI. * @author Team Awesome */ public class GUI extends JFrame implements ActionListener, KeyListener, WindowListener { private static final long serialVersionUID = 1L; private static final int screenWidth = (int)Utils.getScreenWidth(); private static final int screenHeight = (int)Utils.getScreenHeight(); private static BufferedImage mainImage; private static JFrame mainFrame; private static JTextField functionField; private static JTabbedPane mainTabs; private static JComboBox<String> functions; private static JButton buttonAbout; private static JButton buttonBackgroundColor; private static JButton buttonForegroundColor; private static JButton buttonItalic; private static JButton buttonBold; private static JButton buttonRedo; private static JButton buttonUndo; private static JButton buttonSaveAs; private static JButton buttonSave; private static JButton buttonOpen; private static JButton buttonNewTab; private static JButton buttonNew; private static JButton buttonGraphs; /** * Constructs the main window. * @throws IOException */ public GUI() throws IOException { final JPanel buttonPanel = createButtonPanel(); mainImage = ImageIO.read(new File("data/icons/gnumeric.png")); mainFrame = new JFrame ("Excel++"); mainFrame.setLayout (new BorderLayout()); mainFrame.setIconImage(mainImage); mainFrame.setSize (buttonPanel.getPreferredSize().width, 400); mainFrame.setMinimumSize(buttonPanel.getPreferredSize()); //ToDo: andere oplossing voor verdwijnende componenten? mainFrame.setLocation ((screenWidth / 2) - (mainFrame.getWidth() / 2), (screenHeight / 2) - (mainFrame.getHeight() / 2)); //center in het midden mainFrame.setDefaultCloseOperation (JFrame.DO_NOTHING_ON_CLOSE); mainFrame.addWindowListener(this); mainTabs = new JTabbedPane(); createNewTab(null); //open altijd een tab mainFrame.add (buttonPanel, BorderLayout.PAGE_START); mainFrame.add (mainTabs, BorderLayout.CENTER); mainFrame.setVisible (true); } /** * Creates a <code>JPanel</code> holding the required buttons. * @return The <code>JPanel</code> holding all the required buttons */ private final JPanel createButtonPanel() { final JPanel panel = new JPanel(new BorderLayout()); final JPanel buttonPanel = new JPanel(); final JPanel formulaPanel = new JPanel(); formulaPanel.setLayout(new BoxLayout(formulaPanel, BoxLayout.X_AXIS)); formulaPanel.setBorder(BorderFactory.createEmptyBorder(3, 3, 6, 3)); buttonNew = new JButton(); buttonNewTab = new JButton(); buttonOpen = new JButton(); buttonSave = new JButton(); buttonSaveAs = new JButton(); buttonUndo = new JButton(); buttonRedo = new JButton(); functionField = new JTextField(80); buttonBold = new JButton(); buttonItalic = new JButton(); buttonForegroundColor = new JButton(); buttonBackgroundColor = new JButton(); buttonAbout = new JButton(); buttonGraphs = new JButton(); String[] functionList = {"And", "Average", "Count", "CountA", "CountIf", "If", "Int", "IsEven", "IsLogical", "IsNumber", "Lower", "Max", "Median", "Min", "Mod", "Not", "Or", "Power", "Product", "Proper", "Quotient", "RoundDown", "RoundUp", "Sign", "SqrtT", "Subtract", "Sum", "SumIf", "Upper"}; functions = new JComboBox<String>(functionList); final ImageIcon newIcon = new ImageIcon("data/icons/window-new.png"); final ImageIcon newTabIcon = new ImageIcon("data/icons/stock_new-tab.png"); final ImageIcon openIcon = new ImageIcon("data/icons/gtk-open.png"); final ImageIcon saveIcon = new ImageIcon("data/icons/document-save.png"); final ImageIcon saveIconAs = new ImageIcon("data/icons/document-save-as.png"); final ImageIcon undoIcon = new ImageIcon("data/icons/edit-undo.png"); final ImageIcon redoIcon = new ImageIcon("data/icons/edit-redo.png"); final ImageIcon formulaIcon = new ImageIcon("data/icons/formula_piet2.png"); final ImageIcon boldIcon = new ImageIcon("data/icons/format-text-bold.png"); final ImageIcon italicIcon = new ImageIcon("data/icons/format-text-italic.png"); final ImageIcon foregroundIcon = new ImageIcon("data/icons/color_line.png"); final ImageIcon backgroundIcon = new ImageIcon("data/icons/emblem-art.png"); final ImageIcon graphsIcon = new ImageIcon("data/icons/graphs.png"); final ImageIcon aboutIcon = new ImageIcon("data/icons/gtk-about.png"); final JLabel formulaLabel = new JLabel(formulaIcon); buttonNew.setIcon(newIcon); buttonNewTab.setIcon(newTabIcon); buttonOpen.setIcon(openIcon); buttonSave.setIcon(saveIcon); buttonSaveAs.setIcon(saveIconAs); buttonUndo.setIcon(undoIcon); buttonRedo.setIcon(redoIcon); buttonBold.setIcon(boldIcon); buttonItalic.setIcon(italicIcon); buttonForegroundColor.setIcon(foregroundIcon); buttonBackgroundColor.setIcon(backgroundIcon); buttonGraphs.setIcon(graphsIcon); buttonAbout.setIcon(aboutIcon); buttonNew.setToolTipText("New file"); buttonNewTab.setToolTipText("New tab"); buttonOpen.setToolTipText("Open file"); buttonSave.setToolTipText("Save file"); buttonSaveAs.setToolTipText("Save as"); buttonUndo.setToolTipText("Undo last change"); buttonRedo.setToolTipText("Redo last change"); buttonBold.setToolTipText("Make this cell's text bold"); buttonItalic.setToolTipText("Make this cell's text italic"); buttonForegroundColor.setToolTipText("Set this cell's foreground color"); buttonBackgroundColor.setToolTipText("Set this cell's background color"); buttonGraphs.setToolTipText("Graphs"); buttonAbout.setToolTipText("About"); buttonPanel.add(buttonNew); buttonPanel.add(buttonNewTab); buttonPanel.add(buttonOpen); buttonPanel.add(buttonSave); buttonPanel.add(buttonSaveAs); buttonPanel.add(buttonUndo); buttonPanel.add(buttonRedo); formulaPanel.add(functions); formulaPanel.add(Box.createRigidArea(new Dimension(3, 0))); formulaPanel.add(formulaLabel); formulaPanel.add(Box.createRigidArea(new Dimension(3, 0))); formulaPanel.add(functionField); buttonPanel.add(buttonBold); buttonPanel.add(buttonItalic); buttonPanel.add(buttonForegroundColor); buttonPanel.add(buttonBackgroundColor); buttonPanel.add(buttonGraphs); buttonPanel.add(buttonAbout); buttonNew.addActionListener(this); buttonNew.registerKeyboardAction (this, "pressed", KeyStroke.getKeyStroke(KeyEvent.VK_N, KeyEvent.CTRL_DOWN_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW); buttonNewTab.addActionListener(this); buttonNewTab.registerKeyboardAction(this, "pressed", KeyStroke.getKeyStroke(KeyEvent.VK_T, KeyEvent.CTRL_DOWN_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW); buttonOpen.addActionListener(this); buttonOpen.registerKeyboardAction (this, "pressed", KeyStroke.getKeyStroke(KeyEvent.VK_O, KeyEvent.CTRL_DOWN_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW); buttonSave.addActionListener(this); buttonSave.registerKeyboardAction (this, "pressed", KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.CTRL_DOWN_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW); buttonSaveAs.addActionListener(this); buttonSaveAs.registerKeyboardAction(this, "pressed", KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.CTRL_DOWN_MASK + KeyEvent.SHIFT_DOWN_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW); buttonUndo.addActionListener(this); buttonUndo.registerKeyboardAction(this, "pressed", KeyStroke.getKeyStroke(KeyEvent.VK_Z, KeyEvent.CTRL_DOWN_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW); buttonRedo.addActionListener(this); buttonRedo.registerKeyboardAction(this, "pressed", KeyStroke.getKeyStroke(KeyEvent.VK_Z, KeyEvent.SHIFT_DOWN_MASK | KeyEvent.CTRL_DOWN_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW); functions.addActionListener(this); functionField.addKeyListener(this); buttonBold.addActionListener(this); buttonBold.registerKeyboardAction(this, "pressed", KeyStroke.getKeyStroke(KeyEvent.VK_B, KeyEvent.CTRL_DOWN_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW); buttonItalic.addActionListener(this); buttonItalic.registerKeyboardAction(this, "pressed", KeyStroke.getKeyStroke(KeyEvent.VK_I, KeyEvent.CTRL_DOWN_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW); buttonForegroundColor.addActionListener(this); buttonForegroundColor.registerKeyboardAction(this, "pressed", KeyStroke.getKeyStroke(KeyEvent.VK_F, KeyEvent.CTRL_DOWN_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW); buttonBackgroundColor.addActionListener(this); buttonBackgroundColor.registerKeyboardAction(this, "pressed", KeyStroke.getKeyStroke(KeyEvent.VK_A, KeyEvent.CTRL_DOWN_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW); buttonGraphs.addActionListener(this); buttonAbout.addActionListener(this); panel.add(buttonPanel, BorderLayout.PAGE_START); panel.add(formulaPanel, BorderLayout.PAGE_END); return panel; } /** * Opens a help dialog in which the user can get help on formulas and keyboard shortcuts. */ private final void openHelpDialog() { final JDialog helpDialog = new JDialog(this, "Help", true); final JPanel helpPanel = new JPanel(); final JTabbedPane helpTabbedPane = new JTabbedPane(); final String formulaText = "<html><body style='width:300px'>Implemented are the 29 formules one can see inside the combobox." + " Excel++ adheres to the syntax for Microsoft Excel, so if any formula's use is unclear, please see their documentation.<br><br>" + "The parser supports nested formulas and is tested up until a formula with a length of 30751 characters. Should your formula exceed" + " this, we are very curious to hear about your results!<br><br>" + "The syntax is as follows: =And(2+2&lt;=8, \"true\", \"false\")<br>" + "The '=' character indicates the start of a new formula. Hereafter follows the name of the formula, as seen in the combobox." + " Arguments are provided between brackets and are separated by commas. The following logical operators are supported:<br>" + "'==', '&lt;', '&lt;=', '>', '>=' and '!='. Strings and boolean values should be put between quotation marks. Cell ranges are also supported." + " Here is a more complicated example, including Cell ranges:<br>=Sum(Average(A1:A5), 5, Power(2,4))<br><br>" + "Regular math notation, such as =(2+2)*3, is also supported. One can also make Cell references from other Cells: =A1."; final JLabel formulaLabel = new JLabel(formulaText); formulaLabel.setVerticalAlignment(SwingConstants.TOP); final String hotkeyText = "<html><body style='width:300px'>New file <p style='text-align:right'>Control + N" + "<p style='text-align:left'>Open file <p style='text-align:right'>Control + O" + "<p style='text-align:left'>Save file <p style='text-align:right'>Control + S" + "<p style='text-align:left'>Save file as <p style='text-align:right'>Control + Shift + S" + "<p style='text-align:left'>New tab <p style='text-align:right'>Control + T" + "<p style='text-align:left'>Close tab <p style='text-align:right'>Control + W" + "<p style='text-align:left'>Undo last change <p style='text-align:right'>Control + Z" + "<p style='text-align:left'>Redo last change <p style='text-align:right'>Control + Shift + Z" + "<p style='text-align:left'>Make Cell's text bold <p style='text-align:right'>Control + B" + "<p style='text-align:left'>Make Cell's text italic <p style='text-align:right'>Control + I" + "<p style='text-align:left'>Change Cell's foreground color <p style='text-align:right'>Control + F" + "<p style='text-align:left'>Change Cell's background color <p style='text-align:right'>Control + A" + "<p style='text-align:left'>Set current Cell's text bold <p style='text-align:right'>Control + B" + "<p style='text-align:left'>Set current Cell's text italic <p style='text-align:right'>Control + I" + "<p style='text-align:left'>Cel contents to textfield <p style='text-align:right'>Left mouse button" + "<p style='text-align:left'>Cel position to textfield (also works for a selection of Cells) <p style='text-align:right'>Alt + right mouse button"; final JLabel hotkeyLabel = new JLabel(hotkeyText); hotkeyLabel.setVerticalAlignment(SwingConstants.TOP); final String aboutText = "<html><body style='width:300px'>Some code in this project is taken from other people." + " These files were shared in the public domain; see the source files for more information.<br>" + "The icons used come from the gnome-colors icon theme and are licensed under the GPL-2 license.<br><br>" + "Excel++ is a TU Delft project.\nCopyright 2013 Team Awesome."; final JLabel aboutLabel = new JLabel(aboutText); aboutLabel.setVerticalAlignment(SwingConstants.TOP); helpPanel.add(helpTabbedPane); helpTabbedPane.addTab("Formula Help", formulaLabel); helpTabbedPane.setIconAt(0, new ImageIcon("data/icons/formulaHelp.png")); helpTabbedPane.addTab("Hotkeys", hotkeyLabel); helpTabbedPane.setIconAt(1, new ImageIcon("data/icons/keyboard.png")); helpTabbedPane.addTab("About", aboutLabel); helpTabbedPane.setIconAt(2, new ImageIcon("data/icons/gtk-about_16.png")); helpDialog.add(helpPanel); helpDialog.pack(); helpDialog.setIconImage(mainImage); helpDialog.setResizable(false); helpDialog.setLocation ((screenWidth / 2) - (helpPanel.getPreferredSize().width / 2), (screenHeight / 2) - (helpPanel.getPreferredSize().height / 2)); //center in het midden helpDialog.setVisible(true); } /** * Creates a new tab with everything setup inside it. * @param file The file to open inside the new <code>SpreadSheetTable</code> */ public final void createNewTab(File file) { SpreadSheet sheet = new SpreadSheet(); SpreadSheetTable table = new SpreadSheetTable(sheet, file); SpreadSheetScrollPane pane = new SpreadSheetScrollPane(table); String tabTitle = "New file"; mainTabs.addTab(null, null, pane, tabTitle); // Add tab to pane without label or icon but with tooltip int tabCount = mainTabs.getTabCount(); tabCount = tabCount == 0 ? 0 : (tabCount - 1); mainTabs.setTabComponentAt(tabCount, new CloseableTabComponent(tabTitle, tabCount)); // Now assign the component for the tab mainTabs.setSelectedIndex(tabCount); //ToDo: mainTabs.setMnemonicAt(tabCount, KeyEvent.VK_(tabCount + 1)); } /** * Removes the currently active tab. Makes sure there is always one tab remaining. */ public static final void removeTab(int index) { int tabCount = mainTabs.getTabCount(); if(tabCount > 1) { //er moet ten minste een tab open blijven if (closeFile(index) == 0) { CloseableTabComponent[] tabComponents = new CloseableTabComponent[tabCount]; for (int i = index; i < tabCount; i++) { tabComponents[i] = (CloseableTabComponent)mainTabs.getTabComponentAt(i); } mainTabs.remove(index); for(int i = tabCount - 1; i >= index; i--) { //"herstel" alle indices van de CloseableTabComponents tabComponents[i].setIndex(i - 1); } } } } /** * Updates the tab's title. * @param index The index of the tab to update * @param newTitle the new title to set */ private static final void updateTabTitle(int index, String newTitle) { CloseableTabComponent currentComponent = (CloseableTabComponent)mainTabs.getTabComponentAt(index); currentComponent.setTitle(newTitle); } /** * Gets a tab's title. * @param index The index of the tab to get the title from * @return The title */ private static final String getTabTitle(int index) { CloseableTabComponent currentComponent = (CloseableTabComponent)mainTabs.getTabComponentAt(index); return currentComponent.getTitle(); } /** * Helper method to set the text in the function field. * @param text The text to set in the function field */ public static void functionFieldSetText (String text) { functionField.setText(text); } /** * Helper method to get the text from the function field. * @return The text from the function field */ public static String functionFieldGetText() { return functionField.getText(); } /** * Changes markup in the currently selected <code>Cells</code>. * @param index The index of the tab whose <code>Cells</code> need to be updated * @param bold True if the boldness is subject to change */ public final void changeMarkup(int index, boolean bold) { Cell current = null; SpreadSheetScrollPane scrollPane = (SpreadSheetScrollPane)mainTabs.getComponentAt(index); SpreadSheetTable table = scrollPane.getTable(); int[] row = table.getSelectedRows(); int[] column = table.getSelectedColumns(); for (int i = 0; i < column.length; i++) { for (int j = 0; j < row.length; j++) { current = (Cell)table.getValueAt(row[j], column[i]); if(bold == true) { int bolde = current.getBold() == 0 ? 1 : 0; current.setBold(bolde, true); } else if(bold == false) { int italic = current.getItalic() == 0 ? 2 : 0; current.setItalic(italic, true); } } } table.grabFocus(); } /** * Changes the fore- and background <code>Colors</code> in the currently selected <code>Cells</code>. * @param index The index of the tab whose <code>Cells</code> need to be updated * @param foreground True if the foreground <code>Color</code> is subject to change */ public final void changeColors(int index, boolean foreground) { Color newColor = null; Cell current = null; SpreadSheetScrollPane scrollPane = (SpreadSheetScrollPane)mainTabs.getComponentAt(index); SpreadSheetTable table = scrollPane.getTable(); int[] row = table.getSelectedRows(); int[] column = table.getSelectedColumns(); if(foreground == false) newColor = JColorChooser.showDialog(this, "Choose a background color", buttonBackgroundColor.getBackground()); else if(foreground == true) newColor = JColorChooser.showDialog(this, "Choose a foreground color", buttonForegroundColor.getBackground()); for (int i = 0; i < column.length; i++) { for (int j = 0; j < row.length; j++) { current = (Cell)table.getValueAt(row[j], column[i]); if(newColor != null && foreground == false) current.setBackgroundColor(newColor, true); else if(newColor != null && foreground == true) current.setForegroundColor(newColor, true); } } if(newColor != null && foreground == false) buttonBackgroundColor.setBackground(newColor); else if(newColor != null && foreground == true) buttonForegroundColor.setBackground(newColor); table.grabFocus(); } /** * Listens for all events emitted by the elements of the GUI. */ public final void actionPerformed(ActionEvent e) { int index = mainTabs.getSelectedIndex(); if (e.getSource().equals(buttonOpen)) openFile(); else if (e.getSource().equals(buttonNew)) { if(closeFile(index) == 0) { SpreadSheet newSheet = new SpreadSheet(); SpreadSheetTable newTable = new SpreadSheetTable(newSheet, null); SpreadSheetScrollPane scrollPane = (SpreadSheetScrollPane)mainTabs.getComponentAt(index); scrollPane.setTable(newTable); updateTabTitle(index, "New file"); } } else if (e.getSource().equals(buttonNewTab)) createNewTab(null); else if (e.getSource().equals(buttonSave)) saveFile(false); else if (e.getSource().equals(buttonSaveAs)) saveFile(true); else if (e.getSource().equals(buttonBold)) changeMarkup(index, true); else if (e.getSource().equals(buttonItalic)) changeMarkup(index, false); else if (e.getSource().equals(buttonForegroundColor)) changeColors(index, true); else if (e.getSource().equals(buttonBackgroundColor)) changeColors(index, false); else if (e.getSource().equals(buttonAbout)) openHelpDialog(); else if (e.getSource().equals(functions)) { String formula = "=" + (String)functions.getSelectedItem(); functionField.setText(formula + "("); SpreadSheetScrollPane scrollPane = (SpreadSheetScrollPane)mainTabs.getComponentAt(index); scrollPane.getTable().grabFocus(); } else if (e.getSource().equals(buttonUndo)) { SpreadSheetScrollPane scrollPane = (SpreadSheetScrollPane)mainTabs.getComponentAt(index); UndoManager manager = scrollPane.getTable().getUndoManager(); if (manager.canUndo() == true) manager.undo(); } else if (e.getSource().equals(buttonRedo)) { SpreadSheetScrollPane scrollPane = (SpreadSheetScrollPane)mainTabs.getComponentAt(index); UndoManager manager = scrollPane.getTable().getUndoManager(); if (manager.canRedo() == true) manager.redo(); } else if(e.getSource().equals(buttonGraphs)) { SpreadSheetScrollPane scrollPane = (SpreadSheetScrollPane)mainTabs.getComponentAt(index); SpreadSheetTable table = scrollPane.getTable(); new GraphDialog(table, mainImage, screenWidth, screenHeight); } } /** * Listens for all KeyPressed events emitted by the elements of the GUI. */ @Override public final void keyPressed(KeyEvent e) { if (e.getKeyChar() == KeyEvent.VK_ENTER) { SpreadSheetScrollPane scrollPane = (SpreadSheetScrollPane)mainTabs.getSelectedComponent(); SpreadSheetTable table = scrollPane.getTable(); if (table.getCellSelected() == false) JOptionPane.showMessageDialog(this, "Please select a Cell first.", "No Cell selected", JOptionPane.INFORMATION_MESSAGE); else { Cell current = (Cell) table.getValueAt(table.getSelectedRow(), table.getSelectedColumn()); current.setContent(functionField.getText(), true); } } } /** * Is executed right before the window closes. Used to do some clean ups and check if files * need to be saved. */ @Override public final void windowClosing(WindowEvent e) { for(int i = 0; i < mainTabs.getTabCount(); i++) { if(closeFile(i) == 2) return; } System.exit(0); //ToDo: niet de beste oplossing? Bastiaan zei dat we het zo konden laten. } public void keyTyped(KeyEvent e) {} public void keyReleased(KeyEvent e) {} public void windowOpened(WindowEvent e) {} public void windowClosed(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} /** * Opens a file dialog in which the user can select the file to open. */ public final void openFile() { final JFileChooser fc = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter("XML", "xml"); fc.setFileFilter(filter); if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { int index = mainTabs.getSelectedIndex(); File file = fc.getSelectedFile(); SpreadSheetTable table; SpreadSheet sheet; try { Document doc = XML.parse(file); sheet = XML.print(doc); table = new SpreadSheetTable(sheet, file); } catch (IOException ex) { JOptionPane.showMessageDialog(this, "Something went wrong: " + ex.toString(), "Error!", JOptionPane.ERROR_MESSAGE); sheet = new SpreadSheet(); table = new SpreadSheetTable(sheet, null); ex.printStackTrace(); } catch (ParserConfigurationException | SAXException ex) { JOptionPane.showMessageDialog(this, "Something went wrong: " + ex.toString(), "Error!", JOptionPane.ERROR_MESSAGE); sheet = new SpreadSheet(); table = new SpreadSheetTable(sheet, file); ex.printStackTrace(); } SpreadSheetScrollPane scrollPane = (SpreadSheetScrollPane)mainTabs.getComponentAt(index); scrollPane.setTable(table); updateTabTitle(index, file.getName()); } } /** * Saves the currently opened file. * @param saveAs True if the Save As button has been pressed, will spawn a Save As dialog */ public static final void saveFile (boolean saveAs) { SpreadSheetScrollPane scrollPane = (SpreadSheetScrollPane)mainTabs.getSelectedComponent(); SpreadSheetTable table = scrollPane.getTable(); File file = table.getFile(); if (file == null || saveAs == true) { final JFileChooser fc = new JFileChooser(); int choice = fc.showSaveDialog(mainFrame); if (choice == JFileChooser.APPROVE_OPTION) { String fileString = fc.getSelectedFile().getPath(); if (!fileString.endsWith(".xml")) fileString += ".xml"; file = new File(fileString); table.setFile(file); updateTabTitle(mainTabs.getSelectedIndex(), file.getName()); } else if(choice == JFileChooser.CANCEL_OPTION) return; } try { ((SpreadSheet)table.getModel()).write(new XMLWriter(file)); } catch (FileNotFoundException ex) { JOptionPane.showMessageDialog(mainFrame, "Something went wrong: " + ex.toString(), "Error!", JOptionPane.ERROR_MESSAGE); ex.printStackTrace(); } } /** * Handles closing of a file. Pops up a dialog for confirmation if changes will be lost. * @param index The index of the tab whose <code>File</code> will be closed * @return 0 for OK, 1 for save, 2 for cancel */ public static final int closeFile(int index) { int close = 0; Object[] options = { "Continue", "Save file", "Cancel" }; SpreadSheetScrollPane scrollPane = (SpreadSheetScrollPane)mainTabs.getComponentAt(index); SpreadSheetTable table = scrollPane.getTable(); if(getTabTitle(index).equals("New file")) { if(table.getSheet().isEmpty() == false) close = JOptionPane.showOptionDialog(mainFrame, "Changes made to the current spreadsheet will be lost. Continue?", "Continue?", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[2]); } else { try { Document doc = XML.parse(table.getFile()); SpreadSheet fileSheet = XML.print(doc); Cell fileCell = null; breakpoint: for(int i = 0; i < fileSheet.getColumnCount(); i++) { //fileSheet of table.getSheet maakt niet uit; zelfde aantal cellen for(int j = 0; j < fileSheet.getRowCount(); j++) { //fileSheet of table.getSheet maakt niet uit; zelfde aantal cellen fileCell = (Cell)fileSheet.getValueAt(j, i); if(!fileCell.equals(table.getSheet().getValueAt(j, i))) { close = JOptionPane.showOptionDialog(mainFrame, "Changes made to the current spreadsheet will be lost. Continue?", "Continue?", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[2]); break breakpoint; } } } } catch (Exception ex) { JOptionPane.showMessageDialog(mainFrame, "Something went wrong: " + ex.toString(), "Error!", JOptionPane.ERROR_MESSAGE); ex.printStackTrace(); } } if(close == 1) { saveFile(true); close = 0; } return close; } }
Hjdskes/ExcelPP
src/com/awesome/excelpp/gui/GUI.java
7,737
//center in het midden
line_comment
nl
package com.awesome.excelpp.gui; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.image.BufferedImage; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JColorChooser; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JButton; import javax.swing.JTextField; import javax.swing.JTabbedPane; import javax.swing.JComboBox; import javax.swing.ImageIcon; import javax.swing.KeyStroke; import javax.swing.SwingConstants; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.undo.UndoManager; import javax.xml.parsers.ParserConfigurationException; import javax.imageio.ImageIO; import org.w3c.dom.Document; import org.xml.sax.SAXException; import com.awesome.excelpp.models.Cell; import com.awesome.excelpp.models.SpreadSheet; import com.awesome.excelpp.readers.XML; import com.awesome.excelpp.writers.XMLWriter; /** * Class that constructs the main window of the GUI. * @author Team Awesome */ public class GUI extends JFrame implements ActionListener, KeyListener, WindowListener { private static final long serialVersionUID = 1L; private static final int screenWidth = (int)Utils.getScreenWidth(); private static final int screenHeight = (int)Utils.getScreenHeight(); private static BufferedImage mainImage; private static JFrame mainFrame; private static JTextField functionField; private static JTabbedPane mainTabs; private static JComboBox<String> functions; private static JButton buttonAbout; private static JButton buttonBackgroundColor; private static JButton buttonForegroundColor; private static JButton buttonItalic; private static JButton buttonBold; private static JButton buttonRedo; private static JButton buttonUndo; private static JButton buttonSaveAs; private static JButton buttonSave; private static JButton buttonOpen; private static JButton buttonNewTab; private static JButton buttonNew; private static JButton buttonGraphs; /** * Constructs the main window. * @throws IOException */ public GUI() throws IOException { final JPanel buttonPanel = createButtonPanel(); mainImage = ImageIO.read(new File("data/icons/gnumeric.png")); mainFrame = new JFrame ("Excel++"); mainFrame.setLayout (new BorderLayout()); mainFrame.setIconImage(mainImage); mainFrame.setSize (buttonPanel.getPreferredSize().width, 400); mainFrame.setMinimumSize(buttonPanel.getPreferredSize()); //ToDo: andere oplossing voor verdwijnende componenten? mainFrame.setLocation ((screenWidth / 2) - (mainFrame.getWidth() / 2), (screenHeight / 2) - (mainFrame.getHeight() / 2)); //center in<SUF> mainFrame.setDefaultCloseOperation (JFrame.DO_NOTHING_ON_CLOSE); mainFrame.addWindowListener(this); mainTabs = new JTabbedPane(); createNewTab(null); //open altijd een tab mainFrame.add (buttonPanel, BorderLayout.PAGE_START); mainFrame.add (mainTabs, BorderLayout.CENTER); mainFrame.setVisible (true); } /** * Creates a <code>JPanel</code> holding the required buttons. * @return The <code>JPanel</code> holding all the required buttons */ private final JPanel createButtonPanel() { final JPanel panel = new JPanel(new BorderLayout()); final JPanel buttonPanel = new JPanel(); final JPanel formulaPanel = new JPanel(); formulaPanel.setLayout(new BoxLayout(formulaPanel, BoxLayout.X_AXIS)); formulaPanel.setBorder(BorderFactory.createEmptyBorder(3, 3, 6, 3)); buttonNew = new JButton(); buttonNewTab = new JButton(); buttonOpen = new JButton(); buttonSave = new JButton(); buttonSaveAs = new JButton(); buttonUndo = new JButton(); buttonRedo = new JButton(); functionField = new JTextField(80); buttonBold = new JButton(); buttonItalic = new JButton(); buttonForegroundColor = new JButton(); buttonBackgroundColor = new JButton(); buttonAbout = new JButton(); buttonGraphs = new JButton(); String[] functionList = {"And", "Average", "Count", "CountA", "CountIf", "If", "Int", "IsEven", "IsLogical", "IsNumber", "Lower", "Max", "Median", "Min", "Mod", "Not", "Or", "Power", "Product", "Proper", "Quotient", "RoundDown", "RoundUp", "Sign", "SqrtT", "Subtract", "Sum", "SumIf", "Upper"}; functions = new JComboBox<String>(functionList); final ImageIcon newIcon = new ImageIcon("data/icons/window-new.png"); final ImageIcon newTabIcon = new ImageIcon("data/icons/stock_new-tab.png"); final ImageIcon openIcon = new ImageIcon("data/icons/gtk-open.png"); final ImageIcon saveIcon = new ImageIcon("data/icons/document-save.png"); final ImageIcon saveIconAs = new ImageIcon("data/icons/document-save-as.png"); final ImageIcon undoIcon = new ImageIcon("data/icons/edit-undo.png"); final ImageIcon redoIcon = new ImageIcon("data/icons/edit-redo.png"); final ImageIcon formulaIcon = new ImageIcon("data/icons/formula_piet2.png"); final ImageIcon boldIcon = new ImageIcon("data/icons/format-text-bold.png"); final ImageIcon italicIcon = new ImageIcon("data/icons/format-text-italic.png"); final ImageIcon foregroundIcon = new ImageIcon("data/icons/color_line.png"); final ImageIcon backgroundIcon = new ImageIcon("data/icons/emblem-art.png"); final ImageIcon graphsIcon = new ImageIcon("data/icons/graphs.png"); final ImageIcon aboutIcon = new ImageIcon("data/icons/gtk-about.png"); final JLabel formulaLabel = new JLabel(formulaIcon); buttonNew.setIcon(newIcon); buttonNewTab.setIcon(newTabIcon); buttonOpen.setIcon(openIcon); buttonSave.setIcon(saveIcon); buttonSaveAs.setIcon(saveIconAs); buttonUndo.setIcon(undoIcon); buttonRedo.setIcon(redoIcon); buttonBold.setIcon(boldIcon); buttonItalic.setIcon(italicIcon); buttonForegroundColor.setIcon(foregroundIcon); buttonBackgroundColor.setIcon(backgroundIcon); buttonGraphs.setIcon(graphsIcon); buttonAbout.setIcon(aboutIcon); buttonNew.setToolTipText("New file"); buttonNewTab.setToolTipText("New tab"); buttonOpen.setToolTipText("Open file"); buttonSave.setToolTipText("Save file"); buttonSaveAs.setToolTipText("Save as"); buttonUndo.setToolTipText("Undo last change"); buttonRedo.setToolTipText("Redo last change"); buttonBold.setToolTipText("Make this cell's text bold"); buttonItalic.setToolTipText("Make this cell's text italic"); buttonForegroundColor.setToolTipText("Set this cell's foreground color"); buttonBackgroundColor.setToolTipText("Set this cell's background color"); buttonGraphs.setToolTipText("Graphs"); buttonAbout.setToolTipText("About"); buttonPanel.add(buttonNew); buttonPanel.add(buttonNewTab); buttonPanel.add(buttonOpen); buttonPanel.add(buttonSave); buttonPanel.add(buttonSaveAs); buttonPanel.add(buttonUndo); buttonPanel.add(buttonRedo); formulaPanel.add(functions); formulaPanel.add(Box.createRigidArea(new Dimension(3, 0))); formulaPanel.add(formulaLabel); formulaPanel.add(Box.createRigidArea(new Dimension(3, 0))); formulaPanel.add(functionField); buttonPanel.add(buttonBold); buttonPanel.add(buttonItalic); buttonPanel.add(buttonForegroundColor); buttonPanel.add(buttonBackgroundColor); buttonPanel.add(buttonGraphs); buttonPanel.add(buttonAbout); buttonNew.addActionListener(this); buttonNew.registerKeyboardAction (this, "pressed", KeyStroke.getKeyStroke(KeyEvent.VK_N, KeyEvent.CTRL_DOWN_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW); buttonNewTab.addActionListener(this); buttonNewTab.registerKeyboardAction(this, "pressed", KeyStroke.getKeyStroke(KeyEvent.VK_T, KeyEvent.CTRL_DOWN_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW); buttonOpen.addActionListener(this); buttonOpen.registerKeyboardAction (this, "pressed", KeyStroke.getKeyStroke(KeyEvent.VK_O, KeyEvent.CTRL_DOWN_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW); buttonSave.addActionListener(this); buttonSave.registerKeyboardAction (this, "pressed", KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.CTRL_DOWN_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW); buttonSaveAs.addActionListener(this); buttonSaveAs.registerKeyboardAction(this, "pressed", KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.CTRL_DOWN_MASK + KeyEvent.SHIFT_DOWN_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW); buttonUndo.addActionListener(this); buttonUndo.registerKeyboardAction(this, "pressed", KeyStroke.getKeyStroke(KeyEvent.VK_Z, KeyEvent.CTRL_DOWN_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW); buttonRedo.addActionListener(this); buttonRedo.registerKeyboardAction(this, "pressed", KeyStroke.getKeyStroke(KeyEvent.VK_Z, KeyEvent.SHIFT_DOWN_MASK | KeyEvent.CTRL_DOWN_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW); functions.addActionListener(this); functionField.addKeyListener(this); buttonBold.addActionListener(this); buttonBold.registerKeyboardAction(this, "pressed", KeyStroke.getKeyStroke(KeyEvent.VK_B, KeyEvent.CTRL_DOWN_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW); buttonItalic.addActionListener(this); buttonItalic.registerKeyboardAction(this, "pressed", KeyStroke.getKeyStroke(KeyEvent.VK_I, KeyEvent.CTRL_DOWN_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW); buttonForegroundColor.addActionListener(this); buttonForegroundColor.registerKeyboardAction(this, "pressed", KeyStroke.getKeyStroke(KeyEvent.VK_F, KeyEvent.CTRL_DOWN_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW); buttonBackgroundColor.addActionListener(this); buttonBackgroundColor.registerKeyboardAction(this, "pressed", KeyStroke.getKeyStroke(KeyEvent.VK_A, KeyEvent.CTRL_DOWN_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW); buttonGraphs.addActionListener(this); buttonAbout.addActionListener(this); panel.add(buttonPanel, BorderLayout.PAGE_START); panel.add(formulaPanel, BorderLayout.PAGE_END); return panel; } /** * Opens a help dialog in which the user can get help on formulas and keyboard shortcuts. */ private final void openHelpDialog() { final JDialog helpDialog = new JDialog(this, "Help", true); final JPanel helpPanel = new JPanel(); final JTabbedPane helpTabbedPane = new JTabbedPane(); final String formulaText = "<html><body style='width:300px'>Implemented are the 29 formules one can see inside the combobox." + " Excel++ adheres to the syntax for Microsoft Excel, so if any formula's use is unclear, please see their documentation.<br><br>" + "The parser supports nested formulas and is tested up until a formula with a length of 30751 characters. Should your formula exceed" + " this, we are very curious to hear about your results!<br><br>" + "The syntax is as follows: =And(2+2&lt;=8, \"true\", \"false\")<br>" + "The '=' character indicates the start of a new formula. Hereafter follows the name of the formula, as seen in the combobox." + " Arguments are provided between brackets and are separated by commas. The following logical operators are supported:<br>" + "'==', '&lt;', '&lt;=', '>', '>=' and '!='. Strings and boolean values should be put between quotation marks. Cell ranges are also supported." + " Here is a more complicated example, including Cell ranges:<br>=Sum(Average(A1:A5), 5, Power(2,4))<br><br>" + "Regular math notation, such as =(2+2)*3, is also supported. One can also make Cell references from other Cells: =A1."; final JLabel formulaLabel = new JLabel(formulaText); formulaLabel.setVerticalAlignment(SwingConstants.TOP); final String hotkeyText = "<html><body style='width:300px'>New file <p style='text-align:right'>Control + N" + "<p style='text-align:left'>Open file <p style='text-align:right'>Control + O" + "<p style='text-align:left'>Save file <p style='text-align:right'>Control + S" + "<p style='text-align:left'>Save file as <p style='text-align:right'>Control + Shift + S" + "<p style='text-align:left'>New tab <p style='text-align:right'>Control + T" + "<p style='text-align:left'>Close tab <p style='text-align:right'>Control + W" + "<p style='text-align:left'>Undo last change <p style='text-align:right'>Control + Z" + "<p style='text-align:left'>Redo last change <p style='text-align:right'>Control + Shift + Z" + "<p style='text-align:left'>Make Cell's text bold <p style='text-align:right'>Control + B" + "<p style='text-align:left'>Make Cell's text italic <p style='text-align:right'>Control + I" + "<p style='text-align:left'>Change Cell's foreground color <p style='text-align:right'>Control + F" + "<p style='text-align:left'>Change Cell's background color <p style='text-align:right'>Control + A" + "<p style='text-align:left'>Set current Cell's text bold <p style='text-align:right'>Control + B" + "<p style='text-align:left'>Set current Cell's text italic <p style='text-align:right'>Control + I" + "<p style='text-align:left'>Cel contents to textfield <p style='text-align:right'>Left mouse button" + "<p style='text-align:left'>Cel position to textfield (also works for a selection of Cells) <p style='text-align:right'>Alt + right mouse button"; final JLabel hotkeyLabel = new JLabel(hotkeyText); hotkeyLabel.setVerticalAlignment(SwingConstants.TOP); final String aboutText = "<html><body style='width:300px'>Some code in this project is taken from other people." + " These files were shared in the public domain; see the source files for more information.<br>" + "The icons used come from the gnome-colors icon theme and are licensed under the GPL-2 license.<br><br>" + "Excel++ is a TU Delft project.\nCopyright 2013 Team Awesome."; final JLabel aboutLabel = new JLabel(aboutText); aboutLabel.setVerticalAlignment(SwingConstants.TOP); helpPanel.add(helpTabbedPane); helpTabbedPane.addTab("Formula Help", formulaLabel); helpTabbedPane.setIconAt(0, new ImageIcon("data/icons/formulaHelp.png")); helpTabbedPane.addTab("Hotkeys", hotkeyLabel); helpTabbedPane.setIconAt(1, new ImageIcon("data/icons/keyboard.png")); helpTabbedPane.addTab("About", aboutLabel); helpTabbedPane.setIconAt(2, new ImageIcon("data/icons/gtk-about_16.png")); helpDialog.add(helpPanel); helpDialog.pack(); helpDialog.setIconImage(mainImage); helpDialog.setResizable(false); helpDialog.setLocation ((screenWidth / 2) - (helpPanel.getPreferredSize().width / 2), (screenHeight / 2) - (helpPanel.getPreferredSize().height / 2)); //center in het midden helpDialog.setVisible(true); } /** * Creates a new tab with everything setup inside it. * @param file The file to open inside the new <code>SpreadSheetTable</code> */ public final void createNewTab(File file) { SpreadSheet sheet = new SpreadSheet(); SpreadSheetTable table = new SpreadSheetTable(sheet, file); SpreadSheetScrollPane pane = new SpreadSheetScrollPane(table); String tabTitle = "New file"; mainTabs.addTab(null, null, pane, tabTitle); // Add tab to pane without label or icon but with tooltip int tabCount = mainTabs.getTabCount(); tabCount = tabCount == 0 ? 0 : (tabCount - 1); mainTabs.setTabComponentAt(tabCount, new CloseableTabComponent(tabTitle, tabCount)); // Now assign the component for the tab mainTabs.setSelectedIndex(tabCount); //ToDo: mainTabs.setMnemonicAt(tabCount, KeyEvent.VK_(tabCount + 1)); } /** * Removes the currently active tab. Makes sure there is always one tab remaining. */ public static final void removeTab(int index) { int tabCount = mainTabs.getTabCount(); if(tabCount > 1) { //er moet ten minste een tab open blijven if (closeFile(index) == 0) { CloseableTabComponent[] tabComponents = new CloseableTabComponent[tabCount]; for (int i = index; i < tabCount; i++) { tabComponents[i] = (CloseableTabComponent)mainTabs.getTabComponentAt(i); } mainTabs.remove(index); for(int i = tabCount - 1; i >= index; i--) { //"herstel" alle indices van de CloseableTabComponents tabComponents[i].setIndex(i - 1); } } } } /** * Updates the tab's title. * @param index The index of the tab to update * @param newTitle the new title to set */ private static final void updateTabTitle(int index, String newTitle) { CloseableTabComponent currentComponent = (CloseableTabComponent)mainTabs.getTabComponentAt(index); currentComponent.setTitle(newTitle); } /** * Gets a tab's title. * @param index The index of the tab to get the title from * @return The title */ private static final String getTabTitle(int index) { CloseableTabComponent currentComponent = (CloseableTabComponent)mainTabs.getTabComponentAt(index); return currentComponent.getTitle(); } /** * Helper method to set the text in the function field. * @param text The text to set in the function field */ public static void functionFieldSetText (String text) { functionField.setText(text); } /** * Helper method to get the text from the function field. * @return The text from the function field */ public static String functionFieldGetText() { return functionField.getText(); } /** * Changes markup in the currently selected <code>Cells</code>. * @param index The index of the tab whose <code>Cells</code> need to be updated * @param bold True if the boldness is subject to change */ public final void changeMarkup(int index, boolean bold) { Cell current = null; SpreadSheetScrollPane scrollPane = (SpreadSheetScrollPane)mainTabs.getComponentAt(index); SpreadSheetTable table = scrollPane.getTable(); int[] row = table.getSelectedRows(); int[] column = table.getSelectedColumns(); for (int i = 0; i < column.length; i++) { for (int j = 0; j < row.length; j++) { current = (Cell)table.getValueAt(row[j], column[i]); if(bold == true) { int bolde = current.getBold() == 0 ? 1 : 0; current.setBold(bolde, true); } else if(bold == false) { int italic = current.getItalic() == 0 ? 2 : 0; current.setItalic(italic, true); } } } table.grabFocus(); } /** * Changes the fore- and background <code>Colors</code> in the currently selected <code>Cells</code>. * @param index The index of the tab whose <code>Cells</code> need to be updated * @param foreground True if the foreground <code>Color</code> is subject to change */ public final void changeColors(int index, boolean foreground) { Color newColor = null; Cell current = null; SpreadSheetScrollPane scrollPane = (SpreadSheetScrollPane)mainTabs.getComponentAt(index); SpreadSheetTable table = scrollPane.getTable(); int[] row = table.getSelectedRows(); int[] column = table.getSelectedColumns(); if(foreground == false) newColor = JColorChooser.showDialog(this, "Choose a background color", buttonBackgroundColor.getBackground()); else if(foreground == true) newColor = JColorChooser.showDialog(this, "Choose a foreground color", buttonForegroundColor.getBackground()); for (int i = 0; i < column.length; i++) { for (int j = 0; j < row.length; j++) { current = (Cell)table.getValueAt(row[j], column[i]); if(newColor != null && foreground == false) current.setBackgroundColor(newColor, true); else if(newColor != null && foreground == true) current.setForegroundColor(newColor, true); } } if(newColor != null && foreground == false) buttonBackgroundColor.setBackground(newColor); else if(newColor != null && foreground == true) buttonForegroundColor.setBackground(newColor); table.grabFocus(); } /** * Listens for all events emitted by the elements of the GUI. */ public final void actionPerformed(ActionEvent e) { int index = mainTabs.getSelectedIndex(); if (e.getSource().equals(buttonOpen)) openFile(); else if (e.getSource().equals(buttonNew)) { if(closeFile(index) == 0) { SpreadSheet newSheet = new SpreadSheet(); SpreadSheetTable newTable = new SpreadSheetTable(newSheet, null); SpreadSheetScrollPane scrollPane = (SpreadSheetScrollPane)mainTabs.getComponentAt(index); scrollPane.setTable(newTable); updateTabTitle(index, "New file"); } } else if (e.getSource().equals(buttonNewTab)) createNewTab(null); else if (e.getSource().equals(buttonSave)) saveFile(false); else if (e.getSource().equals(buttonSaveAs)) saveFile(true); else if (e.getSource().equals(buttonBold)) changeMarkup(index, true); else if (e.getSource().equals(buttonItalic)) changeMarkup(index, false); else if (e.getSource().equals(buttonForegroundColor)) changeColors(index, true); else if (e.getSource().equals(buttonBackgroundColor)) changeColors(index, false); else if (e.getSource().equals(buttonAbout)) openHelpDialog(); else if (e.getSource().equals(functions)) { String formula = "=" + (String)functions.getSelectedItem(); functionField.setText(formula + "("); SpreadSheetScrollPane scrollPane = (SpreadSheetScrollPane)mainTabs.getComponentAt(index); scrollPane.getTable().grabFocus(); } else if (e.getSource().equals(buttonUndo)) { SpreadSheetScrollPane scrollPane = (SpreadSheetScrollPane)mainTabs.getComponentAt(index); UndoManager manager = scrollPane.getTable().getUndoManager(); if (manager.canUndo() == true) manager.undo(); } else if (e.getSource().equals(buttonRedo)) { SpreadSheetScrollPane scrollPane = (SpreadSheetScrollPane)mainTabs.getComponentAt(index); UndoManager manager = scrollPane.getTable().getUndoManager(); if (manager.canRedo() == true) manager.redo(); } else if(e.getSource().equals(buttonGraphs)) { SpreadSheetScrollPane scrollPane = (SpreadSheetScrollPane)mainTabs.getComponentAt(index); SpreadSheetTable table = scrollPane.getTable(); new GraphDialog(table, mainImage, screenWidth, screenHeight); } } /** * Listens for all KeyPressed events emitted by the elements of the GUI. */ @Override public final void keyPressed(KeyEvent e) { if (e.getKeyChar() == KeyEvent.VK_ENTER) { SpreadSheetScrollPane scrollPane = (SpreadSheetScrollPane)mainTabs.getSelectedComponent(); SpreadSheetTable table = scrollPane.getTable(); if (table.getCellSelected() == false) JOptionPane.showMessageDialog(this, "Please select a Cell first.", "No Cell selected", JOptionPane.INFORMATION_MESSAGE); else { Cell current = (Cell) table.getValueAt(table.getSelectedRow(), table.getSelectedColumn()); current.setContent(functionField.getText(), true); } } } /** * Is executed right before the window closes. Used to do some clean ups and check if files * need to be saved. */ @Override public final void windowClosing(WindowEvent e) { for(int i = 0; i < mainTabs.getTabCount(); i++) { if(closeFile(i) == 2) return; } System.exit(0); //ToDo: niet de beste oplossing? Bastiaan zei dat we het zo konden laten. } public void keyTyped(KeyEvent e) {} public void keyReleased(KeyEvent e) {} public void windowOpened(WindowEvent e) {} public void windowClosed(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} /** * Opens a file dialog in which the user can select the file to open. */ public final void openFile() { final JFileChooser fc = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter("XML", "xml"); fc.setFileFilter(filter); if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { int index = mainTabs.getSelectedIndex(); File file = fc.getSelectedFile(); SpreadSheetTable table; SpreadSheet sheet; try { Document doc = XML.parse(file); sheet = XML.print(doc); table = new SpreadSheetTable(sheet, file); } catch (IOException ex) { JOptionPane.showMessageDialog(this, "Something went wrong: " + ex.toString(), "Error!", JOptionPane.ERROR_MESSAGE); sheet = new SpreadSheet(); table = new SpreadSheetTable(sheet, null); ex.printStackTrace(); } catch (ParserConfigurationException | SAXException ex) { JOptionPane.showMessageDialog(this, "Something went wrong: " + ex.toString(), "Error!", JOptionPane.ERROR_MESSAGE); sheet = new SpreadSheet(); table = new SpreadSheetTable(sheet, file); ex.printStackTrace(); } SpreadSheetScrollPane scrollPane = (SpreadSheetScrollPane)mainTabs.getComponentAt(index); scrollPane.setTable(table); updateTabTitle(index, file.getName()); } } /** * Saves the currently opened file. * @param saveAs True if the Save As button has been pressed, will spawn a Save As dialog */ public static final void saveFile (boolean saveAs) { SpreadSheetScrollPane scrollPane = (SpreadSheetScrollPane)mainTabs.getSelectedComponent(); SpreadSheetTable table = scrollPane.getTable(); File file = table.getFile(); if (file == null || saveAs == true) { final JFileChooser fc = new JFileChooser(); int choice = fc.showSaveDialog(mainFrame); if (choice == JFileChooser.APPROVE_OPTION) { String fileString = fc.getSelectedFile().getPath(); if (!fileString.endsWith(".xml")) fileString += ".xml"; file = new File(fileString); table.setFile(file); updateTabTitle(mainTabs.getSelectedIndex(), file.getName()); } else if(choice == JFileChooser.CANCEL_OPTION) return; } try { ((SpreadSheet)table.getModel()).write(new XMLWriter(file)); } catch (FileNotFoundException ex) { JOptionPane.showMessageDialog(mainFrame, "Something went wrong: " + ex.toString(), "Error!", JOptionPane.ERROR_MESSAGE); ex.printStackTrace(); } } /** * Handles closing of a file. Pops up a dialog for confirmation if changes will be lost. * @param index The index of the tab whose <code>File</code> will be closed * @return 0 for OK, 1 for save, 2 for cancel */ public static final int closeFile(int index) { int close = 0; Object[] options = { "Continue", "Save file", "Cancel" }; SpreadSheetScrollPane scrollPane = (SpreadSheetScrollPane)mainTabs.getComponentAt(index); SpreadSheetTable table = scrollPane.getTable(); if(getTabTitle(index).equals("New file")) { if(table.getSheet().isEmpty() == false) close = JOptionPane.showOptionDialog(mainFrame, "Changes made to the current spreadsheet will be lost. Continue?", "Continue?", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[2]); } else { try { Document doc = XML.parse(table.getFile()); SpreadSheet fileSheet = XML.print(doc); Cell fileCell = null; breakpoint: for(int i = 0; i < fileSheet.getColumnCount(); i++) { //fileSheet of table.getSheet maakt niet uit; zelfde aantal cellen for(int j = 0; j < fileSheet.getRowCount(); j++) { //fileSheet of table.getSheet maakt niet uit; zelfde aantal cellen fileCell = (Cell)fileSheet.getValueAt(j, i); if(!fileCell.equals(table.getSheet().getValueAt(j, i))) { close = JOptionPane.showOptionDialog(mainFrame, "Changes made to the current spreadsheet will be lost. Continue?", "Continue?", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[2]); break breakpoint; } } } } catch (Exception ex) { JOptionPane.showMessageDialog(mainFrame, "Something went wrong: " + ex.toString(), "Error!", JOptionPane.ERROR_MESSAGE); ex.printStackTrace(); } } if(close == 1) { saveFile(true); close = 0; } return close; } }
24970_16
/* * Copyright (C) 2015 B3Partners B.V. */ package nl.b3p.gds2; import com.sun.xml.ws.developer.JAXWSProperties; import java.nio.file.Files; import java.nio.file.Paths; import java.security.KeyStore; import java.security.PrivateKey; import java.security.cert.Certificate; import java.util.ArrayList; import java.util.GregorianCalendar; import java.util.List; import java.util.Map; import java.util.Calendar; import java.util.Date; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManagerFactory; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.ws.BindingProvider; import nl.kadaster.schemas.gds2.afgifte_bestandenlijstgbopvragen.v20130701.BestandenlijstGbOpvragenType; import nl.kadaster.schemas.gds2.afgifte_bestandenlijstgbresultaat.afgifte.v20130701.AfgifteGBType; import nl.kadaster.schemas.gds2.afgifte_bestandenlijstopvragen.v20130701.BestandenlijstOpvragenType; import nl.kadaster.schemas.gds2.afgifte_bestandenlijstresultaat.afgifte.v20130701.AfgifteType; import nl.kadaster.schemas.gds2.afgifte_bestandenlijstselectie.v20130701.AfgifteSelectieCriteriaType; import nl.kadaster.schemas.gds2.afgifte_bestandenlijstselectie.v20130701.BestandKenmerkenType; import nl.kadaster.schemas.gds2.afgifte_proces.v20130701.FilterDatumTijdType; import nl.kadaster.schemas.gds2.service.afgifte.v20130701.Gds2AfgifteServiceV20130701; import nl.kadaster.schemas.gds2.service.afgifte.v20130701.Gds2AfgifteServiceV20130701Service; import nl.kadaster.schemas.gds2.service.afgifte_bestandenlijstgbopvragen.v20130701.BestandenlijstGBOpvragenRequest; import nl.kadaster.schemas.gds2.service.afgifte_bestandenlijstgbopvragen.v20130701.BestandenlijstGBOpvragenResponse; import nl.kadaster.schemas.gds2.service.afgifte_bestandenlijstopvragen.v20130701.BestandenlijstOpvragenRequest; import nl.kadaster.schemas.gds2.service.afgifte_bestandenlijstopvragen.v20130701.BestandenlijstOpvragenResponse; import nl.logius.digikoppeling.gb._2010._10.DataReference; /** * * @author Matthijs Laan * @author mprins */ public class Main { private static final int BESTANDENLIJST_ATTEMPTS = 5; private static final int BESTANDENLIJST_RETRY_WAIT = 10000; public static void main(String[] args) throws Exception { // java.lang.System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true"); // java.lang.System.setProperty("sun.security.ssl.allowLegacyHelloMessages", "true"); // java.lang.System.setProperty("javax.net.debug", "ssl,plaintext"); Gds2AfgifteServiceV20130701 gds2 = new Gds2AfgifteServiceV20130701Service().getAGds2AfgifteServiceV20130701(); BindingProvider bp = (BindingProvider) gds2; Map<String, Object> ctxt = bp.getRequestContext(); String endpoint = (String) ctxt.get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY); System.out.println("Origineel endpoint: " + endpoint); //ctxt.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "http://localhost:8088/AfgifteService"); //System.out.println("Endpoint protocol gewijzigd naar mock"); final char[] thePassword = "changeit".toCharArray(); System.out.println("Loading keystore"); KeyStore ks = KeyStore.getInstance("jks"); ks.load(Main.class.getResourceAsStream("/pkioverheid.jks"), thePassword); System.out.println("Initializing TrustManagerFactory"); TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX"); tmf.init(ks); System.out.println("Initializing KeyManagerFactory"); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); ks = KeyStore.getInstance("jks"); if (args.length > 0) { String keystore = "/gds2_key.jks"; ks.load(Main.class.getResourceAsStream(keystore), thePassword); kmf.init(ks, thePassword); } else { ks.load(null); PrivateKey privateKey = GDS2Util.getPrivateKeyFromPEM(new String(Files.readAllBytes(Paths.get("private.key"))).trim()); Certificate certificate = GDS2Util.getCertificateFromPEM(new String(Files.readAllBytes(Paths.get("public.key"))).trim()); ks.setKeyEntry("thekey", privateKey, thePassword, new Certificate[]{certificate}); kmf.init(ks, thePassword); } System.out.println("Initializing SSLContext"); SSLContext context = SSLContext.getInstance("TLS", "SunJSSE"); context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); SSLContext.setDefault(context); ctxt.put(JAXWSProperties.SSL_SOCKET_FACTORY, context.getSocketFactory()); BestandenlijstOpvragenRequest request = new BestandenlijstOpvragenRequest(); BestandenlijstOpvragenType verzoek = new BestandenlijstOpvragenType(); request.setVerzoek(verzoek); AfgifteSelectieCriteriaType criteria = new AfgifteSelectieCriteriaType(); verzoek.setAfgifteSelectieCriteria(criteria); criteria.setBestandKenmerken(new BestandKenmerkenType()); // alGerapporteerd boolean alGerapporteerd = false; criteria.setNogNietGerapporteerd(alGerapporteerd); // maandelijkse mutaties NL // criteria.getBestandKenmerken().setArtikelnummer("2508"); // dagelijkse mutaties NL // criteria.getBestandKenmerken().setArtikelnummer("2516"); // criteria.getBestandKenmerken().setArtikelnummer("2522"); // soms met voorloopnullen // criteria.getBestandKenmerken().setArtikelnummer("0002522"); // contractnummer // criteria.getBestandKenmerken().setContractnummer("0005014500"); criteria.getBestandKenmerken().setContractnummer("9700004549"); // vanaf 1 jan 2018 GregorianCalendar vanaf = new GregorianCalendar(2018, (1 - 1) /* GregorianCalendar heeft 0-based month */, 1); GregorianCalendar tot = new GregorianCalendar(); // tot vandaag tot.setTime(new Date()); // tot 1 feb 2018 tot = new GregorianCalendar(2018, 2 - 1, 1); System.out.println("Contract nummer: " + criteria.getBestandKenmerken().getContractnummer()); System.out.println("Artikel nummer: " + criteria.getBestandKenmerken().getArtikelnummer()); System.out.println("DatumTijdVanaf criterium: " + vanaf.getTime()); System.out.println("DatumTijdTot criterium: " + tot.getTime()); System.out.println("alGerapporteerd criterium: " + alGerapporteerd); criteria.setPeriode(new FilterDatumTijdType()); XMLGregorianCalendar date = DatatypeFactory.newInstance().newXMLGregorianCalendar(vanaf); criteria.getPeriode().setDatumTijdVanaf(date); BestandenlijstGBOpvragenRequest requestGb = new BestandenlijstGBOpvragenRequest(); BestandenlijstGbOpvragenType verzoekGb = new BestandenlijstGbOpvragenType(); requestGb.setVerzoek(verzoekGb); verzoekGb.setAfgifteSelectieCriteria(criteria); GregorianCalendar currentMoment = null; boolean parseblePeriod = false; int loopType = Calendar.DAY_OF_MONTH; int loopMax = 180; int loopNum = 0; boolean reducePeriod = false; boolean increasePeriod = false; if (vanaf != null && tot != null && vanaf.before(tot)) { parseblePeriod = true; currentMoment = vanaf; } List<AfgifteGBType> afgiftesGb = new ArrayList<>(); try { boolean morePeriods2Process = false; do /* while morePeriods2Process is true */ { System.out.println("\n*** start periode ***"); //zet periode in criteria indien gewenst if (parseblePeriod) { //check of de periodeduur verkleind moet worden if (reducePeriod) { switch (loopType) { case Calendar.DAY_OF_MONTH: currentMoment.add(loopType, -1); loopType = Calendar.HOUR_OF_DAY; System.out.println("* Verklein loop periode naar uur"); break; case Calendar.HOUR_OF_DAY: currentMoment.add(loopType, -1); loopType = Calendar.MINUTE; System.out.println("* Verklein loop periode naar minuut"); break; case Calendar.MINUTE: default: /* * Hier kom je alleen als binnen een minuut meer * dan 2000 berichten zijn aangamaakt en het * vinkje "al rapporteerde berichten * ophalen" ook staat aan. */ System.out.println("Niet alle gevraagde berichten zijn opgehaald"); } reducePeriod = false; } //check of de periodeduur vergroot moet worden if (increasePeriod) { switch (loopType) { case Calendar.HOUR_OF_DAY: loopType = Calendar.DAY_OF_MONTH; System.out.println("* Vergroot loop periode naar dag"); break; case Calendar.MINUTE: loopType = Calendar.HOUR_OF_DAY; System.out.println("* Vergroot loop periode naar uur"); break; case Calendar.DAY_OF_MONTH: default: //not possible } increasePeriod = false; } FilterDatumTijdType d = new FilterDatumTijdType(); d.setDatumTijdVanaf(DatatypeFactory.newInstance().newXMLGregorianCalendar(currentMoment)); System.out.println(String.format("Datum vanaf: %tc", currentMoment.getTime())); currentMoment.add(loopType, 1); d.setDatumTijdTot(DatatypeFactory.newInstance().newXMLGregorianCalendar(currentMoment)); System.out.println(String.format("Datum tot: %tc", currentMoment.getTime())); criteria.setPeriode(d); switch (loopType) { case Calendar.HOUR_OF_DAY: //0-23 if (currentMoment.get(loopType) == 0) { increasePeriod = true; } break; case Calendar.MINUTE: //0-59 if (currentMoment.get(loopType) == 0) { increasePeriod = true; } break; case Calendar.DAY_OF_MONTH: default: //alleen dagen tellen, uur en minuut altijd helemaal loopNum++; } //bereken of einde van periode bereikt is if (currentMoment.before(tot) && loopNum < loopMax) { morePeriods2Process = true; } else { morePeriods2Process = false; } } verzoekGb.setAfgifteSelectieCriteria(criteria); BestandenlijstGBOpvragenResponse responseGb = retryBestandenLijstGBOpvragen(gds2, requestGb); int aantalInAntwoord = responseGb.getAntwoord().getBestandenLijstGB().getAfgifteGB().size(); System.out.println("Aantal in antwoord: " + aantalInAntwoord); // opletten; in de xsd staat een default value van 'J' voor meerAfgiftesbeschikbaar boolean hasMore = responseGb.getAntwoord().getMeerAfgiftesbeschikbaar().equalsIgnoreCase("true"); System.out.println("Meer afgiftes beschikbaar: " + hasMore); /* * Als "al gerapporteerde berichten" moeten worden opgehaald en * er zitten dan 2000 berichten in het antwoord dan heeft het * geen zin om meer keer de berichten op te halen, je krijgt * telkens dezelfde. */ if (hasMore && alGerapporteerd) { reducePeriod = true; morePeriods2Process = true; increasePeriod = false; // als er geen parsable periode is // (geen periode ingevuld en alGerapporteerd is true // dan moet morePeriods2Process false worden om een // eindloze while loop te voorkomen if (!parseblePeriod) { morePeriods2Process = false; } else { continue; } } afgiftesGb.addAll(responseGb.getAntwoord().getBestandenLijstGB().getAfgifteGB()); /* * Indicatie nog niet gerapporteerd: Met deze indicatie wordt * aangegeven of uitsluitend de nog niet gerapporteerde * bestanden moeten worden opgenomen in de lijst, of dat alle * beschikbare bestanden worden genoemd. Niet gerapporteerd * betekent in dit geval ‘niet eerder opgevraagd in deze * bestandenlijst’. Als deze indicator wordt gebruikt, dan * worden na terugmelding van de bestandenlijst de bijbehorende * bestanden gemarkeerd als zijnde ‘gerapporteerd’ in het * systeem van GDS. */ boolean dontGetMoreConfig = false; while (hasMore && !dontGetMoreConfig) { criteria.setNogNietGerapporteerd(true); responseGb = retryBestandenLijstGBOpvragen(gds2, requestGb); List<AfgifteGBType> afgiftes = responseGb.getAntwoord().getBestandenLijstGB().getAfgifteGB(); afgiftesGb.addAll(afgiftes); aantalInAntwoord = afgiftes.size(); System.out.println("Aantal in antwoord: " + aantalInAntwoord); hasMore = responseGb.getAntwoord().getMeerAfgiftesbeschikbaar().equalsIgnoreCase("true"); System.out.println("Nog meer afgiftes beschikbaar: " + hasMore); } } while (morePeriods2Process); System.out.println("Totaal aantal op te halen berichten: " + afgiftesGb.size()); } catch (Exception e) { e.printStackTrace(); } verwerkAfgiftesGb(afgiftesGb); System.out.println("\n\n**** resultaat ****\n"); System.out.println("Aantal afgiftes grote bestanden: " + (afgiftesGb == null ? "<fout>" : afgiftesGb.size())); List<AfgifteType> afgiftes = null; try { BestandenlijstOpvragenResponse response = gds2.bestandenlijstOpvragen(request); afgiftes = response.getAntwoord().getBestandenLijst().getAfgifte(); } catch (Exception e) { e.printStackTrace(); } System.out.println("Aantal afgiftes: " + (afgiftes == null ? "<fout>" : afgiftes.size())); } private static void verwerkAfgiftesGb(List<AfgifteGBType> afgiftesGb) { System.out.println("Afgiftegegevens, bestandskenmerken en Digikoppeling datareference gegevens van de bestandenlijst."); // tab gescheiden output, of kvp System.out.println("ID\treferentie\tbestandsnaam\tbestandref\tbeschikbaarTot\tcontractnr\tartikelnr\tartikelomschrijving\tcontextId\tcreationTime\texpirationTime\tfilename\tchecksum\ttype\tsize\tsenderUrl\treceiverUrl"); for (AfgifteGBType a : afgiftesGb) { // String kenmerken = "(geen)"; String kenmerken = "-\t-\t-"; if (a.getBestandKenmerken() != null) { // kenmerken = String.format("contractnr: %s, artikelnr: %s, artikelomschrijving: %s", kenmerken = String.format("%s\t%s\t%s", a.getBestandKenmerken().getContractnummer(), a.getBestandKenmerken().getArtikelnummer(), a.getBestandKenmerken().getArtikelomschrijving()); } // System.out.printf("ID: %s, referentie: %s, bestandsnaam: %s, bestandref: %s, beschikbaarTot: %s, kenmerken: %s", System.out.printf("%s\t%s\t%s\t%s\t%s\t%s", a.getAfgifteID(), a.getAfgiftereferentie(), a.getBestand().getBestandsnaam(), a.getBestand().getBestandsreferentie(), a.getBeschikbaarTot(), kenmerken); if (a.getDigikoppelingExternalDatareferences() != null && a.getDigikoppelingExternalDatareferences().getDataReference() != null) { for (DataReference dr : a.getDigikoppelingExternalDatareferences().getDataReference()) { // System.out.printf(" Digikoppeling datareference: contextId: %s, creationTime: %s, expirationTime: %s, filename: %s, checksum: %s, size: %d, type: %s, senderUrl: %s, receiverUrl: %s\n", System.out.printf("\t%s\t%s\t%s\t%s\t%s\t%d\t%s\t%s\t%s\n", dr.getContextId(), dr.getLifetime().getCreationTime().getValue(), dr.getLifetime().getExpirationTime().getValue(), dr.getContent().getFilename(), dr.getContent().getChecksum().getValue(), dr.getContent().getSize(), dr.getContent().getContentType(), dr.getTransport().getLocation().getSenderUrl() == null ? "-" : dr.getTransport().getLocation().getSenderUrl().getValue(), dr.getTransport().getLocation().getReceiverUrl() == null ? "-" : dr.getTransport().getLocation().getReceiverUrl().getValue()); } } } } private static BestandenlijstGBOpvragenResponse retryBestandenLijstGBOpvragen(Gds2AfgifteServiceV20130701 gds2, BestandenlijstGBOpvragenRequest requestGb) throws Exception { int attempt = 0; while (true) { try { return gds2.bestandenlijstGBOpvragen(requestGb); } catch (Exception e) { attempt++; if (attempt == BESTANDENLIJST_ATTEMPTS) { System.out.println("Fout bij laatste poging ophalen bestandenlijst: " + e.getClass().getName() + ": " + e.getMessage()); throw e; } else { System.out.println("Fout bij poging " + attempt + " om bestandenlijst op te halen: " + e.getClass().getName() + ": " + e.getMessage()); Thread.sleep(BESTANDENLIJST_RETRY_WAIT); System.out.println("Uitvoeren poging " + (attempt + 1) + " om bestandenlijst op te halen..."); } } } } }
puckipedia/kadaster-gds2
src/main/java/nl/b3p/gds2/Main.java
5,024
//bereken of einde van periode bereikt is
line_comment
nl
/* * Copyright (C) 2015 B3Partners B.V. */ package nl.b3p.gds2; import com.sun.xml.ws.developer.JAXWSProperties; import java.nio.file.Files; import java.nio.file.Paths; import java.security.KeyStore; import java.security.PrivateKey; import java.security.cert.Certificate; import java.util.ArrayList; import java.util.GregorianCalendar; import java.util.List; import java.util.Map; import java.util.Calendar; import java.util.Date; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManagerFactory; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.ws.BindingProvider; import nl.kadaster.schemas.gds2.afgifte_bestandenlijstgbopvragen.v20130701.BestandenlijstGbOpvragenType; import nl.kadaster.schemas.gds2.afgifte_bestandenlijstgbresultaat.afgifte.v20130701.AfgifteGBType; import nl.kadaster.schemas.gds2.afgifte_bestandenlijstopvragen.v20130701.BestandenlijstOpvragenType; import nl.kadaster.schemas.gds2.afgifte_bestandenlijstresultaat.afgifte.v20130701.AfgifteType; import nl.kadaster.schemas.gds2.afgifte_bestandenlijstselectie.v20130701.AfgifteSelectieCriteriaType; import nl.kadaster.schemas.gds2.afgifte_bestandenlijstselectie.v20130701.BestandKenmerkenType; import nl.kadaster.schemas.gds2.afgifte_proces.v20130701.FilterDatumTijdType; import nl.kadaster.schemas.gds2.service.afgifte.v20130701.Gds2AfgifteServiceV20130701; import nl.kadaster.schemas.gds2.service.afgifte.v20130701.Gds2AfgifteServiceV20130701Service; import nl.kadaster.schemas.gds2.service.afgifte_bestandenlijstgbopvragen.v20130701.BestandenlijstGBOpvragenRequest; import nl.kadaster.schemas.gds2.service.afgifte_bestandenlijstgbopvragen.v20130701.BestandenlijstGBOpvragenResponse; import nl.kadaster.schemas.gds2.service.afgifte_bestandenlijstopvragen.v20130701.BestandenlijstOpvragenRequest; import nl.kadaster.schemas.gds2.service.afgifte_bestandenlijstopvragen.v20130701.BestandenlijstOpvragenResponse; import nl.logius.digikoppeling.gb._2010._10.DataReference; /** * * @author Matthijs Laan * @author mprins */ public class Main { private static final int BESTANDENLIJST_ATTEMPTS = 5; private static final int BESTANDENLIJST_RETRY_WAIT = 10000; public static void main(String[] args) throws Exception { // java.lang.System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true"); // java.lang.System.setProperty("sun.security.ssl.allowLegacyHelloMessages", "true"); // java.lang.System.setProperty("javax.net.debug", "ssl,plaintext"); Gds2AfgifteServiceV20130701 gds2 = new Gds2AfgifteServiceV20130701Service().getAGds2AfgifteServiceV20130701(); BindingProvider bp = (BindingProvider) gds2; Map<String, Object> ctxt = bp.getRequestContext(); String endpoint = (String) ctxt.get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY); System.out.println("Origineel endpoint: " + endpoint); //ctxt.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "http://localhost:8088/AfgifteService"); //System.out.println("Endpoint protocol gewijzigd naar mock"); final char[] thePassword = "changeit".toCharArray(); System.out.println("Loading keystore"); KeyStore ks = KeyStore.getInstance("jks"); ks.load(Main.class.getResourceAsStream("/pkioverheid.jks"), thePassword); System.out.println("Initializing TrustManagerFactory"); TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX"); tmf.init(ks); System.out.println("Initializing KeyManagerFactory"); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); ks = KeyStore.getInstance("jks"); if (args.length > 0) { String keystore = "/gds2_key.jks"; ks.load(Main.class.getResourceAsStream(keystore), thePassword); kmf.init(ks, thePassword); } else { ks.load(null); PrivateKey privateKey = GDS2Util.getPrivateKeyFromPEM(new String(Files.readAllBytes(Paths.get("private.key"))).trim()); Certificate certificate = GDS2Util.getCertificateFromPEM(new String(Files.readAllBytes(Paths.get("public.key"))).trim()); ks.setKeyEntry("thekey", privateKey, thePassword, new Certificate[]{certificate}); kmf.init(ks, thePassword); } System.out.println("Initializing SSLContext"); SSLContext context = SSLContext.getInstance("TLS", "SunJSSE"); context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); SSLContext.setDefault(context); ctxt.put(JAXWSProperties.SSL_SOCKET_FACTORY, context.getSocketFactory()); BestandenlijstOpvragenRequest request = new BestandenlijstOpvragenRequest(); BestandenlijstOpvragenType verzoek = new BestandenlijstOpvragenType(); request.setVerzoek(verzoek); AfgifteSelectieCriteriaType criteria = new AfgifteSelectieCriteriaType(); verzoek.setAfgifteSelectieCriteria(criteria); criteria.setBestandKenmerken(new BestandKenmerkenType()); // alGerapporteerd boolean alGerapporteerd = false; criteria.setNogNietGerapporteerd(alGerapporteerd); // maandelijkse mutaties NL // criteria.getBestandKenmerken().setArtikelnummer("2508"); // dagelijkse mutaties NL // criteria.getBestandKenmerken().setArtikelnummer("2516"); // criteria.getBestandKenmerken().setArtikelnummer("2522"); // soms met voorloopnullen // criteria.getBestandKenmerken().setArtikelnummer("0002522"); // contractnummer // criteria.getBestandKenmerken().setContractnummer("0005014500"); criteria.getBestandKenmerken().setContractnummer("9700004549"); // vanaf 1 jan 2018 GregorianCalendar vanaf = new GregorianCalendar(2018, (1 - 1) /* GregorianCalendar heeft 0-based month */, 1); GregorianCalendar tot = new GregorianCalendar(); // tot vandaag tot.setTime(new Date()); // tot 1 feb 2018 tot = new GregorianCalendar(2018, 2 - 1, 1); System.out.println("Contract nummer: " + criteria.getBestandKenmerken().getContractnummer()); System.out.println("Artikel nummer: " + criteria.getBestandKenmerken().getArtikelnummer()); System.out.println("DatumTijdVanaf criterium: " + vanaf.getTime()); System.out.println("DatumTijdTot criterium: " + tot.getTime()); System.out.println("alGerapporteerd criterium: " + alGerapporteerd); criteria.setPeriode(new FilterDatumTijdType()); XMLGregorianCalendar date = DatatypeFactory.newInstance().newXMLGregorianCalendar(vanaf); criteria.getPeriode().setDatumTijdVanaf(date); BestandenlijstGBOpvragenRequest requestGb = new BestandenlijstGBOpvragenRequest(); BestandenlijstGbOpvragenType verzoekGb = new BestandenlijstGbOpvragenType(); requestGb.setVerzoek(verzoekGb); verzoekGb.setAfgifteSelectieCriteria(criteria); GregorianCalendar currentMoment = null; boolean parseblePeriod = false; int loopType = Calendar.DAY_OF_MONTH; int loopMax = 180; int loopNum = 0; boolean reducePeriod = false; boolean increasePeriod = false; if (vanaf != null && tot != null && vanaf.before(tot)) { parseblePeriod = true; currentMoment = vanaf; } List<AfgifteGBType> afgiftesGb = new ArrayList<>(); try { boolean morePeriods2Process = false; do /* while morePeriods2Process is true */ { System.out.println("\n*** start periode ***"); //zet periode in criteria indien gewenst if (parseblePeriod) { //check of de periodeduur verkleind moet worden if (reducePeriod) { switch (loopType) { case Calendar.DAY_OF_MONTH: currentMoment.add(loopType, -1); loopType = Calendar.HOUR_OF_DAY; System.out.println("* Verklein loop periode naar uur"); break; case Calendar.HOUR_OF_DAY: currentMoment.add(loopType, -1); loopType = Calendar.MINUTE; System.out.println("* Verklein loop periode naar minuut"); break; case Calendar.MINUTE: default: /* * Hier kom je alleen als binnen een minuut meer * dan 2000 berichten zijn aangamaakt en het * vinkje "al rapporteerde berichten * ophalen" ook staat aan. */ System.out.println("Niet alle gevraagde berichten zijn opgehaald"); } reducePeriod = false; } //check of de periodeduur vergroot moet worden if (increasePeriod) { switch (loopType) { case Calendar.HOUR_OF_DAY: loopType = Calendar.DAY_OF_MONTH; System.out.println("* Vergroot loop periode naar dag"); break; case Calendar.MINUTE: loopType = Calendar.HOUR_OF_DAY; System.out.println("* Vergroot loop periode naar uur"); break; case Calendar.DAY_OF_MONTH: default: //not possible } increasePeriod = false; } FilterDatumTijdType d = new FilterDatumTijdType(); d.setDatumTijdVanaf(DatatypeFactory.newInstance().newXMLGregorianCalendar(currentMoment)); System.out.println(String.format("Datum vanaf: %tc", currentMoment.getTime())); currentMoment.add(loopType, 1); d.setDatumTijdTot(DatatypeFactory.newInstance().newXMLGregorianCalendar(currentMoment)); System.out.println(String.format("Datum tot: %tc", currentMoment.getTime())); criteria.setPeriode(d); switch (loopType) { case Calendar.HOUR_OF_DAY: //0-23 if (currentMoment.get(loopType) == 0) { increasePeriod = true; } break; case Calendar.MINUTE: //0-59 if (currentMoment.get(loopType) == 0) { increasePeriod = true; } break; case Calendar.DAY_OF_MONTH: default: //alleen dagen tellen, uur en minuut altijd helemaal loopNum++; } //bereken of<SUF> if (currentMoment.before(tot) && loopNum < loopMax) { morePeriods2Process = true; } else { morePeriods2Process = false; } } verzoekGb.setAfgifteSelectieCriteria(criteria); BestandenlijstGBOpvragenResponse responseGb = retryBestandenLijstGBOpvragen(gds2, requestGb); int aantalInAntwoord = responseGb.getAntwoord().getBestandenLijstGB().getAfgifteGB().size(); System.out.println("Aantal in antwoord: " + aantalInAntwoord); // opletten; in de xsd staat een default value van 'J' voor meerAfgiftesbeschikbaar boolean hasMore = responseGb.getAntwoord().getMeerAfgiftesbeschikbaar().equalsIgnoreCase("true"); System.out.println("Meer afgiftes beschikbaar: " + hasMore); /* * Als "al gerapporteerde berichten" moeten worden opgehaald en * er zitten dan 2000 berichten in het antwoord dan heeft het * geen zin om meer keer de berichten op te halen, je krijgt * telkens dezelfde. */ if (hasMore && alGerapporteerd) { reducePeriod = true; morePeriods2Process = true; increasePeriod = false; // als er geen parsable periode is // (geen periode ingevuld en alGerapporteerd is true // dan moet morePeriods2Process false worden om een // eindloze while loop te voorkomen if (!parseblePeriod) { morePeriods2Process = false; } else { continue; } } afgiftesGb.addAll(responseGb.getAntwoord().getBestandenLijstGB().getAfgifteGB()); /* * Indicatie nog niet gerapporteerd: Met deze indicatie wordt * aangegeven of uitsluitend de nog niet gerapporteerde * bestanden moeten worden opgenomen in de lijst, of dat alle * beschikbare bestanden worden genoemd. Niet gerapporteerd * betekent in dit geval ‘niet eerder opgevraagd in deze * bestandenlijst’. Als deze indicator wordt gebruikt, dan * worden na terugmelding van de bestandenlijst de bijbehorende * bestanden gemarkeerd als zijnde ‘gerapporteerd’ in het * systeem van GDS. */ boolean dontGetMoreConfig = false; while (hasMore && !dontGetMoreConfig) { criteria.setNogNietGerapporteerd(true); responseGb = retryBestandenLijstGBOpvragen(gds2, requestGb); List<AfgifteGBType> afgiftes = responseGb.getAntwoord().getBestandenLijstGB().getAfgifteGB(); afgiftesGb.addAll(afgiftes); aantalInAntwoord = afgiftes.size(); System.out.println("Aantal in antwoord: " + aantalInAntwoord); hasMore = responseGb.getAntwoord().getMeerAfgiftesbeschikbaar().equalsIgnoreCase("true"); System.out.println("Nog meer afgiftes beschikbaar: " + hasMore); } } while (morePeriods2Process); System.out.println("Totaal aantal op te halen berichten: " + afgiftesGb.size()); } catch (Exception e) { e.printStackTrace(); } verwerkAfgiftesGb(afgiftesGb); System.out.println("\n\n**** resultaat ****\n"); System.out.println("Aantal afgiftes grote bestanden: " + (afgiftesGb == null ? "<fout>" : afgiftesGb.size())); List<AfgifteType> afgiftes = null; try { BestandenlijstOpvragenResponse response = gds2.bestandenlijstOpvragen(request); afgiftes = response.getAntwoord().getBestandenLijst().getAfgifte(); } catch (Exception e) { e.printStackTrace(); } System.out.println("Aantal afgiftes: " + (afgiftes == null ? "<fout>" : afgiftes.size())); } private static void verwerkAfgiftesGb(List<AfgifteGBType> afgiftesGb) { System.out.println("Afgiftegegevens, bestandskenmerken en Digikoppeling datareference gegevens van de bestandenlijst."); // tab gescheiden output, of kvp System.out.println("ID\treferentie\tbestandsnaam\tbestandref\tbeschikbaarTot\tcontractnr\tartikelnr\tartikelomschrijving\tcontextId\tcreationTime\texpirationTime\tfilename\tchecksum\ttype\tsize\tsenderUrl\treceiverUrl"); for (AfgifteGBType a : afgiftesGb) { // String kenmerken = "(geen)"; String kenmerken = "-\t-\t-"; if (a.getBestandKenmerken() != null) { // kenmerken = String.format("contractnr: %s, artikelnr: %s, artikelomschrijving: %s", kenmerken = String.format("%s\t%s\t%s", a.getBestandKenmerken().getContractnummer(), a.getBestandKenmerken().getArtikelnummer(), a.getBestandKenmerken().getArtikelomschrijving()); } // System.out.printf("ID: %s, referentie: %s, bestandsnaam: %s, bestandref: %s, beschikbaarTot: %s, kenmerken: %s", System.out.printf("%s\t%s\t%s\t%s\t%s\t%s", a.getAfgifteID(), a.getAfgiftereferentie(), a.getBestand().getBestandsnaam(), a.getBestand().getBestandsreferentie(), a.getBeschikbaarTot(), kenmerken); if (a.getDigikoppelingExternalDatareferences() != null && a.getDigikoppelingExternalDatareferences().getDataReference() != null) { for (DataReference dr : a.getDigikoppelingExternalDatareferences().getDataReference()) { // System.out.printf(" Digikoppeling datareference: contextId: %s, creationTime: %s, expirationTime: %s, filename: %s, checksum: %s, size: %d, type: %s, senderUrl: %s, receiverUrl: %s\n", System.out.printf("\t%s\t%s\t%s\t%s\t%s\t%d\t%s\t%s\t%s\n", dr.getContextId(), dr.getLifetime().getCreationTime().getValue(), dr.getLifetime().getExpirationTime().getValue(), dr.getContent().getFilename(), dr.getContent().getChecksum().getValue(), dr.getContent().getSize(), dr.getContent().getContentType(), dr.getTransport().getLocation().getSenderUrl() == null ? "-" : dr.getTransport().getLocation().getSenderUrl().getValue(), dr.getTransport().getLocation().getReceiverUrl() == null ? "-" : dr.getTransport().getLocation().getReceiverUrl().getValue()); } } } } private static BestandenlijstGBOpvragenResponse retryBestandenLijstGBOpvragen(Gds2AfgifteServiceV20130701 gds2, BestandenlijstGBOpvragenRequest requestGb) throws Exception { int attempt = 0; while (true) { try { return gds2.bestandenlijstGBOpvragen(requestGb); } catch (Exception e) { attempt++; if (attempt == BESTANDENLIJST_ATTEMPTS) { System.out.println("Fout bij laatste poging ophalen bestandenlijst: " + e.getClass().getName() + ": " + e.getMessage()); throw e; } else { System.out.println("Fout bij poging " + attempt + " om bestandenlijst op te halen: " + e.getClass().getName() + ": " + e.getMessage()); Thread.sleep(BESTANDENLIJST_RETRY_WAIT); System.out.println("Uitvoeren poging " + (attempt + 1) + " om bestandenlijst op te halen..."); } } } } }
74863_8
package be.ccfun.day22; import java.util.List; public class BoardMapCube { private List<String> map; private int size; private Position position; private Facing facing; private List<Position> luc; // left upper corners private List<Position> ruc; // right upper corners record Wrap(Position position, Facing facing) { } public BoardMapCube(List<String> map) { this.map = map; facing = Facing.RIGHT; position = new Position(map.get(0).indexOf('.'), 0); size = map.get(0).length() / 3; System.out.println(size); } public boolean isWall(Position position) { if (position.getY() == 201) { System.out.println("debug"); } return map.get(position.getY()).charAt(position.getX()) == '#'; } public boolean isEnd(Position position) { try { return map.get(position.getY()).charAt(position.getX()) == ' '; } catch (IndexOutOfBoundsException e) { return true; } } public char getChar(Position position) { return map.get(position.getY()).charAt(position.getX()); } public long getFinalPassword() { System.out.println(facing.ordinal() + " " + position); return facing.ordinal() + 1000L * (position.getY() + 1) + 4L * (position.getX() + 1); } public Wrap getTop(Position position) { // voor side 2, side 4 en side 6 int side = position.getX() / size; int x = position.getX() % size; int y = position.getY() % size; if (side == 2) { // ZIJDE 2 // ga rechterkant van side 3 naar links System.out.println("VAN ONDERKANT ZIJDE 2 NAAR RECHTKANT ZIJDE 3"); System.out.println(position); Position newPosition = new Position(99, 50 + x); System.out.println(newPosition); return new Wrap(newPosition, Facing.LEFT); } else if (side == 1) { // ZIJDE 4 // ga rechterkant side 6 naar links System.out.println("VAN ONDERKANT ZIJDE 4 NAAR RECHTKANT ZIJDE 6"); System.out.println(position); Position newPosition = new Position(49, 150 + x); System.out.println(newPosition); return new Wrap(newPosition, Facing.LEFT); } else if (side == 0) { // ZIJDE 6 // ga naar bovenkant side 2 naar onder System.out.println("VAN ONDERKANT ZIJDE 6 NAAR BOVENKANT ZIJDE 2"); System.out.println(position); Position newPosition = new Position(100 + x, 0); System.out.println(newPosition); return new Wrap(newPosition, Facing.DOWN); } else { System.out.println("Unseen situation top " + side); return null; } } public Wrap getBottom(Position position) { // voor side 1 en side 2 int side = position.getX() / size; int x = position.getX() % size; int y = position.getY() % size; if (side == 0) { // ZIJDE 5 // ga linkerkant 3 naar rechts System.out.println("VAN BOVENKANT ZIJDE 5 NAAR LINKERKANT ZIJDE 3"); System.out.println(position); Position newPosition = new Position(50, 50 + x); System.out.println(newPosition); return new Wrap(new Position(50, 50 + x), Facing.RIGHT); } else if (side == 1) { // ZIJDE 1 // ga linkerkant van side 6 naar rechts System.out.println("VAN BOVENKANT ZIJDE 1 NAAR LINKERKANT ZIJDE 6"); System.out.println(position); Position newPosition = new Position(0, 150 + x); System.out.println(newPosition); return new Wrap(new Position(0, 150 + x), Facing.RIGHT); } else if (side == 2) { // ZIJDE 2 // ga onderkant side 6 omhoog System.out.println("VAN BOVENKANT ZIJDE 2 NAAR ONDERKANT ZIJDE 6"); System.out.println(position); Position newPosition = new Position(x, 199); System.out.println(newPosition); return new Wrap(newPosition, Facing.UP); } else { System.out.println("Unseen situation bottom " + side); return null; } } public Wrap getLeft(Position position) { // voor side 3 en side 4 int side = position.getY() / size; int x = position.getX() % size; int y = position.getY() % size; if (side == 0) { // ZIJDE 2 // ga naar rechterkant side 4 naar links System.out.println("VAN RECHTERKANT ZIJDE 2 NAAR RECHTERKANT ZIJDE 4"); System.out.println(position); Position newPosition = new Position(99, 149 - y); System.out.println(newPosition); return new Wrap(newPosition, Facing.LEFT); // OK } else if (side == 1) { // ZIJDE 3 // ga naar onderkant side 2 naar boven System.out.println("VAN RECHTERKANT ZIJDE 3 NAAR ONDERKANT ZIJDE 2"); System.out.println(position); Position newPosition = new Position(100 + y, 49); System.out.println(newPosition); return new Wrap(newPosition, Facing.UP); // OK } else if (side == 2) { // ZIJDE 4 // ga rechterkant side 2 naar links System.out.println("VAN RECHTERKANT ZIJDE 4 NAAR RECHTERKANT ZIJDE 2"); System.out.println(position); Position newPosition = new Position(149, 49 - y); System.out.println(newPosition); return new Wrap(newPosition, Facing.LEFT); // OK } else if (side == 3) {// ZIJDE 6 // ga onderkant 4 omhoog System.out.println("VAN RECHTERKANT ZIJDE 6 NAAR ONDERKANT ZIJDE 4"); System.out.println(position); Position newPosition = new Position(50+y, 149); System.out.println(newPosition); return new Wrap(newPosition, Facing.UP); } else { System.out.println("Unseen situation left " + side); return null; } } public Wrap getRight(Position position) { // voor side 1, 3, 5 en 6 int side = position.getY() / size; int x = position.getX() % size; int y = position.getY() % size; if (side == 0) { // ZIJDE 1 // ga naar linkerkant side 5 naar rechts System.out.println("VAN LINKERKANT ZIJDE 1 NAAR LINKERKANT ZIJDE 5"); System.out.println(position); Position newPosition = new Position(0, 149 - y); System.out.println(newPosition); return new Wrap(newPosition, Facing.RIGHT); // OK } else if (side == 1) { // ZIJDE 3 // ga naar bovenkant side 5 naar onder System.out.println("VAN LINKERKANT ZIJDE 3 NAAR BOVENKANT ZIJDE 5"); System.out.println(position); Position newPosition = new Position(y, 100); System.out.println(newPosition); return new Wrap(newPosition, Facing.DOWN); // OK } else if (side == 2) { // ZIJDE 5 // ga linkerkant side 1 naar rechts System.out.println("VAN LINKERKANT ZIJDE 5 NAAR LINKERKANT ZIJDE 1"); System.out.println(position); Position newPosition = new Position(50, 49 - y); System.out.println(newPosition); return new Wrap(newPosition, Facing.RIGHT); // OK } else if (side == 3) { // ZIJDE 6 // ga bovenkant 1 naar onder System.out.println("VAN LINKERKANT ZIJDE 6 NAAR BOVENKANT ZIJDE 1"); System.out.println(position); Position newPosition = new Position(50 + y, 0); System.out.println(newPosition); return new Wrap(newPosition, Facing.DOWN); // OK } else { System.out.println("Unseen situation right " + side); return null; } } public void executeSteps(String instructions) { instructions = instructions.replace("L", ",L,").replace("R", ",R,"); String[] split = instructions.split(","); for (int i = 0; i < split.length; i++) { System.out.println("I>" + split[i]); if (split[i].equals("L")) { facing = facing.left(); System.out.println("going " + facing); } else if (split[i].equals("R")) { facing = facing.right(); System.out.println("going " + facing); } else { int number = Integer.parseInt(split[i]); for (int j = 0; j < number; j++) { Position next = position.step(facing); Facing nextFacing = facing; if (isEnd(next)) { switch (facing) { case RIGHT -> { Wrap left = getLeft(position); next = left.position; nextFacing = left.facing; } case LEFT -> { Wrap right = getRight(position); next = right.position; nextFacing = right.facing; } case DOWN -> { Wrap top = getTop(position); next = top.position; nextFacing = top.facing; } case UP -> { Wrap bottom = getBottom(position); next = bottom.position; nextFacing = bottom.facing; } } } if (isWall(next)) { System.out.println("WALL"); break; } else { position = next; System.out.println(getSide(position)); facing = nextFacing; } } } } } public int getSide(Position position) { int col = position.getX() / size; int row = position.getY() / size; if (col == 0) { if (row == 2) { return 5; } else if (row == 3) { return 6; } } else if (col == 1) { if (row == 0) { return 1; } else if (row == 1) { return 3; } else if (row == 2) { return 4; } } else if (col == 2) { return 2; } return -1; } }
custersnele/AoC2022
src/main/java/be/ccfun/day22/BoardMapCube.java
2,969
// ga linkerkant van side 6 naar rechts
line_comment
nl
package be.ccfun.day22; import java.util.List; public class BoardMapCube { private List<String> map; private int size; private Position position; private Facing facing; private List<Position> luc; // left upper corners private List<Position> ruc; // right upper corners record Wrap(Position position, Facing facing) { } public BoardMapCube(List<String> map) { this.map = map; facing = Facing.RIGHT; position = new Position(map.get(0).indexOf('.'), 0); size = map.get(0).length() / 3; System.out.println(size); } public boolean isWall(Position position) { if (position.getY() == 201) { System.out.println("debug"); } return map.get(position.getY()).charAt(position.getX()) == '#'; } public boolean isEnd(Position position) { try { return map.get(position.getY()).charAt(position.getX()) == ' '; } catch (IndexOutOfBoundsException e) { return true; } } public char getChar(Position position) { return map.get(position.getY()).charAt(position.getX()); } public long getFinalPassword() { System.out.println(facing.ordinal() + " " + position); return facing.ordinal() + 1000L * (position.getY() + 1) + 4L * (position.getX() + 1); } public Wrap getTop(Position position) { // voor side 2, side 4 en side 6 int side = position.getX() / size; int x = position.getX() % size; int y = position.getY() % size; if (side == 2) { // ZIJDE 2 // ga rechterkant van side 3 naar links System.out.println("VAN ONDERKANT ZIJDE 2 NAAR RECHTKANT ZIJDE 3"); System.out.println(position); Position newPosition = new Position(99, 50 + x); System.out.println(newPosition); return new Wrap(newPosition, Facing.LEFT); } else if (side == 1) { // ZIJDE 4 // ga rechterkant side 6 naar links System.out.println("VAN ONDERKANT ZIJDE 4 NAAR RECHTKANT ZIJDE 6"); System.out.println(position); Position newPosition = new Position(49, 150 + x); System.out.println(newPosition); return new Wrap(newPosition, Facing.LEFT); } else if (side == 0) { // ZIJDE 6 // ga naar bovenkant side 2 naar onder System.out.println("VAN ONDERKANT ZIJDE 6 NAAR BOVENKANT ZIJDE 2"); System.out.println(position); Position newPosition = new Position(100 + x, 0); System.out.println(newPosition); return new Wrap(newPosition, Facing.DOWN); } else { System.out.println("Unseen situation top " + side); return null; } } public Wrap getBottom(Position position) { // voor side 1 en side 2 int side = position.getX() / size; int x = position.getX() % size; int y = position.getY() % size; if (side == 0) { // ZIJDE 5 // ga linkerkant 3 naar rechts System.out.println("VAN BOVENKANT ZIJDE 5 NAAR LINKERKANT ZIJDE 3"); System.out.println(position); Position newPosition = new Position(50, 50 + x); System.out.println(newPosition); return new Wrap(new Position(50, 50 + x), Facing.RIGHT); } else if (side == 1) { // ZIJDE 1 // ga linkerkant<SUF> System.out.println("VAN BOVENKANT ZIJDE 1 NAAR LINKERKANT ZIJDE 6"); System.out.println(position); Position newPosition = new Position(0, 150 + x); System.out.println(newPosition); return new Wrap(new Position(0, 150 + x), Facing.RIGHT); } else if (side == 2) { // ZIJDE 2 // ga onderkant side 6 omhoog System.out.println("VAN BOVENKANT ZIJDE 2 NAAR ONDERKANT ZIJDE 6"); System.out.println(position); Position newPosition = new Position(x, 199); System.out.println(newPosition); return new Wrap(newPosition, Facing.UP); } else { System.out.println("Unseen situation bottom " + side); return null; } } public Wrap getLeft(Position position) { // voor side 3 en side 4 int side = position.getY() / size; int x = position.getX() % size; int y = position.getY() % size; if (side == 0) { // ZIJDE 2 // ga naar rechterkant side 4 naar links System.out.println("VAN RECHTERKANT ZIJDE 2 NAAR RECHTERKANT ZIJDE 4"); System.out.println(position); Position newPosition = new Position(99, 149 - y); System.out.println(newPosition); return new Wrap(newPosition, Facing.LEFT); // OK } else if (side == 1) { // ZIJDE 3 // ga naar onderkant side 2 naar boven System.out.println("VAN RECHTERKANT ZIJDE 3 NAAR ONDERKANT ZIJDE 2"); System.out.println(position); Position newPosition = new Position(100 + y, 49); System.out.println(newPosition); return new Wrap(newPosition, Facing.UP); // OK } else if (side == 2) { // ZIJDE 4 // ga rechterkant side 2 naar links System.out.println("VAN RECHTERKANT ZIJDE 4 NAAR RECHTERKANT ZIJDE 2"); System.out.println(position); Position newPosition = new Position(149, 49 - y); System.out.println(newPosition); return new Wrap(newPosition, Facing.LEFT); // OK } else if (side == 3) {// ZIJDE 6 // ga onderkant 4 omhoog System.out.println("VAN RECHTERKANT ZIJDE 6 NAAR ONDERKANT ZIJDE 4"); System.out.println(position); Position newPosition = new Position(50+y, 149); System.out.println(newPosition); return new Wrap(newPosition, Facing.UP); } else { System.out.println("Unseen situation left " + side); return null; } } public Wrap getRight(Position position) { // voor side 1, 3, 5 en 6 int side = position.getY() / size; int x = position.getX() % size; int y = position.getY() % size; if (side == 0) { // ZIJDE 1 // ga naar linkerkant side 5 naar rechts System.out.println("VAN LINKERKANT ZIJDE 1 NAAR LINKERKANT ZIJDE 5"); System.out.println(position); Position newPosition = new Position(0, 149 - y); System.out.println(newPosition); return new Wrap(newPosition, Facing.RIGHT); // OK } else if (side == 1) { // ZIJDE 3 // ga naar bovenkant side 5 naar onder System.out.println("VAN LINKERKANT ZIJDE 3 NAAR BOVENKANT ZIJDE 5"); System.out.println(position); Position newPosition = new Position(y, 100); System.out.println(newPosition); return new Wrap(newPosition, Facing.DOWN); // OK } else if (side == 2) { // ZIJDE 5 // ga linkerkant side 1 naar rechts System.out.println("VAN LINKERKANT ZIJDE 5 NAAR LINKERKANT ZIJDE 1"); System.out.println(position); Position newPosition = new Position(50, 49 - y); System.out.println(newPosition); return new Wrap(newPosition, Facing.RIGHT); // OK } else if (side == 3) { // ZIJDE 6 // ga bovenkant 1 naar onder System.out.println("VAN LINKERKANT ZIJDE 6 NAAR BOVENKANT ZIJDE 1"); System.out.println(position); Position newPosition = new Position(50 + y, 0); System.out.println(newPosition); return new Wrap(newPosition, Facing.DOWN); // OK } else { System.out.println("Unseen situation right " + side); return null; } } public void executeSteps(String instructions) { instructions = instructions.replace("L", ",L,").replace("R", ",R,"); String[] split = instructions.split(","); for (int i = 0; i < split.length; i++) { System.out.println("I>" + split[i]); if (split[i].equals("L")) { facing = facing.left(); System.out.println("going " + facing); } else if (split[i].equals("R")) { facing = facing.right(); System.out.println("going " + facing); } else { int number = Integer.parseInt(split[i]); for (int j = 0; j < number; j++) { Position next = position.step(facing); Facing nextFacing = facing; if (isEnd(next)) { switch (facing) { case RIGHT -> { Wrap left = getLeft(position); next = left.position; nextFacing = left.facing; } case LEFT -> { Wrap right = getRight(position); next = right.position; nextFacing = right.facing; } case DOWN -> { Wrap top = getTop(position); next = top.position; nextFacing = top.facing; } case UP -> { Wrap bottom = getBottom(position); next = bottom.position; nextFacing = bottom.facing; } } } if (isWall(next)) { System.out.println("WALL"); break; } else { position = next; System.out.println(getSide(position)); facing = nextFacing; } } } } } public int getSide(Position position) { int col = position.getX() / size; int row = position.getY() / size; if (col == 0) { if (row == 2) { return 5; } else if (row == 3) { return 6; } } else if (col == 1) { if (row == 0) { return 1; } else if (row == 1) { return 3; } else if (row == 2) { return 4; } } else if (col == 2) { return 2; } return -1; } }
46651_14
package com.pjotr.calculator; import java.util.ArrayList; /** * @CalculatorOperation * Deze methode is de main methode van de calculator. Deze methode zet de string van de console om in een arraylist. * Het maakt gebruik van reverse polish notation. Om zo makkelijk de berekening te kunnen opslaan en uitvoeren via een for loop. */ public class CalculatorOperation extends MathUtils { /** @sign is een variabele die gebruikt wordt om te kijken of het getal positief of negatief is. */ /** @finalSign is een variabele die gebruikt wordt om te kijken of het getal positief of negatief is. */ int sign, finalSign; public Double FinalValue = 0.0; ArrayList<Double> Memory = new ArrayList<>(); ArrayList<Integer> divisionOperator = new ArrayList<>(); ArrayList<Integer> multiplicationOperator = new ArrayList<>(); ArrayList<Integer> powerOperator = new ArrayList<>(); /** @tem tem is een string variable die temporary getalen opslaat. */ String tem = ""; /** @testvalue is een variabele die gebruikt wordt om tests uit te voeren. */ Double testvalue = 0.0; /** @system system is een is een variabele die gebruikt wordt voor trigonometry */ char system; /** * @param ConsoleValue is de string die de console inleest. * @return void * @Operation is een methode die de string van de console in een arraylist zet. * Deze functie maakt gebruik van reverse polish notation. Om zo makkelijk de berekening te kunnen uitvoeren via een for loop. */ public Double Operation(String ConsoleValue) { Memory.clear(); divisionOperator.clear(); multiplicationOperator.clear(); powerOperator.clear(); tem = ""; sign = 1; finalSign = 1; FinalValue = 0.0; ConsoleValue = ConsoleValue + "+"; //for loop die de string in een arraylist zet for (int i = 0; i < ConsoleValue.length(); i++) { //als het getal een cijfer is of een punt of een E dan wordt het getal in de tem variable gezet. if ((Character.isDigit(ConsoleValue.charAt(i)) || ConsoleValue.charAt(i) == '.') || ConsoleValue.charAt(i) == 'E') { tem = String.format("%s%s", tem, ConsoleValue.charAt(i)); //als het getal een E is dan wordt er gekeken of het een positief of negatief getal is. if (ConsoleValue.charAt(i) == 'E' && ConsoleValue.charAt(i + 1) == '-') { tem = String.format("%s%s", tem, '-'); tem = String.format("%s%s", tem, ConsoleValue.charAt(i + 2)); i = i + 2; } //als tem.length() 1 is dan wordt de finalSign variable gezet. if (tem.length() == 1) finalSign = sign; } //als het getal een ! is dan wordt de factorial methode aangeroepen. if (ConsoleValue.charAt(i) == '!') tem = String.valueOf(factorial(Long.parseLong(tem))); //als het getal een e is dan wordt het getal vervangen door de waarde van het euler getal. if (ConsoleValue.charAt(i) == 'e') tem = String.valueOf(Math.E); //als het getal een π is dan wordt het getal vervangen door de waarde van het pi getal. if (ConsoleValue.charAt(i) == 'π') tem = String.valueOf(Math.PI); //als het getal een S is dan wordt de sinus methode aangeroepen. if (ConsoleValue.charAt(i) == 'S') i = function(i, 'S', ConsoleValue); //als het getal een C is dan wordt de cosinus methode aangeroepen. if (ConsoleValue.charAt(i) == 'C') i = function(i, 'C', ConsoleValue); //als het getal een T is dan wordt de tangens methode aangeroepen. if (ConsoleValue.charAt(i) == 'T') i = function(i, 'T', ConsoleValue); //als het getal een l is dan wordt de log methode aangeroepen. if (ConsoleValue.charAt(i) == 'l') i = function(i, 'l', ConsoleValue); //als het getal een L is dan wordt de log inverse methode aangeroepen. if (ConsoleValue.charAt(i) == 'L') i = function(i, 'L', ConsoleValue); //als het getal een s is dan wordt de arctangens methode aangeroepen. if (ConsoleValue.charAt(i) == 's') i = function(i, 's', ConsoleValue); //als het getal een c is dan wordt de arccosinus methode aangeroepen. if (ConsoleValue.charAt(i) == 'c') i = function(i, 'c', ConsoleValue); //als het getal een t is dan wordt de arcsinus methode aangeroepen. if (ConsoleValue.charAt(i) == 't') i = function(i, 't', ConsoleValue); //als het getal een r is dan wordt de wortel methode aangeroepen. if (ConsoleValue.charAt(i) == 'r') i = function(i, 'r', ConsoleValue); //als het getal een - is dan wordt de sign variable gezet. Dan is het een negatief getal. if (ConsoleValue.charAt(i) == '-') sign = (-1); //als het getal een + is dan wordt de sign variable gezet. Dan is het een positief getal. if (ConsoleValue.charAt(i) == '+') sign = 1; //als het getal een - of een + is dan wordt de tem variable in de arraylist gezet. if (ConsoleValue.charAt(i) == '-' || ConsoleValue.charAt(i) == '+') { if (!tem.equals("")) { Memory.add(Double.parseDouble(tem) * finalSign); tem = ""; } } //als het getal een / is dan wordt de tem variable in de arraylist gezet en wordt de divisionOperator arraylist aangevuld. if (ConsoleValue.charAt(i) == '/') { sign = 1; if (!tem.equals("")) { Memory.add(Double.parseDouble(tem) * finalSign); tem = ""; } divisionOperator.add(Memory.size() - 1); } //als het getal een * is dan wordt de tem variable in de arraylist gezet en wordt de multiplicationOperator arraylist aangevuld. if (ConsoleValue.charAt(i) == '*') { sign = 1; if (!tem.equals("")) { Memory.add(Double.parseDouble(tem) * finalSign); tem = ""; } multiplicationOperator.add(Memory.size() - 1); } //als het getal een ^ is dan wordt de tem variable in de arraylist gezet en wordt de powerOperator arraylist aangevuld. if (ConsoleValue.charAt(i) == '^') { sign = 1; if (!tem.equals("")) { Memory.add(Double.parseDouble(tem) * finalSign); tem = ""; } powerOperator.add(Memory.size() - 1); testvalue = Memory.get(0); } } return testvalue; } /** * @power * Deze methode zorgt ervoor dat de ^ operator wordt uitgevoerd. * Dan krijg je het getal dat je hebt ingevoerd tot de macht van het getal dat je hebt ingevoerd. * @return the factorial of the number. */ public Double power() { for (int j = 0; j < powerOperator.size(); j++) { Memory.set(powerOperator.get(j), Math.pow(Memory.get(powerOperator.get(j)), (Memory.get(powerOperator.get(j) + 1)))); Memory.remove(powerOperator.get(j) + 1); powerOperator = sizeReducer(powerOperator, powerOperator, j); divisionOperator = sizeReducer(divisionOperator, powerOperator, j); multiplicationOperator = sizeReducer(multiplicationOperator, powerOperator, j); } testvalue = Memory.get(0); return testvalue; } /** * @division * Deze methode berekent het gedeelde getal. * @return het gedeelde nummer. */ public Double division() { for (int i = 0; i < divisionOperator.size(); i++) { Memory.set(divisionOperator.get(i), Memory.get(divisionOperator.get(i)) / Memory.get(divisionOperator.get(i) + 1)); Memory.remove(divisionOperator.get(i) + 1); divisionOperator = sizeReducer(divisionOperator, divisionOperator, i); multiplicationOperator = sizeReducer(multiplicationOperator, divisionOperator, i); } testvalue = Memory.get(0); return testvalue; } /** * @multiplication * Deze methode berekent het vermenigvuldigde getal. * @return het vermenigvuldigde nummer. */ public Double multiplication() { for (int j = 0; j < multiplicationOperator.size(); j++) { Memory.set(multiplicationOperator.get(j), Memory.get(multiplicationOperator.get(j)) * Memory.get(multiplicationOperator.get(j) + 1)); Memory.remove(multiplicationOperator.get(j) + 1); multiplicationOperator = sizeReducer(multiplicationOperator, multiplicationOperator, j); } testvalue = Memory.get(0); return testvalue; } /** * @addition * Deze methode berekent het opgetelde getal of afgetrokken getal. * @return het opgetelde nummer. */ public Double AdditionAndSubtraction() { for (Double aDouble : Memory) FinalValue = FinalValue + aDouble; testvalue = FinalValue; return testvalue; } /** * @function Dit is de functie die de functies aanroept * @param i de index van de character in de string * @param type het type functie * @param Data de string * @return de index van de character in de string */ public int function(int i, char type, String Data) { i = i + 1; tem = ""; finalSign = sign; //terwijl de applicatie draait wordt de tem variable gevuld met de getallen die er achter de functie staan. while (true) { //als de character een getal is dan wordt de tem variable gevuld met de getallen die er achter de functie staan. if (Character.isDigit(Data.charAt(i)) || Data.charAt(i) == '.' || Data.charAt(i) == 'E' || tem.equals("")) { if (Data.charAt(i) == 'E' && Data.charAt(i + 1) == '-') { tem = tem + "E" + "-"; i = i + 2; } else { tem = tem + Data.charAt(i); i = i + 1; } } else { if (system == 'R') { //Trigonometrie in radialen functies if (type == 'S') tem = String.valueOf(Math.sin(Double.parseDouble(tem))); if (type == 'C') tem = String.valueOf(Math.cos(Double.parseDouble(tem))); if (type == 'T') tem = String.valueOf(Math.tan(Double.parseDouble(tem))); if (type == 's') tem = String.valueOf(Math.asin(Double.parseDouble(tem))); if (type == 'c') tem = String.valueOf(Math.acos(Double.parseDouble(tem))); if (type == 't') tem = String.valueOf(Math.atan(Double.parseDouble(tem))); } if (system == 'D') {// Trigonometrie in graden functies if (type == 'S') tem = String.valueOf(Math.sin(Math.toRadians(Double.parseDouble(tem)))); if (type == 'C') tem = String.valueOf(Math.cos(Math.toRadians(Double.parseDouble(tem)))); if (type == 'T') { if (!tem.equals("90.0")) tem = String.valueOf(Math.tan(Math.toRadians(Double.parseDouble(tem)))); else tem = "Infinity"; } if (type == 's') tem = String.valueOf(Math.toDegrees(Math.asin(Double.parseDouble(tem)))); if (type == 'c') tem = String.valueOf(Math.toDegrees(Math.acos(Double.parseDouble(tem)))); if (type == 't') { if (!tem.equals("90.0")) tem = String.valueOf(Math.toDegrees(Math.atan(Double.parseDouble(tem)))); else tem = "Infinity"; } } //log and inverse log if (type == 'l') tem = String.valueOf(Math.log(Double.parseDouble(tem))); if (type == 'L') tem = String.valueOf(Math.log10(Double.parseDouble(tem))); //for root function if (type == 'r') tem = String.valueOf(Math.sqrt(Double.parseDouble(tem))); break; } } return i; } }
Peter-The-Great/java-rekenmachine
src/main/java/com/pjotr/calculator/CalculatorOperation.java
3,264
//als het getal een S is dan wordt de sinus methode aangeroepen.
line_comment
nl
package com.pjotr.calculator; import java.util.ArrayList; /** * @CalculatorOperation * Deze methode is de main methode van de calculator. Deze methode zet de string van de console om in een arraylist. * Het maakt gebruik van reverse polish notation. Om zo makkelijk de berekening te kunnen opslaan en uitvoeren via een for loop. */ public class CalculatorOperation extends MathUtils { /** @sign is een variabele die gebruikt wordt om te kijken of het getal positief of negatief is. */ /** @finalSign is een variabele die gebruikt wordt om te kijken of het getal positief of negatief is. */ int sign, finalSign; public Double FinalValue = 0.0; ArrayList<Double> Memory = new ArrayList<>(); ArrayList<Integer> divisionOperator = new ArrayList<>(); ArrayList<Integer> multiplicationOperator = new ArrayList<>(); ArrayList<Integer> powerOperator = new ArrayList<>(); /** @tem tem is een string variable die temporary getalen opslaat. */ String tem = ""; /** @testvalue is een variabele die gebruikt wordt om tests uit te voeren. */ Double testvalue = 0.0; /** @system system is een is een variabele die gebruikt wordt voor trigonometry */ char system; /** * @param ConsoleValue is de string die de console inleest. * @return void * @Operation is een methode die de string van de console in een arraylist zet. * Deze functie maakt gebruik van reverse polish notation. Om zo makkelijk de berekening te kunnen uitvoeren via een for loop. */ public Double Operation(String ConsoleValue) { Memory.clear(); divisionOperator.clear(); multiplicationOperator.clear(); powerOperator.clear(); tem = ""; sign = 1; finalSign = 1; FinalValue = 0.0; ConsoleValue = ConsoleValue + "+"; //for loop die de string in een arraylist zet for (int i = 0; i < ConsoleValue.length(); i++) { //als het getal een cijfer is of een punt of een E dan wordt het getal in de tem variable gezet. if ((Character.isDigit(ConsoleValue.charAt(i)) || ConsoleValue.charAt(i) == '.') || ConsoleValue.charAt(i) == 'E') { tem = String.format("%s%s", tem, ConsoleValue.charAt(i)); //als het getal een E is dan wordt er gekeken of het een positief of negatief getal is. if (ConsoleValue.charAt(i) == 'E' && ConsoleValue.charAt(i + 1) == '-') { tem = String.format("%s%s", tem, '-'); tem = String.format("%s%s", tem, ConsoleValue.charAt(i + 2)); i = i + 2; } //als tem.length() 1 is dan wordt de finalSign variable gezet. if (tem.length() == 1) finalSign = sign; } //als het getal een ! is dan wordt de factorial methode aangeroepen. if (ConsoleValue.charAt(i) == '!') tem = String.valueOf(factorial(Long.parseLong(tem))); //als het getal een e is dan wordt het getal vervangen door de waarde van het euler getal. if (ConsoleValue.charAt(i) == 'e') tem = String.valueOf(Math.E); //als het getal een π is dan wordt het getal vervangen door de waarde van het pi getal. if (ConsoleValue.charAt(i) == 'π') tem = String.valueOf(Math.PI); //als het<SUF> if (ConsoleValue.charAt(i) == 'S') i = function(i, 'S', ConsoleValue); //als het getal een C is dan wordt de cosinus methode aangeroepen. if (ConsoleValue.charAt(i) == 'C') i = function(i, 'C', ConsoleValue); //als het getal een T is dan wordt de tangens methode aangeroepen. if (ConsoleValue.charAt(i) == 'T') i = function(i, 'T', ConsoleValue); //als het getal een l is dan wordt de log methode aangeroepen. if (ConsoleValue.charAt(i) == 'l') i = function(i, 'l', ConsoleValue); //als het getal een L is dan wordt de log inverse methode aangeroepen. if (ConsoleValue.charAt(i) == 'L') i = function(i, 'L', ConsoleValue); //als het getal een s is dan wordt de arctangens methode aangeroepen. if (ConsoleValue.charAt(i) == 's') i = function(i, 's', ConsoleValue); //als het getal een c is dan wordt de arccosinus methode aangeroepen. if (ConsoleValue.charAt(i) == 'c') i = function(i, 'c', ConsoleValue); //als het getal een t is dan wordt de arcsinus methode aangeroepen. if (ConsoleValue.charAt(i) == 't') i = function(i, 't', ConsoleValue); //als het getal een r is dan wordt de wortel methode aangeroepen. if (ConsoleValue.charAt(i) == 'r') i = function(i, 'r', ConsoleValue); //als het getal een - is dan wordt de sign variable gezet. Dan is het een negatief getal. if (ConsoleValue.charAt(i) == '-') sign = (-1); //als het getal een + is dan wordt de sign variable gezet. Dan is het een positief getal. if (ConsoleValue.charAt(i) == '+') sign = 1; //als het getal een - of een + is dan wordt de tem variable in de arraylist gezet. if (ConsoleValue.charAt(i) == '-' || ConsoleValue.charAt(i) == '+') { if (!tem.equals("")) { Memory.add(Double.parseDouble(tem) * finalSign); tem = ""; } } //als het getal een / is dan wordt de tem variable in de arraylist gezet en wordt de divisionOperator arraylist aangevuld. if (ConsoleValue.charAt(i) == '/') { sign = 1; if (!tem.equals("")) { Memory.add(Double.parseDouble(tem) * finalSign); tem = ""; } divisionOperator.add(Memory.size() - 1); } //als het getal een * is dan wordt de tem variable in de arraylist gezet en wordt de multiplicationOperator arraylist aangevuld. if (ConsoleValue.charAt(i) == '*') { sign = 1; if (!tem.equals("")) { Memory.add(Double.parseDouble(tem) * finalSign); tem = ""; } multiplicationOperator.add(Memory.size() - 1); } //als het getal een ^ is dan wordt de tem variable in de arraylist gezet en wordt de powerOperator arraylist aangevuld. if (ConsoleValue.charAt(i) == '^') { sign = 1; if (!tem.equals("")) { Memory.add(Double.parseDouble(tem) * finalSign); tem = ""; } powerOperator.add(Memory.size() - 1); testvalue = Memory.get(0); } } return testvalue; } /** * @power * Deze methode zorgt ervoor dat de ^ operator wordt uitgevoerd. * Dan krijg je het getal dat je hebt ingevoerd tot de macht van het getal dat je hebt ingevoerd. * @return the factorial of the number. */ public Double power() { for (int j = 0; j < powerOperator.size(); j++) { Memory.set(powerOperator.get(j), Math.pow(Memory.get(powerOperator.get(j)), (Memory.get(powerOperator.get(j) + 1)))); Memory.remove(powerOperator.get(j) + 1); powerOperator = sizeReducer(powerOperator, powerOperator, j); divisionOperator = sizeReducer(divisionOperator, powerOperator, j); multiplicationOperator = sizeReducer(multiplicationOperator, powerOperator, j); } testvalue = Memory.get(0); return testvalue; } /** * @division * Deze methode berekent het gedeelde getal. * @return het gedeelde nummer. */ public Double division() { for (int i = 0; i < divisionOperator.size(); i++) { Memory.set(divisionOperator.get(i), Memory.get(divisionOperator.get(i)) / Memory.get(divisionOperator.get(i) + 1)); Memory.remove(divisionOperator.get(i) + 1); divisionOperator = sizeReducer(divisionOperator, divisionOperator, i); multiplicationOperator = sizeReducer(multiplicationOperator, divisionOperator, i); } testvalue = Memory.get(0); return testvalue; } /** * @multiplication * Deze methode berekent het vermenigvuldigde getal. * @return het vermenigvuldigde nummer. */ public Double multiplication() { for (int j = 0; j < multiplicationOperator.size(); j++) { Memory.set(multiplicationOperator.get(j), Memory.get(multiplicationOperator.get(j)) * Memory.get(multiplicationOperator.get(j) + 1)); Memory.remove(multiplicationOperator.get(j) + 1); multiplicationOperator = sizeReducer(multiplicationOperator, multiplicationOperator, j); } testvalue = Memory.get(0); return testvalue; } /** * @addition * Deze methode berekent het opgetelde getal of afgetrokken getal. * @return het opgetelde nummer. */ public Double AdditionAndSubtraction() { for (Double aDouble : Memory) FinalValue = FinalValue + aDouble; testvalue = FinalValue; return testvalue; } /** * @function Dit is de functie die de functies aanroept * @param i de index van de character in de string * @param type het type functie * @param Data de string * @return de index van de character in de string */ public int function(int i, char type, String Data) { i = i + 1; tem = ""; finalSign = sign; //terwijl de applicatie draait wordt de tem variable gevuld met de getallen die er achter de functie staan. while (true) { //als de character een getal is dan wordt de tem variable gevuld met de getallen die er achter de functie staan. if (Character.isDigit(Data.charAt(i)) || Data.charAt(i) == '.' || Data.charAt(i) == 'E' || tem.equals("")) { if (Data.charAt(i) == 'E' && Data.charAt(i + 1) == '-') { tem = tem + "E" + "-"; i = i + 2; } else { tem = tem + Data.charAt(i); i = i + 1; } } else { if (system == 'R') { //Trigonometrie in radialen functies if (type == 'S') tem = String.valueOf(Math.sin(Double.parseDouble(tem))); if (type == 'C') tem = String.valueOf(Math.cos(Double.parseDouble(tem))); if (type == 'T') tem = String.valueOf(Math.tan(Double.parseDouble(tem))); if (type == 's') tem = String.valueOf(Math.asin(Double.parseDouble(tem))); if (type == 'c') tem = String.valueOf(Math.acos(Double.parseDouble(tem))); if (type == 't') tem = String.valueOf(Math.atan(Double.parseDouble(tem))); } if (system == 'D') {// Trigonometrie in graden functies if (type == 'S') tem = String.valueOf(Math.sin(Math.toRadians(Double.parseDouble(tem)))); if (type == 'C') tem = String.valueOf(Math.cos(Math.toRadians(Double.parseDouble(tem)))); if (type == 'T') { if (!tem.equals("90.0")) tem = String.valueOf(Math.tan(Math.toRadians(Double.parseDouble(tem)))); else tem = "Infinity"; } if (type == 's') tem = String.valueOf(Math.toDegrees(Math.asin(Double.parseDouble(tem)))); if (type == 'c') tem = String.valueOf(Math.toDegrees(Math.acos(Double.parseDouble(tem)))); if (type == 't') { if (!tem.equals("90.0")) tem = String.valueOf(Math.toDegrees(Math.atan(Double.parseDouble(tem)))); else tem = "Infinity"; } } //log and inverse log if (type == 'l') tem = String.valueOf(Math.log(Double.parseDouble(tem))); if (type == 'L') tem = String.valueOf(Math.log10(Double.parseDouble(tem))); //for root function if (type == 'r') tem = String.valueOf(Math.sqrt(Double.parseDouble(tem))); break; } } return i; } }
72817_23
package org.molgenis.animaldb.plugins.administration; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import org.molgenis.animaldb.commonservice.CommonService; import org.molgenis.framework.db.Database; import org.molgenis.framework.db.Query; import org.molgenis.framework.db.QueryRule; import org.molgenis.framework.db.QueryRule.Operator; import org.molgenis.pheno.ObservationTarget; import org.molgenis.pheno.ObservedValue; public class VWAReport5 extends AnimalDBReport { private ArrayList<ArrayList<String>> matrix = new ArrayList<ArrayList<String>>(); private List<Integer> nrOfAnimalList = new ArrayList<Integer>(); private String userName; public VWAReport5(Database db, String userName) { this.userName = userName; this.db = db; ct = CommonService.getInstance(); ct.setDatabase(db); nrCol = 17; warningsList = new ArrayList<String>(); } @Override public void makeReport(int year, String type) { try { this.year = year; SimpleDateFormat fullFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US); SimpleDateFormat dbFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.US); String startOfYearString = year + "-01-01 00:00:00"; Date startOfYear = fullFormat.parse(startOfYearString); String endOfYearString = (year + 1) + "-01-01 00:00:00"; Date endOfYear = fullFormat.parse(endOfYearString); List<String> investigationNames = ct.getOwnUserInvestigationNames(userName); List<ObservationTarget> decappList = ct.getAllMarkedPanels("DecApplication", investigationNames); for (ObservationTarget d : decappList) { String decName = d.getName(); // Check if the DEC application was (partly) in this year Date startOfDec = null; String startOfDecString = ct.getMostRecentValueAsString(decName, "StartDate"); if (startOfDecString != null && !startOfDecString.equals("")) { startOfDec = dbFormat.parse(startOfDecString); if (startOfDec.after(endOfYear)) { continue; } } else { continue; } Date endOfDec = null; String endOfDecString = ct.getMostRecentValueAsString(decName, "EndDate"); if (endOfDecString != null && !endOfDecString.equals("")) { endOfDec = dbFormat.parse(endOfDecString); if (endOfDec.before(startOfYear)) { continue; } } // Get DEC number String decNr = ct.getMostRecentValueAsString(decName, "DecNr"); // Find the experiments belonging to this DEC List<Integer> experimentIdList = new ArrayList<Integer>(); Query<ObservedValue> q = db.query(ObservedValue.class); q.addRules(new QueryRule(ObservedValue.RELATION_NAME, Operator.EQUALS, decName)); q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "DecApplication")); List<ObservedValue> valueList = q.find(); // Make sure we have a list of unique experiments! for (ObservedValue v : valueList) { if (!experimentIdList.contains(v.getTarget_Id())) { experimentIdList.add(v.getTarget_Id()); } } for (int expid : experimentIdList) { String expName = ct.getObservationTargetLabel(expid); // Get the experiment subcode String expCode = ct.getMostRecentValueAsString(expName, "ExperimentNr"); // Doel vd proef (experiment's Goal) String goal = ct.getMostRecentValueAsString(expName, "Goal"); // Belang van de proef (experiment's Concern) String concern = ct.getMostRecentValueAsString(expName, "Concern"); // Wettelijke bepalingen (experiment's LawDef) String lawDef = ct.getMostRecentValueAsString(expName, "LawDef"); // Toxicologisch / veiligheidsonderzoek (experiment's // ToxRes) String toxRes = ct.getMostRecentValueAsString(expName, "ToxRes"); // Technieken byzondere (experiment's SpecialTechn) String specialTechn = ct.getMostRecentValueAsString(expName, "SpecialTechn"); // Get the animals that were in the experiment this year q = db.query(ObservedValue.class); q.addRules(new QueryRule(ObservedValue.RELATION_NAME, Operator.EQUALS, expName)); q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "Experiment")); q.addRules(new QueryRule(ObservedValue.ENDTIME, Operator.LESS_EQUAL, endOfYearString)); q.addRules(new QueryRule(ObservedValue.ENDTIME, Operator.NOT, null)); valueList = q.find(); for (ObservedValue animalInExpValue : valueList) { // Get the corresponding protocol application int protocolApplicationId = animalInExpValue.getProtocolApplication_Id(); // Get animal ID String animalName = animalInExpValue.getTarget_Name(); // Get dates Date entryDate = animalInExpValue.getTime(); Date exitDate = animalInExpValue.getEndtime(); // Check dates if (entryDate.after(endOfYear)) { continue; } if (exitDate == null) { // should not be possible continue; } else if (exitDate.before(startOfYear)) { continue; } // Get the data about the animal in the experiment // Bijzonderheid dier (animal's AnimalType) String animalType = ct.getMostRecentValueAsString(animalName, "AnimalType"); // Diersoort (animal's Species -> VWASpecies and // LatinSpecies) String vwaSpecies = ""; String latinSpecies = ""; String normalSpecies = ct.getMostRecentValueAsXrefName(animalName, "Species"); // Get VWA species Query<ObservedValue> vwaSpeciesQuery = db.query(ObservedValue.class); vwaSpeciesQuery.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, normalSpecies)); vwaSpeciesQuery.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "VWASpecies")); List<ObservedValue> vwaSpeciesValueList = vwaSpeciesQuery.find(); if (vwaSpeciesValueList.size() == 1) { vwaSpecies = vwaSpeciesValueList.get(0).getValue(); } // Get scientific (Latin) species Query<ObservedValue> latinSpeciesQuery = db.query(ObservedValue.class); latinSpeciesQuery.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, normalSpecies)); latinSpeciesQuery.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "LatinSpecies")); List<ObservedValue> latinSpeciesValueList = latinSpeciesQuery.find(); if (latinSpeciesValueList.size() == 1) { latinSpecies = latinSpeciesValueList.get(0).getValue(); } // Herkomst en hergebruik (animal's // SourceTypeSubproject, which includes reuse) String sourceType = ""; q = db.query(ObservedValue.class); q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName)); q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "SourceTypeSubproject")); q.addRules(new QueryRule(ObservedValue.PROTOCOLAPPLICATION, Operator.EQUALS, protocolApplicationId)); valueList = q.find(); if (valueList.size() > 0) { sourceType = valueList.get(0).getValue(); } // Aantal dieren (count later on!) // Anesthesie (animal's Anaesthesia) String anaesthesia = ""; q = db.query(ObservedValue.class); q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName)); q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "Anaesthesia")); q.addRules(new QueryRule(ObservedValue.PROTOCOLAPPLICATION, Operator.EQUALS, protocolApplicationId)); valueList = q.find(); if (valueList.size() > 0) { anaesthesia = valueList.get(0).getValue(); } // Pijnbestrijding, postoperatief (animal's // PainManagement) String painManagement = ""; q = db.query(ObservedValue.class); q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName)); q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "PainManagement")); q.addRules(new QueryRule(ObservedValue.PROTOCOLAPPLICATION, Operator.EQUALS, protocolApplicationId)); valueList = q.find(); if (valueList.size() > 0) { painManagement = valueList.get(0).getValue(); } String actualDiscomfort = ""; String actualAnimalEndStatus = ""; // Find protocol application ID for the removing of this // animal from this DEC subproject q = db.query(ObservedValue.class); q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName)); q.addRules(new QueryRule(ObservedValue.RELATION_NAME, Operator.EQUALS, expName)); q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "FromExperiment")); valueList = q.find(); if (valueList.size() > 0) { int removalProtocolApplicationId = valueList.get(0).getProtocolApplication_Id(); // Ongerief (animal's ActualDiscomfort) q = db.query(ObservedValue.class); q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName)); q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "ActualDiscomfort")); q.addRules(new QueryRule(ObservedValue.PROTOCOLAPPLICATION, Operator.EQUALS, removalProtocolApplicationId)); valueList = q.find(); if (valueList.size() > 0) { actualDiscomfort = valueList.get(0).getValue(); } else { // Something's wrong here... warningsList.add("No 'ActualDiscomfort' value found for Animal " + animalName + " in DEC subproject " + expName); } // Toestand dier na beeindiging proef (animal's most // recent ActualAnimalEndStatus) q = db.query(ObservedValue.class); q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName)); q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "ActualAnimalEndStatus")); q.sortDESC(ObservedValue.TIME); valueList = q.find(); if (valueList.size() > 0) { // Check if most recent end status was in the PA // we're now looking at if (valueList.get(0).getProtocolApplication_Id().equals(removalProtocolApplicationId)) { actualAnimalEndStatus = valueList.get(0).getValue(); // If most recent end status was 'in leven // gelaten' but animal died in given year, // change to 'dood ihkv de proef' because // that's how the law wants it... if (actualAnimalEndStatus.equals("C. Na einde proef in leven gelaten")) { q = db.query(ObservedValue.class); q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName)); q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "Active")); q.addRules(new QueryRule(ObservedValue.ENDTIME, Operator.GREATER_EQUAL, startOfYearString)); q.addRules(new QueryRule(ObservedValue.ENDTIME, Operator.LESS_EQUAL, endOfYearString)); q.addRules(new QueryRule(ObservedValue.ENDTIME, Operator.NOT, null)); valueList = q.find(); if (valueList.size() > 0) { // So animal did indeed die in the // given year actualAnimalEndStatus = "B. Gedood na beeindiging van de proef"; } } } else { // Find the end status value in the PA we're // looking at for (ObservedValue endStatusValue : valueList) { if (endStatusValue.getProtocolApplication_Id().equals( removalProtocolApplicationId)) { actualAnimalEndStatus = endStatusValue.getValue(); } } } } else { // Something's wrong here... warningsList.add("No 'ActualAnimalEndStatus' value(s) found for Animal " + animalName + " in DEC subproject " + expName); } } else { // Something's wrong here... warningsList.add("No 'FromExperiment' value found for Animal " + animalName + " in DEC subproject " + expName); } ArrayList<String> newRow = new ArrayList<String>(); newRow.add(decNr + expCode + " - " + d.getName()); if (endOfDec != null) { newRow.add(dbFormat.format(endOfDec)); } else { newRow.add(""); } newRow.add(animalType); newRow.add(vwaSpecies); newRow.add(sourceType); newRow.add(""); newRow.add(goal); newRow.add(concern); newRow.add(lawDef); newRow.add(toxRes); newRow.add(specialTechn); newRow.add(anaesthesia); newRow.add(painManagement); newRow.add(actualDiscomfort); newRow.add(actualAnimalEndStatus); newRow.add(decNr + expCode); newRow.add(latinSpecies); if (matrix.contains(newRow)) { // If the above values are exactly the same as an // earlier row, aggregate them int rowIndex = matrix.indexOf(newRow); int tmpNr = nrOfAnimalList.get(rowIndex); nrOfAnimalList.set(rowIndex, tmpNr + 1); } else { // Else, make a new row matrix.add(newRow); nrOfAnimalList.add(1); } } } } } catch (Exception e) { e.printStackTrace(); } } @Override public String toString() { String output = "<br /><p><strong>JAARSTAAT DIERPROEVEN registratiejaar " + year + " - Registratieformulier 5</strong></p>"; output += "<br /><div id='reporttablediv'><table border='1' cellpadding='5' cellspacing='5'>"; output += "<tr>"; output += "<th></th>"; output += "<th></th>"; for (int col = 1; col < 15; col++) { output += ("<th>" + col + "</th>"); } output += "<th></th>"; output += "</tr>"; output += "<tr>"; output += "<td style='padding:5px'>DEC-nr.</td>"; output += "<td style='padding:5px'>DEC verlopen op</td>"; output += "<td style='padding:5px'>Bijzonderheid dier</td>"; output += "<td style='padding:5px'>Diersoort</td>"; output += "<td style='padding:5px'>Herkomst en hergebruik</td>"; output += "<td style='padding:5px'>Aantal dieren</td>"; output += "<td style='padding:5px'>Doel vd proef</td>"; output += "<td style='padding:5px'>Belang van de proef</td>"; output += "<td style='padding:5px'>Wettelijke bepalingen</td>"; output += "<td style='padding:5px'>Toxicologisch / veiligheidsonderzoek</td>"; output += "<td style='padding:5px'>Bijzondere technieken</td>"; output += "<td style='padding:5px'>Anesthesie</td>"; output += "<td style='padding:5px'>Pijnbestrijding, postoperatief</td>"; output += "<td style='padding:5px'>Ongerief</td>"; output += "<td style='padding:5px'>Toestand dier na beeindiging proef</td>"; output += "<td style='padding:5px'>DEC-nummer / Onderzoeksprotocol</td>"; output += "<td style='padding:5px'>Naam (wetenschappelijke naam)</td>"; output += "</tr>"; int counter = 0; for (ArrayList<String> currentRow : matrix) { output += "<tr>"; for (int col = 0; col < nrCol; col++) { if (col == 5) { output += ("<td style='padding:5px'>" + nrOfAnimalList.get(counter) + "</td>"); } else { output += ("<td style='padding:5px'>" + currentRow.get(col) + "</td>"); } } output += "</tr>"; counter++; } output += "</table></div>"; // Warnings if (warningsList.size() > 0) { output += "<p><strong>Warnings</strong><br />"; for (String warning : warningsList) { output += (warning + "<br />"); } output += "</p>"; } return output; } }
kantale/molgenis_apps
apps/animaldb/org/molgenis/animaldb/plugins/administration/VWAReport5.java
4,631
// Pijnbestrijding, postoperatief (animal's
line_comment
nl
package org.molgenis.animaldb.plugins.administration; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import org.molgenis.animaldb.commonservice.CommonService; import org.molgenis.framework.db.Database; import org.molgenis.framework.db.Query; import org.molgenis.framework.db.QueryRule; import org.molgenis.framework.db.QueryRule.Operator; import org.molgenis.pheno.ObservationTarget; import org.molgenis.pheno.ObservedValue; public class VWAReport5 extends AnimalDBReport { private ArrayList<ArrayList<String>> matrix = new ArrayList<ArrayList<String>>(); private List<Integer> nrOfAnimalList = new ArrayList<Integer>(); private String userName; public VWAReport5(Database db, String userName) { this.userName = userName; this.db = db; ct = CommonService.getInstance(); ct.setDatabase(db); nrCol = 17; warningsList = new ArrayList<String>(); } @Override public void makeReport(int year, String type) { try { this.year = year; SimpleDateFormat fullFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US); SimpleDateFormat dbFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.US); String startOfYearString = year + "-01-01 00:00:00"; Date startOfYear = fullFormat.parse(startOfYearString); String endOfYearString = (year + 1) + "-01-01 00:00:00"; Date endOfYear = fullFormat.parse(endOfYearString); List<String> investigationNames = ct.getOwnUserInvestigationNames(userName); List<ObservationTarget> decappList = ct.getAllMarkedPanels("DecApplication", investigationNames); for (ObservationTarget d : decappList) { String decName = d.getName(); // Check if the DEC application was (partly) in this year Date startOfDec = null; String startOfDecString = ct.getMostRecentValueAsString(decName, "StartDate"); if (startOfDecString != null && !startOfDecString.equals("")) { startOfDec = dbFormat.parse(startOfDecString); if (startOfDec.after(endOfYear)) { continue; } } else { continue; } Date endOfDec = null; String endOfDecString = ct.getMostRecentValueAsString(decName, "EndDate"); if (endOfDecString != null && !endOfDecString.equals("")) { endOfDec = dbFormat.parse(endOfDecString); if (endOfDec.before(startOfYear)) { continue; } } // Get DEC number String decNr = ct.getMostRecentValueAsString(decName, "DecNr"); // Find the experiments belonging to this DEC List<Integer> experimentIdList = new ArrayList<Integer>(); Query<ObservedValue> q = db.query(ObservedValue.class); q.addRules(new QueryRule(ObservedValue.RELATION_NAME, Operator.EQUALS, decName)); q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "DecApplication")); List<ObservedValue> valueList = q.find(); // Make sure we have a list of unique experiments! for (ObservedValue v : valueList) { if (!experimentIdList.contains(v.getTarget_Id())) { experimentIdList.add(v.getTarget_Id()); } } for (int expid : experimentIdList) { String expName = ct.getObservationTargetLabel(expid); // Get the experiment subcode String expCode = ct.getMostRecentValueAsString(expName, "ExperimentNr"); // Doel vd proef (experiment's Goal) String goal = ct.getMostRecentValueAsString(expName, "Goal"); // Belang van de proef (experiment's Concern) String concern = ct.getMostRecentValueAsString(expName, "Concern"); // Wettelijke bepalingen (experiment's LawDef) String lawDef = ct.getMostRecentValueAsString(expName, "LawDef"); // Toxicologisch / veiligheidsonderzoek (experiment's // ToxRes) String toxRes = ct.getMostRecentValueAsString(expName, "ToxRes"); // Technieken byzondere (experiment's SpecialTechn) String specialTechn = ct.getMostRecentValueAsString(expName, "SpecialTechn"); // Get the animals that were in the experiment this year q = db.query(ObservedValue.class); q.addRules(new QueryRule(ObservedValue.RELATION_NAME, Operator.EQUALS, expName)); q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "Experiment")); q.addRules(new QueryRule(ObservedValue.ENDTIME, Operator.LESS_EQUAL, endOfYearString)); q.addRules(new QueryRule(ObservedValue.ENDTIME, Operator.NOT, null)); valueList = q.find(); for (ObservedValue animalInExpValue : valueList) { // Get the corresponding protocol application int protocolApplicationId = animalInExpValue.getProtocolApplication_Id(); // Get animal ID String animalName = animalInExpValue.getTarget_Name(); // Get dates Date entryDate = animalInExpValue.getTime(); Date exitDate = animalInExpValue.getEndtime(); // Check dates if (entryDate.after(endOfYear)) { continue; } if (exitDate == null) { // should not be possible continue; } else if (exitDate.before(startOfYear)) { continue; } // Get the data about the animal in the experiment // Bijzonderheid dier (animal's AnimalType) String animalType = ct.getMostRecentValueAsString(animalName, "AnimalType"); // Diersoort (animal's Species -> VWASpecies and // LatinSpecies) String vwaSpecies = ""; String latinSpecies = ""; String normalSpecies = ct.getMostRecentValueAsXrefName(animalName, "Species"); // Get VWA species Query<ObservedValue> vwaSpeciesQuery = db.query(ObservedValue.class); vwaSpeciesQuery.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, normalSpecies)); vwaSpeciesQuery.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "VWASpecies")); List<ObservedValue> vwaSpeciesValueList = vwaSpeciesQuery.find(); if (vwaSpeciesValueList.size() == 1) { vwaSpecies = vwaSpeciesValueList.get(0).getValue(); } // Get scientific (Latin) species Query<ObservedValue> latinSpeciesQuery = db.query(ObservedValue.class); latinSpeciesQuery.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, normalSpecies)); latinSpeciesQuery.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "LatinSpecies")); List<ObservedValue> latinSpeciesValueList = latinSpeciesQuery.find(); if (latinSpeciesValueList.size() == 1) { latinSpecies = latinSpeciesValueList.get(0).getValue(); } // Herkomst en hergebruik (animal's // SourceTypeSubproject, which includes reuse) String sourceType = ""; q = db.query(ObservedValue.class); q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName)); q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "SourceTypeSubproject")); q.addRules(new QueryRule(ObservedValue.PROTOCOLAPPLICATION, Operator.EQUALS, protocolApplicationId)); valueList = q.find(); if (valueList.size() > 0) { sourceType = valueList.get(0).getValue(); } // Aantal dieren (count later on!) // Anesthesie (animal's Anaesthesia) String anaesthesia = ""; q = db.query(ObservedValue.class); q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName)); q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "Anaesthesia")); q.addRules(new QueryRule(ObservedValue.PROTOCOLAPPLICATION, Operator.EQUALS, protocolApplicationId)); valueList = q.find(); if (valueList.size() > 0) { anaesthesia = valueList.get(0).getValue(); } // Pijnbestrijding, postoperatief<SUF> // PainManagement) String painManagement = ""; q = db.query(ObservedValue.class); q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName)); q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "PainManagement")); q.addRules(new QueryRule(ObservedValue.PROTOCOLAPPLICATION, Operator.EQUALS, protocolApplicationId)); valueList = q.find(); if (valueList.size() > 0) { painManagement = valueList.get(0).getValue(); } String actualDiscomfort = ""; String actualAnimalEndStatus = ""; // Find protocol application ID for the removing of this // animal from this DEC subproject q = db.query(ObservedValue.class); q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName)); q.addRules(new QueryRule(ObservedValue.RELATION_NAME, Operator.EQUALS, expName)); q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "FromExperiment")); valueList = q.find(); if (valueList.size() > 0) { int removalProtocolApplicationId = valueList.get(0).getProtocolApplication_Id(); // Ongerief (animal's ActualDiscomfort) q = db.query(ObservedValue.class); q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName)); q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "ActualDiscomfort")); q.addRules(new QueryRule(ObservedValue.PROTOCOLAPPLICATION, Operator.EQUALS, removalProtocolApplicationId)); valueList = q.find(); if (valueList.size() > 0) { actualDiscomfort = valueList.get(0).getValue(); } else { // Something's wrong here... warningsList.add("No 'ActualDiscomfort' value found for Animal " + animalName + " in DEC subproject " + expName); } // Toestand dier na beeindiging proef (animal's most // recent ActualAnimalEndStatus) q = db.query(ObservedValue.class); q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName)); q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "ActualAnimalEndStatus")); q.sortDESC(ObservedValue.TIME); valueList = q.find(); if (valueList.size() > 0) { // Check if most recent end status was in the PA // we're now looking at if (valueList.get(0).getProtocolApplication_Id().equals(removalProtocolApplicationId)) { actualAnimalEndStatus = valueList.get(0).getValue(); // If most recent end status was 'in leven // gelaten' but animal died in given year, // change to 'dood ihkv de proef' because // that's how the law wants it... if (actualAnimalEndStatus.equals("C. Na einde proef in leven gelaten")) { q = db.query(ObservedValue.class); q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName)); q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "Active")); q.addRules(new QueryRule(ObservedValue.ENDTIME, Operator.GREATER_EQUAL, startOfYearString)); q.addRules(new QueryRule(ObservedValue.ENDTIME, Operator.LESS_EQUAL, endOfYearString)); q.addRules(new QueryRule(ObservedValue.ENDTIME, Operator.NOT, null)); valueList = q.find(); if (valueList.size() > 0) { // So animal did indeed die in the // given year actualAnimalEndStatus = "B. Gedood na beeindiging van de proef"; } } } else { // Find the end status value in the PA we're // looking at for (ObservedValue endStatusValue : valueList) { if (endStatusValue.getProtocolApplication_Id().equals( removalProtocolApplicationId)) { actualAnimalEndStatus = endStatusValue.getValue(); } } } } else { // Something's wrong here... warningsList.add("No 'ActualAnimalEndStatus' value(s) found for Animal " + animalName + " in DEC subproject " + expName); } } else { // Something's wrong here... warningsList.add("No 'FromExperiment' value found for Animal " + animalName + " in DEC subproject " + expName); } ArrayList<String> newRow = new ArrayList<String>(); newRow.add(decNr + expCode + " - " + d.getName()); if (endOfDec != null) { newRow.add(dbFormat.format(endOfDec)); } else { newRow.add(""); } newRow.add(animalType); newRow.add(vwaSpecies); newRow.add(sourceType); newRow.add(""); newRow.add(goal); newRow.add(concern); newRow.add(lawDef); newRow.add(toxRes); newRow.add(specialTechn); newRow.add(anaesthesia); newRow.add(painManagement); newRow.add(actualDiscomfort); newRow.add(actualAnimalEndStatus); newRow.add(decNr + expCode); newRow.add(latinSpecies); if (matrix.contains(newRow)) { // If the above values are exactly the same as an // earlier row, aggregate them int rowIndex = matrix.indexOf(newRow); int tmpNr = nrOfAnimalList.get(rowIndex); nrOfAnimalList.set(rowIndex, tmpNr + 1); } else { // Else, make a new row matrix.add(newRow); nrOfAnimalList.add(1); } } } } } catch (Exception e) { e.printStackTrace(); } } @Override public String toString() { String output = "<br /><p><strong>JAARSTAAT DIERPROEVEN registratiejaar " + year + " - Registratieformulier 5</strong></p>"; output += "<br /><div id='reporttablediv'><table border='1' cellpadding='5' cellspacing='5'>"; output += "<tr>"; output += "<th></th>"; output += "<th></th>"; for (int col = 1; col < 15; col++) { output += ("<th>" + col + "</th>"); } output += "<th></th>"; output += "</tr>"; output += "<tr>"; output += "<td style='padding:5px'>DEC-nr.</td>"; output += "<td style='padding:5px'>DEC verlopen op</td>"; output += "<td style='padding:5px'>Bijzonderheid dier</td>"; output += "<td style='padding:5px'>Diersoort</td>"; output += "<td style='padding:5px'>Herkomst en hergebruik</td>"; output += "<td style='padding:5px'>Aantal dieren</td>"; output += "<td style='padding:5px'>Doel vd proef</td>"; output += "<td style='padding:5px'>Belang van de proef</td>"; output += "<td style='padding:5px'>Wettelijke bepalingen</td>"; output += "<td style='padding:5px'>Toxicologisch / veiligheidsonderzoek</td>"; output += "<td style='padding:5px'>Bijzondere technieken</td>"; output += "<td style='padding:5px'>Anesthesie</td>"; output += "<td style='padding:5px'>Pijnbestrijding, postoperatief</td>"; output += "<td style='padding:5px'>Ongerief</td>"; output += "<td style='padding:5px'>Toestand dier na beeindiging proef</td>"; output += "<td style='padding:5px'>DEC-nummer / Onderzoeksprotocol</td>"; output += "<td style='padding:5px'>Naam (wetenschappelijke naam)</td>"; output += "</tr>"; int counter = 0; for (ArrayList<String> currentRow : matrix) { output += "<tr>"; for (int col = 0; col < nrCol; col++) { if (col == 5) { output += ("<td style='padding:5px'>" + nrOfAnimalList.get(counter) + "</td>"); } else { output += ("<td style='padding:5px'>" + currentRow.get(col) + "</td>"); } } output += "</tr>"; counter++; } output += "</table></div>"; // Warnings if (warningsList.size() > 0) { output += "<p><strong>Warnings</strong><br />"; for (String warning : warningsList) { output += (warning + "<br />"); } output += "</p>"; } return output; } }
22217_9
package eu.ludiq.pws.world3d; public class Quaternion { // Een quaternion bestaat uit 4 getallen: a, b, c, d // Het quaternion is dan dus gelijk aan: q = a + bi + cj + dk private double a, b, c, d; public Quaternion() { // Als je deze manier kiest van een Quaternion maken, wordt een // Quaternion, // die de rotatie van 0 graden voorstelt, gemaakt. this(1, 0, 0, 0); } public Quaternion(double a, double b, double c, double d) { // Om een quaternion te gebruiken, moet je een beginwaarde voor a, b, c // en d geven. this.a = a; this.b = b; this.c = c; this.d = d; } // De volgende acties zijn gedefinieerd: public Quaternion conjugate() { // Geeft de geconjugeerde terug return new Quaternion(a, -b, -c, -d); } public Quaternion multiply(Quaternion q) { // Geeft het product van dit quaternion en q terug double newA = a * q.a - b * q.b - c * q.c - d * q.d; double newB = a * q.b + b * q.a + c * q.d - d * q.c; double newC = a * q.c - b * q.d + c * q.a + d * q.b; double newD = a * q.d + b * q.c - c * q.b + d * q.a; return new Quaternion(newA, newB, newC, newD); } public Quaternion rotate(Quaternion rotation) { // Geeft het beeld terug nadat dit punt gedraaid is volgens rotation. // p' = q * p * q^-1 return rotation.multiply(this).multiply(rotation.conjugate()); } public Point3D toPoint() { // Dit is nodig, want bij het draaien van een punt, moet de gedraaide // quaternion terug naar een punt worden veranderd. return new Point3D(b, c, d); } public double length() { // Geeft de lengte van de Quaternion. // Dit wordt gedaan volgens de stelling van Pythagoras return Math.sqrt(a * a + b * b + c * c + d * d); } public void normalize() { // Schaalt de quaternion zo, dat de lengte weer precies 1 is. // Bij afrondingsfouten kan de lengte steeds verder afwijken van 1, // waardoor het roteren niet meer goed gaat. double len = length(); a /= len; b /= len; c /= len; d /= len; } }
ludopulles/QuaternionExample
src/eu/ludiq/pws/world3d/Quaternion.java
698
// Geeft het beeld terug nadat dit punt gedraaid is volgens rotation.
line_comment
nl
package eu.ludiq.pws.world3d; public class Quaternion { // Een quaternion bestaat uit 4 getallen: a, b, c, d // Het quaternion is dan dus gelijk aan: q = a + bi + cj + dk private double a, b, c, d; public Quaternion() { // Als je deze manier kiest van een Quaternion maken, wordt een // Quaternion, // die de rotatie van 0 graden voorstelt, gemaakt. this(1, 0, 0, 0); } public Quaternion(double a, double b, double c, double d) { // Om een quaternion te gebruiken, moet je een beginwaarde voor a, b, c // en d geven. this.a = a; this.b = b; this.c = c; this.d = d; } // De volgende acties zijn gedefinieerd: public Quaternion conjugate() { // Geeft de geconjugeerde terug return new Quaternion(a, -b, -c, -d); } public Quaternion multiply(Quaternion q) { // Geeft het product van dit quaternion en q terug double newA = a * q.a - b * q.b - c * q.c - d * q.d; double newB = a * q.b + b * q.a + c * q.d - d * q.c; double newC = a * q.c - b * q.d + c * q.a + d * q.b; double newD = a * q.d + b * q.c - c * q.b + d * q.a; return new Quaternion(newA, newB, newC, newD); } public Quaternion rotate(Quaternion rotation) { // Geeft het<SUF> // p' = q * p * q^-1 return rotation.multiply(this).multiply(rotation.conjugate()); } public Point3D toPoint() { // Dit is nodig, want bij het draaien van een punt, moet de gedraaide // quaternion terug naar een punt worden veranderd. return new Point3D(b, c, d); } public double length() { // Geeft de lengte van de Quaternion. // Dit wordt gedaan volgens de stelling van Pythagoras return Math.sqrt(a * a + b * b + c * c + d * d); } public void normalize() { // Schaalt de quaternion zo, dat de lengte weer precies 1 is. // Bij afrondingsfouten kan de lengte steeds verder afwijken van 1, // waardoor het roteren niet meer goed gaat. double len = length(); a /= len; b /= len; c /= len; d /= len; } }
102997_57
/****************************************************************************** * Product: ADempiere ERP & CRM Smart Business Solution * * Copyright (C) 2006-2017 ADempiere Foundation, All Rights Reserved. * * This program is free software, you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * * or (at your option) any later version. * * by the Free Software Foundation. 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, write to the Free Software Foundation, Inc., * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * For the text or an alternative of this public license, you may reach us * * or via [email protected] or http://www.adempiere.net/license.html * *****************************************************************************/ /** Generated Model - DO NOT CHANGE */ package org.compiere.model; import java.math.BigDecimal; import java.sql.ResultSet; import java.util.Properties; import org.compiere.util.Env; import org.compiere.util.KeyNamePair; /** Generated Model for PA_DashboardContent * @author Adempiere (generated) * @version Release 3.9.2 - $Id$ */ public class X_PA_DashboardContent extends PO implements I_PA_DashboardContent, I_Persistent { /** * */ private static final long serialVersionUID = 20191120L; /** Standard Constructor */ public X_PA_DashboardContent (Properties ctx, int PA_DashboardContent_ID, String trxName) { super (ctx, PA_DashboardContent_ID, trxName); /** if (PA_DashboardContent_ID == 0) { setIsCollapsible (true); // Y setName (null); setPA_DashboardContent_ID (0); } */ } /** Load Constructor */ public X_PA_DashboardContent (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** AccessLevel * @return 6 - System - Client */ protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_PA_DashboardContent[") .append(get_ID()).append("]"); return sb.toString(); } public org.adempiere.model.I_AD_Browse getAD_Browse() throws RuntimeException { return (org.adempiere.model.I_AD_Browse)MTable.get(getCtx(), org.adempiere.model.I_AD_Browse.Table_Name) .getPO(getAD_Browse_ID(), get_TrxName()); } /** Set Smart Browse. @param AD_Browse_ID Smart Browse */ public void setAD_Browse_ID (int AD_Browse_ID) { if (AD_Browse_ID < 1) set_Value (COLUMNNAME_AD_Browse_ID, null); else set_Value (COLUMNNAME_AD_Browse_ID, Integer.valueOf(AD_Browse_ID)); } /** Get Smart Browse. @return Smart Browse */ public int getAD_Browse_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Browse_ID); if (ii == null) return 0; return ii.intValue(); } public org.compiere.model.I_AD_Window getAD_Window() throws RuntimeException { return (org.compiere.model.I_AD_Window)MTable.get(getCtx(), org.compiere.model.I_AD_Window.Table_Name) .getPO(getAD_Window_ID(), get_TrxName()); } /** Set Window. @param AD_Window_ID Data entry or display window */ public void setAD_Window_ID (int AD_Window_ID) { if (AD_Window_ID < 1) set_Value (COLUMNNAME_AD_Window_ID, null); else set_Value (COLUMNNAME_AD_Window_ID, Integer.valueOf(AD_Window_ID)); } /** Get Window. @return Data entry or display window */ public int getAD_Window_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Window_ID); if (ii == null) return 0; return ii.intValue(); } /** AccessLevel AD_Reference_ID=5 */ public static final int ACCESSLEVEL_AD_Reference_ID=5; /** Organization = 1 */ public static final String ACCESSLEVEL_Organization = "1"; /** Client+Organization = 3 */ public static final String ACCESSLEVEL_ClientPlusOrganization = "3"; /** System only = 4 */ public static final String ACCESSLEVEL_SystemOnly = "4"; /** All = 7 */ public static final String ACCESSLEVEL_All = "7"; /** System+Client = 6 */ public static final String ACCESSLEVEL_SystemPlusClient = "6"; /** Client only = 2 */ public static final String ACCESSLEVEL_ClientOnly = "2"; /** Set Data Access Level. @param AccessLevel Access Level required */ public void setAccessLevel (String AccessLevel) { set_Value (COLUMNNAME_AccessLevel, AccessLevel); } /** Get Data Access Level. @return Access Level required */ public String getAccessLevel () { return (String)get_Value(COLUMNNAME_AccessLevel); } /** Set Column No. @param ColumnNo Dashboard content column number */ public void setColumnNo (int ColumnNo) { set_Value (COLUMNNAME_ColumnNo, Integer.valueOf(ColumnNo)); } /** Get Column No. @return Dashboard content column number */ public int getColumnNo () { Integer ii = (Integer)get_Value(COLUMNNAME_ColumnNo); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** GoalDisplay AD_Reference_ID=53316 */ public static final int GOALDISPLAY_AD_Reference_ID=53316; /** HTML Table = T */ public static final String GOALDISPLAY_HTMLTable = "T"; /** Chart = C */ public static final String GOALDISPLAY_Chart = "C"; /** Set Goal Display. @param GoalDisplay Type of goal display on dashboard */ public void setGoalDisplay (String GoalDisplay) { set_Value (COLUMNNAME_GoalDisplay, GoalDisplay); } /** Get Goal Display. @return Type of goal display on dashboard */ public String getGoalDisplay () { return (String)get_Value(COLUMNNAME_GoalDisplay); } /** Set HTML. @param HTML HTML */ public void setHTML (String HTML) { set_Value (COLUMNNAME_HTML, HTML); } /** Get HTML. @return HTML */ public String getHTML () { return (String)get_Value(COLUMNNAME_HTML); } /** Set Collapsible. @param IsCollapsible Flag to indicate the state of the dashboard panel */ public void setIsCollapsible (boolean IsCollapsible) { set_Value (COLUMNNAME_IsCollapsible, Boolean.valueOf(IsCollapsible)); } /** Get Collapsible. @return Flag to indicate the state of the dashboard panel */ public boolean isCollapsible () { Object oo = get_Value(COLUMNNAME_IsCollapsible); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set IsEventRequired. @param IsEventRequired IsEventRequired */ public void setIsEventRequired (boolean IsEventRequired) { set_Value (COLUMNNAME_IsEventRequired, Boolean.valueOf(IsEventRequired)); } /** Get IsEventRequired. @return IsEventRequired */ public boolean isEventRequired () { Object oo = get_Value(COLUMNNAME_IsEventRequired); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Open By Default. @param IsOpenByDefault Open By Default */ public void setIsOpenByDefault (boolean IsOpenByDefault) { set_Value (COLUMNNAME_IsOpenByDefault, Boolean.valueOf(IsOpenByDefault)); } /** Get Open By Default. @return Open By Default */ public boolean isOpenByDefault () { Object oo = get_Value(COLUMNNAME_IsOpenByDefault); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Line No. @param Line Unique line for this document */ public void setLine (int Line) { set_Value (COLUMNNAME_Line, Integer.valueOf(Line)); } /** Get Line No. @return Unique line for this document */ public int getLine () { Integer ii = (Integer)get_Value(COLUMNNAME_Line); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Dashboard Content. @param PA_DashboardContent_ID Dashboard Content */ public void setPA_DashboardContent_ID (int PA_DashboardContent_ID) { if (PA_DashboardContent_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_DashboardContent_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_DashboardContent_ID, Integer.valueOf(PA_DashboardContent_ID)); } /** Get Dashboard Content. @return Dashboard Content */ public int getPA_DashboardContent_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_DashboardContent_ID); if (ii == null) return 0; return ii.intValue(); } public org.compiere.model.I_PA_Goal getPA_Goal() throws RuntimeException { return (org.compiere.model.I_PA_Goal)MTable.get(getCtx(), org.compiere.model.I_PA_Goal.Table_Name) .getPO(getPA_Goal_ID(), get_TrxName()); } /** Set Goal. @param PA_Goal_ID Performance Goal */ public void setPA_Goal_ID (int PA_Goal_ID) { if (PA_Goal_ID < 1) set_Value (COLUMNNAME_PA_Goal_ID, null); else set_Value (COLUMNNAME_PA_Goal_ID, Integer.valueOf(PA_Goal_ID)); } /** Get Goal. @return Performance Goal */ public int getPA_Goal_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_Goal_ID); if (ii == null) return 0; return ii.intValue(); } /** Set PageSize. @param PageSize PageSize */ public void setPageSize (BigDecimal PageSize) { set_Value (COLUMNNAME_PageSize, PageSize); } /** Get PageSize. @return PageSize */ public BigDecimal getPageSize () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PageSize); if (bd == null) return Env.ZERO; return bd; } /** Set Immutable Universally Unique Identifier. @param UUID Immutable Universally Unique Identifier */ public void setUUID (String UUID) { set_Value (COLUMNNAME_UUID, UUID); } /** Get Immutable Universally Unique Identifier. @return Immutable Universally Unique Identifier */ public String getUUID () { return (String)get_Value(COLUMNNAME_UUID); } public org.adempiere.model.I_AD_Browse_Field getZoom_Field() throws RuntimeException { return (org.adempiere.model.I_AD_Browse_Field)MTable.get(getCtx(), org.adempiere.model.I_AD_Browse_Field.Table_Name) .getPO(getZoom_Field_ID(), get_TrxName()); } /** Set Zoom_Field_ID. @param Zoom_Field_ID Zoom_Field_ID */ public void setZoom_Field_ID (int Zoom_Field_ID) { if (Zoom_Field_ID < 1) set_Value (COLUMNNAME_Zoom_Field_ID, null); else set_Value (COLUMNNAME_Zoom_Field_ID, Integer.valueOf(Zoom_Field_ID)); } /** Get Zoom_Field_ID. @return Zoom_Field_ID */ public int getZoom_Field_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Zoom_Field_ID); if (ii == null) return 0; return ii.intValue(); } public org.compiere.model.I_AD_Tab getZoom_Tab() throws RuntimeException { return (org.compiere.model.I_AD_Tab)MTable.get(getCtx(), org.compiere.model.I_AD_Tab.Table_Name) .getPO(getZoom_Tab_ID(), get_TrxName()); } /** Set Zoom_Tab_ID. @param Zoom_Tab_ID Zoom_Tab_ID */ public void setZoom_Tab_ID (int Zoom_Tab_ID) { if (Zoom_Tab_ID < 1) set_Value (COLUMNNAME_Zoom_Tab_ID, null); else set_Value (COLUMNNAME_Zoom_Tab_ID, Integer.valueOf(Zoom_Tab_ID)); } /** Get Zoom_Tab_ID. @return Zoom_Tab_ID */ public int getZoom_Tab_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Zoom_Tab_ID); if (ii == null) return 0; return ii.intValue(); } public org.compiere.model.I_AD_Window getZoom_Window() throws RuntimeException { return (org.compiere.model.I_AD_Window)MTable.get(getCtx(), org.compiere.model.I_AD_Window.Table_Name) .getPO(getZoom_Window_ID(), get_TrxName()); } /** Set Zoom_Window_ID. @param Zoom_Window_ID Zoom_Window_ID */ public void setZoom_Window_ID (int Zoom_Window_ID) { if (Zoom_Window_ID < 1) set_Value (COLUMNNAME_Zoom_Window_ID, null); else set_Value (COLUMNNAME_Zoom_Window_ID, Integer.valueOf(Zoom_Window_ID)); } /** Get Zoom_Window_ID. @return Zoom_Window_ID */ public int getZoom_Window_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Zoom_Window_ID); if (ii == null) return 0; return ii.intValue(); } /** Set ZUL File Path. @param ZulFilePath Absolute path to zul file */ public void setZulFilePath (String ZulFilePath) { set_Value (COLUMNNAME_ZulFilePath, ZulFilePath); } /** Get ZUL File Path. @return Absolute path to zul file */ public String getZulFilePath () { return (String)get_Value(COLUMNNAME_ZulFilePath); } /** onevent AD_Reference_ID=53574 */ public static final int ONEVENT_AD_Reference_ID=53574; /** onClick = onClick */ public static final String ONEVENT_OnClick = "onClick"; /** onDoubleClick = onDoubleClick */ public static final String ONEVENT_OnDoubleClick = "onDoubleClick"; /** Set onevent. @param onevent onevent */ public void setonevent (String onevent) { set_Value (COLUMNNAME_onevent, onevent); } /** Get onevent. @return onevent */ public String getonevent () { return (String)get_Value(COLUMNNAME_onevent); } }
EmerisScala/adempiere
base/src/org/compiere/model/X_PA_DashboardContent.java
4,689
/** Set onevent. @param onevent onevent */
block_comment
nl
/****************************************************************************** * Product: ADempiere ERP & CRM Smart Business Solution * * Copyright (C) 2006-2017 ADempiere Foundation, All Rights Reserved. * * This program is free software, you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * * or (at your option) any later version. * * by the Free Software Foundation. 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, write to the Free Software Foundation, Inc., * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * For the text or an alternative of this public license, you may reach us * * or via [email protected] or http://www.adempiere.net/license.html * *****************************************************************************/ /** Generated Model - DO NOT CHANGE */ package org.compiere.model; import java.math.BigDecimal; import java.sql.ResultSet; import java.util.Properties; import org.compiere.util.Env; import org.compiere.util.KeyNamePair; /** Generated Model for PA_DashboardContent * @author Adempiere (generated) * @version Release 3.9.2 - $Id$ */ public class X_PA_DashboardContent extends PO implements I_PA_DashboardContent, I_Persistent { /** * */ private static final long serialVersionUID = 20191120L; /** Standard Constructor */ public X_PA_DashboardContent (Properties ctx, int PA_DashboardContent_ID, String trxName) { super (ctx, PA_DashboardContent_ID, trxName); /** if (PA_DashboardContent_ID == 0) { setIsCollapsible (true); // Y setName (null); setPA_DashboardContent_ID (0); } */ } /** Load Constructor */ public X_PA_DashboardContent (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** AccessLevel * @return 6 - System - Client */ protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_PA_DashboardContent[") .append(get_ID()).append("]"); return sb.toString(); } public org.adempiere.model.I_AD_Browse getAD_Browse() throws RuntimeException { return (org.adempiere.model.I_AD_Browse)MTable.get(getCtx(), org.adempiere.model.I_AD_Browse.Table_Name) .getPO(getAD_Browse_ID(), get_TrxName()); } /** Set Smart Browse. @param AD_Browse_ID Smart Browse */ public void setAD_Browse_ID (int AD_Browse_ID) { if (AD_Browse_ID < 1) set_Value (COLUMNNAME_AD_Browse_ID, null); else set_Value (COLUMNNAME_AD_Browse_ID, Integer.valueOf(AD_Browse_ID)); } /** Get Smart Browse. @return Smart Browse */ public int getAD_Browse_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Browse_ID); if (ii == null) return 0; return ii.intValue(); } public org.compiere.model.I_AD_Window getAD_Window() throws RuntimeException { return (org.compiere.model.I_AD_Window)MTable.get(getCtx(), org.compiere.model.I_AD_Window.Table_Name) .getPO(getAD_Window_ID(), get_TrxName()); } /** Set Window. @param AD_Window_ID Data entry or display window */ public void setAD_Window_ID (int AD_Window_ID) { if (AD_Window_ID < 1) set_Value (COLUMNNAME_AD_Window_ID, null); else set_Value (COLUMNNAME_AD_Window_ID, Integer.valueOf(AD_Window_ID)); } /** Get Window. @return Data entry or display window */ public int getAD_Window_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Window_ID); if (ii == null) return 0; return ii.intValue(); } /** AccessLevel AD_Reference_ID=5 */ public static final int ACCESSLEVEL_AD_Reference_ID=5; /** Organization = 1 */ public static final String ACCESSLEVEL_Organization = "1"; /** Client+Organization = 3 */ public static final String ACCESSLEVEL_ClientPlusOrganization = "3"; /** System only = 4 */ public static final String ACCESSLEVEL_SystemOnly = "4"; /** All = 7 */ public static final String ACCESSLEVEL_All = "7"; /** System+Client = 6 */ public static final String ACCESSLEVEL_SystemPlusClient = "6"; /** Client only = 2 */ public static final String ACCESSLEVEL_ClientOnly = "2"; /** Set Data Access Level. @param AccessLevel Access Level required */ public void setAccessLevel (String AccessLevel) { set_Value (COLUMNNAME_AccessLevel, AccessLevel); } /** Get Data Access Level. @return Access Level required */ public String getAccessLevel () { return (String)get_Value(COLUMNNAME_AccessLevel); } /** Set Column No. @param ColumnNo Dashboard content column number */ public void setColumnNo (int ColumnNo) { set_Value (COLUMNNAME_ColumnNo, Integer.valueOf(ColumnNo)); } /** Get Column No. @return Dashboard content column number */ public int getColumnNo () { Integer ii = (Integer)get_Value(COLUMNNAME_ColumnNo); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** GoalDisplay AD_Reference_ID=53316 */ public static final int GOALDISPLAY_AD_Reference_ID=53316; /** HTML Table = T */ public static final String GOALDISPLAY_HTMLTable = "T"; /** Chart = C */ public static final String GOALDISPLAY_Chart = "C"; /** Set Goal Display. @param GoalDisplay Type of goal display on dashboard */ public void setGoalDisplay (String GoalDisplay) { set_Value (COLUMNNAME_GoalDisplay, GoalDisplay); } /** Get Goal Display. @return Type of goal display on dashboard */ public String getGoalDisplay () { return (String)get_Value(COLUMNNAME_GoalDisplay); } /** Set HTML. @param HTML HTML */ public void setHTML (String HTML) { set_Value (COLUMNNAME_HTML, HTML); } /** Get HTML. @return HTML */ public String getHTML () { return (String)get_Value(COLUMNNAME_HTML); } /** Set Collapsible. @param IsCollapsible Flag to indicate the state of the dashboard panel */ public void setIsCollapsible (boolean IsCollapsible) { set_Value (COLUMNNAME_IsCollapsible, Boolean.valueOf(IsCollapsible)); } /** Get Collapsible. @return Flag to indicate the state of the dashboard panel */ public boolean isCollapsible () { Object oo = get_Value(COLUMNNAME_IsCollapsible); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set IsEventRequired. @param IsEventRequired IsEventRequired */ public void setIsEventRequired (boolean IsEventRequired) { set_Value (COLUMNNAME_IsEventRequired, Boolean.valueOf(IsEventRequired)); } /** Get IsEventRequired. @return IsEventRequired */ public boolean isEventRequired () { Object oo = get_Value(COLUMNNAME_IsEventRequired); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Open By Default. @param IsOpenByDefault Open By Default */ public void setIsOpenByDefault (boolean IsOpenByDefault) { set_Value (COLUMNNAME_IsOpenByDefault, Boolean.valueOf(IsOpenByDefault)); } /** Get Open By Default. @return Open By Default */ public boolean isOpenByDefault () { Object oo = get_Value(COLUMNNAME_IsOpenByDefault); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Line No. @param Line Unique line for this document */ public void setLine (int Line) { set_Value (COLUMNNAME_Line, Integer.valueOf(Line)); } /** Get Line No. @return Unique line for this document */ public int getLine () { Integer ii = (Integer)get_Value(COLUMNNAME_Line); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Dashboard Content. @param PA_DashboardContent_ID Dashboard Content */ public void setPA_DashboardContent_ID (int PA_DashboardContent_ID) { if (PA_DashboardContent_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_DashboardContent_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_DashboardContent_ID, Integer.valueOf(PA_DashboardContent_ID)); } /** Get Dashboard Content. @return Dashboard Content */ public int getPA_DashboardContent_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_DashboardContent_ID); if (ii == null) return 0; return ii.intValue(); } public org.compiere.model.I_PA_Goal getPA_Goal() throws RuntimeException { return (org.compiere.model.I_PA_Goal)MTable.get(getCtx(), org.compiere.model.I_PA_Goal.Table_Name) .getPO(getPA_Goal_ID(), get_TrxName()); } /** Set Goal. @param PA_Goal_ID Performance Goal */ public void setPA_Goal_ID (int PA_Goal_ID) { if (PA_Goal_ID < 1) set_Value (COLUMNNAME_PA_Goal_ID, null); else set_Value (COLUMNNAME_PA_Goal_ID, Integer.valueOf(PA_Goal_ID)); } /** Get Goal. @return Performance Goal */ public int getPA_Goal_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_Goal_ID); if (ii == null) return 0; return ii.intValue(); } /** Set PageSize. @param PageSize PageSize */ public void setPageSize (BigDecimal PageSize) { set_Value (COLUMNNAME_PageSize, PageSize); } /** Get PageSize. @return PageSize */ public BigDecimal getPageSize () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PageSize); if (bd == null) return Env.ZERO; return bd; } /** Set Immutable Universally Unique Identifier. @param UUID Immutable Universally Unique Identifier */ public void setUUID (String UUID) { set_Value (COLUMNNAME_UUID, UUID); } /** Get Immutable Universally Unique Identifier. @return Immutable Universally Unique Identifier */ public String getUUID () { return (String)get_Value(COLUMNNAME_UUID); } public org.adempiere.model.I_AD_Browse_Field getZoom_Field() throws RuntimeException { return (org.adempiere.model.I_AD_Browse_Field)MTable.get(getCtx(), org.adempiere.model.I_AD_Browse_Field.Table_Name) .getPO(getZoom_Field_ID(), get_TrxName()); } /** Set Zoom_Field_ID. @param Zoom_Field_ID Zoom_Field_ID */ public void setZoom_Field_ID (int Zoom_Field_ID) { if (Zoom_Field_ID < 1) set_Value (COLUMNNAME_Zoom_Field_ID, null); else set_Value (COLUMNNAME_Zoom_Field_ID, Integer.valueOf(Zoom_Field_ID)); } /** Get Zoom_Field_ID. @return Zoom_Field_ID */ public int getZoom_Field_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Zoom_Field_ID); if (ii == null) return 0; return ii.intValue(); } public org.compiere.model.I_AD_Tab getZoom_Tab() throws RuntimeException { return (org.compiere.model.I_AD_Tab)MTable.get(getCtx(), org.compiere.model.I_AD_Tab.Table_Name) .getPO(getZoom_Tab_ID(), get_TrxName()); } /** Set Zoom_Tab_ID. @param Zoom_Tab_ID Zoom_Tab_ID */ public void setZoom_Tab_ID (int Zoom_Tab_ID) { if (Zoom_Tab_ID < 1) set_Value (COLUMNNAME_Zoom_Tab_ID, null); else set_Value (COLUMNNAME_Zoom_Tab_ID, Integer.valueOf(Zoom_Tab_ID)); } /** Get Zoom_Tab_ID. @return Zoom_Tab_ID */ public int getZoom_Tab_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Zoom_Tab_ID); if (ii == null) return 0; return ii.intValue(); } public org.compiere.model.I_AD_Window getZoom_Window() throws RuntimeException { return (org.compiere.model.I_AD_Window)MTable.get(getCtx(), org.compiere.model.I_AD_Window.Table_Name) .getPO(getZoom_Window_ID(), get_TrxName()); } /** Set Zoom_Window_ID. @param Zoom_Window_ID Zoom_Window_ID */ public void setZoom_Window_ID (int Zoom_Window_ID) { if (Zoom_Window_ID < 1) set_Value (COLUMNNAME_Zoom_Window_ID, null); else set_Value (COLUMNNAME_Zoom_Window_ID, Integer.valueOf(Zoom_Window_ID)); } /** Get Zoom_Window_ID. @return Zoom_Window_ID */ public int getZoom_Window_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Zoom_Window_ID); if (ii == null) return 0; return ii.intValue(); } /** Set ZUL File Path. @param ZulFilePath Absolute path to zul file */ public void setZulFilePath (String ZulFilePath) { set_Value (COLUMNNAME_ZulFilePath, ZulFilePath); } /** Get ZUL File Path. @return Absolute path to zul file */ public String getZulFilePath () { return (String)get_Value(COLUMNNAME_ZulFilePath); } /** onevent AD_Reference_ID=53574 */ public static final int ONEVENT_AD_Reference_ID=53574; /** onClick = onClick */ public static final String ONEVENT_OnClick = "onClick"; /** onDoubleClick = onDoubleClick */ public static final String ONEVENT_OnDoubleClick = "onDoubleClick"; /** Set onevent. <SUF>*/ public void setonevent (String onevent) { set_Value (COLUMNNAME_onevent, onevent); } /** Get onevent. @return onevent */ public String getonevent () { return (String)get_Value(COLUMNNAME_onevent); } }
121928_3
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,163
//TODO Maak gebruik van accessible boolean in Hexagon om te bepalen of je er op kan lopen.
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 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<SUF> 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; } }
20837_6
/* * SPDX-FileCopyrightText: 2021 Atos * SPDX-License-Identifier: EUPL-1.2+ */ package net.atos.client.zgw.zrc.model; import java.net.URI; import java.time.LocalDate; import java.util.Set; import java.util.stream.Collectors; import javax.ws.rs.QueryParam; import org.apache.commons.collections4.CollectionUtils; import net.atos.client.zgw.shared.model.AbstractListParameters; import net.atos.client.zgw.shared.model.Archiefnominatie; import net.atos.client.zgw.shared.model.Vertrouwelijkheidaanduiding; import net.atos.client.zgw.ztc.model.AardVanRol; /** * */ public class ZaakListParameters extends AbstractListParameters { /** * De unieke identificatie van de ZAAK binnen de organisatie die verantwoordelijk is voor de behandeling van de ZAAK. */ @QueryParam("identificatie") private String identificatie; /** * Het RSIN van de Niet-natuurlijk persoon zijnde de organisatie die de zaak heeft gecreeerd. * Dit moet een geldig RSIN zijn van 9 nummers en voldoen aan https://nl.wikipedia.org/wiki/Burgerservicenummer#11-proef */ @QueryParam("bronorganisatie") private String bronorganisatie; /** * URL-referentie naar het ZAAKTYPE (in de Catalogi API) in de CATALOGUS waar deze voorkomt */ @QueryParam("zaaktype") private URI zaaktype; /** * Aanduiding of het zaakdossier blijvend bewaard of na een bepaalde termijn vernietigd moet worden. */ private Archiefnominatie archiefnominatie; private Set<Archiefnominatie> archiefnominatieIn; /** * De datum waarop het gearchiveerde zaakdossier vernietigd moet worden dan wel overgebracht moet worden naar een archiefbewaarplaats. * Wordt automatisch berekend bij het aanmaken of wijzigen van een RESULTAAT aan deze ZAAK indien nog leeg. */ @QueryParam("archiefactiedatum") private LocalDate archiefactiedatum; @QueryParam("archiefactiedatum__lt") private LocalDate archiefactiedatumLessThan; @QueryParam("archiefactiedatum__gt") private LocalDate archiefactiedatumGreaterThan; /** * Aanduiding of het zaakdossier blijvend bewaard of na een bepaalde termijn vernietigd moet worden. */ private Archiefstatus archiefstatus; private Set<Archiefstatus> archiefstatusIn; /** * De datum waarop met de uitvoering van de zaak is gestart */ @QueryParam("startdatum") private LocalDate startdatum; @QueryParam("startdatum__gt") private LocalDate startdatumGreaterThan; @QueryParam("startdatum__gte") private LocalDate startdatumGreaterThanOrEqual; @QueryParam("startdatum__lt") private LocalDate startdatumLessThan; @QueryParam("startdatum__lte") private LocalDate startdatumLessThanOrEqual; /** * Type van de `betrokkene` */ private BetrokkeneType rolBetrokkeneType; /** * URL-referentie naar een betrokkene gerelateerd aan de ZAAK. */ @QueryParam("rol__betrokkene") private URI rolBetrokkene; /** * Algemeen gehanteerde benaming van de aard van de ROL, afgeleid uit het ROLTYPE. */ private AardVanRol rolOmschrijvingGeneriek; /** * Zaken met een vertrouwelijkheidaanduiding die beperkter is dan de aangegeven aanduiding worden uit de resultaten gefiltered. */ private Vertrouwelijkheidaanduiding maximaleVertrouwelijkheidaanduiding; /** * Het burgerservicenummer, bedoeld in artikel 1.1 van de Wet algemene bepalingen burgerservicenummer. */ @QueryParam("rol__betrokkeneIdentificatie__natuurlijkPersoon__inpBsn") private String rolBetrokkeneIdentificatieNatuurlijkPersoonInpBsn; /** * Een korte unieke aanduiding van de MEDEWERKER. */ @QueryParam("rol__betrokkeneIdentificatie__medewerker__identificatie") private String rolBetrokkeneIdentificatieMedewerkerIdentificatie; /** * Een korte identificatie van de organisatorische eenheid. */ @QueryParam("rol__betrokkeneIdentificatie__organisatorischeEenheid__identificatie") private String rolBetrokkeneIdentificatieOrganisatorischeEenheidIdentificatie; /** * Which field to use when ordering the results, * [field] voor asc en -[field] voor desc */ @QueryParam("ordering") private String ordering; public String getIdentificatie() { return identificatie; } public void setIdentificatie(final String identificatie) { this.identificatie = identificatie; } public String getBronorganisatie() { return bronorganisatie; } public void setBronorganisatie(final String bronorganisatie) { this.bronorganisatie = bronorganisatie; } public URI getZaaktype() { return zaaktype; } public void setZaaktype(final URI zaaktype) { this.zaaktype = zaaktype; } @QueryParam("archiefnominatie") public String getArchiefnominatie() { return archiefnominatie != null ? archiefnominatie.getValue() : null; } public void setArchiefnominatie(final Archiefnominatie archiefnominatie) { this.archiefnominatie = archiefnominatie; } @QueryParam("archiefnominatie__in") public String getArchiefnominatieIn() { if (CollectionUtils.isNotEmpty(archiefnominatieIn)) { return archiefnominatieIn.stream() .map(Archiefnominatie::getValue) .collect(Collectors.joining(",")); } else { return null; } } public void setArchiefnominatieIn(final Set<Archiefnominatie> archiefnominatieIn) { this.archiefnominatieIn = archiefnominatieIn; } public LocalDate getArchiefactiedatum() { return archiefactiedatum; } public void setArchiefactiedatum(final LocalDate archiefactiedatum) { this.archiefactiedatum = archiefactiedatum; } public LocalDate getArchiefactiedatumLessThan() { return archiefactiedatumLessThan; } public void setArchiefactiedatumLessThan(final LocalDate archiefactiedatumLessThan) { this.archiefactiedatumLessThan = archiefactiedatumLessThan; } public LocalDate getArchiefactiedatumGreaterThan() { return archiefactiedatumGreaterThan; } public void setArchiefactiedatumGreaterThan(final LocalDate archiefactiedatumGreaterThan) { this.archiefactiedatumGreaterThan = archiefactiedatumGreaterThan; } @QueryParam("archiefstatus") public String getArchiefstatus() { return archiefstatus != null ? archiefstatus.toValue() : null; } public void setArchiefstatus(final Archiefstatus archiefstatus) { this.archiefstatus = archiefstatus; } @QueryParam("archiefstatus__in") public String getArchiefstatusIn() { if (CollectionUtils.isNotEmpty(archiefstatusIn)) { return archiefstatusIn.stream() .map(Archiefstatus::toValue) .collect(Collectors.joining(",")); } else { return null; } } public void setArchiefstatusIn(final Set<Archiefstatus> archiefstatusIn) { this.archiefstatusIn = archiefstatusIn; } public LocalDate getStartdatum() { return startdatum; } public void setStartdatum(final LocalDate startdatum) { this.startdatum = startdatum; } public LocalDate getStartdatumGreaterThan() { return startdatumGreaterThan; } public void setStartdatumGreaterThan(final LocalDate startdatumGreaterThan) { this.startdatumGreaterThan = startdatumGreaterThan; } public LocalDate getStartdatumGreaterThanOrEqual() { return startdatumGreaterThanOrEqual; } public void setStartdatumGreaterThanOrEqual(final LocalDate startdatumGreaterThanOrEqual) { this.startdatumGreaterThanOrEqual = startdatumGreaterThanOrEqual; } public LocalDate getStartdatumLessThan() { return startdatumLessThan; } public void setStartdatumLessThan(final LocalDate startdatumLessThan) { this.startdatumLessThan = startdatumLessThan; } public LocalDate getStartdatumLessThanOrEqual() { return startdatumLessThanOrEqual; } public void setStartdatumLessThanOrEqual(final LocalDate startdatumLessThanOrEqual) { this.startdatumLessThanOrEqual = startdatumLessThanOrEqual; } @QueryParam("rol__betrokkeneType") public String getRolBetrokkeneType() { return rolBetrokkeneType != null ? rolBetrokkeneType.toValue() : null; } public void setRolBetrokkeneType(final BetrokkeneType rolBetrokkeneType) { this.rolBetrokkeneType = rolBetrokkeneType; } public URI getRolBetrokkene() { return rolBetrokkene; } public void setRolBetrokkene(final URI rolBetrokkene) { this.rolBetrokkene = rolBetrokkene; } @QueryParam("rol__omschrijvingGeneriek") public String getRolOmschrijvingGeneriek() { return rolOmschrijvingGeneriek != null ? rolOmschrijvingGeneriek.toValue() : null; } public void setRolOmschrijvingGeneriek(final AardVanRol rolOmschrijvingGeneriek) { this.rolOmschrijvingGeneriek = rolOmschrijvingGeneriek; } @QueryParam("maximaleVertrouwelijkheidaanduiding") public String getMaximaleVertrouwelijkheidaanduiding() { return maximaleVertrouwelijkheidaanduiding != null ? maximaleVertrouwelijkheidaanduiding.toValue() : null; } public void setMaximaleVertrouwelijkheidaanduiding(final Vertrouwelijkheidaanduiding maximaleVertrouwelijkheidaanduiding) { this.maximaleVertrouwelijkheidaanduiding = maximaleVertrouwelijkheidaanduiding; } public String getRolBetrokkeneIdentificatieNatuurlijkPersoonInpBsn() { return rolBetrokkeneIdentificatieNatuurlijkPersoonInpBsn; } public void setRolBetrokkeneIdentificatieNatuurlijkPersoonInpBsn(final String rolBetrokkeneIdentificatieNatuurlijkPersoonInpBsn) { this.rolBetrokkeneIdentificatieNatuurlijkPersoonInpBsn = rolBetrokkeneIdentificatieNatuurlijkPersoonInpBsn; } public String getRolBetrokkeneIdentificatieMedewerkerIdentificatie() { return rolBetrokkeneIdentificatieMedewerkerIdentificatie; } public void setRolBetrokkeneIdentificatieMedewerkerIdentificatie(final String rolBetrokkeneIdentificatieMedewerkerIdentificatie) { this.rolBetrokkeneIdentificatieMedewerkerIdentificatie = rolBetrokkeneIdentificatieMedewerkerIdentificatie; } public String getRolBetrokkeneIdentificatieOrganisatorischeEenheidIdentificatie() { return rolBetrokkeneIdentificatieOrganisatorischeEenheidIdentificatie; } public void setRolBetrokkeneIdentificatieOrganisatorischeEenheidIdentificatie(final String rolBetrokkeneIdentificatieOrganisatorischeEenheidIdentificatie) { this.rolBetrokkeneIdentificatieOrganisatorischeEenheidIdentificatie = rolBetrokkeneIdentificatieOrganisatorischeEenheidIdentificatie; } public String getOrdering() { return ordering; } public void setOrdering(final String ordering) { this.ordering = ordering; } }
bartlukens/zaakafhandelcomponent
src/main/java/net/atos/client/zgw/zrc/model/ZaakListParameters.java
2,970
/** * Aanduiding of het zaakdossier blijvend bewaard of na een bepaalde termijn vernietigd moet worden. */
block_comment
nl
/* * SPDX-FileCopyrightText: 2021 Atos * SPDX-License-Identifier: EUPL-1.2+ */ package net.atos.client.zgw.zrc.model; import java.net.URI; import java.time.LocalDate; import java.util.Set; import java.util.stream.Collectors; import javax.ws.rs.QueryParam; import org.apache.commons.collections4.CollectionUtils; import net.atos.client.zgw.shared.model.AbstractListParameters; import net.atos.client.zgw.shared.model.Archiefnominatie; import net.atos.client.zgw.shared.model.Vertrouwelijkheidaanduiding; import net.atos.client.zgw.ztc.model.AardVanRol; /** * */ public class ZaakListParameters extends AbstractListParameters { /** * De unieke identificatie van de ZAAK binnen de organisatie die verantwoordelijk is voor de behandeling van de ZAAK. */ @QueryParam("identificatie") private String identificatie; /** * Het RSIN van de Niet-natuurlijk persoon zijnde de organisatie die de zaak heeft gecreeerd. * Dit moet een geldig RSIN zijn van 9 nummers en voldoen aan https://nl.wikipedia.org/wiki/Burgerservicenummer#11-proef */ @QueryParam("bronorganisatie") private String bronorganisatie; /** * URL-referentie naar het ZAAKTYPE (in de Catalogi API) in de CATALOGUS waar deze voorkomt */ @QueryParam("zaaktype") private URI zaaktype; /** * Aanduiding of het zaakdossier blijvend bewaard of na een bepaalde termijn vernietigd moet worden. */ private Archiefnominatie archiefnominatie; private Set<Archiefnominatie> archiefnominatieIn; /** * De datum waarop het gearchiveerde zaakdossier vernietigd moet worden dan wel overgebracht moet worden naar een archiefbewaarplaats. * Wordt automatisch berekend bij het aanmaken of wijzigen van een RESULTAAT aan deze ZAAK indien nog leeg. */ @QueryParam("archiefactiedatum") private LocalDate archiefactiedatum; @QueryParam("archiefactiedatum__lt") private LocalDate archiefactiedatumLessThan; @QueryParam("archiefactiedatum__gt") private LocalDate archiefactiedatumGreaterThan; /** * Aanduiding of het<SUF>*/ private Archiefstatus archiefstatus; private Set<Archiefstatus> archiefstatusIn; /** * De datum waarop met de uitvoering van de zaak is gestart */ @QueryParam("startdatum") private LocalDate startdatum; @QueryParam("startdatum__gt") private LocalDate startdatumGreaterThan; @QueryParam("startdatum__gte") private LocalDate startdatumGreaterThanOrEqual; @QueryParam("startdatum__lt") private LocalDate startdatumLessThan; @QueryParam("startdatum__lte") private LocalDate startdatumLessThanOrEqual; /** * Type van de `betrokkene` */ private BetrokkeneType rolBetrokkeneType; /** * URL-referentie naar een betrokkene gerelateerd aan de ZAAK. */ @QueryParam("rol__betrokkene") private URI rolBetrokkene; /** * Algemeen gehanteerde benaming van de aard van de ROL, afgeleid uit het ROLTYPE. */ private AardVanRol rolOmschrijvingGeneriek; /** * Zaken met een vertrouwelijkheidaanduiding die beperkter is dan de aangegeven aanduiding worden uit de resultaten gefiltered. */ private Vertrouwelijkheidaanduiding maximaleVertrouwelijkheidaanduiding; /** * Het burgerservicenummer, bedoeld in artikel 1.1 van de Wet algemene bepalingen burgerservicenummer. */ @QueryParam("rol__betrokkeneIdentificatie__natuurlijkPersoon__inpBsn") private String rolBetrokkeneIdentificatieNatuurlijkPersoonInpBsn; /** * Een korte unieke aanduiding van de MEDEWERKER. */ @QueryParam("rol__betrokkeneIdentificatie__medewerker__identificatie") private String rolBetrokkeneIdentificatieMedewerkerIdentificatie; /** * Een korte identificatie van de organisatorische eenheid. */ @QueryParam("rol__betrokkeneIdentificatie__organisatorischeEenheid__identificatie") private String rolBetrokkeneIdentificatieOrganisatorischeEenheidIdentificatie; /** * Which field to use when ordering the results, * [field] voor asc en -[field] voor desc */ @QueryParam("ordering") private String ordering; public String getIdentificatie() { return identificatie; } public void setIdentificatie(final String identificatie) { this.identificatie = identificatie; } public String getBronorganisatie() { return bronorganisatie; } public void setBronorganisatie(final String bronorganisatie) { this.bronorganisatie = bronorganisatie; } public URI getZaaktype() { return zaaktype; } public void setZaaktype(final URI zaaktype) { this.zaaktype = zaaktype; } @QueryParam("archiefnominatie") public String getArchiefnominatie() { return archiefnominatie != null ? archiefnominatie.getValue() : null; } public void setArchiefnominatie(final Archiefnominatie archiefnominatie) { this.archiefnominatie = archiefnominatie; } @QueryParam("archiefnominatie__in") public String getArchiefnominatieIn() { if (CollectionUtils.isNotEmpty(archiefnominatieIn)) { return archiefnominatieIn.stream() .map(Archiefnominatie::getValue) .collect(Collectors.joining(",")); } else { return null; } } public void setArchiefnominatieIn(final Set<Archiefnominatie> archiefnominatieIn) { this.archiefnominatieIn = archiefnominatieIn; } public LocalDate getArchiefactiedatum() { return archiefactiedatum; } public void setArchiefactiedatum(final LocalDate archiefactiedatum) { this.archiefactiedatum = archiefactiedatum; } public LocalDate getArchiefactiedatumLessThan() { return archiefactiedatumLessThan; } public void setArchiefactiedatumLessThan(final LocalDate archiefactiedatumLessThan) { this.archiefactiedatumLessThan = archiefactiedatumLessThan; } public LocalDate getArchiefactiedatumGreaterThan() { return archiefactiedatumGreaterThan; } public void setArchiefactiedatumGreaterThan(final LocalDate archiefactiedatumGreaterThan) { this.archiefactiedatumGreaterThan = archiefactiedatumGreaterThan; } @QueryParam("archiefstatus") public String getArchiefstatus() { return archiefstatus != null ? archiefstatus.toValue() : null; } public void setArchiefstatus(final Archiefstatus archiefstatus) { this.archiefstatus = archiefstatus; } @QueryParam("archiefstatus__in") public String getArchiefstatusIn() { if (CollectionUtils.isNotEmpty(archiefstatusIn)) { return archiefstatusIn.stream() .map(Archiefstatus::toValue) .collect(Collectors.joining(",")); } else { return null; } } public void setArchiefstatusIn(final Set<Archiefstatus> archiefstatusIn) { this.archiefstatusIn = archiefstatusIn; } public LocalDate getStartdatum() { return startdatum; } public void setStartdatum(final LocalDate startdatum) { this.startdatum = startdatum; } public LocalDate getStartdatumGreaterThan() { return startdatumGreaterThan; } public void setStartdatumGreaterThan(final LocalDate startdatumGreaterThan) { this.startdatumGreaterThan = startdatumGreaterThan; } public LocalDate getStartdatumGreaterThanOrEqual() { return startdatumGreaterThanOrEqual; } public void setStartdatumGreaterThanOrEqual(final LocalDate startdatumGreaterThanOrEqual) { this.startdatumGreaterThanOrEqual = startdatumGreaterThanOrEqual; } public LocalDate getStartdatumLessThan() { return startdatumLessThan; } public void setStartdatumLessThan(final LocalDate startdatumLessThan) { this.startdatumLessThan = startdatumLessThan; } public LocalDate getStartdatumLessThanOrEqual() { return startdatumLessThanOrEqual; } public void setStartdatumLessThanOrEqual(final LocalDate startdatumLessThanOrEqual) { this.startdatumLessThanOrEqual = startdatumLessThanOrEqual; } @QueryParam("rol__betrokkeneType") public String getRolBetrokkeneType() { return rolBetrokkeneType != null ? rolBetrokkeneType.toValue() : null; } public void setRolBetrokkeneType(final BetrokkeneType rolBetrokkeneType) { this.rolBetrokkeneType = rolBetrokkeneType; } public URI getRolBetrokkene() { return rolBetrokkene; } public void setRolBetrokkene(final URI rolBetrokkene) { this.rolBetrokkene = rolBetrokkene; } @QueryParam("rol__omschrijvingGeneriek") public String getRolOmschrijvingGeneriek() { return rolOmschrijvingGeneriek != null ? rolOmschrijvingGeneriek.toValue() : null; } public void setRolOmschrijvingGeneriek(final AardVanRol rolOmschrijvingGeneriek) { this.rolOmschrijvingGeneriek = rolOmschrijvingGeneriek; } @QueryParam("maximaleVertrouwelijkheidaanduiding") public String getMaximaleVertrouwelijkheidaanduiding() { return maximaleVertrouwelijkheidaanduiding != null ? maximaleVertrouwelijkheidaanduiding.toValue() : null; } public void setMaximaleVertrouwelijkheidaanduiding(final Vertrouwelijkheidaanduiding maximaleVertrouwelijkheidaanduiding) { this.maximaleVertrouwelijkheidaanduiding = maximaleVertrouwelijkheidaanduiding; } public String getRolBetrokkeneIdentificatieNatuurlijkPersoonInpBsn() { return rolBetrokkeneIdentificatieNatuurlijkPersoonInpBsn; } public void setRolBetrokkeneIdentificatieNatuurlijkPersoonInpBsn(final String rolBetrokkeneIdentificatieNatuurlijkPersoonInpBsn) { this.rolBetrokkeneIdentificatieNatuurlijkPersoonInpBsn = rolBetrokkeneIdentificatieNatuurlijkPersoonInpBsn; } public String getRolBetrokkeneIdentificatieMedewerkerIdentificatie() { return rolBetrokkeneIdentificatieMedewerkerIdentificatie; } public void setRolBetrokkeneIdentificatieMedewerkerIdentificatie(final String rolBetrokkeneIdentificatieMedewerkerIdentificatie) { this.rolBetrokkeneIdentificatieMedewerkerIdentificatie = rolBetrokkeneIdentificatieMedewerkerIdentificatie; } public String getRolBetrokkeneIdentificatieOrganisatorischeEenheidIdentificatie() { return rolBetrokkeneIdentificatieOrganisatorischeEenheidIdentificatie; } public void setRolBetrokkeneIdentificatieOrganisatorischeEenheidIdentificatie(final String rolBetrokkeneIdentificatieOrganisatorischeEenheidIdentificatie) { this.rolBetrokkeneIdentificatieOrganisatorischeEenheidIdentificatie = rolBetrokkeneIdentificatieOrganisatorischeEenheidIdentificatie; } public String getOrdering() { return ordering; } public void setOrdering(final String ordering) { this.ordering = ordering; } }
47878_3
package com.fsd.inventopilot.dtos; import lombok.Data; @Data public class JwtAuthResponse { private String jwt; // Deze wordt meegestuurd voor de opdrachten meegestuurd met de response, // zodat hij kan worden getest in postman met een dummy functie. // In de praktijk zou ik deze token niet letterlijk declareren in objecten die worden verzonden private String refreshToken; } // voor extra veiligheid kan nog gecheckt worden of er niet geknoeid is met de jwt en refreshtoken; // zo ver wordt in de cursus echter niet ingegaan op security // // Verify the JWT's Signature: // To ensure the JWT is not tampered with, you need to verify its signature using the public key // of the issuer. The public key can be obtained from the issuer's JWKS (JSON Web Key Set) endpoint. // // Check the JWT's Claims: // You should verify the standard claims (e.g., expiration time, issuer, audience) // and any custom claims you may have added to the JWT. // // Check the Refresh Token: // Verify that the refresh token is valid and not expired. // The validation process may involve checking against a database // or cache where valid refresh tokens are stored.
BadKarmaL33t/InventoPilot-Backend
src/main/java/com/fsd/inventopilot/dtos/JwtAuthResponse.java
301
// voor extra veiligheid kan nog gecheckt worden of er niet geknoeid is met de jwt en refreshtoken;
line_comment
nl
package com.fsd.inventopilot.dtos; import lombok.Data; @Data public class JwtAuthResponse { private String jwt; // Deze wordt meegestuurd voor de opdrachten meegestuurd met de response, // zodat hij kan worden getest in postman met een dummy functie. // In de praktijk zou ik deze token niet letterlijk declareren in objecten die worden verzonden private String refreshToken; } // voor extra<SUF> // zo ver wordt in de cursus echter niet ingegaan op security // // Verify the JWT's Signature: // To ensure the JWT is not tampered with, you need to verify its signature using the public key // of the issuer. The public key can be obtained from the issuer's JWKS (JSON Web Key Set) endpoint. // // Check the JWT's Claims: // You should verify the standard claims (e.g., expiration time, issuer, audience) // and any custom claims you may have added to the JWT. // // Check the Refresh Token: // Verify that the refresh token is valid and not expired. // The validation process may involve checking against a database // or cache where valid refresh tokens are stored.
68243_0
import java.sql.Timestamp; import java.util.Calendar; import java.util.Date; /** * Kan alle waarden uit de database omrekenen naar de Nederlands gangbare eenheden * * @author Projectgroep B5 */ public class Calculator { // Luchtdruk in hPa // Malek&Tom public static double luchtdruk(short mval) { double luchtdruk = (mval / 1000f) * 33.86389; return luchtdruk; } // Temperatuur in graden Celcius // Malek&Tom public static double temperatuur(short mval) { double temperatuur = (((double)mval / 10) -32) / 1.8; return temperatuur; } // Relatieve luchtvochtigheid in % // Malek&Tom public static double luchtVochtigheid(short mval) { double luchtvochtigheid = mval; return luchtvochtigheid; } // Windsnelheid in m/s // Janco&Tim public static double windSnelheid(short mval) { double windSpeed = mval * 0.44704; return windSpeed; } // Windrichting in noord, oost, zuid en west. // Kenneth&Daniël public static String windRichting(short mval) { String direction = "Error"; if(mval < 12) { direction = "N"; } else if(mval < 34) { direction = "NNO"; } else if(mval < 57) { direction = "NO"; } else if(mval < 79) { direction = "ONO"; } else if(mval < 102) { direction = "O"; } else if(mval < 124) { direction = "OZO"; } else if(mval < 147) { direction = "ZO"; } else if(mval < 169) { direction = "ZZO"; } else if(mval < 192) { direction = "Z"; } else if(mval < 214) { direction = "ZZW"; } else if(mval < 237) { direction = "ZW"; } else if(mval < 259) { direction = "WZW"; } else if(mval < 282) { direction = "W"; } else if(mval < 304) { direction = "WNW"; } else if(mval < 327) { direction = "NW"; } else if(mval < 349) { direction = "NNW"; } else if(mval < 360) { direction = "N"; } return direction; } // Regenmeter in mm // Kenneth&Daniël public static double regenmeter(short mval) { double rainAmount = (double)mval*0.2; return rainAmount; } // uvIndex in index // Kenneth&Daniël public static double uvIndex(short mval) { double index = (double) mval/10; return index; } // BatterySpanning in Volt // Janco&Tim public static double batterySpanning(short mval){ double voltage = (((double)mval * 300)/512)/100; return voltage; } // sunRise en Sunset in tijdformaat hh:mm // Janco&Tim public static String sunRise(short mval){ return sun(mval); } public static String sunSet(short mval){ return sun(mval); } //Sunrise en Sunset tijden private static String sun(short sunRaw){ String tijd = ""; for(int i = 0; i <= 3; i++){ tijd = sunRaw % 10 + tijd; sunRaw /= 10; if(i == 1){ tijd = ":" + tijd; } } return tijd; } //Zonsterkte public static double solarRad(short mval){ double zonSterkte = mval; return zonSterkte; } //windchill in graden Celcius //Janco en Keneth public static double windChill(short grdnFh, short mph) { double gradenFahrenheit = grdnFh; double mijlPerUur = mph; double windChill2 = (35.74 + (0.6215*gradenFahrenheit) - 35.75*Math.pow(mijlPerUur, 0.16) + 0.4275*gradenFahrenheit*Math.pow(mijlPerUur, 0.16)); short windChill = (short) windChill2; return temperatuur(windChill); } //Heatindex in celcius //Tom en Malek public static double heatIndex(short RH, short T2) { double T = T2/10; double HI = -42.379 + 2.04901523*T + 10.14333127*RH - .22475541*T*RH - .00683783*T*T - .05481717*RH*RH + .00122874*T*T*RH + .00085282*T*RH*RH - .00000199*T*T*RH*RH; if (RH < 13 && T < 112 && T > 80) { HI =- ((13-RH)/4)*Math.sqrt((17-Math.abs(T-95.))/17); } if (RH > 85 && T < 87 && T > 80) { HI =+ ((RH-85)/10) * ((87-T)/5); } if (T > 80) { HI = 0.5 * (T + 61.0 + ((T-68.0)*1.2) + (RH*0.094)); } double heatindex = Calculator.temperatuur( (short) (HI*10) ); return heatindex; } //Dauwpunt in Celcius //Daniel en Tim public static double dewPoint(double omgevingsTemp, short luchtVochtigheid) { double hm = luchtVochtigheid/100f; double dauwpunt = Math.pow( hm, (1/8f)) * (112 + 0.9*omgevingsTemp) + (0.1*omgevingsTemp) - 112; return dauwpunt; } //Wolkhoogte in meters //Malek public static double cloudHeight(double temp, short luchtVochtigheid ){ double wolkhoogte = 125 * (temp-dewPoint(temp, luchtVochtigheid)); return wolkhoogte; } public static Periode timeStampToPeriode(Timestamp timeStamp1, Timestamp timeStamp2) { Periode periode = new Periode("-"); int year,month,day; String[] ts1 = timeStamp1.toString().split(" "); ts1 = ts1[0].split("-"); periode.setBeginPeriode(Integer.valueOf(ts1[0]), Integer.valueOf(ts1[1]), Integer.valueOf(ts1[2])); String[] ts2 = timeStamp2.toString().split(" "); ts2 = ts2[0].split("-"); periode.setEindePeriode(Integer.valueOf(ts2[0]), Integer.valueOf(ts2[1]), Integer.valueOf(ts2[2])); return periode; } }
ProjectgroepB5/weerstation
Calculator.java
2,215
/** * Kan alle waarden uit de database omrekenen naar de Nederlands gangbare eenheden * * @author Projectgroep B5 */
block_comment
nl
import java.sql.Timestamp; import java.util.Calendar; import java.util.Date; /** * Kan alle waarden<SUF>*/ public class Calculator { // Luchtdruk in hPa // Malek&Tom public static double luchtdruk(short mval) { double luchtdruk = (mval / 1000f) * 33.86389; return luchtdruk; } // Temperatuur in graden Celcius // Malek&Tom public static double temperatuur(short mval) { double temperatuur = (((double)mval / 10) -32) / 1.8; return temperatuur; } // Relatieve luchtvochtigheid in % // Malek&Tom public static double luchtVochtigheid(short mval) { double luchtvochtigheid = mval; return luchtvochtigheid; } // Windsnelheid in m/s // Janco&Tim public static double windSnelheid(short mval) { double windSpeed = mval * 0.44704; return windSpeed; } // Windrichting in noord, oost, zuid en west. // Kenneth&Daniël public static String windRichting(short mval) { String direction = "Error"; if(mval < 12) { direction = "N"; } else if(mval < 34) { direction = "NNO"; } else if(mval < 57) { direction = "NO"; } else if(mval < 79) { direction = "ONO"; } else if(mval < 102) { direction = "O"; } else if(mval < 124) { direction = "OZO"; } else if(mval < 147) { direction = "ZO"; } else if(mval < 169) { direction = "ZZO"; } else if(mval < 192) { direction = "Z"; } else if(mval < 214) { direction = "ZZW"; } else if(mval < 237) { direction = "ZW"; } else if(mval < 259) { direction = "WZW"; } else if(mval < 282) { direction = "W"; } else if(mval < 304) { direction = "WNW"; } else if(mval < 327) { direction = "NW"; } else if(mval < 349) { direction = "NNW"; } else if(mval < 360) { direction = "N"; } return direction; } // Regenmeter in mm // Kenneth&Daniël public static double regenmeter(short mval) { double rainAmount = (double)mval*0.2; return rainAmount; } // uvIndex in index // Kenneth&Daniël public static double uvIndex(short mval) { double index = (double) mval/10; return index; } // BatterySpanning in Volt // Janco&Tim public static double batterySpanning(short mval){ double voltage = (((double)mval * 300)/512)/100; return voltage; } // sunRise en Sunset in tijdformaat hh:mm // Janco&Tim public static String sunRise(short mval){ return sun(mval); } public static String sunSet(short mval){ return sun(mval); } //Sunrise en Sunset tijden private static String sun(short sunRaw){ String tijd = ""; for(int i = 0; i <= 3; i++){ tijd = sunRaw % 10 + tijd; sunRaw /= 10; if(i == 1){ tijd = ":" + tijd; } } return tijd; } //Zonsterkte public static double solarRad(short mval){ double zonSterkte = mval; return zonSterkte; } //windchill in graden Celcius //Janco en Keneth public static double windChill(short grdnFh, short mph) { double gradenFahrenheit = grdnFh; double mijlPerUur = mph; double windChill2 = (35.74 + (0.6215*gradenFahrenheit) - 35.75*Math.pow(mijlPerUur, 0.16) + 0.4275*gradenFahrenheit*Math.pow(mijlPerUur, 0.16)); short windChill = (short) windChill2; return temperatuur(windChill); } //Heatindex in celcius //Tom en Malek public static double heatIndex(short RH, short T2) { double T = T2/10; double HI = -42.379 + 2.04901523*T + 10.14333127*RH - .22475541*T*RH - .00683783*T*T - .05481717*RH*RH + .00122874*T*T*RH + .00085282*T*RH*RH - .00000199*T*T*RH*RH; if (RH < 13 && T < 112 && T > 80) { HI =- ((13-RH)/4)*Math.sqrt((17-Math.abs(T-95.))/17); } if (RH > 85 && T < 87 && T > 80) { HI =+ ((RH-85)/10) * ((87-T)/5); } if (T > 80) { HI = 0.5 * (T + 61.0 + ((T-68.0)*1.2) + (RH*0.094)); } double heatindex = Calculator.temperatuur( (short) (HI*10) ); return heatindex; } //Dauwpunt in Celcius //Daniel en Tim public static double dewPoint(double omgevingsTemp, short luchtVochtigheid) { double hm = luchtVochtigheid/100f; double dauwpunt = Math.pow( hm, (1/8f)) * (112 + 0.9*omgevingsTemp) + (0.1*omgevingsTemp) - 112; return dauwpunt; } //Wolkhoogte in meters //Malek public static double cloudHeight(double temp, short luchtVochtigheid ){ double wolkhoogte = 125 * (temp-dewPoint(temp, luchtVochtigheid)); return wolkhoogte; } public static Periode timeStampToPeriode(Timestamp timeStamp1, Timestamp timeStamp2) { Periode periode = new Periode("-"); int year,month,day; String[] ts1 = timeStamp1.toString().split(" "); ts1 = ts1[0].split("-"); periode.setBeginPeriode(Integer.valueOf(ts1[0]), Integer.valueOf(ts1[1]), Integer.valueOf(ts1[2])); String[] ts2 = timeStamp2.toString().split(" "); ts2 = ts2[0].split("-"); periode.setEindePeriode(Integer.valueOf(ts2[0]), Integer.valueOf(ts2[1]), Integer.valueOf(ts2[2])); return periode; } }
69750_2
/* * 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 proftaak; import java.net.MalformedURLException; import java.rmi.Naming; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Observable; import java.util.Observer; import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.Application; import rmichat.server.iLobby; /** * * @author Sander */ public class Lobby implements Observer{ private ArrayList<String> berichten = new ArrayList<String>(); public Gebruiker gebruiker; private Chatbox chatbox; private List<Gebruiker> gebruikers; private ArrayList<Spel> spellen; private ArrayList<Spel> spellenRMI; private iLobby il; private Proftaak p; public String ipAdress; public boolean firstLobby = true; public Lobby() { chatbox = new Chatbox(); gebruikers = new ArrayList<>(); spellen = new ArrayList<>(); if(firstLobby){ ipAdress = "127.0.0.1"; gebruiker = new Gebruiker("test"); try { gebruiker.startServer(ipAdress); this.startServer(); } catch (NotBoundException ex) { Logger.getLogger(Lobby.class.getName()).log(Level.SEVERE, null, ex); } catch (MalformedURLException ex) { Logger.getLogger(Lobby.class.getName()).log(Level.SEVERE, null, ex); } catch (RemoteException ex) { Logger.getLogger(Lobby.class.getName()).log(Level.SEVERE, null, ex); } firstLobby = false; } } /** * * @return Alle bestaande spellen. */ public ArrayList<Spel> getSpellenRMI()throws NotBoundException, MalformedURLException { spellenRMI = new ArrayList<Spel>(); try { for(String s:il.getSpellen()) { String[] arr = s.split("/"); spellenRMI.add(new Spel(arr[0],new Gebruiker(arr[1]),true,Integer.parseInt(arr[2]))); } } catch (RemoteException exc) { System.out.println(exc); } return spellenRMI; } public ArrayList<String> showSpellen() { try { spellen = getSpellenRMI(); // zet naar tekst array } catch (NotBoundException ex) { Logger.getLogger(Lobby.class.getName()).log(Level.SEVERE, null, ex); } catch (MalformedURLException ex) { Logger.getLogger(Lobby.class.getName()).log(Level.SEVERE, null, ex); } ArrayList<String> spellenStrings = new ArrayList<String>(); for(Spel s: spellen) { spellenStrings.add(s.toString()); } return spellenStrings; } /** * * @return Alle gebruikers in de lobby. */ public List<Gebruiker> getGebruikers() { return Collections.unmodifiableList(gebruikers); } public List<Bericht> getChatBerichten() { return chatbox.getBerichtenlijst(); } /** * Voeg spel toe aan de lobby. * @param naam De naam van het spel. * @param publicGame Openbaar of privé. */ public void voegSpelToe(String naam, Boolean publicGame) throws RemoteException { il.voegSpelToe(naam, gebruiker.getNaam(),gebruiker.getScore(),gebruiker.getRating(),gebruiker.getRatingLijst(), publicGame); } /** * * @return Lijst met highscores van alle gebruikers in de lobby. */ public List<Integer> toonHighScores() { List<Integer> highScores = new ArrayList<>(); for(Gebruiker g : gebruikers) { highScores.add(g.getScore()); } return Collections.unmodifiableList(highScores); //Bewaard voor de volgende iteratie } /** * * @param naam * @param wachtwoord * @return true als het inloggen is geslaagd, anders false */ public Boolean login(String naam, String wachtwoord) { //Bewaard voor volgende iteratie gebruikers.add(gebruiker); return true; } /** * Gebruiker uitloggen (nog niet geimplementeerd) */ public void logout() { //Bewaard voor volgende iteratie } /** * Bericht toevoegen aan de chatbox * @param bericht string met inhoud van het bericht */ public void stuurBericht(String bericht) { try { gebruiker.addBericht(bericht); } catch (RemoteException ex) { Logger.getLogger(Lobby.class.getName()).log(Level.SEVERE, null, ex); } // chatbox.voegBerichtToe(bericht, gebruiker); } /** * Nieuwe gebruiker registreren (nog niet geimplementeerd) * @param naam * @param wachtwoord * @param email * @return */ public Boolean registreer(String naam, String wachtwoord, String email) { //Bewaard voor volgende iteratie return true; } @Override public void update(Observable o, Object arg) { for(int i = 0; i < spellen.size(); i++) { Spel s = spellen.get(i); if(s.getId() == ((Spel)o).getId()) { spellen.remove(i); } } } public ArrayList<String> getBerichten() throws NotBoundException, MalformedURLException { berichten = gebruiker.getBerichtenRMI(); return berichten; } public void showBerichten() throws NotBoundException, MalformedURLException { } public void startServer() throws NotBoundException, MalformedURLException, RemoteException { System.out.println("Connecting"); il = (iLobby) Naming.lookup("rmi://127.0.0.1/ls"); System.out.println("Connected"); } }
eternalflamez/Proftaak
src/proftaak/Lobby.java
1,741
/** * * @return Alle bestaande spellen. */
block_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 proftaak; import java.net.MalformedURLException; import java.rmi.Naming; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Observable; import java.util.Observer; import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.Application; import rmichat.server.iLobby; /** * * @author Sander */ public class Lobby implements Observer{ private ArrayList<String> berichten = new ArrayList<String>(); public Gebruiker gebruiker; private Chatbox chatbox; private List<Gebruiker> gebruikers; private ArrayList<Spel> spellen; private ArrayList<Spel> spellenRMI; private iLobby il; private Proftaak p; public String ipAdress; public boolean firstLobby = true; public Lobby() { chatbox = new Chatbox(); gebruikers = new ArrayList<>(); spellen = new ArrayList<>(); if(firstLobby){ ipAdress = "127.0.0.1"; gebruiker = new Gebruiker("test"); try { gebruiker.startServer(ipAdress); this.startServer(); } catch (NotBoundException ex) { Logger.getLogger(Lobby.class.getName()).log(Level.SEVERE, null, ex); } catch (MalformedURLException ex) { Logger.getLogger(Lobby.class.getName()).log(Level.SEVERE, null, ex); } catch (RemoteException ex) { Logger.getLogger(Lobby.class.getName()).log(Level.SEVERE, null, ex); } firstLobby = false; } } /** * * @return Alle bestaande<SUF>*/ public ArrayList<Spel> getSpellenRMI()throws NotBoundException, MalformedURLException { spellenRMI = new ArrayList<Spel>(); try { for(String s:il.getSpellen()) { String[] arr = s.split("/"); spellenRMI.add(new Spel(arr[0],new Gebruiker(arr[1]),true,Integer.parseInt(arr[2]))); } } catch (RemoteException exc) { System.out.println(exc); } return spellenRMI; } public ArrayList<String> showSpellen() { try { spellen = getSpellenRMI(); // zet naar tekst array } catch (NotBoundException ex) { Logger.getLogger(Lobby.class.getName()).log(Level.SEVERE, null, ex); } catch (MalformedURLException ex) { Logger.getLogger(Lobby.class.getName()).log(Level.SEVERE, null, ex); } ArrayList<String> spellenStrings = new ArrayList<String>(); for(Spel s: spellen) { spellenStrings.add(s.toString()); } return spellenStrings; } /** * * @return Alle gebruikers in de lobby. */ public List<Gebruiker> getGebruikers() { return Collections.unmodifiableList(gebruikers); } public List<Bericht> getChatBerichten() { return chatbox.getBerichtenlijst(); } /** * Voeg spel toe aan de lobby. * @param naam De naam van het spel. * @param publicGame Openbaar of privé. */ public void voegSpelToe(String naam, Boolean publicGame) throws RemoteException { il.voegSpelToe(naam, gebruiker.getNaam(),gebruiker.getScore(),gebruiker.getRating(),gebruiker.getRatingLijst(), publicGame); } /** * * @return Lijst met highscores van alle gebruikers in de lobby. */ public List<Integer> toonHighScores() { List<Integer> highScores = new ArrayList<>(); for(Gebruiker g : gebruikers) { highScores.add(g.getScore()); } return Collections.unmodifiableList(highScores); //Bewaard voor de volgende iteratie } /** * * @param naam * @param wachtwoord * @return true als het inloggen is geslaagd, anders false */ public Boolean login(String naam, String wachtwoord) { //Bewaard voor volgende iteratie gebruikers.add(gebruiker); return true; } /** * Gebruiker uitloggen (nog niet geimplementeerd) */ public void logout() { //Bewaard voor volgende iteratie } /** * Bericht toevoegen aan de chatbox * @param bericht string met inhoud van het bericht */ public void stuurBericht(String bericht) { try { gebruiker.addBericht(bericht); } catch (RemoteException ex) { Logger.getLogger(Lobby.class.getName()).log(Level.SEVERE, null, ex); } // chatbox.voegBerichtToe(bericht, gebruiker); } /** * Nieuwe gebruiker registreren (nog niet geimplementeerd) * @param naam * @param wachtwoord * @param email * @return */ public Boolean registreer(String naam, String wachtwoord, String email) { //Bewaard voor volgende iteratie return true; } @Override public void update(Observable o, Object arg) { for(int i = 0; i < spellen.size(); i++) { Spel s = spellen.get(i); if(s.getId() == ((Spel)o).getId()) { spellen.remove(i); } } } public ArrayList<String> getBerichten() throws NotBoundException, MalformedURLException { berichten = gebruiker.getBerichtenRMI(); return berichten; } public void showBerichten() throws NotBoundException, MalformedURLException { } public void startServer() throws NotBoundException, MalformedURLException, RemoteException { System.out.println("Connecting"); il = (iLobby) Naming.lookup("rmi://127.0.0.1/ls"); System.out.println("Connected"); } }
39018_17
package com.marbl.warehouse.domain; import java.io.FileInputStream; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; public class Database { /** * Het connectie-object voor de database. */ private Connection connection = null; /** * Maakt een nieuw databaseConnectie-object. Zoekt connectie met de database * met de properties die op worden gehaald uit de file: db.properties. */ public Database() throws SQLException { try { Properties properties = new Properties(); properties.load(new FileInputStream("src/main/resources/db.properties")); String serverEnPort = properties.getProperty("ServerEnPort"); String url = "jdbc:oracle:thin:@" + serverEnPort + ":xe"; String username = properties.getProperty("Username"); String password = properties.getProperty("Password"); Class.forName("oracle.jdbc.OracleDriver"); connection = DriverManager.getConnection(url, username, password); connection.setAutoCommit(true); } catch (ClassNotFoundException | IOException ex) { Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="SELECT Methoden"> /** * Haalt zo mogelijk een lijst van onderdelen op uit de database. * * @return Een lijst met Onderdeel-objecten, als het fout gaat of de tabel * leeg is wordt een lege lijst gereturneerd. */ public Collection<Onderdeel> selectOnderdelen() throws SQLException { Collection<Onderdeel> onderdelen = new ArrayList<Onderdeel>(); String sql = "SELECT * FROM ONDERDEEL"; try (PreparedStatement ps = connection.prepareStatement(sql)) { try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { int code = rs.getInt("CODE"); String omschrijving = rs.getString("OMSCHRIJVING"); int aantal = rs.getInt("AANTAL"); int prijs = rs.getInt("PRIJS"); onderdelen.add(new Onderdeel(code, omschrijving, aantal, prijs)); } } } return onderdelen; } /** * Haalt zo mogelijk een lijst van factuurregels op uit de database. * * @return Een lijst met FactuurRegel-objecten, als het fout gaat of de * tabel leeg is wordt een lege lijst gereturneerd. */ public Collection<FactuurRegel> selectFactuurRegels() throws SQLException { Collection<FactuurRegel> factuurRegels = new ArrayList<FactuurRegel>(); String sql = "SELECT * FROM FACTUURREGEL"; try (PreparedStatement ps = connection.prepareStatement(sql)) { try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { int factuurCode = rs.getInt("FACTUURCODE"); int onderdeelCode = rs.getInt("ONDERDEELCODE"); int aantal = rs.getInt("AANTAL"); factuurRegels.add(new FactuurRegel(factuurCode, onderdeelCode, aantal)); } } } return factuurRegels; } /** * Haalt zo mogelijk een lijst van facturen op uit de database. * * @return Een lijst met Factuur-objecten, als het fout gaat of de tabel * leeg is wordt een lege lijst gereturneerd. */ public Collection<Factuur> selectFacturen() throws SQLException { Collection<Factuur> facturen = new ArrayList<Factuur>(); Collection<FactuurRegel> factuurRegels = selectFactuurRegels(); String sql = "SELECT * FROM FACTUUR"; try (PreparedStatement ps = connection.prepareStatement(sql)) { try (ResultSet rs = ps.executeQuery()) { int index = 0; while (rs.next()) { int code = rs.getInt("CODE"); int klantID = rs.getInt("KLANTCODE"); String datum = rs.getString("DATUM"); ArrayList<FactuurRegel> regels = new ArrayList<FactuurRegel>(); for (FactuurRegel factuurRegel : factuurRegels) { if (factuurRegel.getFactuurCode() == code) { regels.add(factuurRegel); } } facturen.add(new Factuur(code, klantID, datum, regels)); index++; } } } return facturen; } /** * Haalt zo mogelijk een lijst van klanten op uit de database. * * @return Ee lijst met Klant-objecten, als het fout gaat of de tabel leeg * is wordt een lege lijst gereturneerd. */ public Collection<Klant> selectKlanten() throws SQLException { Collection<Klant> klanten = new ArrayList<Klant>(); String sql = "SELECT * FROM KLANT"; try (PreparedStatement ps = connection.prepareStatement(sql)) { try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { int code = rs.getInt("CODE"); String naam = rs.getString("NAAM"); String adres = rs.getString("ADRES"); Klant kl = new Klant(code, naam, adres); klanten.add(kl); } } } return klanten; } /** * Haalt zo mogelijk het onderdeel op uit de database die hoort bij de * ingevoerde onderdeelcode. * * @param onderdeelCode De code van het onderdeel dat opgehaald moet worden. * @return Een Onderdeel-object dat de waardes heeft van een row uit de * Onderdeel-tabel. */ public Onderdeel selectOnderdeel(int onderdeelCode) throws SQLException { Onderdeel onderdeel = null; String sql = "SELECT * FROM ONDERDEEL WHERE CODE = ?"; try (PreparedStatement ps = connection.prepareStatement(sql)) { ps.setInt(1, onderdeelCode); try (ResultSet rs = ps.executeQuery()) { if (rs.next()) { int code = rs.getInt("CODE"); String omschr = rs.getString("OMSCHRIJVING"); int aantal = rs.getInt("AANTAL"); int prijs = rs.getInt("PRIJS"); onderdeel = new Onderdeel(code, omschr, aantal, prijs); } } } return onderdeel; } //</editor-fold> //<editor-fold desc="INSERT Methoden"> /** * Voegt een Onderdeel toe in de database. * * @param onderdeel Het onderdeel dat moet worden toegevoegd in de database. * @return True als het onderdeel correct is toegevoegd, anders false. */ public void insert(Onderdeel onderdeel) throws SQLException { String sql = "INSERT INTO ONDERDEEL VALUES (?,?,?,?)"; try (PreparedStatement ps = connection.prepareStatement(sql)) { ps.setInt(1, onderdeel.getCode()); ps.setString(2, onderdeel.getOmschrijving()); ps.setInt(3, onderdeel.getAantal()); ps.setInt(4, onderdeel.getPrijs()); ps.execute(); } } /** * Voegt een klant toe aan de database. * * @param klant De klant die moet worden toegevoegd in de database. * @return True als de klant correct is toegevoegd, anders false. */ public void insert(Klant klant) throws SQLException { String sql = "INSERT INTO KLANT VALUES (?,?,?)"; try (PreparedStatement ps = connection.prepareStatement(sql)) { ps.setInt(1, klant.getCode()); ps.setString(2, klant.getNaam()); ps.setString(3, klant.getAdres()); ps.execute(); } } /** * Voegt een row toe aan de factuurregel tabel met bijbehorende factuurCode, * OnderdeelID en het aantal van het Onderdeel. (Deze methode wordt alleen * gebruikt door de methode insert in deze klasse). * * @param factuurRegel De regel die moet worden toegevoegd in de database. */ public void insert(FactuurRegel factuurRegel) throws SQLException { String sql = "INSERT INTO FACTUURREGEL VALUES (?,?,?)"; try (PreparedStatement ps = connection.prepareStatement(sql)) { ps.setInt(1, factuurRegel.getFactuurCode()); ps.setInt(2, factuurRegel.getOnderdeelCode()); ps.setInt(3, factuurRegel.getAantal()); ps.execute(); } } /** * Voegt een factuur toe aan de database, met bijbehorende ingevoerde * waardes. Voegt ook de factuurregels toe aan de database, waarin staat: * FactuurCode, OnderdeelID en aantal van het onderdeel. * * @param factuur De factuur die moet worden toegevoegd. * @return True als de factuur correct is toegevoegd, anders false. */ public void insert(Factuur factuur) throws SQLException { String sql = "INSERT INTO FACTUUR VALUES (?,?,?)"; try (PreparedStatement ps = connection.prepareStatement(sql)) { ps.setInt(1, factuur.getCode()); ps.setInt(2, factuur.getKlantCode()); ps.setString(3, factuur.getDatum()); ps.execute(); for (FactuurRegel factuurRegel : factuur.getRegels()) { insert(factuurRegel); } } } //</editor-fold> //<editor-fold desc="DELETE Methoden"> /** * Verwijdert het onderdeel dat hoort bij het ingevoerde code. * * @param code De code van het onderdeel dat moet worden verwijdert. * @return True als het onderdeel correct is verwijdert, anders false. */ public void deleteOnderdeel(int code) throws SQLException { String sql = "DELETE FROM ONDERDEEL WHERE CODE = ?"; try (PreparedStatement ps = connection.prepareStatement(sql)) { ps.setInt(1, code); ps.execute(); } } /** * Verwijdert de klant uit de database die hoort bij de ingevoerde code. * * @param code De code van de klant die verwijdert moet worden. * @return True als de klant correct is verwijdert, anders false. */ public void deleteKlant(int code) throws SQLException { try (PreparedStatement ps = connection.prepareStatement("DELETE FROM KLANT WHERE CODE = ?")) { ps.setInt(1, code); ps.execute(); } } //</editor-fold> //<editor-fold desc="UPDATE Methoden"> /** * Verandert het onderdeel dat hoort bij de ingoeverde code, de nieuwe * waardes zitten in het Onderdeel-object. (Alleen de omschrijving, het * aantal en de prijs kan veranderd worden, de code blijft hetzelfde!). * * @param onderdeelCode De code die hoort bij het onderdeel dat verandert * moet worden. * @param onderdeel De nieuwe gegevens van het onderdeel. * @return True als het onderdeel correct is veranderd, anders false. */ public void update(Onderdeel onderdeel) throws SQLException { try (PreparedStatement ps = connection.prepareStatement("UPDATE ONDERDEEL SET OMSCHRIJVING = ?, AANTAL = ?, PRIJS = ? WHERE CODE = ?")) { ps.setString(1, onderdeel.getOmschrijving()); ps.setInt(2, onderdeel.getAantal()); ps.setInt(3, onderdeel.getPrijs()); ps.setInt(4, onderdeel.getCode()); ps.execute(); } } /** * Verandert de klant die hoort bij de ingevoerde code, de nieuwe waardes * zitten in het Klant-object. (Alleen de naam en het adres kan veranderd * worden, de code blijft hetzelfde!). * * @param klant De nieuwe gegevens van de klant. * @return True als de klant correct is veranderd, anders false. */ public void update(Klant klant) throws SQLException { try (PreparedStatement ps = connection.prepareStatement("UPDATE KLANT SET NAAM = ?, ADRES = ? WHERE CODE = ?")) { ps.setString(1, klant.getNaam()); ps.setString(2, klant.getAdres()); ps.setInt(3, klant.getCode()); ps.execute(); } } //</editor-fold> }
MathijsStertefeld/Parafiksit
ParafiksitDomain/src/main/java/com/marbl/warehouse/domain/Database.java
3,120
/** * Verandert het onderdeel dat hoort bij de ingoeverde code, de nieuwe * waardes zitten in het Onderdeel-object. (Alleen de omschrijving, het * aantal en de prijs kan veranderd worden, de code blijft hetzelfde!). * * @param onderdeelCode De code die hoort bij het onderdeel dat verandert * moet worden. * @param onderdeel De nieuwe gegevens van het onderdeel. * @return True als het onderdeel correct is veranderd, anders false. */
block_comment
nl
package com.marbl.warehouse.domain; import java.io.FileInputStream; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; public class Database { /** * Het connectie-object voor de database. */ private Connection connection = null; /** * Maakt een nieuw databaseConnectie-object. Zoekt connectie met de database * met de properties die op worden gehaald uit de file: db.properties. */ public Database() throws SQLException { try { Properties properties = new Properties(); properties.load(new FileInputStream("src/main/resources/db.properties")); String serverEnPort = properties.getProperty("ServerEnPort"); String url = "jdbc:oracle:thin:@" + serverEnPort + ":xe"; String username = properties.getProperty("Username"); String password = properties.getProperty("Password"); Class.forName("oracle.jdbc.OracleDriver"); connection = DriverManager.getConnection(url, username, password); connection.setAutoCommit(true); } catch (ClassNotFoundException | IOException ex) { Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex); } } //<editor-fold desc="SELECT Methoden"> /** * Haalt zo mogelijk een lijst van onderdelen op uit de database. * * @return Een lijst met Onderdeel-objecten, als het fout gaat of de tabel * leeg is wordt een lege lijst gereturneerd. */ public Collection<Onderdeel> selectOnderdelen() throws SQLException { Collection<Onderdeel> onderdelen = new ArrayList<Onderdeel>(); String sql = "SELECT * FROM ONDERDEEL"; try (PreparedStatement ps = connection.prepareStatement(sql)) { try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { int code = rs.getInt("CODE"); String omschrijving = rs.getString("OMSCHRIJVING"); int aantal = rs.getInt("AANTAL"); int prijs = rs.getInt("PRIJS"); onderdelen.add(new Onderdeel(code, omschrijving, aantal, prijs)); } } } return onderdelen; } /** * Haalt zo mogelijk een lijst van factuurregels op uit de database. * * @return Een lijst met FactuurRegel-objecten, als het fout gaat of de * tabel leeg is wordt een lege lijst gereturneerd. */ public Collection<FactuurRegel> selectFactuurRegels() throws SQLException { Collection<FactuurRegel> factuurRegels = new ArrayList<FactuurRegel>(); String sql = "SELECT * FROM FACTUURREGEL"; try (PreparedStatement ps = connection.prepareStatement(sql)) { try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { int factuurCode = rs.getInt("FACTUURCODE"); int onderdeelCode = rs.getInt("ONDERDEELCODE"); int aantal = rs.getInt("AANTAL"); factuurRegels.add(new FactuurRegel(factuurCode, onderdeelCode, aantal)); } } } return factuurRegels; } /** * Haalt zo mogelijk een lijst van facturen op uit de database. * * @return Een lijst met Factuur-objecten, als het fout gaat of de tabel * leeg is wordt een lege lijst gereturneerd. */ public Collection<Factuur> selectFacturen() throws SQLException { Collection<Factuur> facturen = new ArrayList<Factuur>(); Collection<FactuurRegel> factuurRegels = selectFactuurRegels(); String sql = "SELECT * FROM FACTUUR"; try (PreparedStatement ps = connection.prepareStatement(sql)) { try (ResultSet rs = ps.executeQuery()) { int index = 0; while (rs.next()) { int code = rs.getInt("CODE"); int klantID = rs.getInt("KLANTCODE"); String datum = rs.getString("DATUM"); ArrayList<FactuurRegel> regels = new ArrayList<FactuurRegel>(); for (FactuurRegel factuurRegel : factuurRegels) { if (factuurRegel.getFactuurCode() == code) { regels.add(factuurRegel); } } facturen.add(new Factuur(code, klantID, datum, regels)); index++; } } } return facturen; } /** * Haalt zo mogelijk een lijst van klanten op uit de database. * * @return Ee lijst met Klant-objecten, als het fout gaat of de tabel leeg * is wordt een lege lijst gereturneerd. */ public Collection<Klant> selectKlanten() throws SQLException { Collection<Klant> klanten = new ArrayList<Klant>(); String sql = "SELECT * FROM KLANT"; try (PreparedStatement ps = connection.prepareStatement(sql)) { try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { int code = rs.getInt("CODE"); String naam = rs.getString("NAAM"); String adres = rs.getString("ADRES"); Klant kl = new Klant(code, naam, adres); klanten.add(kl); } } } return klanten; } /** * Haalt zo mogelijk het onderdeel op uit de database die hoort bij de * ingevoerde onderdeelcode. * * @param onderdeelCode De code van het onderdeel dat opgehaald moet worden. * @return Een Onderdeel-object dat de waardes heeft van een row uit de * Onderdeel-tabel. */ public Onderdeel selectOnderdeel(int onderdeelCode) throws SQLException { Onderdeel onderdeel = null; String sql = "SELECT * FROM ONDERDEEL WHERE CODE = ?"; try (PreparedStatement ps = connection.prepareStatement(sql)) { ps.setInt(1, onderdeelCode); try (ResultSet rs = ps.executeQuery()) { if (rs.next()) { int code = rs.getInt("CODE"); String omschr = rs.getString("OMSCHRIJVING"); int aantal = rs.getInt("AANTAL"); int prijs = rs.getInt("PRIJS"); onderdeel = new Onderdeel(code, omschr, aantal, prijs); } } } return onderdeel; } //</editor-fold> //<editor-fold desc="INSERT Methoden"> /** * Voegt een Onderdeel toe in de database. * * @param onderdeel Het onderdeel dat moet worden toegevoegd in de database. * @return True als het onderdeel correct is toegevoegd, anders false. */ public void insert(Onderdeel onderdeel) throws SQLException { String sql = "INSERT INTO ONDERDEEL VALUES (?,?,?,?)"; try (PreparedStatement ps = connection.prepareStatement(sql)) { ps.setInt(1, onderdeel.getCode()); ps.setString(2, onderdeel.getOmschrijving()); ps.setInt(3, onderdeel.getAantal()); ps.setInt(4, onderdeel.getPrijs()); ps.execute(); } } /** * Voegt een klant toe aan de database. * * @param klant De klant die moet worden toegevoegd in de database. * @return True als de klant correct is toegevoegd, anders false. */ public void insert(Klant klant) throws SQLException { String sql = "INSERT INTO KLANT VALUES (?,?,?)"; try (PreparedStatement ps = connection.prepareStatement(sql)) { ps.setInt(1, klant.getCode()); ps.setString(2, klant.getNaam()); ps.setString(3, klant.getAdres()); ps.execute(); } } /** * Voegt een row toe aan de factuurregel tabel met bijbehorende factuurCode, * OnderdeelID en het aantal van het Onderdeel. (Deze methode wordt alleen * gebruikt door de methode insert in deze klasse). * * @param factuurRegel De regel die moet worden toegevoegd in de database. */ public void insert(FactuurRegel factuurRegel) throws SQLException { String sql = "INSERT INTO FACTUURREGEL VALUES (?,?,?)"; try (PreparedStatement ps = connection.prepareStatement(sql)) { ps.setInt(1, factuurRegel.getFactuurCode()); ps.setInt(2, factuurRegel.getOnderdeelCode()); ps.setInt(3, factuurRegel.getAantal()); ps.execute(); } } /** * Voegt een factuur toe aan de database, met bijbehorende ingevoerde * waardes. Voegt ook de factuurregels toe aan de database, waarin staat: * FactuurCode, OnderdeelID en aantal van het onderdeel. * * @param factuur De factuur die moet worden toegevoegd. * @return True als de factuur correct is toegevoegd, anders false. */ public void insert(Factuur factuur) throws SQLException { String sql = "INSERT INTO FACTUUR VALUES (?,?,?)"; try (PreparedStatement ps = connection.prepareStatement(sql)) { ps.setInt(1, factuur.getCode()); ps.setInt(2, factuur.getKlantCode()); ps.setString(3, factuur.getDatum()); ps.execute(); for (FactuurRegel factuurRegel : factuur.getRegels()) { insert(factuurRegel); } } } //</editor-fold> //<editor-fold desc="DELETE Methoden"> /** * Verwijdert het onderdeel dat hoort bij het ingevoerde code. * * @param code De code van het onderdeel dat moet worden verwijdert. * @return True als het onderdeel correct is verwijdert, anders false. */ public void deleteOnderdeel(int code) throws SQLException { String sql = "DELETE FROM ONDERDEEL WHERE CODE = ?"; try (PreparedStatement ps = connection.prepareStatement(sql)) { ps.setInt(1, code); ps.execute(); } } /** * Verwijdert de klant uit de database die hoort bij de ingevoerde code. * * @param code De code van de klant die verwijdert moet worden. * @return True als de klant correct is verwijdert, anders false. */ public void deleteKlant(int code) throws SQLException { try (PreparedStatement ps = connection.prepareStatement("DELETE FROM KLANT WHERE CODE = ?")) { ps.setInt(1, code); ps.execute(); } } //</editor-fold> //<editor-fold desc="UPDATE Methoden"> /** * Verandert het onderdeel<SUF>*/ public void update(Onderdeel onderdeel) throws SQLException { try (PreparedStatement ps = connection.prepareStatement("UPDATE ONDERDEEL SET OMSCHRIJVING = ?, AANTAL = ?, PRIJS = ? WHERE CODE = ?")) { ps.setString(1, onderdeel.getOmschrijving()); ps.setInt(2, onderdeel.getAantal()); ps.setInt(3, onderdeel.getPrijs()); ps.setInt(4, onderdeel.getCode()); ps.execute(); } } /** * Verandert de klant die hoort bij de ingevoerde code, de nieuwe waardes * zitten in het Klant-object. (Alleen de naam en het adres kan veranderd * worden, de code blijft hetzelfde!). * * @param klant De nieuwe gegevens van de klant. * @return True als de klant correct is veranderd, anders false. */ public void update(Klant klant) throws SQLException { try (PreparedStatement ps = connection.prepareStatement("UPDATE KLANT SET NAAM = ?, ADRES = ? WHERE CODE = ?")) { ps.setString(1, klant.getNaam()); ps.setString(2, klant.getAdres()); ps.setInt(3, klant.getCode()); ps.execute(); } } //</editor-fold> }
7882_6
/* INFORMATIE/OMSCHRIJVING: * ------------------------ * Wanneer er eerst een teken ingegeven wordt (+, *, /), krijgt de gebruiker een foutmelding * met een error-geluid. Enkel een '.' ingeven, wordt ook gezien als foutief. * Bij het eerst ingeven van een '-', wordt het getal negatief. * Na een punt ingegeven te hebben, wordt deze knop op 'disabled' gezet. Wanneer vervolgens * op '<' geklikt wordt en de gebruiker zijn punt wordt verwijderd, wordt deze knop weer actief. * Na op 'bereken' geklikt te hebben, moet de gebruiker op 'reset' klikken om verder te kunnen. * * Bij de uitkomst wordt gekeken of dit een decimaal getal is of niet. Naargelijk als dit zo is * wordt de uitkomst getoond als double, anders wordt deze getoond als een int. * * Wanneer vele voorloopnullen ingegeven worden, worden deze verwijderd. Er blijft wel nog een nul * staan als deze volgt door een punt. * * In de testklasse (Calculator_Main.java) is op regel 11 een code in commentaar gezet. Als deze * code gebruikt wordt, worden ALLE swing-componenten op het uiterlijk van de gebruiker zijn besturings- * systeem gezet. LET OP: wanneer deze code gebruikt wordt, zijn de buttons met witte tekst niet goed * leesbaar. Met deze code moeten alle buttons met witte tekst weer zwart gemaakt worden. Om deze code * te gebruiken, moet er een try-catch geplaatst worden. Dit is ook de reden waarom deze in de * main-klasse staat. * * Om ervoor de zorgen dat de knoppen niet te ver uitgerokken kunnen worden, is de JFrame op * 'setResizable(false)' gezet. Hierdoor kan de gebruiker zijn venster niet verkleinen of vergroten. * * Deze rekenmachine is gemaakt door Steven Verheyen (2TinA) en is vanaf 0 gemaakt. Hier en daar zijn * kleine opzoekwerken gedaan voor o.a. het krijgen van een error-geluid (regel 380), de look-and-feel * van swing-componenten (regel 11 Calculator_Main.java) en hoe een JFrame in het midden van de gebruiker * zijn scherm komt te staan bij het uitvoeren (regel 25 Calculator_Main.java) en hoe een ArrayList leeg- * gemaakt moet worden (regel 369). De rest is zelf gemaakt zonder opzoekwerk. * Dit is gemaakt na het leren van hoofstuk 11 (Exceptions) en hoofstuk 14 (GUI) en is enkel gemaakt om * de leerstof te leren op basis van iets wat in het dagelijks leven gebruikt wordt. */ package calculator; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import java.awt.GridLayout; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Iterator; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; public class Calculator extends JFrame { private static JButton btnPlus, btnMin, btnMaal, btnDeling, btnBereken, btnKomma, btnEenTerug, btnReset; private static JButton btnNul, btnEen, btnTwee, btnDrie, btnVier, btnVijf, btnZes, btnZeven, btnAcht, btnNegen; // Reden van aanmaken al deze buttons: later moeten deze op 'disabled' gezet // kunnen worden. (anders for-lus gebruiken bij aanmaken) private JTextField txtIngave; private static JTextField txtTotaleBerekening; private JPanel pnlNoord, pnlCenter, pnlZuid, pnlOost; private double uitkomst = 0.0; static ArrayList<String> ingave = new ArrayList<String>(); public Calculator() { // Panelen aanmaken // ---------------- pnlNoord = new JPanel(new BorderLayout()); pnlOost = new JPanel(new GridLayout(4, 1)); pnlCenter = new JPanel(new GridLayout(4, 3)); pnlZuid = new JPanel(new BorderLayout()); // Innerklasse gebruiken om events te doen // --------------------------------------- GetActionCommandHandler handlerEvents = new GetActionCommandHandler(); // Bewerkingsknoppen // ----------------- btnPlus = new JButton("+"); btnMaal = new JButton("x"); btnMin = new JButton("-"); btnDeling = new JButton("/"); btnPlus.addActionListener(handlerEvents); btnMaal.addActionListener(handlerEvents); btnMin.addActionListener(handlerEvents); btnDeling.addActionListener(handlerEvents); btnPlus.setBackground(Color.DARK_GRAY); btnMaal.setBackground(Color.DARK_GRAY); btnMin.setBackground(Color.DARK_GRAY); btnDeling.setBackground(Color.DARK_GRAY); btnPlus.setForeground(Color.WHITE); btnMaal.setForeground(Color.WHITE); btnMin.setForeground(Color.WHITE); btnDeling.setForeground(Color.WHITE); btnPlus.setFont(new Font("", Font.PLAIN, 18)); btnMin.setFont(new Font("", Font.PLAIN, 18)); btnMaal.setFont(new Font("", Font.PLAIN, 18)); btnDeling.setFont(new Font("", Font.PLAIN, 18)); pnlOost.add(btnPlus); pnlOost.add(btnMin); pnlOost.add(btnMaal); pnlOost.add(btnDeling); // Cijferknoppen // ------------- btnNul = new JButton("0"); btnNul.setBackground(Color.LIGHT_GRAY); btnNul.addActionListener(handlerEvents); btnEen = new JButton("1"); btnEen.setBackground(Color.LIGHT_GRAY); btnEen.addActionListener(handlerEvents); btnTwee = new JButton("2"); btnTwee.setBackground(Color.LIGHT_GRAY); btnTwee.addActionListener(handlerEvents); btnDrie = new JButton("3"); btnDrie.setBackground(Color.LIGHT_GRAY); btnDrie.addActionListener(handlerEvents); btnVier = new JButton("4"); btnVier.setBackground(Color.LIGHT_GRAY); btnVier.addActionListener(handlerEvents); btnVijf = new JButton("5"); btnVijf.setBackground(Color.LIGHT_GRAY); btnVijf.addActionListener(handlerEvents); btnZes = new JButton("6"); btnZes.setBackground(Color.LIGHT_GRAY); btnZes.addActionListener(handlerEvents); btnZeven = new JButton("7"); btnZeven.setBackground(Color.LIGHT_GRAY); btnZeven.addActionListener(handlerEvents); btnAcht = new JButton("8"); btnAcht.setBackground(Color.LIGHT_GRAY); btnAcht.addActionListener(handlerEvents); pnlCenter.add(btnNul); pnlCenter.add(btnEen); pnlCenter.add(btnTwee); pnlCenter.add(btnDrie); pnlCenter.add(btnVier); pnlCenter.add(btnVijf); pnlCenter.add(btnZes); pnlCenter.add(btnZeven); pnlCenter.add(btnAcht); btnEenTerug = new JButton("<"); btnEenTerug.setToolTipText("Verwijdert laatste cijfer van een getal"); btnEenTerug.setBackground(Color.LIGHT_GRAY); btnEenTerug.addActionListener(handlerEvents); btnNegen = new JButton("9"); btnNegen.setBackground(Color.LIGHT_GRAY); btnNegen.addActionListener(handlerEvents); btnKomma = new JButton("."); btnKomma.setBackground(Color.LIGHT_GRAY); btnKomma.addActionListener(handlerEvents); pnlCenter.add(btnEenTerug); pnlCenter.add(btnNegen); pnlCenter.add(btnKomma); txtTotaleBerekening = new JTextField(); txtTotaleBerekening.setHorizontalAlignment(JTextField.RIGHT); txtTotaleBerekening.setFont(new Font("", Font.PLAIN, 15)); txtTotaleBerekening.setEditable(false); txtTotaleBerekening.setToolTipText("Totale berekening voluit"); pnlNoord.add(txtTotaleBerekening, BorderLayout.NORTH); txtIngave = new JTextField(); txtIngave.setHorizontalAlignment(JTextField.RIGHT); txtIngave.setEditable(false); txtIngave.setToolTipText("Waarde die ingegeven wordt"); pnlNoord.add(txtIngave, BorderLayout.SOUTH); btnReset = new JButton("Reset"); btnReset.setBackground(Color.DARK_GRAY); btnReset.setForeground(Color.WHITE); btnReset.setToolTipText("Reset uw berekeningen"); btnReset.addActionListener(handlerEvents); pnlZuid.add(btnReset, BorderLayout.WEST); btnBereken = new JButton("="); btnBereken.setBackground(Color.BLACK); btnBereken.setForeground(Color.WHITE); btnBereken.setFont(new Font("", Font.PLAIN, 18)); btnBereken.setToolTipText("Berekent de uitkomst"); btnBereken.addActionListener(handlerEvents); pnlZuid.add(btnBereken, BorderLayout.CENTER); // pnlPaneel toevoegen aan JFrame // ------------------------------ add(pnlNoord, BorderLayout.NORTH); add(pnlOost, BorderLayout.EAST); add(pnlCenter, BorderLayout.CENTER); add(pnlZuid, BorderLayout.SOUTH); } // Een 'inner-class' om de events op te vangen private class GetActionCommandHandler implements ActionListener { public void actionPerformed(ActionEvent e) { try { if (e.getActionCommand().equals("0")) { txtIngave.setText(txtIngave.getText() + "0"); } else if (e.getActionCommand().equals("1")) { txtIngave.setText(txtIngave.getText() + "1"); } else if (e.getActionCommand().equals("2")) { txtIngave.setText(txtIngave.getText() + "2"); } else if (e.getActionCommand().equals("3")) { txtIngave.setText(txtIngave.getText() + "3"); } else if (e.getActionCommand().equals("4")) { txtIngave.setText(txtIngave.getText() + "4"); } else if (e.getActionCommand().equals("5")) { txtIngave.setText(txtIngave.getText() + "5"); } else if (e.getActionCommand().equals("6")) { txtIngave.setText(txtIngave.getText() + "6"); } else if (e.getActionCommand().equals("7")) { txtIngave.setText(txtIngave.getText() + "7"); } else if (e.getActionCommand().equals("8")) { txtIngave.setText(txtIngave.getText() + "8"); } else if (e.getActionCommand().equals("9")) { txtIngave.setText(txtIngave.getText() + "9"); } else if (e.getActionCommand().equals(".")) { txtIngave.setText(txtIngave.getText() + "."); btnKomma.setEnabled(false); } else if (e.getActionCommand().equals("=")) { if (!(txtIngave.getText().equals("") || txtIngave.getText().equals(".") || txtIngave.getText().equals("-") || txtIngave.getText().equals("-."))) { ingave.add(getInvoerZonderNul(txtIngave.getText())); // Laatst ingegeven getal nog in de // ArrayList plaatsen setTotaleBerekening(); uitkomst = Double.parseDouble(ingave.get(0)); // Zorgen dat ook met het 1ste getal gerekend // wordt for (int i = 0; i < ingave.size(); i++) { if (ingave.get(i).equals("+")) { double conversieHulp = Double.parseDouble(ingave.get(i + 1)); uitkomst += conversieHulp; } else if (ingave.get(i).equals("-")) { double conversieHulp = Double.parseDouble(ingave.get(i + 1)); uitkomst -= conversieHulp; } else if (ingave.get(i).equals("*")) { double conversieHulp = Double.parseDouble(ingave.get(i + 1)); uitkomst = uitkomst * conversieHulp; } else if (ingave.get(i).equals("/")) { double conversieHulp = Double.parseDouble(ingave.get(i + 1)); uitkomst = uitkomst / conversieHulp; } } setDisabled(); txtIngave.setForeground(Color.RED); if (((int) uitkomst == uitkomst)) // Kijken of uitkomst een kommagetal is of niet { txtIngave.setText((int) uitkomst + ""); // Drukt getal zonder komma (lees punt) } else { txtIngave.setText(uitkomst + ""); // Drukt getal met komma (lees punt) } } else throw new NumberFormatException(); } else if (e.getActionCommand().equals("<")) { int lengte = txtIngave.getText().length(); ArrayList<Character> characters = new ArrayList<Character>(); for (int i = 0; i < lengte - 1; i++) // Lengte met 1 verminderen om 1 cijfer te kunnen verwijderen { characters.add(txtIngave.getText().charAt(i)); } Iterator<Character> iter = characters.iterator(); String nieuwWaarde = ""; while (iter.hasNext()) { nieuwWaarde = nieuwWaarde + iter.next(); } char laatsteChar = txtIngave.getText().charAt(lengte - 1); if (laatsteChar == '.') // char is een primitive datatype -> == gebruiken + ENKELE QUOTES!!! { btnKomma.setEnabled(true); } txtIngave.setText(nieuwWaarde); } else if (e.getActionCommand().equals("+")) { if (!(txtIngave.getText().equals("") || txtIngave.getText().equals(".") || txtIngave.getText().equals("-") || txtIngave.getText().equals("-."))) // Enkel een '.' // wordt gezien als // fout { ingave.add(getInvoerZonderNul(txtIngave.getText())); ingave.add("+"); txtIngave.setText(""); setTotaleBerekening(); setKommaTrue(); } else throw new NumberFormatException(); } else if (e.getActionCommand().equals("-")) { if (txtIngave.getText().equals("")) { txtIngave.setText("-"); } else { if (!(txtIngave.getText().equals("-") || txtIngave.getText().equals(".") || txtIngave.getText().equals("-") || txtIngave.getText().equals("-."))) { ingave.add(getInvoerZonderNul(txtIngave.getText())); ingave.add("-"); txtIngave.setText(""); setTotaleBerekening(); setKommaTrue(); } else throw new NumberFormatException(); } } else if (e.getActionCommand().equals("x")) { if (!(txtIngave.getText().equals("") || txtIngave.getText().equals(".") || txtIngave.getText().equals("-") || txtIngave.getText().equals("-."))) { ingave.add(getInvoerZonderNul(txtIngave.getText())); ingave.add("*"); txtIngave.setText(""); setTotaleBerekening(); setKommaTrue(); } else throw new NumberFormatException(); } else if (e.getActionCommand().equals("/")) { if (!(txtIngave.getText().equals("") || txtIngave.getText().equals(".") || txtIngave.getText().equals("-") || txtIngave.getText().equals("-."))) { ingave.add(getInvoerZonderNul(txtIngave.getText())); ingave.add("/"); txtIngave.setText(""); setTotaleBerekening(); setKommaTrue(); } else throw new NumberFormatException(); } else if (e.getActionCommand().equals("Reset")) { txtIngave.setText(""); txtIngave.setForeground(Color.BLACK); txtTotaleBerekening.setText(""); uitkomst = 0.0; ingave.clear(); // ArrayList leegmaken setEnabled(); } } catch (NumberFormatException NFE) { Toolkit.getDefaultToolkit().beep(); JOptionPane.showMessageDialog(Calculator.this, "Gelieve eerst een getal in te geven!", "Geen getal", 0); } catch (StringIndexOutOfBoundsException SIOOBE) // Wanneer op '<' geklikt wordt en geen getal ingegeven is { Toolkit.getDefaultToolkit().beep(); JOptionPane.showMessageDialog(Calculator.this, "Gelieve eerst een getal in te geven!", "Geen getal", 0); } } } public static void setKommaTrue() { btnKomma.setEnabled(true); } public static void setEnabled() { btnKomma.setEnabled(true); btnBereken.setEnabled(true); btnDeling.setEnabled(true); btnKomma.setEnabled(true); btnPlus.setEnabled(true); btnMin.setEnabled(true); btnMaal.setEnabled(true); btnNul.setEnabled(true); btnEen.setEnabled(true); btnTwee.setEnabled(true); btnDrie.setEnabled(true); btnVier.setEnabled(true); btnVijf.setEnabled(true); btnZes.setEnabled(true); btnZeven.setEnabled(true); btnAcht.setEnabled(true); btnNegen.setEnabled(true); btnEenTerug.setEnabled(true); } public static void setDisabled() { btnBereken.setEnabled(false); btnDeling.setEnabled(false); btnKomma.setEnabled(false); btnPlus.setEnabled(false); btnMin.setEnabled(false); btnMaal.setEnabled(false); btnNul.setEnabled(false); btnEen.setEnabled(false); btnTwee.setEnabled(false); btnDrie.setEnabled(false); btnVier.setEnabled(false); btnVijf.setEnabled(false); btnZes.setEnabled(false); btnZeven.setEnabled(false); btnAcht.setEnabled(false); btnNegen.setEnabled(false); btnEenTerug.setEnabled(false); } public static void setTotaleBerekening() { txtTotaleBerekening.setText(""); for (int i = 0; i < ingave.size(); i++) { txtTotaleBerekening.setText(txtTotaleBerekening.getText() + " " + ingave.get(i)); } } public static String getInvoerZonderNul(String tekst) { String invoerWaarde = tekst; int lengte = invoerWaarde.length(); boolean controleNull = true; while (controleNull) { // Reden lengte>1: // De gebruiker kan bijv. 12*0 doen. Als deze controle niet gedaan wordt, kan 0 // niet ingevoerd worden (Geeft een foutmelding) if (lengte > 1 && invoerWaarde.substring(0, 1).equals("0") && !invoerWaarde.substring(1, 2).equals(".")) { invoerWaarde = invoerWaarde.substring(1); // zorgen voor geen voorloopnullen (indien het 2de char een // punt is) lengte = invoerWaarde.length(); } else if (invoerWaarde.substring(0, 1).equals(".")) // Zorgen voor een voorloopnul bij een decimaal getal { invoerWaarde = "0" + invoerWaarde; lengte = invoerWaarde.length(); } else if (invoerWaarde.substring(lengte - 1, lengte).equals(".")) // Zorgen voor een 0 na een punt wanneer // het punt de laatste char is { invoerWaarde = invoerWaarde + "0"; lengte = invoerWaarde.length(); } else if (invoerWaarde.substring(0, 1).equals("-") && invoerWaarde.substring(1, 2).equals(".")) { invoerWaarde = "-0." + invoerWaarde.substring(2); } else { controleNull = false; } } return invoerWaarde; } }
Tom4U/clean-coding
Java/finale/challenge/src/main/java/calculator/Calculator.java
5,085
// Laatst ingegeven getal nog in de
line_comment
nl
/* INFORMATIE/OMSCHRIJVING: * ------------------------ * Wanneer er eerst een teken ingegeven wordt (+, *, /), krijgt de gebruiker een foutmelding * met een error-geluid. Enkel een '.' ingeven, wordt ook gezien als foutief. * Bij het eerst ingeven van een '-', wordt het getal negatief. * Na een punt ingegeven te hebben, wordt deze knop op 'disabled' gezet. Wanneer vervolgens * op '<' geklikt wordt en de gebruiker zijn punt wordt verwijderd, wordt deze knop weer actief. * Na op 'bereken' geklikt te hebben, moet de gebruiker op 'reset' klikken om verder te kunnen. * * Bij de uitkomst wordt gekeken of dit een decimaal getal is of niet. Naargelijk als dit zo is * wordt de uitkomst getoond als double, anders wordt deze getoond als een int. * * Wanneer vele voorloopnullen ingegeven worden, worden deze verwijderd. Er blijft wel nog een nul * staan als deze volgt door een punt. * * In de testklasse (Calculator_Main.java) is op regel 11 een code in commentaar gezet. Als deze * code gebruikt wordt, worden ALLE swing-componenten op het uiterlijk van de gebruiker zijn besturings- * systeem gezet. LET OP: wanneer deze code gebruikt wordt, zijn de buttons met witte tekst niet goed * leesbaar. Met deze code moeten alle buttons met witte tekst weer zwart gemaakt worden. Om deze code * te gebruiken, moet er een try-catch geplaatst worden. Dit is ook de reden waarom deze in de * main-klasse staat. * * Om ervoor de zorgen dat de knoppen niet te ver uitgerokken kunnen worden, is de JFrame op * 'setResizable(false)' gezet. Hierdoor kan de gebruiker zijn venster niet verkleinen of vergroten. * * Deze rekenmachine is gemaakt door Steven Verheyen (2TinA) en is vanaf 0 gemaakt. Hier en daar zijn * kleine opzoekwerken gedaan voor o.a. het krijgen van een error-geluid (regel 380), de look-and-feel * van swing-componenten (regel 11 Calculator_Main.java) en hoe een JFrame in het midden van de gebruiker * zijn scherm komt te staan bij het uitvoeren (regel 25 Calculator_Main.java) en hoe een ArrayList leeg- * gemaakt moet worden (regel 369). De rest is zelf gemaakt zonder opzoekwerk. * Dit is gemaakt na het leren van hoofstuk 11 (Exceptions) en hoofstuk 14 (GUI) en is enkel gemaakt om * de leerstof te leren op basis van iets wat in het dagelijks leven gebruikt wordt. */ package calculator; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import java.awt.GridLayout; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Iterator; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; public class Calculator extends JFrame { private static JButton btnPlus, btnMin, btnMaal, btnDeling, btnBereken, btnKomma, btnEenTerug, btnReset; private static JButton btnNul, btnEen, btnTwee, btnDrie, btnVier, btnVijf, btnZes, btnZeven, btnAcht, btnNegen; // Reden van aanmaken al deze buttons: later moeten deze op 'disabled' gezet // kunnen worden. (anders for-lus gebruiken bij aanmaken) private JTextField txtIngave; private static JTextField txtTotaleBerekening; private JPanel pnlNoord, pnlCenter, pnlZuid, pnlOost; private double uitkomst = 0.0; static ArrayList<String> ingave = new ArrayList<String>(); public Calculator() { // Panelen aanmaken // ---------------- pnlNoord = new JPanel(new BorderLayout()); pnlOost = new JPanel(new GridLayout(4, 1)); pnlCenter = new JPanel(new GridLayout(4, 3)); pnlZuid = new JPanel(new BorderLayout()); // Innerklasse gebruiken om events te doen // --------------------------------------- GetActionCommandHandler handlerEvents = new GetActionCommandHandler(); // Bewerkingsknoppen // ----------------- btnPlus = new JButton("+"); btnMaal = new JButton("x"); btnMin = new JButton("-"); btnDeling = new JButton("/"); btnPlus.addActionListener(handlerEvents); btnMaal.addActionListener(handlerEvents); btnMin.addActionListener(handlerEvents); btnDeling.addActionListener(handlerEvents); btnPlus.setBackground(Color.DARK_GRAY); btnMaal.setBackground(Color.DARK_GRAY); btnMin.setBackground(Color.DARK_GRAY); btnDeling.setBackground(Color.DARK_GRAY); btnPlus.setForeground(Color.WHITE); btnMaal.setForeground(Color.WHITE); btnMin.setForeground(Color.WHITE); btnDeling.setForeground(Color.WHITE); btnPlus.setFont(new Font("", Font.PLAIN, 18)); btnMin.setFont(new Font("", Font.PLAIN, 18)); btnMaal.setFont(new Font("", Font.PLAIN, 18)); btnDeling.setFont(new Font("", Font.PLAIN, 18)); pnlOost.add(btnPlus); pnlOost.add(btnMin); pnlOost.add(btnMaal); pnlOost.add(btnDeling); // Cijferknoppen // ------------- btnNul = new JButton("0"); btnNul.setBackground(Color.LIGHT_GRAY); btnNul.addActionListener(handlerEvents); btnEen = new JButton("1"); btnEen.setBackground(Color.LIGHT_GRAY); btnEen.addActionListener(handlerEvents); btnTwee = new JButton("2"); btnTwee.setBackground(Color.LIGHT_GRAY); btnTwee.addActionListener(handlerEvents); btnDrie = new JButton("3"); btnDrie.setBackground(Color.LIGHT_GRAY); btnDrie.addActionListener(handlerEvents); btnVier = new JButton("4"); btnVier.setBackground(Color.LIGHT_GRAY); btnVier.addActionListener(handlerEvents); btnVijf = new JButton("5"); btnVijf.setBackground(Color.LIGHT_GRAY); btnVijf.addActionListener(handlerEvents); btnZes = new JButton("6"); btnZes.setBackground(Color.LIGHT_GRAY); btnZes.addActionListener(handlerEvents); btnZeven = new JButton("7"); btnZeven.setBackground(Color.LIGHT_GRAY); btnZeven.addActionListener(handlerEvents); btnAcht = new JButton("8"); btnAcht.setBackground(Color.LIGHT_GRAY); btnAcht.addActionListener(handlerEvents); pnlCenter.add(btnNul); pnlCenter.add(btnEen); pnlCenter.add(btnTwee); pnlCenter.add(btnDrie); pnlCenter.add(btnVier); pnlCenter.add(btnVijf); pnlCenter.add(btnZes); pnlCenter.add(btnZeven); pnlCenter.add(btnAcht); btnEenTerug = new JButton("<"); btnEenTerug.setToolTipText("Verwijdert laatste cijfer van een getal"); btnEenTerug.setBackground(Color.LIGHT_GRAY); btnEenTerug.addActionListener(handlerEvents); btnNegen = new JButton("9"); btnNegen.setBackground(Color.LIGHT_GRAY); btnNegen.addActionListener(handlerEvents); btnKomma = new JButton("."); btnKomma.setBackground(Color.LIGHT_GRAY); btnKomma.addActionListener(handlerEvents); pnlCenter.add(btnEenTerug); pnlCenter.add(btnNegen); pnlCenter.add(btnKomma); txtTotaleBerekening = new JTextField(); txtTotaleBerekening.setHorizontalAlignment(JTextField.RIGHT); txtTotaleBerekening.setFont(new Font("", Font.PLAIN, 15)); txtTotaleBerekening.setEditable(false); txtTotaleBerekening.setToolTipText("Totale berekening voluit"); pnlNoord.add(txtTotaleBerekening, BorderLayout.NORTH); txtIngave = new JTextField(); txtIngave.setHorizontalAlignment(JTextField.RIGHT); txtIngave.setEditable(false); txtIngave.setToolTipText("Waarde die ingegeven wordt"); pnlNoord.add(txtIngave, BorderLayout.SOUTH); btnReset = new JButton("Reset"); btnReset.setBackground(Color.DARK_GRAY); btnReset.setForeground(Color.WHITE); btnReset.setToolTipText("Reset uw berekeningen"); btnReset.addActionListener(handlerEvents); pnlZuid.add(btnReset, BorderLayout.WEST); btnBereken = new JButton("="); btnBereken.setBackground(Color.BLACK); btnBereken.setForeground(Color.WHITE); btnBereken.setFont(new Font("", Font.PLAIN, 18)); btnBereken.setToolTipText("Berekent de uitkomst"); btnBereken.addActionListener(handlerEvents); pnlZuid.add(btnBereken, BorderLayout.CENTER); // pnlPaneel toevoegen aan JFrame // ------------------------------ add(pnlNoord, BorderLayout.NORTH); add(pnlOost, BorderLayout.EAST); add(pnlCenter, BorderLayout.CENTER); add(pnlZuid, BorderLayout.SOUTH); } // Een 'inner-class' om de events op te vangen private class GetActionCommandHandler implements ActionListener { public void actionPerformed(ActionEvent e) { try { if (e.getActionCommand().equals("0")) { txtIngave.setText(txtIngave.getText() + "0"); } else if (e.getActionCommand().equals("1")) { txtIngave.setText(txtIngave.getText() + "1"); } else if (e.getActionCommand().equals("2")) { txtIngave.setText(txtIngave.getText() + "2"); } else if (e.getActionCommand().equals("3")) { txtIngave.setText(txtIngave.getText() + "3"); } else if (e.getActionCommand().equals("4")) { txtIngave.setText(txtIngave.getText() + "4"); } else if (e.getActionCommand().equals("5")) { txtIngave.setText(txtIngave.getText() + "5"); } else if (e.getActionCommand().equals("6")) { txtIngave.setText(txtIngave.getText() + "6"); } else if (e.getActionCommand().equals("7")) { txtIngave.setText(txtIngave.getText() + "7"); } else if (e.getActionCommand().equals("8")) { txtIngave.setText(txtIngave.getText() + "8"); } else if (e.getActionCommand().equals("9")) { txtIngave.setText(txtIngave.getText() + "9"); } else if (e.getActionCommand().equals(".")) { txtIngave.setText(txtIngave.getText() + "."); btnKomma.setEnabled(false); } else if (e.getActionCommand().equals("=")) { if (!(txtIngave.getText().equals("") || txtIngave.getText().equals(".") || txtIngave.getText().equals("-") || txtIngave.getText().equals("-."))) { ingave.add(getInvoerZonderNul(txtIngave.getText())); // Laatst ingegeven<SUF> // ArrayList plaatsen setTotaleBerekening(); uitkomst = Double.parseDouble(ingave.get(0)); // Zorgen dat ook met het 1ste getal gerekend // wordt for (int i = 0; i < ingave.size(); i++) { if (ingave.get(i).equals("+")) { double conversieHulp = Double.parseDouble(ingave.get(i + 1)); uitkomst += conversieHulp; } else if (ingave.get(i).equals("-")) { double conversieHulp = Double.parseDouble(ingave.get(i + 1)); uitkomst -= conversieHulp; } else if (ingave.get(i).equals("*")) { double conversieHulp = Double.parseDouble(ingave.get(i + 1)); uitkomst = uitkomst * conversieHulp; } else if (ingave.get(i).equals("/")) { double conversieHulp = Double.parseDouble(ingave.get(i + 1)); uitkomst = uitkomst / conversieHulp; } } setDisabled(); txtIngave.setForeground(Color.RED); if (((int) uitkomst == uitkomst)) // Kijken of uitkomst een kommagetal is of niet { txtIngave.setText((int) uitkomst + ""); // Drukt getal zonder komma (lees punt) } else { txtIngave.setText(uitkomst + ""); // Drukt getal met komma (lees punt) } } else throw new NumberFormatException(); } else if (e.getActionCommand().equals("<")) { int lengte = txtIngave.getText().length(); ArrayList<Character> characters = new ArrayList<Character>(); for (int i = 0; i < lengte - 1; i++) // Lengte met 1 verminderen om 1 cijfer te kunnen verwijderen { characters.add(txtIngave.getText().charAt(i)); } Iterator<Character> iter = characters.iterator(); String nieuwWaarde = ""; while (iter.hasNext()) { nieuwWaarde = nieuwWaarde + iter.next(); } char laatsteChar = txtIngave.getText().charAt(lengte - 1); if (laatsteChar == '.') // char is een primitive datatype -> == gebruiken + ENKELE QUOTES!!! { btnKomma.setEnabled(true); } txtIngave.setText(nieuwWaarde); } else if (e.getActionCommand().equals("+")) { if (!(txtIngave.getText().equals("") || txtIngave.getText().equals(".") || txtIngave.getText().equals("-") || txtIngave.getText().equals("-."))) // Enkel een '.' // wordt gezien als // fout { ingave.add(getInvoerZonderNul(txtIngave.getText())); ingave.add("+"); txtIngave.setText(""); setTotaleBerekening(); setKommaTrue(); } else throw new NumberFormatException(); } else if (e.getActionCommand().equals("-")) { if (txtIngave.getText().equals("")) { txtIngave.setText("-"); } else { if (!(txtIngave.getText().equals("-") || txtIngave.getText().equals(".") || txtIngave.getText().equals("-") || txtIngave.getText().equals("-."))) { ingave.add(getInvoerZonderNul(txtIngave.getText())); ingave.add("-"); txtIngave.setText(""); setTotaleBerekening(); setKommaTrue(); } else throw new NumberFormatException(); } } else if (e.getActionCommand().equals("x")) { if (!(txtIngave.getText().equals("") || txtIngave.getText().equals(".") || txtIngave.getText().equals("-") || txtIngave.getText().equals("-."))) { ingave.add(getInvoerZonderNul(txtIngave.getText())); ingave.add("*"); txtIngave.setText(""); setTotaleBerekening(); setKommaTrue(); } else throw new NumberFormatException(); } else if (e.getActionCommand().equals("/")) { if (!(txtIngave.getText().equals("") || txtIngave.getText().equals(".") || txtIngave.getText().equals("-") || txtIngave.getText().equals("-."))) { ingave.add(getInvoerZonderNul(txtIngave.getText())); ingave.add("/"); txtIngave.setText(""); setTotaleBerekening(); setKommaTrue(); } else throw new NumberFormatException(); } else if (e.getActionCommand().equals("Reset")) { txtIngave.setText(""); txtIngave.setForeground(Color.BLACK); txtTotaleBerekening.setText(""); uitkomst = 0.0; ingave.clear(); // ArrayList leegmaken setEnabled(); } } catch (NumberFormatException NFE) { Toolkit.getDefaultToolkit().beep(); JOptionPane.showMessageDialog(Calculator.this, "Gelieve eerst een getal in te geven!", "Geen getal", 0); } catch (StringIndexOutOfBoundsException SIOOBE) // Wanneer op '<' geklikt wordt en geen getal ingegeven is { Toolkit.getDefaultToolkit().beep(); JOptionPane.showMessageDialog(Calculator.this, "Gelieve eerst een getal in te geven!", "Geen getal", 0); } } } public static void setKommaTrue() { btnKomma.setEnabled(true); } public static void setEnabled() { btnKomma.setEnabled(true); btnBereken.setEnabled(true); btnDeling.setEnabled(true); btnKomma.setEnabled(true); btnPlus.setEnabled(true); btnMin.setEnabled(true); btnMaal.setEnabled(true); btnNul.setEnabled(true); btnEen.setEnabled(true); btnTwee.setEnabled(true); btnDrie.setEnabled(true); btnVier.setEnabled(true); btnVijf.setEnabled(true); btnZes.setEnabled(true); btnZeven.setEnabled(true); btnAcht.setEnabled(true); btnNegen.setEnabled(true); btnEenTerug.setEnabled(true); } public static void setDisabled() { btnBereken.setEnabled(false); btnDeling.setEnabled(false); btnKomma.setEnabled(false); btnPlus.setEnabled(false); btnMin.setEnabled(false); btnMaal.setEnabled(false); btnNul.setEnabled(false); btnEen.setEnabled(false); btnTwee.setEnabled(false); btnDrie.setEnabled(false); btnVier.setEnabled(false); btnVijf.setEnabled(false); btnZes.setEnabled(false); btnZeven.setEnabled(false); btnAcht.setEnabled(false); btnNegen.setEnabled(false); btnEenTerug.setEnabled(false); } public static void setTotaleBerekening() { txtTotaleBerekening.setText(""); for (int i = 0; i < ingave.size(); i++) { txtTotaleBerekening.setText(txtTotaleBerekening.getText() + " " + ingave.get(i)); } } public static String getInvoerZonderNul(String tekst) { String invoerWaarde = tekst; int lengte = invoerWaarde.length(); boolean controleNull = true; while (controleNull) { // Reden lengte>1: // De gebruiker kan bijv. 12*0 doen. Als deze controle niet gedaan wordt, kan 0 // niet ingevoerd worden (Geeft een foutmelding) if (lengte > 1 && invoerWaarde.substring(0, 1).equals("0") && !invoerWaarde.substring(1, 2).equals(".")) { invoerWaarde = invoerWaarde.substring(1); // zorgen voor geen voorloopnullen (indien het 2de char een // punt is) lengte = invoerWaarde.length(); } else if (invoerWaarde.substring(0, 1).equals(".")) // Zorgen voor een voorloopnul bij een decimaal getal { invoerWaarde = "0" + invoerWaarde; lengte = invoerWaarde.length(); } else if (invoerWaarde.substring(lengte - 1, lengte).equals(".")) // Zorgen voor een 0 na een punt wanneer // het punt de laatste char is { invoerWaarde = invoerWaarde + "0"; lengte = invoerWaarde.length(); } else if (invoerWaarde.substring(0, 1).equals("-") && invoerWaarde.substring(1, 2).equals(".")) { invoerWaarde = "-0." + invoerWaarde.substring(2); } else { controleNull = false; } } return invoerWaarde; } }
21683_2
package nl.consumergram.consumergramv2.models; //Deze klasse definieert de structuur van de gebruikersidentiteit met zijn eigenschappen en de relatie met autoriteiten. // Het wordt gebruikt om gebruikersgegevens in de database op te slaan en te manipuleren met behulp van JPA. import jakarta.persistence.*; import lombok.Data; import lombok.Setter; import org.hibernate.annotations.OnDelete; import org.hibernate.annotations.OnDeleteAction; import java.util.HashSet; import java.util.List; import java.util.Set; //De @Entity-annotatie geeft aan dat dit een JPA-entity is, wat betekent dat het overeenkomt met een tabel in de database. @Entity @Data @Setter //De @Table(name = "users")-annotatie specificeert de naam van de database-tabel waarmee deze entiteit overeenkomt. @Table(name = "users") public class User { // Deze eerste 3 variabelen zijn verplicht om te kunnen inloggen met een username, password en rol. // @Column(nullable = false, unique = true) specificeert dat username niet leeg mag zijn // (nullable = false) en uniek moet zijn in de database. @Id @Column(nullable = false, unique = true) private String username; @Column(nullable = false, length = 255) private String password; // Dit definieert een een-op-veel-relatie tussen User en Authority // (waarschijnlijk een andere entiteit die de rollen of rechten van een gebruiker vertegenwoordigt). @OneToMany( targetEntity = Authority.class, // mappedBy = "username" geeft aan dat de User-entiteit de kant is die de relatie // beheert via het veld username in de Authority-entiteit. mappedBy = "username", // cascade = CascadeType.ALL geeft aan dat wijzigingen in User // (zoals toevoegen of verwijderen van Authority) moeten worden doorgegeven aan de gerelateerde Authority-entiteiten. cascade = CascadeType.ALL, orphanRemoval = true, // fetch = FetchType.EAGER specificeert dat de authorities bij // het laden van een User-object onmiddellijk moeten worden opgehaald. fetch = FetchType.EAGER) private Set<Authority> authorities = new HashSet<>(); // Deze 3 variabelen zijn niet verplicht. // Je mag ook een "String banaan;" toevoegen, als je dat graag wilt. //@Column word gebruikt om de tabel aan te passen @Column(nullable = false) private boolean enabled = true; @Column private String apikey; @Column private String email; @OneToOne(mappedBy = "user") private ImageData imageData; @OneToOne(mappedBy = "user") private UserProfile userProfile; // @OneToMany(mappedBy = "user") // private List<BlogPost> blogPosts; @OneToMany(mappedBy = "user", cascade = CascadeType.ALL) @OnDelete(action = OnDeleteAction.CASCADE) private List<BlogPost> blogPosts; // De getters en setters worden gebruikt om toegang te krijgen tot en wijzigingen // aan te brengen in de eigenschappen van het gebruikersobject. // Set<Authority> authorities-verzameling: // Dit is een set van Authority-objecten die de rollen of rechten van de gebruiker vertegenwoordigen. // De addAuthority en removeAuthority-methoden worden gebruikt om autoriteiten toe te voegen of te verwijderen. public void addAuthority(Authority authority) { this.authorities.add(authority); } public void removeAuthority(Authority authority) { this.authorities.remove(authority); } }
rayzathegrave/ConsumerGramBackendv2
src/main/java/nl/consumergram/consumergramv2/models/User.java
878
//De @Entity-annotatie geeft aan dat dit een JPA-entity is, wat betekent dat het overeenkomt met een tabel in de database.
line_comment
nl
package nl.consumergram.consumergramv2.models; //Deze klasse definieert de structuur van de gebruikersidentiteit met zijn eigenschappen en de relatie met autoriteiten. // Het wordt gebruikt om gebruikersgegevens in de database op te slaan en te manipuleren met behulp van JPA. import jakarta.persistence.*; import lombok.Data; import lombok.Setter; import org.hibernate.annotations.OnDelete; import org.hibernate.annotations.OnDeleteAction; import java.util.HashSet; import java.util.List; import java.util.Set; //De @Entity-annotatie<SUF> @Entity @Data @Setter //De @Table(name = "users")-annotatie specificeert de naam van de database-tabel waarmee deze entiteit overeenkomt. @Table(name = "users") public class User { // Deze eerste 3 variabelen zijn verplicht om te kunnen inloggen met een username, password en rol. // @Column(nullable = false, unique = true) specificeert dat username niet leeg mag zijn // (nullable = false) en uniek moet zijn in de database. @Id @Column(nullable = false, unique = true) private String username; @Column(nullable = false, length = 255) private String password; // Dit definieert een een-op-veel-relatie tussen User en Authority // (waarschijnlijk een andere entiteit die de rollen of rechten van een gebruiker vertegenwoordigt). @OneToMany( targetEntity = Authority.class, // mappedBy = "username" geeft aan dat de User-entiteit de kant is die de relatie // beheert via het veld username in de Authority-entiteit. mappedBy = "username", // cascade = CascadeType.ALL geeft aan dat wijzigingen in User // (zoals toevoegen of verwijderen van Authority) moeten worden doorgegeven aan de gerelateerde Authority-entiteiten. cascade = CascadeType.ALL, orphanRemoval = true, // fetch = FetchType.EAGER specificeert dat de authorities bij // het laden van een User-object onmiddellijk moeten worden opgehaald. fetch = FetchType.EAGER) private Set<Authority> authorities = new HashSet<>(); // Deze 3 variabelen zijn niet verplicht. // Je mag ook een "String banaan;" toevoegen, als je dat graag wilt. //@Column word gebruikt om de tabel aan te passen @Column(nullable = false) private boolean enabled = true; @Column private String apikey; @Column private String email; @OneToOne(mappedBy = "user") private ImageData imageData; @OneToOne(mappedBy = "user") private UserProfile userProfile; // @OneToMany(mappedBy = "user") // private List<BlogPost> blogPosts; @OneToMany(mappedBy = "user", cascade = CascadeType.ALL) @OnDelete(action = OnDeleteAction.CASCADE) private List<BlogPost> blogPosts; // De getters en setters worden gebruikt om toegang te krijgen tot en wijzigingen // aan te brengen in de eigenschappen van het gebruikersobject. // Set<Authority> authorities-verzameling: // Dit is een set van Authority-objecten die de rollen of rechten van de gebruiker vertegenwoordigen. // De addAuthority en removeAuthority-methoden worden gebruikt om autoriteiten toe te voegen of te verwijderen. public void addAuthority(Authority authority) { this.authorities.add(authority); } public void removeAuthority(Authority authority) { this.authorities.remove(authority); } }
169774_6
package com.app.vinnie.myapplication; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import android.Manifest; import android.app.Activity; import android.app.ProgressDialog; import android.content.ContentValues; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.ContactsContract; import android.provider.MediaStore; import android.text.TextUtils; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.android.material.bottomnavigation.BottomNavigationView; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.Query; import com.google.firebase.database.ValueEventListener; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.EventListener; import com.google.firebase.firestore.FieldValue; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.FirebaseFirestoreException; import com.google.firebase.firestore.SetOptions; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; import com.squareup.picasso.Picasso; import java.security.Key; import java.util.HashMap; import java.util.Map; import static com.google.firebase.storage.FirebaseStorage.getInstance; public class Profile extends AppCompatActivity { BottomNavigationView mBottomnavigation; Button mdeleteButton; TextView mUsername, mPhone, mEmail; ImageView mProfilepic; FloatingActionButton mfab; ProgressDialog pd; //farebase FirebaseUser muser; FirebaseAuth mAuth; FirebaseFirestore mStore; DatabaseReference mDatabaseref; FirebaseDatabase mdatabase; //storage StorageReference storageReference; //path where images of user profile will be stored String storagePath = "Users_Profile_Imgs/"; String userID; //uri of picked image Uri image_uri; // private static final int CAMERA_REQUEST_CODE = 100; private static final int STORAGE_REQUEST_CODE = 200; private static final int IMAGE_PICK_GALLERY_CODE = 300; private static final int IMAGE_PICK_CAMERA_CODE = 400; //arrays of permission to be requested String cameraPermissions[]; String storagePermissions[]; //TRY @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); //TRY //init firebase muser = FirebaseAuth.getInstance().getCurrentUser(); mAuth = FirebaseAuth.getInstance(); mStore = FirebaseFirestore.getInstance(); userID = mAuth.getCurrentUser().getUid(); storageReference = getInstance().getReference(); //fbase stor ref //views mdeleteButton = findViewById(R.id.ButtonDelete); mBottomnavigation = findViewById(R.id.bottom_navigation); mUsername = findViewById(R.id.username_Textview); mPhone = findViewById(R.id.phonenumber_Textview); mEmail = findViewById(R.id.userEmail_Textview); mProfilepic = findViewById(R.id.Profilepic); mfab = findViewById(R.id.fab); //init progress dialog pd = new ProgressDialog(getApplication()); //init arrays of permissons cameraPermissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}; storagePermissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}; //referentie naar de userTest deel en vervolgens adhv USERID de momenteel ingelogde user DocumentReference documentReference = mStore.collection("usersTest").document(userID); documentReference.addSnapshotListener(this, new EventListener<DocumentSnapshot>() { @Override public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) { //userinfo uit database halen en in textviews zetten mPhone.setText(documentSnapshot.getString("phone")); mUsername.setText(documentSnapshot.getString("uname")); mEmail.setText(documentSnapshot.getString("email")); String image = documentSnapshot.getString("image"); try { Picasso.get().load(image).into(mProfilepic); } catch (Exception d){ Picasso.get().load(R.drawable.ic_user_name).into(mProfilepic); } } }); //set profile selected mBottomnavigation.setSelectedItemId(R.id.profile); //fab onclicklist mfab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showEditProfileDialog(); } }); //perform itemSelectedListner mBottomnavigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) { switch (menuItem.getItemId()){ case R.id.home: startActivity(new Intent(getApplicationContext(), MainActivity.class)); overridePendingTransition(0,0); return true; case R.id.profile: return true; case R.id.settings: startActivity(new Intent(getApplicationContext(), Settings.class)); overridePendingTransition(0,0); return true; case R.id.saunaList: startActivity(new Intent(getApplicationContext(), SaunaList.class)); overridePendingTransition(0,0); return true; } return false; } }); mdeleteButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder dialog = new AlertDialog.Builder(Profile.this); dialog.setTitle("Are you sure you want to delete your account?"); dialog.setMessage("Deleting your account is permanent and will remove all content including comments, avatars and profile settings. "); dialog.setPositiveButton("DELETE", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { muser.delete().addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()){ deleteUser(userID); Toast.makeText(Profile.this, "Account deleted", Toast.LENGTH_SHORT).show(); startActivity(new Intent(getApplicationContext(), Login.class)); finish(); } else{ String errormessage = task.getException().getMessage(); Toast.makeText(Profile.this,"error acquired" + errormessage,Toast.LENGTH_LONG).show(); } } }); } }); dialog.setNegativeButton("Dismiss", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog alertDialog = dialog.create(); alertDialog.show(); } }); } private boolean checkStoragePermission(){ boolean result = ContextCompat.checkSelfPermission(Profile.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED); return result; } @RequiresApi(api = Build.VERSION_CODES.M) private void requestStoragePermission(){ //min api verhogen requestPermissions(storagePermissions ,STORAGE_REQUEST_CODE); } private boolean checkCameraPermission(){ boolean result = ContextCompat.checkSelfPermission(Profile.this, Manifest.permission.CAMERA) == (PackageManager.PERMISSION_GRANTED); boolean result1 = ContextCompat.checkSelfPermission(Profile.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED); return result && result1; } //min api verhogen @RequiresApi(api = Build.VERSION_CODES.M) private void requestCameraPermission(){ requestPermissions(cameraPermissions ,CAMERA_REQUEST_CODE); } private void showEditProfileDialog() { //show dialog options //edit profile picture, name, phone number String options[]= {"Edit profile picture", "Edit name", "Edit phone number"}; //alert AlertDialog.Builder builder = new AlertDialog.Builder(Profile.this); //set title builder.setTitle("Choose Action"); // set items to dialog builder.setItems(options, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //handle dialog item clicks switch (which){ case 0: pd.setMessage("Updating profile picture"); showImagePicDialog(); break; case 1: pd.setMessage("Updating username"); showNamePhoneUpdateDialog("uname"); break; case 2: pd.setMessage("Updating phone number"); showNamePhoneUpdateDialog("phone"); break; } } }); //create and show dialog builder.create(); builder.show(); } private void showNamePhoneUpdateDialog(final String key) { AlertDialog.Builder builder = new AlertDialog.Builder(Profile.this); builder.setTitle("update"+ key); //set layout of dialog LinearLayout linearLayout = new LinearLayout(getApplication()); linearLayout.setOrientation(LinearLayout.VERTICAL); linearLayout.setPadding(10,10,10,10); //add edit text final EditText editText = new EditText(getApplication()); editText.setHint("Enter"+key); //edit update name or photo linearLayout.addView(editText); builder.setView(linearLayout); builder.setPositiveButton("update", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //input text from edit text String value = editText.getText().toString().trim(); if (!TextUtils.isEmpty(value)){ HashMap<String, Object> result = new HashMap<>(); result.put(key, value); DocumentReference documentReference = mStore.collection("usersTest").document(userID); documentReference.update(key, value); } else { Toast.makeText(Profile.this, "please enter"+key, Toast.LENGTH_SHORT).show(); } } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); //create and show dialog builder.create(); builder.show(); } private void showImagePicDialog() { //show dialog options //Camera, choose from gallery String options[]= {"Open camera", "Choose from gallery"}; //alert AlertDialog.Builder builder = new AlertDialog.Builder(Profile.this); //set title builder.setTitle("Pick image from:"); // set items to dialog builder.setItems(options, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //handle dialog item clicks switch (which){ case 0: //pd.setMessage("Camera"); // showImagePicDialog(); if(!checkCameraPermission()){ requestCameraPermission(); } else { pickFromCamera(); } break; case 1: if(!checkStoragePermission()){ requestStoragePermission(); } else { requestStoragePermission(); } // pd.setMessage("Choose from gallery"); break; } } }); //create and show dialog builder.create(); builder.show(); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { //deze methode wordt aangeroepen wanneer de user Allow of Deny kiest van de dialog //deze keuze wordt hier afgehandeld switch (requestCode){ case CAMERA_REQUEST_CODE:{ if (grantResults.length>0){ //checken of we toegang hebben tot camera boolean cameraAccepted =grantResults[0] == PackageManager.PERMISSION_GRANTED; boolean writeStorageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED; if(cameraAccepted && writeStorageAccepted){ pickFromCamera(); } } else { //toegang geweigerd Toast.makeText(Profile.this, "please enalble camera & storage permission", Toast.LENGTH_SHORT).show(); } } break; case STORAGE_REQUEST_CODE:{ //van gallerij: eerst checkn of we hiervoor toestemming hebben if (grantResults.length>0){ boolean writeStorageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED; if(writeStorageAccepted){ pickFromGallery(); } } else { //toegang geweigerd Toast.makeText(Profile.this, "please enalble storage permission", Toast.LENGTH_SHORT).show(); } } break; } } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { //deze methode wordt opgeroepne na het nemen van een foto van camera of gallerij if (resultCode == RESULT_OK) { if (requestCode == IMAGE_PICK_GALLERY_CODE) { //abeelding gekozen vanuit de gallerij --> verkrijgen van uri van de image image_uri = data.getData(); uploadProfileCoverphoto(image_uri); } if (requestCode == IMAGE_PICK_CAMERA_CODE) { //afbeelding gekozen met camera uploadProfileCoverphoto(image_uri); } } super.onActivityResult(requestCode, resultCode, data); } private void uploadProfileCoverphoto(final Uri uri) { //path and name of image t be stored in firebase storage String filePathandName = storagePath+ "" + "image" + "_"+ userID; StorageReference storageReference2 = storageReference.child(filePathandName); storageReference2.putFile(uri) .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl(); while (!uriTask.isSuccessful()); Uri downloadUti = uriTask.getResult(); //check if image is dowloaded or not if (uriTask.isSuccessful()){ //image upload //add/update url in users database HashMap<String, Object> results = new HashMap<>(); results.put("image", downloadUti.toString()); DocumentReference documentReference = mStore.collection("usersTest").document(userID); documentReference.update("image", downloadUti.toString()); } else { //error Toast.makeText(Profile.this, "Some error occured", Toast.LENGTH_SHORT).show(); } } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { pd.dismiss(); Toast.makeText(Profile.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } }); } private void pickFromCamera() { //intent of picking image from device camera ContentValues values = new ContentValues(); values.put(MediaStore.Images.Media.TITLE, "Temp Pic"); values.put(MediaStore.Images.Media.DESCRIPTION, "Temp Description"); //put image uri image_uri = Profile.this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); //intent to start camera Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri); startActivityForResult(cameraIntent, IMAGE_PICK_CAMERA_CODE); } //check private void pickFromGallery(){ //pick from gallery Intent galleryIntent = new Intent(Intent.ACTION_PICK); galleryIntent.setType("image/*"); startActivityForResult(galleryIntent, IMAGE_PICK_GALLERY_CODE); } //logout voor ap --> terug naar login activity public void logout(View view) { FirebaseAuth.getInstance().signOut();//logout startActivity(new Intent(Profile.this, Login.class)); this.finish(); } public void deleteUser(String userid){ mStore.collection("usersTest").document(userid).delete(); } }
AP-IT-GH/intprojectrepo-thermo-team
thermo-sauna/app/src/main/java/com/app/vinnie/myapplication/Profile.java
4,214
//referentie naar de userTest deel en vervolgens adhv USERID de momenteel ingelogde user
line_comment
nl
package com.app.vinnie.myapplication; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import android.Manifest; import android.app.Activity; import android.app.ProgressDialog; import android.content.ContentValues; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.ContactsContract; import android.provider.MediaStore; import android.text.TextUtils; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.android.material.bottomnavigation.BottomNavigationView; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.Query; import com.google.firebase.database.ValueEventListener; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.EventListener; import com.google.firebase.firestore.FieldValue; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.FirebaseFirestoreException; import com.google.firebase.firestore.SetOptions; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; import com.squareup.picasso.Picasso; import java.security.Key; import java.util.HashMap; import java.util.Map; import static com.google.firebase.storage.FirebaseStorage.getInstance; public class Profile extends AppCompatActivity { BottomNavigationView mBottomnavigation; Button mdeleteButton; TextView mUsername, mPhone, mEmail; ImageView mProfilepic; FloatingActionButton mfab; ProgressDialog pd; //farebase FirebaseUser muser; FirebaseAuth mAuth; FirebaseFirestore mStore; DatabaseReference mDatabaseref; FirebaseDatabase mdatabase; //storage StorageReference storageReference; //path where images of user profile will be stored String storagePath = "Users_Profile_Imgs/"; String userID; //uri of picked image Uri image_uri; // private static final int CAMERA_REQUEST_CODE = 100; private static final int STORAGE_REQUEST_CODE = 200; private static final int IMAGE_PICK_GALLERY_CODE = 300; private static final int IMAGE_PICK_CAMERA_CODE = 400; //arrays of permission to be requested String cameraPermissions[]; String storagePermissions[]; //TRY @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); //TRY //init firebase muser = FirebaseAuth.getInstance().getCurrentUser(); mAuth = FirebaseAuth.getInstance(); mStore = FirebaseFirestore.getInstance(); userID = mAuth.getCurrentUser().getUid(); storageReference = getInstance().getReference(); //fbase stor ref //views mdeleteButton = findViewById(R.id.ButtonDelete); mBottomnavigation = findViewById(R.id.bottom_navigation); mUsername = findViewById(R.id.username_Textview); mPhone = findViewById(R.id.phonenumber_Textview); mEmail = findViewById(R.id.userEmail_Textview); mProfilepic = findViewById(R.id.Profilepic); mfab = findViewById(R.id.fab); //init progress dialog pd = new ProgressDialog(getApplication()); //init arrays of permissons cameraPermissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}; storagePermissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}; //referentie naar<SUF> DocumentReference documentReference = mStore.collection("usersTest").document(userID); documentReference.addSnapshotListener(this, new EventListener<DocumentSnapshot>() { @Override public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) { //userinfo uit database halen en in textviews zetten mPhone.setText(documentSnapshot.getString("phone")); mUsername.setText(documentSnapshot.getString("uname")); mEmail.setText(documentSnapshot.getString("email")); String image = documentSnapshot.getString("image"); try { Picasso.get().load(image).into(mProfilepic); } catch (Exception d){ Picasso.get().load(R.drawable.ic_user_name).into(mProfilepic); } } }); //set profile selected mBottomnavigation.setSelectedItemId(R.id.profile); //fab onclicklist mfab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showEditProfileDialog(); } }); //perform itemSelectedListner mBottomnavigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) { switch (menuItem.getItemId()){ case R.id.home: startActivity(new Intent(getApplicationContext(), MainActivity.class)); overridePendingTransition(0,0); return true; case R.id.profile: return true; case R.id.settings: startActivity(new Intent(getApplicationContext(), Settings.class)); overridePendingTransition(0,0); return true; case R.id.saunaList: startActivity(new Intent(getApplicationContext(), SaunaList.class)); overridePendingTransition(0,0); return true; } return false; } }); mdeleteButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder dialog = new AlertDialog.Builder(Profile.this); dialog.setTitle("Are you sure you want to delete your account?"); dialog.setMessage("Deleting your account is permanent and will remove all content including comments, avatars and profile settings. "); dialog.setPositiveButton("DELETE", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { muser.delete().addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()){ deleteUser(userID); Toast.makeText(Profile.this, "Account deleted", Toast.LENGTH_SHORT).show(); startActivity(new Intent(getApplicationContext(), Login.class)); finish(); } else{ String errormessage = task.getException().getMessage(); Toast.makeText(Profile.this,"error acquired" + errormessage,Toast.LENGTH_LONG).show(); } } }); } }); dialog.setNegativeButton("Dismiss", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog alertDialog = dialog.create(); alertDialog.show(); } }); } private boolean checkStoragePermission(){ boolean result = ContextCompat.checkSelfPermission(Profile.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED); return result; } @RequiresApi(api = Build.VERSION_CODES.M) private void requestStoragePermission(){ //min api verhogen requestPermissions(storagePermissions ,STORAGE_REQUEST_CODE); } private boolean checkCameraPermission(){ boolean result = ContextCompat.checkSelfPermission(Profile.this, Manifest.permission.CAMERA) == (PackageManager.PERMISSION_GRANTED); boolean result1 = ContextCompat.checkSelfPermission(Profile.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED); return result && result1; } //min api verhogen @RequiresApi(api = Build.VERSION_CODES.M) private void requestCameraPermission(){ requestPermissions(cameraPermissions ,CAMERA_REQUEST_CODE); } private void showEditProfileDialog() { //show dialog options //edit profile picture, name, phone number String options[]= {"Edit profile picture", "Edit name", "Edit phone number"}; //alert AlertDialog.Builder builder = new AlertDialog.Builder(Profile.this); //set title builder.setTitle("Choose Action"); // set items to dialog builder.setItems(options, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //handle dialog item clicks switch (which){ case 0: pd.setMessage("Updating profile picture"); showImagePicDialog(); break; case 1: pd.setMessage("Updating username"); showNamePhoneUpdateDialog("uname"); break; case 2: pd.setMessage("Updating phone number"); showNamePhoneUpdateDialog("phone"); break; } } }); //create and show dialog builder.create(); builder.show(); } private void showNamePhoneUpdateDialog(final String key) { AlertDialog.Builder builder = new AlertDialog.Builder(Profile.this); builder.setTitle("update"+ key); //set layout of dialog LinearLayout linearLayout = new LinearLayout(getApplication()); linearLayout.setOrientation(LinearLayout.VERTICAL); linearLayout.setPadding(10,10,10,10); //add edit text final EditText editText = new EditText(getApplication()); editText.setHint("Enter"+key); //edit update name or photo linearLayout.addView(editText); builder.setView(linearLayout); builder.setPositiveButton("update", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //input text from edit text String value = editText.getText().toString().trim(); if (!TextUtils.isEmpty(value)){ HashMap<String, Object> result = new HashMap<>(); result.put(key, value); DocumentReference documentReference = mStore.collection("usersTest").document(userID); documentReference.update(key, value); } else { Toast.makeText(Profile.this, "please enter"+key, Toast.LENGTH_SHORT).show(); } } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); //create and show dialog builder.create(); builder.show(); } private void showImagePicDialog() { //show dialog options //Camera, choose from gallery String options[]= {"Open camera", "Choose from gallery"}; //alert AlertDialog.Builder builder = new AlertDialog.Builder(Profile.this); //set title builder.setTitle("Pick image from:"); // set items to dialog builder.setItems(options, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //handle dialog item clicks switch (which){ case 0: //pd.setMessage("Camera"); // showImagePicDialog(); if(!checkCameraPermission()){ requestCameraPermission(); } else { pickFromCamera(); } break; case 1: if(!checkStoragePermission()){ requestStoragePermission(); } else { requestStoragePermission(); } // pd.setMessage("Choose from gallery"); break; } } }); //create and show dialog builder.create(); builder.show(); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { //deze methode wordt aangeroepen wanneer de user Allow of Deny kiest van de dialog //deze keuze wordt hier afgehandeld switch (requestCode){ case CAMERA_REQUEST_CODE:{ if (grantResults.length>0){ //checken of we toegang hebben tot camera boolean cameraAccepted =grantResults[0] == PackageManager.PERMISSION_GRANTED; boolean writeStorageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED; if(cameraAccepted && writeStorageAccepted){ pickFromCamera(); } } else { //toegang geweigerd Toast.makeText(Profile.this, "please enalble camera & storage permission", Toast.LENGTH_SHORT).show(); } } break; case STORAGE_REQUEST_CODE:{ //van gallerij: eerst checkn of we hiervoor toestemming hebben if (grantResults.length>0){ boolean writeStorageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED; if(writeStorageAccepted){ pickFromGallery(); } } else { //toegang geweigerd Toast.makeText(Profile.this, "please enalble storage permission", Toast.LENGTH_SHORT).show(); } } break; } } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { //deze methode wordt opgeroepne na het nemen van een foto van camera of gallerij if (resultCode == RESULT_OK) { if (requestCode == IMAGE_PICK_GALLERY_CODE) { //abeelding gekozen vanuit de gallerij --> verkrijgen van uri van de image image_uri = data.getData(); uploadProfileCoverphoto(image_uri); } if (requestCode == IMAGE_PICK_CAMERA_CODE) { //afbeelding gekozen met camera uploadProfileCoverphoto(image_uri); } } super.onActivityResult(requestCode, resultCode, data); } private void uploadProfileCoverphoto(final Uri uri) { //path and name of image t be stored in firebase storage String filePathandName = storagePath+ "" + "image" + "_"+ userID; StorageReference storageReference2 = storageReference.child(filePathandName); storageReference2.putFile(uri) .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl(); while (!uriTask.isSuccessful()); Uri downloadUti = uriTask.getResult(); //check if image is dowloaded or not if (uriTask.isSuccessful()){ //image upload //add/update url in users database HashMap<String, Object> results = new HashMap<>(); results.put("image", downloadUti.toString()); DocumentReference documentReference = mStore.collection("usersTest").document(userID); documentReference.update("image", downloadUti.toString()); } else { //error Toast.makeText(Profile.this, "Some error occured", Toast.LENGTH_SHORT).show(); } } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { pd.dismiss(); Toast.makeText(Profile.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } }); } private void pickFromCamera() { //intent of picking image from device camera ContentValues values = new ContentValues(); values.put(MediaStore.Images.Media.TITLE, "Temp Pic"); values.put(MediaStore.Images.Media.DESCRIPTION, "Temp Description"); //put image uri image_uri = Profile.this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); //intent to start camera Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri); startActivityForResult(cameraIntent, IMAGE_PICK_CAMERA_CODE); } //check private void pickFromGallery(){ //pick from gallery Intent galleryIntent = new Intent(Intent.ACTION_PICK); galleryIntent.setType("image/*"); startActivityForResult(galleryIntent, IMAGE_PICK_GALLERY_CODE); } //logout voor ap --> terug naar login activity public void logout(View view) { FirebaseAuth.getInstance().signOut();//logout startActivity(new Intent(Profile.this, Login.class)); this.finish(); } public void deleteUser(String userid){ mStore.collection("usersTest").document(userid).delete(); } }
62113_0
package com.nhlstenden.amazonsimulatie.models; import com.nhlstenden.amazonsimulatie.models.generated.Object3D; import com.nhlstenden.amazonsimulatie.models.generated.Rack; /* * Deze class wordt gebruikt om informatie van het model aan de view te kunnen geven. Dit * gaat via het zogenaamde proxy design pattern. Een proxy pattern is een manier om alleen * de getters van een object open te stellen voor andere objecten, maar de setters niet. * Hieronder zie je dat ook gebeuren. De class ProxyObject3D implementeerd wel de Object3D * interface, maar verwijsd door naar een Object3D dat hij binnen in zich houdt. Dit * Object3D, met de naam object (zie code hier direct onder), kan in principe van alles zijn. * Dat object kan ook setters hebben of een updatemethode, etc. Deze methoden mag de view niet * aanroepen, omdat de view dan direct het model veranderd. Dat is niet toegestaan binnen onze * implementatie van MVC. Op deze manier beschermen we daartegen, omdat de view alleen maar ProxyObject3D * objecten krijgt. Hiermee garanderen we dat de view dus alleen objecten krijgt die alleen maar getters * hebben. Zouden we dit niet doen, en bijvoorbeeld een Robot object aan de view geven, dan zouden er * mogelijkheden kunnen zijn zodat de view toch bij de updatemethode van de robot kan komen. Deze mag * alleen de World class aanroepen, dus dat zou onveilige software betekenen. */ public class ProxyObject3D { private Object3D object; public ProxyObject3D(Object3D object) { this.object = object; } public String getId() { return this.object.getId(); } public String getType() { return this.object.getClass().getSimpleName().toLowerCase(); } public String getItem() { if(object instanceof Rack) return ((Rack) object).getItem(); else return null; } public int getX() { return this.object.getX(); } public int getY() { return this.object.getY(); } public int getZ() { return this.object.getZ(); } public int getRotationX() { return this.object.getRotationX(); } public int getRotationY() { return this.object.getRotationY(); } public int getRotationZ() { return this.object.getRotationZ(); } }
AnotherFoxGuy/AzwSimulatie
src/main/java/com/nhlstenden/amazonsimulatie/models/ProxyObject3D.java
600
/* * Deze class wordt gebruikt om informatie van het model aan de view te kunnen geven. Dit * gaat via het zogenaamde proxy design pattern. Een proxy pattern is een manier om alleen * de getters van een object open te stellen voor andere objecten, maar de setters niet. * Hieronder zie je dat ook gebeuren. De class ProxyObject3D implementeerd wel de Object3D * interface, maar verwijsd door naar een Object3D dat hij binnen in zich houdt. Dit * Object3D, met de naam object (zie code hier direct onder), kan in principe van alles zijn. * Dat object kan ook setters hebben of een updatemethode, etc. Deze methoden mag de view niet * aanroepen, omdat de view dan direct het model veranderd. Dat is niet toegestaan binnen onze * implementatie van MVC. Op deze manier beschermen we daartegen, omdat de view alleen maar ProxyObject3D * objecten krijgt. Hiermee garanderen we dat de view dus alleen objecten krijgt die alleen maar getters * hebben. Zouden we dit niet doen, en bijvoorbeeld een Robot object aan de view geven, dan zouden er * mogelijkheden kunnen zijn zodat de view toch bij de updatemethode van de robot kan komen. Deze mag * alleen de World class aanroepen, dus dat zou onveilige software betekenen. */
block_comment
nl
package com.nhlstenden.amazonsimulatie.models; import com.nhlstenden.amazonsimulatie.models.generated.Object3D; import com.nhlstenden.amazonsimulatie.models.generated.Rack; /* * Deze class wordt<SUF>*/ public class ProxyObject3D { private Object3D object; public ProxyObject3D(Object3D object) { this.object = object; } public String getId() { return this.object.getId(); } public String getType() { return this.object.getClass().getSimpleName().toLowerCase(); } public String getItem() { if(object instanceof Rack) return ((Rack) object).getItem(); else return null; } public int getX() { return this.object.getX(); } public int getY() { return this.object.getY(); } public int getZ() { return this.object.getZ(); } public int getRotationX() { return this.object.getRotationX(); } public int getRotationY() { return this.object.getRotationY(); } public int getRotationZ() { return this.object.getRotationZ(); } }
97801_0
package gui.screens; import domein.DomeinController; import gui.company.CompanyCardComponent; import gui.components.CustomMenu; import gui.components.LanguageBundle; import io.github.palexdev.materialfx.controls.MFXButton; import io.github.palexdev.materialfx.controls.MFXCheckbox; import io.github.palexdev.materialfx.controls.MFXScrollPane; import io.github.palexdev.materialfx.controls.MFXSlider; import javafx.geometry.Pos; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Priority; import javafx.scene.layout.VBox; import resources.ResourceController; import java.util.Locale; public class SettingScreen extends MFXScrollPane { private DomeinController dc; private ResourceController rs; private BorderPane root; private CustomMenu menu; private VBox pane = new VBox(); private ComboBox<String> languageComboBox; private static Label title; private static MFXCheckbox checkbox; private static Label soundLabel; private static Label languageLabel; public SettingScreen(BorderPane root, CustomMenu menu, DomeinController dc, ResourceController rs) { this.dc = dc; pane.setAlignment(Pos.TOP_CENTER); pane.setSpacing(200); this.rs = rs; this.root = root; this.menu = menu; this.setContent(pane); this.setFitToHeight(true); this.setFitToWidth(true); setup(); } public void setup() { title = new Label(LanguageBundle.getString("SettingScreen_setting")); title.getStyleClass().add("title"); soundLabel = new Label(LanguageBundle.getString("SettingScreen_sound")); VBox layoutBox = new VBox(); MFXSlider slider = new MFXSlider(); slider.setMin(0); slider.setMax(100); slider.setValue(rs.getCurrentVolume()*100); slider.setOnMouseReleased(e -> { System.out.println(slider.getValue()); rs.changeVolume(slider.getValue()); }); languageLabel = new Label("Language"); languageComboBox = new ComboBox<>(); HBox.setHgrow(languageComboBox, Priority.ALWAYS); languageComboBox.getItems().addAll("en", "nl"); languageComboBox.setValue("en"); // voeg een listener toe aan de ComboBox om de taal te wijzigen languageComboBox.setOnAction(e -> switchLanguage()); layoutBox.setAlignment(Pos.CENTER); checkbox = new MFXCheckbox(LanguageBundle.getString("SettingScreen_mute")); checkbox.setSelected(rs.isMute()); checkbox.setOnAction(e -> rs.handleMute(checkbox.isSelected())); layoutBox.setSpacing(20); layoutBox.getChildren().addAll(soundLabel, slider, checkbox, languageLabel, languageComboBox); pane.getChildren().addAll(title, layoutBox); } private void switchLanguage() { Locale selectedLocale; String selectedLanguage = languageComboBox.getValue(); if (selectedLanguage.equals("en")) { selectedLocale = new Locale("en"); } else { selectedLocale = new Locale("nl"); } // Wijzig de taal in de hele applicatie LanguageBundle.setLocale(selectedLocale); //update taal van pagina waarop je staat updateText(); /*LoginScreen.updateText(); MainScreen.updateText(); CompanyCardComponent.updateText(); NotificationScreen.updateText(); OrderScreen.updateText(); TransportDienstScreen.updateText(); RegisterScreen.updateText(); MyProductsScreen.updateText();*/ } public static void updateText() { title.setText(LanguageBundle.getString("SettingScreen_setting")); checkbox.setText(LanguageBundle.getString("SettingScreen_mute")); soundLabel.setText(LanguageBundle.getString("SettingScreen_sound")); } }
LaurensDM/Webshop-desktop
src/main/java/gui/screens/SettingScreen.java
982
// voeg een listener toe aan de ComboBox om de taal te wijzigen
line_comment
nl
package gui.screens; import domein.DomeinController; import gui.company.CompanyCardComponent; import gui.components.CustomMenu; import gui.components.LanguageBundle; import io.github.palexdev.materialfx.controls.MFXButton; import io.github.palexdev.materialfx.controls.MFXCheckbox; import io.github.palexdev.materialfx.controls.MFXScrollPane; import io.github.palexdev.materialfx.controls.MFXSlider; import javafx.geometry.Pos; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Priority; import javafx.scene.layout.VBox; import resources.ResourceController; import java.util.Locale; public class SettingScreen extends MFXScrollPane { private DomeinController dc; private ResourceController rs; private BorderPane root; private CustomMenu menu; private VBox pane = new VBox(); private ComboBox<String> languageComboBox; private static Label title; private static MFXCheckbox checkbox; private static Label soundLabel; private static Label languageLabel; public SettingScreen(BorderPane root, CustomMenu menu, DomeinController dc, ResourceController rs) { this.dc = dc; pane.setAlignment(Pos.TOP_CENTER); pane.setSpacing(200); this.rs = rs; this.root = root; this.menu = menu; this.setContent(pane); this.setFitToHeight(true); this.setFitToWidth(true); setup(); } public void setup() { title = new Label(LanguageBundle.getString("SettingScreen_setting")); title.getStyleClass().add("title"); soundLabel = new Label(LanguageBundle.getString("SettingScreen_sound")); VBox layoutBox = new VBox(); MFXSlider slider = new MFXSlider(); slider.setMin(0); slider.setMax(100); slider.setValue(rs.getCurrentVolume()*100); slider.setOnMouseReleased(e -> { System.out.println(slider.getValue()); rs.changeVolume(slider.getValue()); }); languageLabel = new Label("Language"); languageComboBox = new ComboBox<>(); HBox.setHgrow(languageComboBox, Priority.ALWAYS); languageComboBox.getItems().addAll("en", "nl"); languageComboBox.setValue("en"); // voeg een<SUF> languageComboBox.setOnAction(e -> switchLanguage()); layoutBox.setAlignment(Pos.CENTER); checkbox = new MFXCheckbox(LanguageBundle.getString("SettingScreen_mute")); checkbox.setSelected(rs.isMute()); checkbox.setOnAction(e -> rs.handleMute(checkbox.isSelected())); layoutBox.setSpacing(20); layoutBox.getChildren().addAll(soundLabel, slider, checkbox, languageLabel, languageComboBox); pane.getChildren().addAll(title, layoutBox); } private void switchLanguage() { Locale selectedLocale; String selectedLanguage = languageComboBox.getValue(); if (selectedLanguage.equals("en")) { selectedLocale = new Locale("en"); } else { selectedLocale = new Locale("nl"); } // Wijzig de taal in de hele applicatie LanguageBundle.setLocale(selectedLocale); //update taal van pagina waarop je staat updateText(); /*LoginScreen.updateText(); MainScreen.updateText(); CompanyCardComponent.updateText(); NotificationScreen.updateText(); OrderScreen.updateText(); TransportDienstScreen.updateText(); RegisterScreen.updateText(); MyProductsScreen.updateText();*/ } public static void updateText() { title.setText(LanguageBundle.getString("SettingScreen_setting")); checkbox.setText(LanguageBundle.getString("SettingScreen_mute")); soundLabel.setText(LanguageBundle.getString("SettingScreen_sound")); } }
33374_6
package login; import logging.LoggingAdapter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Scanner; public abstract class Authentication { private static final Scanner scanner = new Scanner (System.in); private static Authentication singleton; private ArrayList<User> users; /* * Omdat de constructor bereikbaar moet zijn voor de subclasses (in de constructor daarvan), moet deze veranderen * van private (wat gewenst is voor toepassing van het Singleton Pattern) naar protected. */ protected Authentication () { users = new ArrayList<>(); users.add (new User ("user1", "1")); users.add (new User ("user2", "2")); users.add (new User ("user3", "3")); } private ArrayList<User> getUsers () { return users; } private void setUsers (ArrayList<User> users) { this.users = users; } protected static Authentication getInstance (Class classDefinition) { try { // Er wordt een object aangemaakt dat verwijst naar de static methode 'getNewInstance' die dan wel // gedefinieerd moet zijn in de subclass van Authentication (bijv. AuthenticationSimple) die als parameter // van het type Class is meegegeven. Method method = classDefinition.getDeclaredMethod ("getNewInstance"); method.setAccessible (true); if (singleton == null) { singleton = (Authentication) method.invoke(null); } // Als wordt gewisseld tussen eenvoudige en normale authenticatie (of andersom), moet de lijst met gebruikers // (inclusief de actieve of ingelogde gebruiker in die lijst) worden bewaard in het nieuwe // object. else if (!singleton.getClass().getName().equals(classDefinition.getName())) { ArrayList<User> activeUsers = singleton.getUsers(); singleton = (Authentication) method.invoke (null); singleton.setUsers(activeUsers); } method.setAccessible (false); } catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException e) { e.printStackTrace(); LoggingAdapter.getInstance ().printLog (e); } return singleton; } /* * In de lijst met users wordt gezocht naar een gebruiker met userName. */ protected User getUser (String userName) { for (User user : users) { if (user.getUserName().equals (userName)) { return user; } } return null; } /* * In de lijst met user wordt gezocht naar een actieve gebruiker (die misschien zelfs is ingelogd). */ protected User getActiveUser () { for (User user : users) { if (user.isActive ()) { return user; } } return null; } /* * De gebruikersnaam van de actieve gebruiker wordt opgezocht. */ public String getUserNameOfActiveUser () { User activeUser = getActiveUser (); if (activeUser != null) { return activeUser.getUserName (); } else { return "unknown"; } } /* * De naam van een gebruiker wordt ingelezen vanaf het toetsenbord. */ protected String readUserName () { System.out.print ("Voer uw gebruikersnaam in: "); return scanner.nextLine (); } /* * Het password van een gebruiker wordt ingelezen vanaf het toetsenbord. */ protected String readPassword () { System.out.print ("Voer uw password in: "); return scanner.nextLine (); } /* * Een melding (bijv. 'Mislukt') wordt in het volgende formaat getoond: * * ======================================== * = Mislukt = * ======================================== */ protected void printMessage (String message) { System.out.println ("=".repeat (40)); int numberOfSpaces = message.length () > 36 ? 0 : 40 - message.length (); System.out.printf ("= %s%s =", message, " ".repeat (numberOfSpaces)); System.out.println ("=".repeat (40)); } /* * De actieve gebruiker wordt uitgelogd. */ public void logout () { User user = getActiveUser (); if (user != null) { user.logout (); } } protected abstract User getAuthenticatedUser (); protected abstract boolean authenticate (); protected abstract boolean authenticate (User user, String... password); /* * Dit is nu een template method om de zelfde stappen bij lichte (simple) en normale authenticatie te doorlopen. */ public boolean authenticate (String userName, String... password) { // Als de ingelogde gebruiker de gebruiker met userName is, is hij al ingelogd. User user = getAuthenticatedUser (); if ((user != null) && (user.getUserName ().equals (userName))) { return true; } // Als de gebruiker niet bestaat kan hij/zij ook niet inloggen. user = getUser (userName); if (user == null) { LoggingAdapter.getInstance ().printLog (String.format ("Authentication:authenticat - unknow user with username '%s' tried to login.", userName)); return false; } else { // Een eventuele gebruiker die al was ingelogd, wordt uitgelogd. Daarna wordt de nieuwe gebruiker ingelogd. logout (); return authenticate (user, password); } } /* * Dit is nu een template method om de zelfde stappen bij lichte (simple) en normale authenticatie te doorlopen. */ public boolean userIsAuthenticated () { // Als er nog geen gebruiker is ingelogd, wordt die volgens de methode voor lichte of normale authenticatie // ingelogd. if (getAuthenticatedUser () != null) { return true; } else { return authenticate (); } } }
kadmosb1/2021LoggingSolvedWithAdapterPattern
src/main/java/login/Authentication.java
1,465
/* * In de lijst met users wordt gezocht naar een gebruiker met userName. */
block_comment
nl
package login; import logging.LoggingAdapter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Scanner; public abstract class Authentication { private static final Scanner scanner = new Scanner (System.in); private static Authentication singleton; private ArrayList<User> users; /* * Omdat de constructor bereikbaar moet zijn voor de subclasses (in de constructor daarvan), moet deze veranderen * van private (wat gewenst is voor toepassing van het Singleton Pattern) naar protected. */ protected Authentication () { users = new ArrayList<>(); users.add (new User ("user1", "1")); users.add (new User ("user2", "2")); users.add (new User ("user3", "3")); } private ArrayList<User> getUsers () { return users; } private void setUsers (ArrayList<User> users) { this.users = users; } protected static Authentication getInstance (Class classDefinition) { try { // Er wordt een object aangemaakt dat verwijst naar de static methode 'getNewInstance' die dan wel // gedefinieerd moet zijn in de subclass van Authentication (bijv. AuthenticationSimple) die als parameter // van het type Class is meegegeven. Method method = classDefinition.getDeclaredMethod ("getNewInstance"); method.setAccessible (true); if (singleton == null) { singleton = (Authentication) method.invoke(null); } // Als wordt gewisseld tussen eenvoudige en normale authenticatie (of andersom), moet de lijst met gebruikers // (inclusief de actieve of ingelogde gebruiker in die lijst) worden bewaard in het nieuwe // object. else if (!singleton.getClass().getName().equals(classDefinition.getName())) { ArrayList<User> activeUsers = singleton.getUsers(); singleton = (Authentication) method.invoke (null); singleton.setUsers(activeUsers); } method.setAccessible (false); } catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException e) { e.printStackTrace(); LoggingAdapter.getInstance ().printLog (e); } return singleton; } /* * In de lijst<SUF>*/ protected User getUser (String userName) { for (User user : users) { if (user.getUserName().equals (userName)) { return user; } } return null; } /* * In de lijst met user wordt gezocht naar een actieve gebruiker (die misschien zelfs is ingelogd). */ protected User getActiveUser () { for (User user : users) { if (user.isActive ()) { return user; } } return null; } /* * De gebruikersnaam van de actieve gebruiker wordt opgezocht. */ public String getUserNameOfActiveUser () { User activeUser = getActiveUser (); if (activeUser != null) { return activeUser.getUserName (); } else { return "unknown"; } } /* * De naam van een gebruiker wordt ingelezen vanaf het toetsenbord. */ protected String readUserName () { System.out.print ("Voer uw gebruikersnaam in: "); return scanner.nextLine (); } /* * Het password van een gebruiker wordt ingelezen vanaf het toetsenbord. */ protected String readPassword () { System.out.print ("Voer uw password in: "); return scanner.nextLine (); } /* * Een melding (bijv. 'Mislukt') wordt in het volgende formaat getoond: * * ======================================== * = Mislukt = * ======================================== */ protected void printMessage (String message) { System.out.println ("=".repeat (40)); int numberOfSpaces = message.length () > 36 ? 0 : 40 - message.length (); System.out.printf ("= %s%s =", message, " ".repeat (numberOfSpaces)); System.out.println ("=".repeat (40)); } /* * De actieve gebruiker wordt uitgelogd. */ public void logout () { User user = getActiveUser (); if (user != null) { user.logout (); } } protected abstract User getAuthenticatedUser (); protected abstract boolean authenticate (); protected abstract boolean authenticate (User user, String... password); /* * Dit is nu een template method om de zelfde stappen bij lichte (simple) en normale authenticatie te doorlopen. */ public boolean authenticate (String userName, String... password) { // Als de ingelogde gebruiker de gebruiker met userName is, is hij al ingelogd. User user = getAuthenticatedUser (); if ((user != null) && (user.getUserName ().equals (userName))) { return true; } // Als de gebruiker niet bestaat kan hij/zij ook niet inloggen. user = getUser (userName); if (user == null) { LoggingAdapter.getInstance ().printLog (String.format ("Authentication:authenticat - unknow user with username '%s' tried to login.", userName)); return false; } else { // Een eventuele gebruiker die al was ingelogd, wordt uitgelogd. Daarna wordt de nieuwe gebruiker ingelogd. logout (); return authenticate (user, password); } } /* * Dit is nu een template method om de zelfde stappen bij lichte (simple) en normale authenticatie te doorlopen. */ public boolean userIsAuthenticated () { // Als er nog geen gebruiker is ingelogd, wordt die volgens de methode voor lichte of normale authenticatie // ingelogd. if (getAuthenticatedUser () != null) { return true; } else { return authenticate (); } } }
118668_1
/** *De klasse PartTimeWerknemer is een java applicatie * *@author Sophie Moons *@version 1,0 */ import java.lang.*; public class Factuur implements Betaalbaar{ /** *Dit is een main function, hier start het programma */ public int factuurNr; public float factuurBedrag; public Factuur(int factuurNr,float factuurBedrag) { this.factuurNr=factuurNr; this.factuurBedrag=factuurBedrag; } public void betaal() { System.out.println("Betaal het factuur "+factuurNr+" voor een bedrag van "+factuurBedrag); } }//einde programma
MTA-Digital-Broadcast-2/A-Moons-Sophie-De-Cock-Nicolas-Project-MHP
Sophie Moons/Labo Java/blz31/Oef10/Factuur.java
167
/** *Dit is een main function, hier start het programma */
block_comment
nl
/** *De klasse PartTimeWerknemer is een java applicatie * *@author Sophie Moons *@version 1,0 */ import java.lang.*; public class Factuur implements Betaalbaar{ /** *Dit is een<SUF>*/ public int factuurNr; public float factuurBedrag; public Factuur(int factuurNr,float factuurBedrag) { this.factuurNr=factuurNr; this.factuurBedrag=factuurBedrag; } public void betaal() { System.out.println("Betaal het factuur "+factuurNr+" voor een bedrag van "+factuurBedrag); } }//einde programma
78707_2
//hier maken we nog een controller, maar deze geeft alleen de String returntypes , zodat we als het goed is geen tv objecten nodig hebben en de tv model import als het goed is overbodig wordt //todo: class herschrijven voor versimpelde output volgens de opdracht package com.example.novi_be10_techiteasy.controllers; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; //todo deze controller doet vooralsnog niks met de model en repository klasse. hier moet vast verandering in komen //todo voordat ik deze controller ga aanpassen eerst postman apicalls opzetten om responses te testen. @RestController @RequestMapping("televisions")//vaste prefix voor requests gerelateerd aan television requests public class TelevisionControllerBasis { //geen properties hier, de methods doen niks, maar returnen alleen een statuscode en eventueel een string //get all tv's @GetMapping public ResponseEntity<String> getTelevisions() { return ResponseEntity.ok("televisions!");//return de String met een 200 status } //get 1 tv @GetMapping("/{id}") public ResponseEntity<String> getTelevision(@PathVariable int id) { String reqTv = "television number " + id; return ResponseEntity.ok(reqTv); } //post 1 @PostMapping public ResponseEntity<String> createTelevision(@RequestBody String tv){ return ResponseEntity.created(null).body("new television!" +tv);//deze milde error negeren we even omdat deze response letterlijk uit de opgave komt. returnt 201 created status en de string } //put 1 tv @PutMapping("/{id}") public ResponseEntity<Void> updateTelevision(@PathVariable int id ,@RequestBody String televisionData){ //return 204 status return ResponseEntity.noContent().build(); } //delete 1 tv @DeleteMapping("/{id}")//deze method delete niks, maar geeft alleen een melding terug public ResponseEntity<Void> deleteTelevision(@PathVariable int id){ return ResponseEntity.noContent().build();//return 204 status en verder niks } }
szuiderweg/be-hw-techiteasy
src/main/java/com/example/novi_be10_techiteasy/controllers/TelevisionControllerBasis.java
500
//todo deze controller doet vooralsnog niks met de model en repository klasse. hier moet vast verandering in komen
line_comment
nl
//hier maken we nog een controller, maar deze geeft alleen de String returntypes , zodat we als het goed is geen tv objecten nodig hebben en de tv model import als het goed is overbodig wordt //todo: class herschrijven voor versimpelde output volgens de opdracht package com.example.novi_be10_techiteasy.controllers; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; //todo deze<SUF> //todo voordat ik deze controller ga aanpassen eerst postman apicalls opzetten om responses te testen. @RestController @RequestMapping("televisions")//vaste prefix voor requests gerelateerd aan television requests public class TelevisionControllerBasis { //geen properties hier, de methods doen niks, maar returnen alleen een statuscode en eventueel een string //get all tv's @GetMapping public ResponseEntity<String> getTelevisions() { return ResponseEntity.ok("televisions!");//return de String met een 200 status } //get 1 tv @GetMapping("/{id}") public ResponseEntity<String> getTelevision(@PathVariable int id) { String reqTv = "television number " + id; return ResponseEntity.ok(reqTv); } //post 1 @PostMapping public ResponseEntity<String> createTelevision(@RequestBody String tv){ return ResponseEntity.created(null).body("new television!" +tv);//deze milde error negeren we even omdat deze response letterlijk uit de opgave komt. returnt 201 created status en de string } //put 1 tv @PutMapping("/{id}") public ResponseEntity<Void> updateTelevision(@PathVariable int id ,@RequestBody String televisionData){ //return 204 status return ResponseEntity.noContent().build(); } //delete 1 tv @DeleteMapping("/{id}")//deze method delete niks, maar geeft alleen een melding terug public ResponseEntity<Void> deleteTelevision(@PathVariable int id){ return ResponseEntity.noContent().build();//return 204 status en verder niks } }
26136_20
package crepetete.arcgis.evemapp; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.http.client.ClientProtocolException; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.support.v4.app.FragmentActivity; public class HttpManager { // Onze HttpManager regelt alle functies die via het internet werken. Dit // doen we ook door de juiste meegestuurde parameters toe te voegen. private Map<String, String> postParams = new HashMap<String, String>(); private static HttpURLConnection httpConn; private String[] response; private URL url; public HttpURLConnection post(URL url) throws ClientProtocolException, IOException { httpConn = (HttpURLConnection) url.openConnection(); httpConn.setUseCaches(false); httpConn.setDoInput(true); // true indicates the server returns response System.out.println(url); StringBuffer requestParams = new StringBuffer(); if (postParams != null && postParams.size() > 0) { httpConn.setDoOutput(true); // true indicates POST request // creates the params string, encode them using URLEncoder Iterator<String> paramIterator = (postParams).keySet().iterator(); while (paramIterator.hasNext()) { String key = paramIterator.next(); String value = postParams.get(key); requestParams.append(URLEncoder.encode(key, "UTF-8")); requestParams.append("=").append( URLEncoder.encode(value, "UTF-8")); requestParams.append("&"); } // sends POST data OutputStreamWriter writer = new OutputStreamWriter( httpConn.getOutputStream()); writer.write(requestParams.toString()); writer.flush(); } response = readMultipleLinesRespone(); System.out.println(response); return httpConn; } // We hebben twee POST functies, omdat de ene soms een JSON response krijgt // die gelezen moet worden. public JSONObject postWithJSONResponse(URL url, String source) throws ClientProtocolException, IOException, JSONException { httpConn = (HttpURLConnection) url.openConnection(); httpConn.setUseCaches(false); httpConn.setDoInput(true); // true indicates the server returns response StringBuffer requestParams = new StringBuffer(); if (postParams != null && postParams.size() > 0) { httpConn.setDoOutput(true); // true indicates POST request // creates the params string, encode them using URLEncoder Iterator<String> paramIterator = (postParams).keySet().iterator(); while (paramIterator.hasNext()) { String key = paramIterator.next(); String value = postParams.get(key); requestParams.append(URLEncoder.encode(key, "UTF-8")); requestParams.append("=").append( URLEncoder.encode(value, "UTF-8")); requestParams.append("&"); } // sends POST data OutputStreamWriter writer = new OutputStreamWriter( httpConn.getOutputStream()); writer.write(requestParams.toString()); writer.flush(); } response = readMultipleLinesRespone(); JSONObject jsonObj = null; if (!response[0].contains("<br />")) { jsonObj = new JSONObject(response[0]); } else { System.out.println("null"); } return jsonObj; } // Check of er internet is public boolean isOnline(MainMap mainMap) { ConnectivityManager cm = (ConnectivityManager) mainMap .getSystemService(FragmentActivity.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnectedOrConnecting()) { return true; } return false; } // Functie om de locatie van vrienden op te halen. public JSONObject getLocOthers(User user, Context c) throws ClientProtocolException, IOException, JSONException { postParams.clear(); postParams.put("id", user.getMyId()); postParams.put("event_id", "1"); url = new URL(c.getString(R.string.backend_loc_others)); return postWithJSONResponse(url, "getLocOthers"); } // Functie om informatie van een evenement te krijgen via het ID. public JSONObject getEvent(String eventId, Context c) throws ClientProtocolException, IOException, JSONException { postParams.clear(); postParams.put("id", eventId); url = new URL(c.getString(R.string.backend_events)); return postWithJSONResponse(url, "getEvent"); } // Functie om de objecten op de kaart op te halen van een evenement // (Stage/WC etc). public JSONObject getEventMapInfo(String eventId, Context c) throws ClientProtocolException, IOException, JSONException { postParams.clear(); postParams.put("id", eventId); url = new URL(c.getString(R.string.backend_event_map_info)); return postWithJSONResponse(url, "getEventMapInfo"); } // Functie om een plaatje op te halen van een URL. public Drawable LoadImageFromWebOperations(String url) { try { InputStream is = (InputStream) new URL(url).getContent(); Drawable d = Drawable.createFromStream(is, "info"); return d; } catch (Exception e) { return null; } } // Functie waarmee een gebruiker in de database wordt gestopt als hij de app // voor het eerst gebruikt, anders heeft deze functie geen effect. public void makeRegisterParams(User user, Context c, ArrayList<Friend> friendsList) throws ClientProtocolException, IOException { postParams.clear(); postParams.put("id", user.getMyId()); for (int i = 0; i < friendsList.size(); i++) { postParams.put("friends", friendsList.get(i).getId()); } postParams.put("privacysetting", "full"); url = new URL(c.getString(R.string.backend_register)); post(url); } // Functie om de locatie van de gebruiker op te slaan in de database zodat // andere gebruikers deze locatie ook kunnen updaten. public void makeLoc_SelfParams(User user, Context c) throws ClientProtocolException, IOException { postParams.clear(); postParams.put("id", user.getMyId()); postParams.put("lat", Double.toString(user.getMyLat())); postParams.put("lng", Double.toString(user.getMyLng())); postParams.put("event_id", "1"); url = new URL(c.getString(R.string.backend_location_self)); post(url); } // Functie om de response van een request leesbaar te maken. public String[] readMultipleLinesRespone() throws IOException { InputStream inputStream = null; if (httpConn != null) { inputStream = httpConn.getInputStream(); } else { throw new IOException("Connection is not established."); } BufferedReader reader = new BufferedReader(new InputStreamReader( inputStream)); List<String> response = new ArrayList<String>(); String line = ""; while ((line = reader.readLine()) != null) { response.add(line); } reader.close(); return (String[]) response.toArray(new String[0]); } // Functie om een Facebook foto op te halen als BitMap, zodat deze makkelijk // resized kan worden. public Bitmap getFacebookBitMap(String s) throws IOException { URL url_value = new URL(s); Bitmap bm = getRoundedShape(BitmapFactory.decodeStream(url_value .openConnection().getInputStream())); return bm; } // Hier zorgen we ervoor dat de facebook plaatjes als rondjes op de kaart // kunnen worden gezet. public Bitmap getRoundedShape(Bitmap scaleBitmapImage) { int targetWidth = 50; int targetHeight = 50; Bitmap targetBitmap = Bitmap.createBitmap(targetWidth, targetHeight, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(targetBitmap); Path path = new Path(); path.addCircle(((float) targetWidth) / 2, ((float) targetHeight) / 2, (Math.min(((float) targetWidth), ((float) targetHeight)) / 2), Path.Direction.CW); Paint paint = new Paint(); paint.setColor(Color.GRAY); // paint.setStyle(Paint.Style.STROKE); paint.setStyle(Paint.Style.FILL); paint.setAntiAlias(true); paint.setDither(true); paint.setFilterBitmap(true); canvas.drawOval(new RectF(0, 0, targetWidth, targetHeight), paint); // paint.setColor(Color.TRANSPARENT); canvas.clipPath(path); Bitmap sourceBitmap = scaleBitmapImage; canvas.drawBitmap(sourceBitmap, new Rect(0, 0, sourceBitmap.getWidth(), sourceBitmap.getHeight()), new RectF(0, 0, targetWidth, targetHeight), paint); return targetBitmap; } }
PatrickvdGraaf/EveGisApp
src/crepetete/arcgis/evemapp/HttpManager.java
2,498
// andere gebruikers deze locatie ook kunnen updaten.
line_comment
nl
package crepetete.arcgis.evemapp; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.http.client.ClientProtocolException; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.support.v4.app.FragmentActivity; public class HttpManager { // Onze HttpManager regelt alle functies die via het internet werken. Dit // doen we ook door de juiste meegestuurde parameters toe te voegen. private Map<String, String> postParams = new HashMap<String, String>(); private static HttpURLConnection httpConn; private String[] response; private URL url; public HttpURLConnection post(URL url) throws ClientProtocolException, IOException { httpConn = (HttpURLConnection) url.openConnection(); httpConn.setUseCaches(false); httpConn.setDoInput(true); // true indicates the server returns response System.out.println(url); StringBuffer requestParams = new StringBuffer(); if (postParams != null && postParams.size() > 0) { httpConn.setDoOutput(true); // true indicates POST request // creates the params string, encode them using URLEncoder Iterator<String> paramIterator = (postParams).keySet().iterator(); while (paramIterator.hasNext()) { String key = paramIterator.next(); String value = postParams.get(key); requestParams.append(URLEncoder.encode(key, "UTF-8")); requestParams.append("=").append( URLEncoder.encode(value, "UTF-8")); requestParams.append("&"); } // sends POST data OutputStreamWriter writer = new OutputStreamWriter( httpConn.getOutputStream()); writer.write(requestParams.toString()); writer.flush(); } response = readMultipleLinesRespone(); System.out.println(response); return httpConn; } // We hebben twee POST functies, omdat de ene soms een JSON response krijgt // die gelezen moet worden. public JSONObject postWithJSONResponse(URL url, String source) throws ClientProtocolException, IOException, JSONException { httpConn = (HttpURLConnection) url.openConnection(); httpConn.setUseCaches(false); httpConn.setDoInput(true); // true indicates the server returns response StringBuffer requestParams = new StringBuffer(); if (postParams != null && postParams.size() > 0) { httpConn.setDoOutput(true); // true indicates POST request // creates the params string, encode them using URLEncoder Iterator<String> paramIterator = (postParams).keySet().iterator(); while (paramIterator.hasNext()) { String key = paramIterator.next(); String value = postParams.get(key); requestParams.append(URLEncoder.encode(key, "UTF-8")); requestParams.append("=").append( URLEncoder.encode(value, "UTF-8")); requestParams.append("&"); } // sends POST data OutputStreamWriter writer = new OutputStreamWriter( httpConn.getOutputStream()); writer.write(requestParams.toString()); writer.flush(); } response = readMultipleLinesRespone(); JSONObject jsonObj = null; if (!response[0].contains("<br />")) { jsonObj = new JSONObject(response[0]); } else { System.out.println("null"); } return jsonObj; } // Check of er internet is public boolean isOnline(MainMap mainMap) { ConnectivityManager cm = (ConnectivityManager) mainMap .getSystemService(FragmentActivity.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnectedOrConnecting()) { return true; } return false; } // Functie om de locatie van vrienden op te halen. public JSONObject getLocOthers(User user, Context c) throws ClientProtocolException, IOException, JSONException { postParams.clear(); postParams.put("id", user.getMyId()); postParams.put("event_id", "1"); url = new URL(c.getString(R.string.backend_loc_others)); return postWithJSONResponse(url, "getLocOthers"); } // Functie om informatie van een evenement te krijgen via het ID. public JSONObject getEvent(String eventId, Context c) throws ClientProtocolException, IOException, JSONException { postParams.clear(); postParams.put("id", eventId); url = new URL(c.getString(R.string.backend_events)); return postWithJSONResponse(url, "getEvent"); } // Functie om de objecten op de kaart op te halen van een evenement // (Stage/WC etc). public JSONObject getEventMapInfo(String eventId, Context c) throws ClientProtocolException, IOException, JSONException { postParams.clear(); postParams.put("id", eventId); url = new URL(c.getString(R.string.backend_event_map_info)); return postWithJSONResponse(url, "getEventMapInfo"); } // Functie om een plaatje op te halen van een URL. public Drawable LoadImageFromWebOperations(String url) { try { InputStream is = (InputStream) new URL(url).getContent(); Drawable d = Drawable.createFromStream(is, "info"); return d; } catch (Exception e) { return null; } } // Functie waarmee een gebruiker in de database wordt gestopt als hij de app // voor het eerst gebruikt, anders heeft deze functie geen effect. public void makeRegisterParams(User user, Context c, ArrayList<Friend> friendsList) throws ClientProtocolException, IOException { postParams.clear(); postParams.put("id", user.getMyId()); for (int i = 0; i < friendsList.size(); i++) { postParams.put("friends", friendsList.get(i).getId()); } postParams.put("privacysetting", "full"); url = new URL(c.getString(R.string.backend_register)); post(url); } // Functie om de locatie van de gebruiker op te slaan in de database zodat // andere gebruikers<SUF> public void makeLoc_SelfParams(User user, Context c) throws ClientProtocolException, IOException { postParams.clear(); postParams.put("id", user.getMyId()); postParams.put("lat", Double.toString(user.getMyLat())); postParams.put("lng", Double.toString(user.getMyLng())); postParams.put("event_id", "1"); url = new URL(c.getString(R.string.backend_location_self)); post(url); } // Functie om de response van een request leesbaar te maken. public String[] readMultipleLinesRespone() throws IOException { InputStream inputStream = null; if (httpConn != null) { inputStream = httpConn.getInputStream(); } else { throw new IOException("Connection is not established."); } BufferedReader reader = new BufferedReader(new InputStreamReader( inputStream)); List<String> response = new ArrayList<String>(); String line = ""; while ((line = reader.readLine()) != null) { response.add(line); } reader.close(); return (String[]) response.toArray(new String[0]); } // Functie om een Facebook foto op te halen als BitMap, zodat deze makkelijk // resized kan worden. public Bitmap getFacebookBitMap(String s) throws IOException { URL url_value = new URL(s); Bitmap bm = getRoundedShape(BitmapFactory.decodeStream(url_value .openConnection().getInputStream())); return bm; } // Hier zorgen we ervoor dat de facebook plaatjes als rondjes op de kaart // kunnen worden gezet. public Bitmap getRoundedShape(Bitmap scaleBitmapImage) { int targetWidth = 50; int targetHeight = 50; Bitmap targetBitmap = Bitmap.createBitmap(targetWidth, targetHeight, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(targetBitmap); Path path = new Path(); path.addCircle(((float) targetWidth) / 2, ((float) targetHeight) / 2, (Math.min(((float) targetWidth), ((float) targetHeight)) / 2), Path.Direction.CW); Paint paint = new Paint(); paint.setColor(Color.GRAY); // paint.setStyle(Paint.Style.STROKE); paint.setStyle(Paint.Style.FILL); paint.setAntiAlias(true); paint.setDither(true); paint.setFilterBitmap(true); canvas.drawOval(new RectF(0, 0, targetWidth, targetHeight), paint); // paint.setColor(Color.TRANSPARENT); canvas.clipPath(path); Bitmap sourceBitmap = scaleBitmapImage; canvas.drawBitmap(sourceBitmap, new Rect(0, 0, sourceBitmap.getWidth(), sourceBitmap.getHeight()), new RectF(0, 0, targetWidth, targetHeight), paint); return targetBitmap; } }
20202_7
/* * Copyright (C) 2023 Lightbend Inc. <https://www.lightbend.com> */ package docs.persistence.state; // #plugin-imports import akka.Done; import akka.actor.ExtendedActorSystem; import akka.persistence.state.javadsl.DurableStateUpdateWithChangeEventStore; import akka.persistence.state.javadsl.GetObjectResult; import com.typesafe.config.Config; import java.util.concurrent.CompletionStage; // #plugin-imports // #state-store-plugin-api class MyChangeEventJavaStateStore<A> implements DurableStateUpdateWithChangeEventStore<A> { private ExtendedActorSystem system; private Config config; private String cfgPath; public MyChangeEventJavaStateStore(ExtendedActorSystem system, Config config, String cfgPath) { this.system = system; this.config = config; this.cfgPath = cfgPath; } /** * Will delete the state by setting it to the empty state and the revision number will be * incremented by 1. */ @Override public CompletionStage<Done> deleteObject(String persistenceId, long revision) { // implement deleteObject here return null; } @Override public CompletionStage<Done> deleteObject( String persistenceId, long revision, Object changeEvent) { // implement deleteObject here return null; } /** Returns the current state for the given persistence id. */ @Override public CompletionStage<GetObjectResult<A>> getObject(String persistenceId) { // implement getObject here return null; } /** * Will persist the latest state. If it’s a new persistence id, the record will be inserted. * * <p>In case of an existing persistence id, the record will be updated only if the revision * number of the incoming record is 1 more than the already existing record. Otherwise persist * will fail. */ @Override public CompletionStage<Done> upsertObject( String persistenceId, long revision, Object value, String tag) { // implement upsertObject here return null; } /** Deprecated. Use the deleteObject overload with revision instead. */ @Override public CompletionStage<Done> deleteObject(String persistenceId) { return deleteObject(persistenceId, 0); } @Override public CompletionStage<Done> upsertObject( String persistenceId, long revision, A value, String tag, Object changeEvent) { // implement deleteObject here return null; } } // #state-store-plugin-api
akka/akka
akka-docs/src/main/java/docs/persistence/state/MyChangeEventJavaStateStore.java
635
// implement upsertObject here
line_comment
nl
/* * Copyright (C) 2023 Lightbend Inc. <https://www.lightbend.com> */ package docs.persistence.state; // #plugin-imports import akka.Done; import akka.actor.ExtendedActorSystem; import akka.persistence.state.javadsl.DurableStateUpdateWithChangeEventStore; import akka.persistence.state.javadsl.GetObjectResult; import com.typesafe.config.Config; import java.util.concurrent.CompletionStage; // #plugin-imports // #state-store-plugin-api class MyChangeEventJavaStateStore<A> implements DurableStateUpdateWithChangeEventStore<A> { private ExtendedActorSystem system; private Config config; private String cfgPath; public MyChangeEventJavaStateStore(ExtendedActorSystem system, Config config, String cfgPath) { this.system = system; this.config = config; this.cfgPath = cfgPath; } /** * Will delete the state by setting it to the empty state and the revision number will be * incremented by 1. */ @Override public CompletionStage<Done> deleteObject(String persistenceId, long revision) { // implement deleteObject here return null; } @Override public CompletionStage<Done> deleteObject( String persistenceId, long revision, Object changeEvent) { // implement deleteObject here return null; } /** Returns the current state for the given persistence id. */ @Override public CompletionStage<GetObjectResult<A>> getObject(String persistenceId) { // implement getObject here return null; } /** * Will persist the latest state. If it’s a new persistence id, the record will be inserted. * * <p>In case of an existing persistence id, the record will be updated only if the revision * number of the incoming record is 1 more than the already existing record. Otherwise persist * will fail. */ @Override public CompletionStage<Done> upsertObject( String persistenceId, long revision, Object value, String tag) { // implement upsertObject<SUF> return null; } /** Deprecated. Use the deleteObject overload with revision instead. */ @Override public CompletionStage<Done> deleteObject(String persistenceId) { return deleteObject(persistenceId, 0); } @Override public CompletionStage<Done> upsertObject( String persistenceId, long revision, A value, String tag, Object changeEvent) { // implement deleteObject here return null; } } // #state-store-plugin-api
160234_1
package nl.novi.Behavioral.ChainOfResponsibility.ChainOfResponsibility; import java.util.HashMap; import java.util.Map; /** * Server class. */ public class Server { private Map<String, String> users = new HashMap<>(); private Handler handler; /** * De Client geeft de Handlet chain door aan de server. * Dit zorgt voor meer flexibiliteit en maakt dat de server klasse makkelijker getest kan worden. */ public void setHandler(Handler handler) { this.handler = handler; } /** * De server krijgt het email en password van de Client en stuurt deze door naar de handler chain. */ public boolean logIn(String email, String password) { if (handler.check(email, password)) { System.out.println("Authorization have been successful!"); // Hier staat code voor geauthoriseerde gebruikers. return true; } return false; } public void register(String email, String password) { users.put(email, password); } public boolean hasEmail(String email) { return users.containsKey(email); } public boolean isValidPassword(String email, String password) { return users.get(email).equals(password); } }
hogeschoolnovi/design-patterns-voorbeelden
src/main/java/nl/novi/Behavioral/ChainOfResponsibility/ChainOfResponsibility/Server.java
313
/** * De Client geeft de Handlet chain door aan de server. * Dit zorgt voor meer flexibiliteit en maakt dat de server klasse makkelijker getest kan worden. */
block_comment
nl
package nl.novi.Behavioral.ChainOfResponsibility.ChainOfResponsibility; import java.util.HashMap; import java.util.Map; /** * Server class. */ public class Server { private Map<String, String> users = new HashMap<>(); private Handler handler; /** * De Client geeft<SUF>*/ public void setHandler(Handler handler) { this.handler = handler; } /** * De server krijgt het email en password van de Client en stuurt deze door naar de handler chain. */ public boolean logIn(String email, String password) { if (handler.check(email, password)) { System.out.println("Authorization have been successful!"); // Hier staat code voor geauthoriseerde gebruikers. return true; } return false; } public void register(String email, String password) { users.put(email, password); } public boolean hasEmail(String email) { return users.containsKey(email); } public boolean isValidPassword(String email, String password) { return users.get(email).equals(password); } }
19052_34
/* * Created on 6-mei-2005 * */ package com.plexus.beans; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.Rectangle; import java.awt.font.FontRenderContext; import java.awt.font.TextLayout; import java.awt.geom.Rectangle2D; import java.util.List; import java.util.ArrayList; import java.util.ListIterator; import javax.swing.Box; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; /** * Swing gebaseerde component voor een horizontale of verticale meter. Default is verticaal, onder naar boven. * De meter kan op twee manieren gebruikt worden. Ofwel stelt men een minimum en een maximum waarde in, * en ten slotte een huidige waarde, ofwel stelt men de huidige waarde in met een percentage. Deze * methoden kunnen ook door elkaar gebruikt worden. * * @author Arne Brasseur */ public class JMeterBar extends JPanel { /********* constanten **************/ /** * Orientatie van een meter van onder naar boven */ public static final int BOTTOM_TO_TOP = 1; /** * Orientatie van een meter van boven naar onder */ public static final int TOP_TO_BOTTOM = 2; /** * Orientatie van een meter van links naar rechts */ public static final int LEFT_TO_RIGHT = 3; /** * Orientatie van een meter van rechts naar links */ public static final int RIGHT_TO_LEFT = 4; private int padding = 5; /********** javaBean properties ****/ private float current_percentage; private float current_value; private float min = 0; private float max = 1; private String opschrift, subtext=""; private int orientation; private int labelcount; //aantal labels naast de meter private boolean showLabels = false; /********** GUI componenten *******/ private GridBagLayout layout; private JLabel tekstLabel; private JLabel subtekstLabel; private Meter meterLabel; /********* Configuratie ***********/ /** * Constructor met gebruik van percenten. Orientatie : zie gedeclareerde constanten. * * @param opschrift het opschrift van de meter * @param percentage huidig ingesteld percentage * @param orientatie richting waarin de meter beweegt * @param aantallabels het aantal labels met opschrift naast de meter */ public JMeterBar(String opschrift, float percentage, int orientatie, int aantallabels) { setOpschrift(opschrift); setPercentage(percentage); setOrientatie(orientatie); createLayout(); try { labelcount = aantallabels; } catch (NumberFormatException e) { labelcount = 5; System.err.println("The configured value for 'meter_numberoflabels' is not a valid integer."); } catch (Exception e) { labelcount = 5; } } /** * Constructor met gebruik van percenten en 5 labels naast de meter. Orientatie : zie gedeclareerde constanten. * * @param orientatie richting waarin de meter beweegt * @param opschrift het opschrift van de meter * @param percentage huidig ingesteld percentage */ public JMeterBar(int orientatie, String opschrift, float percentage) { this(opschrift, percentage, orientatie, 5); } /** * Constructor met gebruik van percenten en default orientatie (JMeterBar.BOTTOM_TO_TOP). * * @param opschrift het opschrift van de meter * @param percentage huidig ingesteld percentage * @param aantallabels het aantal labels met opschrift naast de meter */ public JMeterBar(String opschrift,float percentage, int aantallabels) { this(opschrift, percentage, BOTTOM_TO_TOP, aantallabels); } /** * Constructor met gebruik van percenten en default orientatie (JMeterBar.BOTTOM_TO_TOP) * en vijf labels. * * @param opschrift het opschrift van de meter * @param percentage huidig ingesteld percentage */ public JMeterBar(String opschrift,float percentage) { this(opschrift, percentage, 5); } /** * Constructor met gebruik van minimum en maximum waarde. Orientatie : zie gedeclareerde constanten. * * @param opschrift het opschrift van de meter * @param min ondergrens van wat de meter kan tonen * @param max bovengrens van wat de meter kan tonen * @param waarde huidige waarde * @param orientatie richting waarin de meter beweegt * @param aantallabels aantal labels naast de meter */ public JMeterBar(String opschrift, float min, float max, float waarde, int orientatie, int aantallabels) { setOpschrift(opschrift); setMinimum(min); setMaximum(max); setWaarde(waarde); setOrientatie(orientatie); labelcount = aantallabels; createLayout(); } /** * Constructor met gebruik van minimum en maximum waarde. Orientatie : zie gedeclareerde constanten. * * @param opschrift het opschrift van de meter * @param min ondergrens van wat de meter kan tonen * @param max bovengrens van wat de meter kan tonen * @param waarde huidige waarde * @param orientatie richting waarin de meter beweegt */ public JMeterBar(String opschrift, float min, float max, float waarde, int orientatie) { this(opschrift, min, max, waarde, orientatie, 5); } /** * Constructor met gebruik van minimum en maximum waarde, en default orientatie (JMeterBar.BOTTOM_TO_TOP) * * @param opschrift het opschrift van de meter * @param min ondergrens van wat de meter kan tonen * @param max bovengrens van wat de meter kan tonen * @param waarde huidige waarde */ public JMeterBar(String opschrift, float min, float max, float waarde) { this(opschrift, min, max, waarde, BOTTOM_TO_TOP); } /************** Layout ***********************/ /** * Creer de layout <br> * <ul> * <li>layoutmanager instellen (springlayout)</li> * <li>tekstlabel en meterlabel aanmaken</li> * <li>tekst- en meterlabel toevoegen aan het panel</li> * <li>componentListener bij het panel registreren om bij resizen het tekstlabel centraal te houden</li> * <li>redoLayout() oproepen om alles goed te zetten</li> * </ul> */ private void createLayout() { layout = new GridBagLayout(); this.setLayout(layout); tekstLabel = new JLabel(opschrift); subtekstLabel = new JLabel(subtext); meterLabel = new Meter(this); redoLayout(); } /** * (Her)doe de layout, bijvoorbeeld als de orientatie verandert. */ private void redoLayout() { this.removeAll(); if (tekstLabel != null && meterLabel != null) { GridBagConstraints gbcM = new GridBagConstraints(); GridBagConstraints gbcL = new GridBagConstraints(); Insets insets = new Insets(padding, padding, padding, padding); Box labelBox = Box.createVerticalBox(); labelBox.add(tekstLabel); labelBox.add(subtekstLabel); if (isAscending()) { this.add(labelBox); this.add(meterLabel); } else { this.add(meterLabel); this.add(labelBox); } switch(orientation) { case LEFT_TO_RIGHT: case RIGHT_TO_LEFT: gbcL.weightx = 0; gbcL.weighty = 0; gbcL.insets = insets; gbcM.weightx = 1; gbcM.weighty = 1; gbcM.fill = GridBagConstraints.BOTH; gbcM.insets = insets; break; case TOP_TO_BOTTOM: case BOTTOM_TO_TOP: gbcL.gridx=0; gbcM.gridx=0; gbcL.weightx = 0; gbcL.weighty = 0; gbcL.insets = insets; gbcM.weightx = 1; gbcM.weighty = 1; gbcM.fill = GridBagConstraints.BOTH; gbcM.insets = insets; break; } layout.setConstraints(meterLabel, gbcM); layout.setConstraints(labelBox, gbcL); } } /** * Stel een kleur in corresponderend met een bepaalde waarde. Voor tussenliggende waarden worden * kleuren lineair geinterpoleerd. * * @param c in te stellen kleur * @param v corresponderende waarde */ public void addColorValuePair(Color c, float v) { if(meterLabel != null) meterLabel.addColor(c, v); } /************* JavaBean property accesors and mutators *************/ /** * Mimimumwaarde van de property <i>waarde</i> * * @return minimum */ public float getMinimum() { return min; } /** * Stel de mimimumwaarde in van de property <i>waarde</i> * * @param min minimum */ public void setMinimum(float min) { this.min=min; } /** * Maximumwaarde van de property <i>waarde</i> * * @return maximum */ public float getMaximum() { return max; } /** * Stel de maximumwaarde in van de property <i>waarde</i> * * @param max maximum */ public void setMaximum(float max) { this.max=max; } /** * De huidige waarde (gelegen tussen <i>minimum</i> en <i>maximum</i>, grenzen inclusief). * * @return huidige waarde */ public float getWaarde() { return current_value; } /** * Stel een waarde in gelegen tussen <i>minimum</i> en <i>maximum</i>, grenzen inclusief. * * @param waarde huidige waarde */ public void setWaarde(float waarde) { this.current_value = waarde; if (current_value > max) current_value = max; if (current_value < min) current_value = min; this.current_percentage = (current_value - min) / (max - min); repaint(); } /** * De huidige ingestelde waarde, uitgedrukt als percentage. * * @return 0 <= percentage <=1 */ public float getPercentage() { return current_percentage; } /** * Stel de huidige waarde in aan de hand van een percentage (tussen 0 en 1, grenzen inclusief).<br> * De property <i>waarde</i> wordt automatisch aangepast, relatief ten opzichte van <i>minimum</i> en </maximum>. * * @param percentage percentage van de meter dat gevuld is */ public void setPercentage(float percentage) { this.current_percentage = percentage; if (current_percentage > 1) current_percentage = 1; if (current_percentage < 0) current_percentage = 0; setWaarde(min + (max - min)*current_percentage); } /** * Het opschrift, datgene wat de meterbar toont. * * @return het huidige opschrift */ public String getOpschrift() { return opschrift; } /** * Stel het opschrift in, datgene wat de meterbar toont. * * @param opschrift nieuw opschrift van de meter */ public void setOpschrift(String opschrift) { this.opschrift = opschrift; if (tekstLabel != null) tekstLabel.setText(opschrift); revalidate(); } /** * Het onderschrift, onder het eigenlijke opschrift * * @return het huidig onderschrift */ public String getOnderschrift() { return subtext; } /** * Stel het onderschrift in, dat onder het opschrift komt * * @param onderschrift het in te stellen onderschrift */ public void setOnderschrift(String onderschrift) { this.subtext = onderschrift; if (subtekstLabel != null) subtekstLabel.setText(subtext); revalidate(); } /** * Geeft de orientatie van deze meterbar. Zie gedeclareerde constanten. * * @return de huidige orientatie */ public int getOrientatie() { return orientation; } /** * Stel de orientatie in van de meterbar. Zie gedeclareerde constanten. * * @param orientatie de in te stellen orientatie */ public void setOrientatie(int orientatie) { if (orientatie > 0 && orientatie < 5) { this.orientation = orientatie; redoLayout(); } } /** * Vraag op of de labels naast de meter zichtbaar zijn * * @return de showLabels property van deze JMeterBar */ public boolean getShowLabels() { return showLabels; } /** * Stel in of er naast de meter labels horen te staan * * @param b de toe te kennen waarde aan de showLabels property */ public void setShowLabels(boolean b) { this.showLabels = b; } /** * Vraag op hoeveel labels er naast de meter staan * * @return de labelCount property */ public int getLabelCount() { return labelcount; } /** * Stel in hoeveel labels er naast de meter moeten komen te staan * * @param c de labelCount property van deze JMeterBar */ public void setLabelCount(int c) { if (c < 2) this.labelcount = 2; else this.labelcount = c; } /** * Stel het font in van deze JMeterBar, zowel van het basislabel, als van de labels naast de meter * * @param f in te stellen font */ @Override public void setFont(Font f) { super.setFont(f); if(tekstLabel!=null) this.tekstLabel.setFont(f); if(subtekstLabel!=null) this.subtekstLabel.setFont(f); //De labels naast de meter zullen ook dit Font gebruiken via getFont } /** * Stel de padding in tussen de deelcomponenten * * @param p padding in px */ public void setPadding(int p) { this.padding = p; redoLayout(); } /************* Hulpmethoden *******************/ /** * Is de orientatie van deze meterbar horizontaal : links naar rechts of rechts naar links * * @return meter is horizontaal */ public boolean isHorizontal() { return ((orientation == LEFT_TO_RIGHT) || (orientation == RIGHT_TO_LEFT)); } /** * Stijgt de meter in dezelfde richting als de pixels : boven naar beneden of links naar rechts * * @return meter is stijgend */ public boolean isAscending() { return ((orientation == TOP_TO_BOTTOM) || (orientation == LEFT_TO_RIGHT)); } /** * Remove all colorvalue mappings * */ public synchronized void clear() { this.meterLabel.clear(); } /************* Binnenklassen ******************/ /** * De eigenlijke metercomponent, toont de meter met de ingestelde kleuren (zie </code>addColor</code>). * Heeft een property <code>showLabels</code> die bepaalt of er tekstlabels met waarden naast de meter komen te staan. * * */ private class Meter extends JComponent { private JMeterBar parent; private List<ColorValuePair> colors = new ArrayList<ColorValuePair>(); /** * Creer meter met een JMeterBar als ouder. * Deze ouder wordt gebruikt om de minimum, maximum en huidige waarde op te vragen. * * @param parent oudercomponent */ public Meter(JMeterBar parent) { this.parent = parent; this.setBackground(Color.LIGHT_GRAY); this.setOpaque(true); } /************** Publieke methodes *****************/ /** * Associeer een kleur met een bepaalde waarde. Kleuren tussen gegeven waarden worden geinterpoleerd. * * @param c * @param v */ public void addColor(Color c, float v) { if(colors.isEmpty()) colors.add(new ColorValuePair(c,v)); else { ListIterator<ColorValuePair> i = colors.listIterator(); ColorValuePair cvp = i.next(); while(i.hasNext() && cvp.getValue() < v) { cvp = i.next(); } if(cvp.getValue() > v) i.previous(); i.add(new ColorValuePair(c,v)); } } /************* Interne keuken **************/ /** * Converteer een waarde (float) naar een pixel-waarde relatief in het vlak van de meter. * * @param value waarde op interne schaal * @return relatieve meterpositie in pixels */ private int valueToPx(float value) { float range = (parent.getMaximum() - parent.getMinimum()); return Math.round((lengthInPx()*value)/range); } /** * Converteer een waarde van pixels naar value, int naar float, waarbij de int gelegen is in het interval * [0, lengte van de meter in pixels], en de teruggeven waarde in het interval [Minimum, maximum] van het ouderobject. * * @param px * @return De overeenkomstige waarde met px */ private float pxToValue(int px) { if (px == 0) return parent.getMinimum(); float range = (parent.getMaximum() - parent.getMinimum()); return parent.getMinimum()+range*px/lengthInPx(); } /** * Bereken de kleur die een bepaalde positie in de meter krijgen moet. * * @param px * @return kleur */ private Color colorAtPosition(int px) { ColorValuePair c1,c2; synchronized (colors) { if(colors.isEmpty()) return this.getBackground(); ListIterator i = colors.listIterator(); c1 = (ColorValuePair)i.next(); if(px <= valueToPx(c1.getValue()) || (!i.hasNext())) return c1.getColor(); c2 = (ColorValuePair)i.next(); while(i.hasNext() && c2.getValue() < pxToValue(px)) { c1 = c2; c2 = (ColorValuePair)i.next(); } } if(px >= valueToPx(c2.getValue())) return c2.getColor(); int r1 = c1.getColor().getRed(); int g1 = c1.getColor().getGreen(); int b1 = c1.getColor().getBlue(); int r2 = c2.getColor().getRed(); int g2 = c2.getColor().getGreen(); int b2 = c2.getColor().getBlue(); double factor1 = (pxToValue(px)-c1.getValue())/(c2.getValue()-c1.getValue()); double factor2 = 1 - factor1; int r = (int)Math.round(factor2*r1+factor1*r2); int g = (int)Math.round(factor2*g1+factor1*g2); int b = (int)Math.round(factor2*b1+factor1*b2); if (r>255) r=255; if (g>255) g=255; if (b>255) b=255; if (r<0) r=0; if (g<0) g=0; if (b<0) b=0; return new Color( r, g, b ); } /** * Teken de meter * * @param g grafische context */ private void paintMeter(Graphics2D g) { for(int i=0; i < this.lengthInPx() && pxToValue(i) < parent.getWaarde(); i++) { drawColoredLine(g, i); } } /** * Teken een lijn op positie i met de gepaste kleur, zie <code>getColorAtPosition</code>. * De richtinggevoelige code zit hier samengebracht. * @param g grafische context * @param i hoeveelste lijn (in pixels) in de betreffende richting */ private void drawColoredLine(Graphics2D g, int i) { Color c = colorAtPosition(i); int x1 = 0, x2 = 0, y1 = 0, y2 = 0; switch (parent.getOrientatie()) { case LEFT_TO_RIGHT: y1 = 0; y2 = meterWidth(); x1 = i; x2 = i; break; case RIGHT_TO_LEFT: y1 = 0; y2 = meterWidth(); x1 = this.lengthInPx() - i; x2 = this.lengthInPx() - i; break; case TOP_TO_BOTTOM: x1 = 0; x2 = meterWidth(); y1 = i; y2 = i; break; case BOTTOM_TO_TOP: x1 = 0; x2 = meterWidth(); y1 = this.lengthInPx() - i; y2 = this.lengthInPx() - i; break; } g.setColor(c); g.drawLine(x1,y1,x2,y2); } /** * Teken de tekstlabels. * * @param g grafische context */ private void paintLabels(Graphics2D g) { int count = parent.getLabelCount(); float pxInterval = this.lengthInPx()/(count-1); float valueInterval = (parent.getMaximum()-parent.getMinimum())/(count-1); float pxCurr = 0; float valueCurr = parent.getMinimum(); int px; String label; for(int p = 0; p < count; p++) { label = Integer.toString(Math.round(valueCurr)); px = Math.round(pxCurr); if (p == count-1) px = lengthInPx()-1; drawLabel(g, px, label); pxCurr += pxInterval; if(pxCurr > this.lengthInPx()) pxCurr = this.lengthInPx(); valueCurr +=valueInterval; } } /** * Teken een maatstreepje en tekstlabel op de opgegeven grafische context, op positie pxCurr, met opgegeven tekst. * * @param g grafische context * @param pxCurr positie op de meter * @param label in te stellen tekst */ private void drawLabel(Graphics2D g, int pxCurr, String label) { Font f = parent.getFont(); FontRenderContext frc = g.getFontRenderContext(); TextLayout text = new TextLayout(label, f, frc); Rectangle2D rect = text.getBounds(); if(parent.isHorizontal()) { if(rect.getHeight() >= this.meterWidth()) { label = "..."; text = new TextLayout(label, f, frc); rect = text.getBounds(); } } else { if(rect.getWidth() >= this.meterWidth()) { label = "..."; text = new TextLayout(label, f, frc); rect = text.getBounds(); } } int x1 = 0, x2 = 0, y1 = 0, y2 = 0; //lijnstuk float tekst_x = 0, tekst_y = 0; //tekstpositie switch (parent.getOrientatie()) { case LEFT_TO_RIGHT: x1 = pxCurr; x2 = pxCurr; y1 = meterWidth(); y2 = (int)Math.round(this.getHeight() - rect.getHeight() - 2); tekst_x = (float)(pxCurr - (rect.getWidth()/2)); if (tekst_x < 0) tekst_x = 0; if((tekst_x + rect.getWidth()) > this.getWidth()) tekst_x = (float)(this.getWidth() - rect.getWidth() - 1); tekst_y = this.getHeight(); break; case RIGHT_TO_LEFT: x1 = lengthInPx() - pxCurr - 1; x2 = lengthInPx() - pxCurr - 1; y1 = meterWidth(); y2 = (int)Math.round(this.getHeight() - rect.getHeight() - 2); tekst_x = (float)(x1 - (rect.getWidth()/2)); if (tekst_x < 0) tekst_x = 0; if((tekst_x + rect.getWidth()) > this.getWidth()) tekst_x = (float)(this.getWidth() - rect.getWidth() - 1); tekst_y = this.getHeight(); break; case TOP_TO_BOTTOM: x1 = meterWidth(); x2 = (int)Math.round(this.getWidth() - rect.getWidth() - 1); y1 = pxCurr; y2 = pxCurr; tekst_x = (float)(this.getWidth() - rect.getWidth() - 2); tekst_y = (float)(pxCurr + (rect.getHeight()/2)); if (tekst_y < rect.getHeight()) tekst_y = (float)(rect.getHeight()); if(tekst_y > this.getHeight()) tekst_y = this.getHeight() - 1; break; case BOTTOM_TO_TOP: x1 = meterWidth(); x2 = (int)Math.round(this.getWidth() - rect.getWidth() - 2); y1 = lengthInPx() - pxCurr - 1; y2 = lengthInPx() - pxCurr - 1; tekst_x = (float)(this.getWidth() - rect.getWidth() - 1); tekst_y = (float)(this.getHeight() - pxCurr + (rect.getHeight()/2)); if (tekst_y < rect.getHeight()) tekst_y = (float)(rect.getHeight()); if(tekst_y > this.getHeight()) tekst_y = this.getHeight() - 1; } g.setColor(Color.BLACK); if (x1 <= x2 && y1 <= y2) g.drawLine(x1,y1,x2,y2); if(parent.isHorizontal()) { if(rect.getHeight() < this.meterWidth()) { text.draw(g, tekst_x, tekst_y); } } else { if(rect.getWidth() < this.meterWidth()) { text.draw(g, tekst_x, tekst_y); } } } /** * Teken deze component op de grafische context. Deze methode wordt opgeroepen door de GUI thread. * * @param g grafische context */ @Override protected void paintComponent(Graphics g) { super.paintComponents(g); if (isOpaque()) { //paint background g.setColor(getBackground()); g.fillRect(0, 0, getWidth(), getHeight()); } Graphics2D g2d = (Graphics2D)g.create(); paintMeter(g2d); if (parent.getShowLabels()) paintLabels(g2d); g2d.setColor(Color.BLACK); if(parent.isHorizontal()) g2d.draw(new Rectangle(0,0,this.getWidth()-1,this.meterWidth())); else g2d.draw(new Rectangle(0,0,this.meterWidth(),this.getHeight()-1)); g2d.dispose(); } /** * Lengte in pixels van deze meter * * @return lengte van de meter */ private int lengthInPx() { if(parent.isHorizontal()) return this.getWidth(); return this.getHeight(); } /** * De breedte van de meter zelf, afhankelijk van of de labels aanstaan is dit de volledige, of de halve breedte van het label. * * @return breedte van de meter in pixels */ private int meterWidth() { if(parent.isHorizontal()) return Math.round(parent.getShowLabels()?this.getHeight()/2:this.getHeight()-1); return Math.round(parent.getShowLabels()?this.getWidth()/2:this.getWidth()-1); } public void clear() { synchronized (colors) { this.colors.clear(); this.addColor(Color.BLUE, 0); } } } /** * Groepering van een kleur en een waarde * */ private class ColorValuePair { private Color c; private float v; /** * Stel kleur in en corresponderende waarde * * @param c kleur * @param v waarde */ public ColorValuePair(Color c, float v) { this.c = c; this.v = v; } /** * Stel kleur in en waarde 0 * * @param c kleur */ public void setColor(Color c) { this.c = c; } /** * Stel waarde in en kleur null * @param v */ public void setValue(float v) { this.v = v; this.c = null; } /** * @return float-waarde */ public float getValue() { return v; } /** * @return kleur */ public Color getColor() { return c; } /** * @return "ColorValuePair[v:\<waarde\>,c:(\<R\>,\<G\>,\<B\>)" */ @Override public String toString() { return "ColorValuePair[v:"+v+",c:("+c.getRed()+","+c.getGreen()+","+c.getBlue()+")]"; } } }
plexus/SAM
src/com/plexus/beans/JMeterBar.java
8,136
/** * Vraag op hoeveel labels er naast de meter staan * * @return de labelCount property */
block_comment
nl
/* * Created on 6-mei-2005 * */ package com.plexus.beans; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.Rectangle; import java.awt.font.FontRenderContext; import java.awt.font.TextLayout; import java.awt.geom.Rectangle2D; import java.util.List; import java.util.ArrayList; import java.util.ListIterator; import javax.swing.Box; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; /** * Swing gebaseerde component voor een horizontale of verticale meter. Default is verticaal, onder naar boven. * De meter kan op twee manieren gebruikt worden. Ofwel stelt men een minimum en een maximum waarde in, * en ten slotte een huidige waarde, ofwel stelt men de huidige waarde in met een percentage. Deze * methoden kunnen ook door elkaar gebruikt worden. * * @author Arne Brasseur */ public class JMeterBar extends JPanel { /********* constanten **************/ /** * Orientatie van een meter van onder naar boven */ public static final int BOTTOM_TO_TOP = 1; /** * Orientatie van een meter van boven naar onder */ public static final int TOP_TO_BOTTOM = 2; /** * Orientatie van een meter van links naar rechts */ public static final int LEFT_TO_RIGHT = 3; /** * Orientatie van een meter van rechts naar links */ public static final int RIGHT_TO_LEFT = 4; private int padding = 5; /********** javaBean properties ****/ private float current_percentage; private float current_value; private float min = 0; private float max = 1; private String opschrift, subtext=""; private int orientation; private int labelcount; //aantal labels naast de meter private boolean showLabels = false; /********** GUI componenten *******/ private GridBagLayout layout; private JLabel tekstLabel; private JLabel subtekstLabel; private Meter meterLabel; /********* Configuratie ***********/ /** * Constructor met gebruik van percenten. Orientatie : zie gedeclareerde constanten. * * @param opschrift het opschrift van de meter * @param percentage huidig ingesteld percentage * @param orientatie richting waarin de meter beweegt * @param aantallabels het aantal labels met opschrift naast de meter */ public JMeterBar(String opschrift, float percentage, int orientatie, int aantallabels) { setOpschrift(opschrift); setPercentage(percentage); setOrientatie(orientatie); createLayout(); try { labelcount = aantallabels; } catch (NumberFormatException e) { labelcount = 5; System.err.println("The configured value for 'meter_numberoflabels' is not a valid integer."); } catch (Exception e) { labelcount = 5; } } /** * Constructor met gebruik van percenten en 5 labels naast de meter. Orientatie : zie gedeclareerde constanten. * * @param orientatie richting waarin de meter beweegt * @param opschrift het opschrift van de meter * @param percentage huidig ingesteld percentage */ public JMeterBar(int orientatie, String opschrift, float percentage) { this(opschrift, percentage, orientatie, 5); } /** * Constructor met gebruik van percenten en default orientatie (JMeterBar.BOTTOM_TO_TOP). * * @param opschrift het opschrift van de meter * @param percentage huidig ingesteld percentage * @param aantallabels het aantal labels met opschrift naast de meter */ public JMeterBar(String opschrift,float percentage, int aantallabels) { this(opschrift, percentage, BOTTOM_TO_TOP, aantallabels); } /** * Constructor met gebruik van percenten en default orientatie (JMeterBar.BOTTOM_TO_TOP) * en vijf labels. * * @param opschrift het opschrift van de meter * @param percentage huidig ingesteld percentage */ public JMeterBar(String opschrift,float percentage) { this(opschrift, percentage, 5); } /** * Constructor met gebruik van minimum en maximum waarde. Orientatie : zie gedeclareerde constanten. * * @param opschrift het opschrift van de meter * @param min ondergrens van wat de meter kan tonen * @param max bovengrens van wat de meter kan tonen * @param waarde huidige waarde * @param orientatie richting waarin de meter beweegt * @param aantallabels aantal labels naast de meter */ public JMeterBar(String opschrift, float min, float max, float waarde, int orientatie, int aantallabels) { setOpschrift(opschrift); setMinimum(min); setMaximum(max); setWaarde(waarde); setOrientatie(orientatie); labelcount = aantallabels; createLayout(); } /** * Constructor met gebruik van minimum en maximum waarde. Orientatie : zie gedeclareerde constanten. * * @param opschrift het opschrift van de meter * @param min ondergrens van wat de meter kan tonen * @param max bovengrens van wat de meter kan tonen * @param waarde huidige waarde * @param orientatie richting waarin de meter beweegt */ public JMeterBar(String opschrift, float min, float max, float waarde, int orientatie) { this(opschrift, min, max, waarde, orientatie, 5); } /** * Constructor met gebruik van minimum en maximum waarde, en default orientatie (JMeterBar.BOTTOM_TO_TOP) * * @param opschrift het opschrift van de meter * @param min ondergrens van wat de meter kan tonen * @param max bovengrens van wat de meter kan tonen * @param waarde huidige waarde */ public JMeterBar(String opschrift, float min, float max, float waarde) { this(opschrift, min, max, waarde, BOTTOM_TO_TOP); } /************** Layout ***********************/ /** * Creer de layout <br> * <ul> * <li>layoutmanager instellen (springlayout)</li> * <li>tekstlabel en meterlabel aanmaken</li> * <li>tekst- en meterlabel toevoegen aan het panel</li> * <li>componentListener bij het panel registreren om bij resizen het tekstlabel centraal te houden</li> * <li>redoLayout() oproepen om alles goed te zetten</li> * </ul> */ private void createLayout() { layout = new GridBagLayout(); this.setLayout(layout); tekstLabel = new JLabel(opschrift); subtekstLabel = new JLabel(subtext); meterLabel = new Meter(this); redoLayout(); } /** * (Her)doe de layout, bijvoorbeeld als de orientatie verandert. */ private void redoLayout() { this.removeAll(); if (tekstLabel != null && meterLabel != null) { GridBagConstraints gbcM = new GridBagConstraints(); GridBagConstraints gbcL = new GridBagConstraints(); Insets insets = new Insets(padding, padding, padding, padding); Box labelBox = Box.createVerticalBox(); labelBox.add(tekstLabel); labelBox.add(subtekstLabel); if (isAscending()) { this.add(labelBox); this.add(meterLabel); } else { this.add(meterLabel); this.add(labelBox); } switch(orientation) { case LEFT_TO_RIGHT: case RIGHT_TO_LEFT: gbcL.weightx = 0; gbcL.weighty = 0; gbcL.insets = insets; gbcM.weightx = 1; gbcM.weighty = 1; gbcM.fill = GridBagConstraints.BOTH; gbcM.insets = insets; break; case TOP_TO_BOTTOM: case BOTTOM_TO_TOP: gbcL.gridx=0; gbcM.gridx=0; gbcL.weightx = 0; gbcL.weighty = 0; gbcL.insets = insets; gbcM.weightx = 1; gbcM.weighty = 1; gbcM.fill = GridBagConstraints.BOTH; gbcM.insets = insets; break; } layout.setConstraints(meterLabel, gbcM); layout.setConstraints(labelBox, gbcL); } } /** * Stel een kleur in corresponderend met een bepaalde waarde. Voor tussenliggende waarden worden * kleuren lineair geinterpoleerd. * * @param c in te stellen kleur * @param v corresponderende waarde */ public void addColorValuePair(Color c, float v) { if(meterLabel != null) meterLabel.addColor(c, v); } /************* JavaBean property accesors and mutators *************/ /** * Mimimumwaarde van de property <i>waarde</i> * * @return minimum */ public float getMinimum() { return min; } /** * Stel de mimimumwaarde in van de property <i>waarde</i> * * @param min minimum */ public void setMinimum(float min) { this.min=min; } /** * Maximumwaarde van de property <i>waarde</i> * * @return maximum */ public float getMaximum() { return max; } /** * Stel de maximumwaarde in van de property <i>waarde</i> * * @param max maximum */ public void setMaximum(float max) { this.max=max; } /** * De huidige waarde (gelegen tussen <i>minimum</i> en <i>maximum</i>, grenzen inclusief). * * @return huidige waarde */ public float getWaarde() { return current_value; } /** * Stel een waarde in gelegen tussen <i>minimum</i> en <i>maximum</i>, grenzen inclusief. * * @param waarde huidige waarde */ public void setWaarde(float waarde) { this.current_value = waarde; if (current_value > max) current_value = max; if (current_value < min) current_value = min; this.current_percentage = (current_value - min) / (max - min); repaint(); } /** * De huidige ingestelde waarde, uitgedrukt als percentage. * * @return 0 <= percentage <=1 */ public float getPercentage() { return current_percentage; } /** * Stel de huidige waarde in aan de hand van een percentage (tussen 0 en 1, grenzen inclusief).<br> * De property <i>waarde</i> wordt automatisch aangepast, relatief ten opzichte van <i>minimum</i> en </maximum>. * * @param percentage percentage van de meter dat gevuld is */ public void setPercentage(float percentage) { this.current_percentage = percentage; if (current_percentage > 1) current_percentage = 1; if (current_percentage < 0) current_percentage = 0; setWaarde(min + (max - min)*current_percentage); } /** * Het opschrift, datgene wat de meterbar toont. * * @return het huidige opschrift */ public String getOpschrift() { return opschrift; } /** * Stel het opschrift in, datgene wat de meterbar toont. * * @param opschrift nieuw opschrift van de meter */ public void setOpschrift(String opschrift) { this.opschrift = opschrift; if (tekstLabel != null) tekstLabel.setText(opschrift); revalidate(); } /** * Het onderschrift, onder het eigenlijke opschrift * * @return het huidig onderschrift */ public String getOnderschrift() { return subtext; } /** * Stel het onderschrift in, dat onder het opschrift komt * * @param onderschrift het in te stellen onderschrift */ public void setOnderschrift(String onderschrift) { this.subtext = onderschrift; if (subtekstLabel != null) subtekstLabel.setText(subtext); revalidate(); } /** * Geeft de orientatie van deze meterbar. Zie gedeclareerde constanten. * * @return de huidige orientatie */ public int getOrientatie() { return orientation; } /** * Stel de orientatie in van de meterbar. Zie gedeclareerde constanten. * * @param orientatie de in te stellen orientatie */ public void setOrientatie(int orientatie) { if (orientatie > 0 && orientatie < 5) { this.orientation = orientatie; redoLayout(); } } /** * Vraag op of de labels naast de meter zichtbaar zijn * * @return de showLabels property van deze JMeterBar */ public boolean getShowLabels() { return showLabels; } /** * Stel in of er naast de meter labels horen te staan * * @param b de toe te kennen waarde aan de showLabels property */ public void setShowLabels(boolean b) { this.showLabels = b; } /** * Vraag op hoeveel<SUF>*/ public int getLabelCount() { return labelcount; } /** * Stel in hoeveel labels er naast de meter moeten komen te staan * * @param c de labelCount property van deze JMeterBar */ public void setLabelCount(int c) { if (c < 2) this.labelcount = 2; else this.labelcount = c; } /** * Stel het font in van deze JMeterBar, zowel van het basislabel, als van de labels naast de meter * * @param f in te stellen font */ @Override public void setFont(Font f) { super.setFont(f); if(tekstLabel!=null) this.tekstLabel.setFont(f); if(subtekstLabel!=null) this.subtekstLabel.setFont(f); //De labels naast de meter zullen ook dit Font gebruiken via getFont } /** * Stel de padding in tussen de deelcomponenten * * @param p padding in px */ public void setPadding(int p) { this.padding = p; redoLayout(); } /************* Hulpmethoden *******************/ /** * Is de orientatie van deze meterbar horizontaal : links naar rechts of rechts naar links * * @return meter is horizontaal */ public boolean isHorizontal() { return ((orientation == LEFT_TO_RIGHT) || (orientation == RIGHT_TO_LEFT)); } /** * Stijgt de meter in dezelfde richting als de pixels : boven naar beneden of links naar rechts * * @return meter is stijgend */ public boolean isAscending() { return ((orientation == TOP_TO_BOTTOM) || (orientation == LEFT_TO_RIGHT)); } /** * Remove all colorvalue mappings * */ public synchronized void clear() { this.meterLabel.clear(); } /************* Binnenklassen ******************/ /** * De eigenlijke metercomponent, toont de meter met de ingestelde kleuren (zie </code>addColor</code>). * Heeft een property <code>showLabels</code> die bepaalt of er tekstlabels met waarden naast de meter komen te staan. * * */ private class Meter extends JComponent { private JMeterBar parent; private List<ColorValuePair> colors = new ArrayList<ColorValuePair>(); /** * Creer meter met een JMeterBar als ouder. * Deze ouder wordt gebruikt om de minimum, maximum en huidige waarde op te vragen. * * @param parent oudercomponent */ public Meter(JMeterBar parent) { this.parent = parent; this.setBackground(Color.LIGHT_GRAY); this.setOpaque(true); } /************** Publieke methodes *****************/ /** * Associeer een kleur met een bepaalde waarde. Kleuren tussen gegeven waarden worden geinterpoleerd. * * @param c * @param v */ public void addColor(Color c, float v) { if(colors.isEmpty()) colors.add(new ColorValuePair(c,v)); else { ListIterator<ColorValuePair> i = colors.listIterator(); ColorValuePair cvp = i.next(); while(i.hasNext() && cvp.getValue() < v) { cvp = i.next(); } if(cvp.getValue() > v) i.previous(); i.add(new ColorValuePair(c,v)); } } /************* Interne keuken **************/ /** * Converteer een waarde (float) naar een pixel-waarde relatief in het vlak van de meter. * * @param value waarde op interne schaal * @return relatieve meterpositie in pixels */ private int valueToPx(float value) { float range = (parent.getMaximum() - parent.getMinimum()); return Math.round((lengthInPx()*value)/range); } /** * Converteer een waarde van pixels naar value, int naar float, waarbij de int gelegen is in het interval * [0, lengte van de meter in pixels], en de teruggeven waarde in het interval [Minimum, maximum] van het ouderobject. * * @param px * @return De overeenkomstige waarde met px */ private float pxToValue(int px) { if (px == 0) return parent.getMinimum(); float range = (parent.getMaximum() - parent.getMinimum()); return parent.getMinimum()+range*px/lengthInPx(); } /** * Bereken de kleur die een bepaalde positie in de meter krijgen moet. * * @param px * @return kleur */ private Color colorAtPosition(int px) { ColorValuePair c1,c2; synchronized (colors) { if(colors.isEmpty()) return this.getBackground(); ListIterator i = colors.listIterator(); c1 = (ColorValuePair)i.next(); if(px <= valueToPx(c1.getValue()) || (!i.hasNext())) return c1.getColor(); c2 = (ColorValuePair)i.next(); while(i.hasNext() && c2.getValue() < pxToValue(px)) { c1 = c2; c2 = (ColorValuePair)i.next(); } } if(px >= valueToPx(c2.getValue())) return c2.getColor(); int r1 = c1.getColor().getRed(); int g1 = c1.getColor().getGreen(); int b1 = c1.getColor().getBlue(); int r2 = c2.getColor().getRed(); int g2 = c2.getColor().getGreen(); int b2 = c2.getColor().getBlue(); double factor1 = (pxToValue(px)-c1.getValue())/(c2.getValue()-c1.getValue()); double factor2 = 1 - factor1; int r = (int)Math.round(factor2*r1+factor1*r2); int g = (int)Math.round(factor2*g1+factor1*g2); int b = (int)Math.round(factor2*b1+factor1*b2); if (r>255) r=255; if (g>255) g=255; if (b>255) b=255; if (r<0) r=0; if (g<0) g=0; if (b<0) b=0; return new Color( r, g, b ); } /** * Teken de meter * * @param g grafische context */ private void paintMeter(Graphics2D g) { for(int i=0; i < this.lengthInPx() && pxToValue(i) < parent.getWaarde(); i++) { drawColoredLine(g, i); } } /** * Teken een lijn op positie i met de gepaste kleur, zie <code>getColorAtPosition</code>. * De richtinggevoelige code zit hier samengebracht. * @param g grafische context * @param i hoeveelste lijn (in pixels) in de betreffende richting */ private void drawColoredLine(Graphics2D g, int i) { Color c = colorAtPosition(i); int x1 = 0, x2 = 0, y1 = 0, y2 = 0; switch (parent.getOrientatie()) { case LEFT_TO_RIGHT: y1 = 0; y2 = meterWidth(); x1 = i; x2 = i; break; case RIGHT_TO_LEFT: y1 = 0; y2 = meterWidth(); x1 = this.lengthInPx() - i; x2 = this.lengthInPx() - i; break; case TOP_TO_BOTTOM: x1 = 0; x2 = meterWidth(); y1 = i; y2 = i; break; case BOTTOM_TO_TOP: x1 = 0; x2 = meterWidth(); y1 = this.lengthInPx() - i; y2 = this.lengthInPx() - i; break; } g.setColor(c); g.drawLine(x1,y1,x2,y2); } /** * Teken de tekstlabels. * * @param g grafische context */ private void paintLabels(Graphics2D g) { int count = parent.getLabelCount(); float pxInterval = this.lengthInPx()/(count-1); float valueInterval = (parent.getMaximum()-parent.getMinimum())/(count-1); float pxCurr = 0; float valueCurr = parent.getMinimum(); int px; String label; for(int p = 0; p < count; p++) { label = Integer.toString(Math.round(valueCurr)); px = Math.round(pxCurr); if (p == count-1) px = lengthInPx()-1; drawLabel(g, px, label); pxCurr += pxInterval; if(pxCurr > this.lengthInPx()) pxCurr = this.lengthInPx(); valueCurr +=valueInterval; } } /** * Teken een maatstreepje en tekstlabel op de opgegeven grafische context, op positie pxCurr, met opgegeven tekst. * * @param g grafische context * @param pxCurr positie op de meter * @param label in te stellen tekst */ private void drawLabel(Graphics2D g, int pxCurr, String label) { Font f = parent.getFont(); FontRenderContext frc = g.getFontRenderContext(); TextLayout text = new TextLayout(label, f, frc); Rectangle2D rect = text.getBounds(); if(parent.isHorizontal()) { if(rect.getHeight() >= this.meterWidth()) { label = "..."; text = new TextLayout(label, f, frc); rect = text.getBounds(); } } else { if(rect.getWidth() >= this.meterWidth()) { label = "..."; text = new TextLayout(label, f, frc); rect = text.getBounds(); } } int x1 = 0, x2 = 0, y1 = 0, y2 = 0; //lijnstuk float tekst_x = 0, tekst_y = 0; //tekstpositie switch (parent.getOrientatie()) { case LEFT_TO_RIGHT: x1 = pxCurr; x2 = pxCurr; y1 = meterWidth(); y2 = (int)Math.round(this.getHeight() - rect.getHeight() - 2); tekst_x = (float)(pxCurr - (rect.getWidth()/2)); if (tekst_x < 0) tekst_x = 0; if((tekst_x + rect.getWidth()) > this.getWidth()) tekst_x = (float)(this.getWidth() - rect.getWidth() - 1); tekst_y = this.getHeight(); break; case RIGHT_TO_LEFT: x1 = lengthInPx() - pxCurr - 1; x2 = lengthInPx() - pxCurr - 1; y1 = meterWidth(); y2 = (int)Math.round(this.getHeight() - rect.getHeight() - 2); tekst_x = (float)(x1 - (rect.getWidth()/2)); if (tekst_x < 0) tekst_x = 0; if((tekst_x + rect.getWidth()) > this.getWidth()) tekst_x = (float)(this.getWidth() - rect.getWidth() - 1); tekst_y = this.getHeight(); break; case TOP_TO_BOTTOM: x1 = meterWidth(); x2 = (int)Math.round(this.getWidth() - rect.getWidth() - 1); y1 = pxCurr; y2 = pxCurr; tekst_x = (float)(this.getWidth() - rect.getWidth() - 2); tekst_y = (float)(pxCurr + (rect.getHeight()/2)); if (tekst_y < rect.getHeight()) tekst_y = (float)(rect.getHeight()); if(tekst_y > this.getHeight()) tekst_y = this.getHeight() - 1; break; case BOTTOM_TO_TOP: x1 = meterWidth(); x2 = (int)Math.round(this.getWidth() - rect.getWidth() - 2); y1 = lengthInPx() - pxCurr - 1; y2 = lengthInPx() - pxCurr - 1; tekst_x = (float)(this.getWidth() - rect.getWidth() - 1); tekst_y = (float)(this.getHeight() - pxCurr + (rect.getHeight()/2)); if (tekst_y < rect.getHeight()) tekst_y = (float)(rect.getHeight()); if(tekst_y > this.getHeight()) tekst_y = this.getHeight() - 1; } g.setColor(Color.BLACK); if (x1 <= x2 && y1 <= y2) g.drawLine(x1,y1,x2,y2); if(parent.isHorizontal()) { if(rect.getHeight() < this.meterWidth()) { text.draw(g, tekst_x, tekst_y); } } else { if(rect.getWidth() < this.meterWidth()) { text.draw(g, tekst_x, tekst_y); } } } /** * Teken deze component op de grafische context. Deze methode wordt opgeroepen door de GUI thread. * * @param g grafische context */ @Override protected void paintComponent(Graphics g) { super.paintComponents(g); if (isOpaque()) { //paint background g.setColor(getBackground()); g.fillRect(0, 0, getWidth(), getHeight()); } Graphics2D g2d = (Graphics2D)g.create(); paintMeter(g2d); if (parent.getShowLabels()) paintLabels(g2d); g2d.setColor(Color.BLACK); if(parent.isHorizontal()) g2d.draw(new Rectangle(0,0,this.getWidth()-1,this.meterWidth())); else g2d.draw(new Rectangle(0,0,this.meterWidth(),this.getHeight()-1)); g2d.dispose(); } /** * Lengte in pixels van deze meter * * @return lengte van de meter */ private int lengthInPx() { if(parent.isHorizontal()) return this.getWidth(); return this.getHeight(); } /** * De breedte van de meter zelf, afhankelijk van of de labels aanstaan is dit de volledige, of de halve breedte van het label. * * @return breedte van de meter in pixels */ private int meterWidth() { if(parent.isHorizontal()) return Math.round(parent.getShowLabels()?this.getHeight()/2:this.getHeight()-1); return Math.round(parent.getShowLabels()?this.getWidth()/2:this.getWidth()-1); } public void clear() { synchronized (colors) { this.colors.clear(); this.addColor(Color.BLUE, 0); } } } /** * Groepering van een kleur en een waarde * */ private class ColorValuePair { private Color c; private float v; /** * Stel kleur in en corresponderende waarde * * @param c kleur * @param v waarde */ public ColorValuePair(Color c, float v) { this.c = c; this.v = v; } /** * Stel kleur in en waarde 0 * * @param c kleur */ public void setColor(Color c) { this.c = c; } /** * Stel waarde in en kleur null * @param v */ public void setValue(float v) { this.v = v; this.c = null; } /** * @return float-waarde */ public float getValue() { return v; } /** * @return kleur */ public Color getColor() { return c; } /** * @return "ColorValuePair[v:\<waarde\>,c:(\<R\>,\<G\>,\<B\>)" */ @Override public String toString() { return "ColorValuePair[v:"+v+",c:("+c.getRed()+","+c.getGreen()+","+c.getBlue()+")]"; } } }
35107_14
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,369
// Zorgt ervoor dat er een response komt als de zoek button ingedrukt wordt.
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 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<SUF> 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(); } }); //////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////// } }
103406_0
package com.huaweicloud.sdk.iotedge.v2.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonValue; import com.huaweicloud.sdk.core.SdkResponse; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.function.Consumer; /** * Response Object */ public class CreateEdgeApplicationVersionResponse extends SdkResponse { @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "edge_app_id") private String edgeAppId; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "name") private String name; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "deploy_type") private String deployType; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "deploy_multi_instance") private Boolean deployMultiInstance; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "version") private String version; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "sdk_version") private String sdkVersion; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "description") private String description; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "create_time") private String createTime; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "update_time") private String updateTime; /** * 应用版本状态 */ public static final class StateEnum { /** * Enum DRAFT for value: "DRAFT" */ public static final StateEnum DRAFT = new StateEnum("DRAFT"); /** * Enum PUBLISHED for value: "PUBLISHED" */ public static final StateEnum PUBLISHED = new StateEnum("PUBLISHED"); /** * Enum OFF_SHELF for value: "OFF_SHELF" */ public static final StateEnum OFF_SHELF = new StateEnum("OFF_SHELF"); private static final Map<String, StateEnum> STATIC_FIELDS = createStaticFields(); private static Map<String, StateEnum> createStaticFields() { Map<String, StateEnum> map = new HashMap<>(); map.put("DRAFT", DRAFT); map.put("PUBLISHED", PUBLISHED); map.put("OFF_SHELF", OFF_SHELF); return Collections.unmodifiableMap(map); } private String value; StateEnum(String value) { this.value = value; } @JsonValue public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } @JsonCreator public static StateEnum fromValue(String value) { if (value == null) { return null; } return java.util.Optional.ofNullable(STATIC_FIELDS.get(value)).orElse(new StateEnum(value)); } public static StateEnum valueOf(String value) { if (value == null) { return null; } return java.util.Optional.ofNullable(STATIC_FIELDS.get(value)) .orElseThrow(() -> new IllegalArgumentException("Unexpected value '" + value + "'")); } @Override public boolean equals(Object obj) { if (obj instanceof StateEnum) { return this.value.equals(((StateEnum) obj).value); } return false; } @Override public int hashCode() { return this.value.hashCode(); } } @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "state") private StateEnum state; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "liveness_probe") private ProbeDTO livenessProbe; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "readiness_probe") private ProbeDTO readinessProbe; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "arch") private List<String> arch = null; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "command") private List<String> command = null; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "args") private List<String> args = null; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "container_settings") private ContainerSettingsDTO containerSettings; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "outputs") private List<String> outputs = null; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "inputs") private List<String> inputs = null; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "services") private List<String> services = null; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "publish_time") private String publishTime; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "off_shelf_time") private String offShelfTime; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "supplier") private String supplier; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "tpl_id") private String tplId; public CreateEdgeApplicationVersionResponse withEdgeAppId(String edgeAppId) { this.edgeAppId = edgeAppId; return this; } /** * 应用ID * @return edgeAppId */ public String getEdgeAppId() { return edgeAppId; } public void setEdgeAppId(String edgeAppId) { this.edgeAppId = edgeAppId; } public CreateEdgeApplicationVersionResponse withName(String name) { this.name = name; return this; } /** * 应用名称 * @return name */ public String getName() { return name; } public void setName(String name) { this.name = name; } public CreateEdgeApplicationVersionResponse withDeployType(String deployType) { this.deployType = deployType; return this; } /** * 部署类型docker|process * @return deployType */ public String getDeployType() { return deployType; } public void setDeployType(String deployType) { this.deployType = deployType; } public CreateEdgeApplicationVersionResponse withDeployMultiInstance(Boolean deployMultiInstance) { this.deployMultiInstance = deployMultiInstance; return this; } /** * 是否允许部署多实例 * @return deployMultiInstance */ public Boolean getDeployMultiInstance() { return deployMultiInstance; } public void setDeployMultiInstance(Boolean deployMultiInstance) { this.deployMultiInstance = deployMultiInstance; } public CreateEdgeApplicationVersionResponse withVersion(String version) { this.version = version; return this; } /** * 应用版本 * @return version */ public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public CreateEdgeApplicationVersionResponse withSdkVersion(String sdkVersion) { this.sdkVersion = sdkVersion; return this; } /** * 应用集成的边缘SDK版本 * @return sdkVersion */ public String getSdkVersion() { return sdkVersion; } public void setSdkVersion(String sdkVersion) { this.sdkVersion = sdkVersion; } public CreateEdgeApplicationVersionResponse withDescription(String description) { this.description = description; return this; } /** * 应用描述 * @return description */ public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public CreateEdgeApplicationVersionResponse withCreateTime(String createTime) { this.createTime = createTime; return this; } /** * 创建时间 * @return createTime */ public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public CreateEdgeApplicationVersionResponse withUpdateTime(String updateTime) { this.updateTime = updateTime; return this; } /** * 最后一次修改时间 * @return updateTime */ public String getUpdateTime() { return updateTime; } public void setUpdateTime(String updateTime) { this.updateTime = updateTime; } public CreateEdgeApplicationVersionResponse withState(StateEnum state) { this.state = state; return this; } /** * 应用版本状态 * @return state */ public StateEnum getState() { return state; } public void setState(StateEnum state) { this.state = state; } public CreateEdgeApplicationVersionResponse withLivenessProbe(ProbeDTO livenessProbe) { this.livenessProbe = livenessProbe; return this; } public CreateEdgeApplicationVersionResponse withLivenessProbe(Consumer<ProbeDTO> livenessProbeSetter) { if (this.livenessProbe == null) { this.livenessProbe = new ProbeDTO(); livenessProbeSetter.accept(this.livenessProbe); } return this; } /** * Get livenessProbe * @return livenessProbe */ public ProbeDTO getLivenessProbe() { return livenessProbe; } public void setLivenessProbe(ProbeDTO livenessProbe) { this.livenessProbe = livenessProbe; } public CreateEdgeApplicationVersionResponse withReadinessProbe(ProbeDTO readinessProbe) { this.readinessProbe = readinessProbe; return this; } public CreateEdgeApplicationVersionResponse withReadinessProbe(Consumer<ProbeDTO> readinessProbeSetter) { if (this.readinessProbe == null) { this.readinessProbe = new ProbeDTO(); readinessProbeSetter.accept(this.readinessProbe); } return this; } /** * Get readinessProbe * @return readinessProbe */ public ProbeDTO getReadinessProbe() { return readinessProbe; } public void setReadinessProbe(ProbeDTO readinessProbe) { this.readinessProbe = readinessProbe; } public CreateEdgeApplicationVersionResponse withArch(List<String> arch) { this.arch = arch; return this; } public CreateEdgeApplicationVersionResponse addArchItem(String archItem) { if (this.arch == null) { this.arch = new ArrayList<>(); } this.arch.add(archItem); return this; } public CreateEdgeApplicationVersionResponse withArch(Consumer<List<String>> archSetter) { if (this.arch == null) { this.arch = new ArrayList<>(); } archSetter.accept(this.arch); return this; } /** * 架构 * @return arch */ public List<String> getArch() { return arch; } public void setArch(List<String> arch) { this.arch = arch; } public CreateEdgeApplicationVersionResponse withCommand(List<String> command) { this.command = command; return this; } public CreateEdgeApplicationVersionResponse addCommandItem(String commandItem) { if (this.command == null) { this.command = new ArrayList<>(); } this.command.add(commandItem); return this; } public CreateEdgeApplicationVersionResponse withCommand(Consumer<List<String>> commandSetter) { if (this.command == null) { this.command = new ArrayList<>(); } commandSetter.accept(this.command); return this; } /** * 启动命令 * @return command */ public List<String> getCommand() { return command; } public void setCommand(List<String> command) { this.command = command; } public CreateEdgeApplicationVersionResponse withArgs(List<String> args) { this.args = args; return this; } public CreateEdgeApplicationVersionResponse addArgsItem(String argsItem) { if (this.args == null) { this.args = new ArrayList<>(); } this.args.add(argsItem); return this; } public CreateEdgeApplicationVersionResponse withArgs(Consumer<List<String>> argsSetter) { if (this.args == null) { this.args = new ArrayList<>(); } argsSetter.accept(this.args); return this; } /** * 启动参数 * @return args */ public List<String> getArgs() { return args; } public void setArgs(List<String> args) { this.args = args; } public CreateEdgeApplicationVersionResponse withContainerSettings(ContainerSettingsDTO containerSettings) { this.containerSettings = containerSettings; return this; } public CreateEdgeApplicationVersionResponse withContainerSettings( Consumer<ContainerSettingsDTO> containerSettingsSetter) { if (this.containerSettings == null) { this.containerSettings = new ContainerSettingsDTO(); containerSettingsSetter.accept(this.containerSettings); } return this; } /** * Get containerSettings * @return containerSettings */ public ContainerSettingsDTO getContainerSettings() { return containerSettings; } public void setContainerSettings(ContainerSettingsDTO containerSettings) { this.containerSettings = containerSettings; } public CreateEdgeApplicationVersionResponse withOutputs(List<String> outputs) { this.outputs = outputs; return this; } public CreateEdgeApplicationVersionResponse addOutputsItem(String outputsItem) { if (this.outputs == null) { this.outputs = new ArrayList<>(); } this.outputs.add(outputsItem); return this; } public CreateEdgeApplicationVersionResponse withOutputs(Consumer<List<String>> outputsSetter) { if (this.outputs == null) { this.outputs = new ArrayList<>(); } outputsSetter.accept(this.outputs); return this; } /** * 应用输出路由端点 * @return outputs */ public List<String> getOutputs() { return outputs; } public void setOutputs(List<String> outputs) { this.outputs = outputs; } public CreateEdgeApplicationVersionResponse withInputs(List<String> inputs) { this.inputs = inputs; return this; } public CreateEdgeApplicationVersionResponse addInputsItem(String inputsItem) { if (this.inputs == null) { this.inputs = new ArrayList<>(); } this.inputs.add(inputsItem); return this; } public CreateEdgeApplicationVersionResponse withInputs(Consumer<List<String>> inputsSetter) { if (this.inputs == null) { this.inputs = new ArrayList<>(); } inputsSetter.accept(this.inputs); return this; } /** * 应用输入路由 * @return inputs */ public List<String> getInputs() { return inputs; } public void setInputs(List<String> inputs) { this.inputs = inputs; } public CreateEdgeApplicationVersionResponse withServices(List<String> services) { this.services = services; return this; } public CreateEdgeApplicationVersionResponse addServicesItem(String servicesItem) { if (this.services == null) { this.services = new ArrayList<>(); } this.services.add(servicesItem); return this; } public CreateEdgeApplicationVersionResponse withServices(Consumer<List<String>> servicesSetter) { if (this.services == null) { this.services = new ArrayList<>(); } servicesSetter.accept(this.services); return this; } /** * 应用实现的服务列表 * @return services */ public List<String> getServices() { return services; } public void setServices(List<String> services) { this.services = services; } public CreateEdgeApplicationVersionResponse withPublishTime(String publishTime) { this.publishTime = publishTime; return this; } /** * 发布时间 * @return publishTime */ public String getPublishTime() { return publishTime; } public void setPublishTime(String publishTime) { this.publishTime = publishTime; } public CreateEdgeApplicationVersionResponse withOffShelfTime(String offShelfTime) { this.offShelfTime = offShelfTime; return this; } /** * 下线时间 * @return offShelfTime */ public String getOffShelfTime() { return offShelfTime; } public void setOffShelfTime(String offShelfTime) { this.offShelfTime = offShelfTime; } public CreateEdgeApplicationVersionResponse withSupplier(String supplier) { this.supplier = supplier; return this; } /** * 驱动厂商 * @return supplier */ public String getSupplier() { return supplier; } public void setSupplier(String supplier) { this.supplier = supplier; } public CreateEdgeApplicationVersionResponse withTplId(String tplId) { this.tplId = tplId; return this; } /** * 模板id * @return tplId */ public String getTplId() { return tplId; } public void setTplId(String tplId) { this.tplId = tplId; } @Override public boolean equals(java.lang.Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } CreateEdgeApplicationVersionResponse that = (CreateEdgeApplicationVersionResponse) obj; return Objects.equals(this.edgeAppId, that.edgeAppId) && Objects.equals(this.name, that.name) && Objects.equals(this.deployType, that.deployType) && Objects.equals(this.deployMultiInstance, that.deployMultiInstance) && Objects.equals(this.version, that.version) && Objects.equals(this.sdkVersion, that.sdkVersion) && Objects.equals(this.description, that.description) && Objects.equals(this.createTime, that.createTime) && Objects.equals(this.updateTime, that.updateTime) && Objects.equals(this.state, that.state) && Objects.equals(this.livenessProbe, that.livenessProbe) && Objects.equals(this.readinessProbe, that.readinessProbe) && Objects.equals(this.arch, that.arch) && Objects.equals(this.command, that.command) && Objects.equals(this.args, that.args) && Objects.equals(this.containerSettings, that.containerSettings) && Objects.equals(this.outputs, that.outputs) && Objects.equals(this.inputs, that.inputs) && Objects.equals(this.services, that.services) && Objects.equals(this.publishTime, that.publishTime) && Objects.equals(this.offShelfTime, that.offShelfTime) && Objects.equals(this.supplier, that.supplier) && Objects.equals(this.tplId, that.tplId); } @Override public int hashCode() { return Objects.hash(edgeAppId, name, deployType, deployMultiInstance, version, sdkVersion, description, createTime, updateTime, state, livenessProbe, readinessProbe, arch, command, args, containerSettings, outputs, inputs, services, publishTime, offShelfTime, supplier, tplId); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class CreateEdgeApplicationVersionResponse {\n"); sb.append(" edgeAppId: ").append(toIndentedString(edgeAppId)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" deployType: ").append(toIndentedString(deployType)).append("\n"); sb.append(" deployMultiInstance: ").append(toIndentedString(deployMultiInstance)).append("\n"); sb.append(" version: ").append(toIndentedString(version)).append("\n"); sb.append(" sdkVersion: ").append(toIndentedString(sdkVersion)).append("\n"); sb.append(" description: ").append(toIndentedString(description)).append("\n"); sb.append(" createTime: ").append(toIndentedString(createTime)).append("\n"); sb.append(" updateTime: ").append(toIndentedString(updateTime)).append("\n"); sb.append(" state: ").append(toIndentedString(state)).append("\n"); sb.append(" livenessProbe: ").append(toIndentedString(livenessProbe)).append("\n"); sb.append(" readinessProbe: ").append(toIndentedString(readinessProbe)).append("\n"); sb.append(" arch: ").append(toIndentedString(arch)).append("\n"); sb.append(" command: ").append(toIndentedString(command)).append("\n"); sb.append(" args: ").append(toIndentedString(args)).append("\n"); sb.append(" containerSettings: ").append(toIndentedString(containerSettings)).append("\n"); sb.append(" outputs: ").append(toIndentedString(outputs)).append("\n"); sb.append(" inputs: ").append(toIndentedString(inputs)).append("\n"); sb.append(" services: ").append(toIndentedString(services)).append("\n"); sb.append(" publishTime: ").append(toIndentedString(publishTime)).append("\n"); sb.append(" offShelfTime: ").append(toIndentedString(offShelfTime)).append("\n"); sb.append(" supplier: ").append(toIndentedString(supplier)).append("\n"); sb.append(" tplId: ").append(toIndentedString(tplId)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
huaweicloud/huaweicloud-sdk-java-v3
services/iotedge/src/main/java/com/huaweicloud/sdk/iotedge/v2/model/CreateEdgeApplicationVersionResponse.java
5,791
/** * Response Object */
block_comment
nl
package com.huaweicloud.sdk.iotedge.v2.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonValue; import com.huaweicloud.sdk.core.SdkResponse; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.function.Consumer; /** * Response Object <SUF>*/ public class CreateEdgeApplicationVersionResponse extends SdkResponse { @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "edge_app_id") private String edgeAppId; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "name") private String name; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "deploy_type") private String deployType; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "deploy_multi_instance") private Boolean deployMultiInstance; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "version") private String version; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "sdk_version") private String sdkVersion; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "description") private String description; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "create_time") private String createTime; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "update_time") private String updateTime; /** * 应用版本状态 */ public static final class StateEnum { /** * Enum DRAFT for value: "DRAFT" */ public static final StateEnum DRAFT = new StateEnum("DRAFT"); /** * Enum PUBLISHED for value: "PUBLISHED" */ public static final StateEnum PUBLISHED = new StateEnum("PUBLISHED"); /** * Enum OFF_SHELF for value: "OFF_SHELF" */ public static final StateEnum OFF_SHELF = new StateEnum("OFF_SHELF"); private static final Map<String, StateEnum> STATIC_FIELDS = createStaticFields(); private static Map<String, StateEnum> createStaticFields() { Map<String, StateEnum> map = new HashMap<>(); map.put("DRAFT", DRAFT); map.put("PUBLISHED", PUBLISHED); map.put("OFF_SHELF", OFF_SHELF); return Collections.unmodifiableMap(map); } private String value; StateEnum(String value) { this.value = value; } @JsonValue public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } @JsonCreator public static StateEnum fromValue(String value) { if (value == null) { return null; } return java.util.Optional.ofNullable(STATIC_FIELDS.get(value)).orElse(new StateEnum(value)); } public static StateEnum valueOf(String value) { if (value == null) { return null; } return java.util.Optional.ofNullable(STATIC_FIELDS.get(value)) .orElseThrow(() -> new IllegalArgumentException("Unexpected value '" + value + "'")); } @Override public boolean equals(Object obj) { if (obj instanceof StateEnum) { return this.value.equals(((StateEnum) obj).value); } return false; } @Override public int hashCode() { return this.value.hashCode(); } } @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "state") private StateEnum state; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "liveness_probe") private ProbeDTO livenessProbe; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "readiness_probe") private ProbeDTO readinessProbe; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "arch") private List<String> arch = null; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "command") private List<String> command = null; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "args") private List<String> args = null; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "container_settings") private ContainerSettingsDTO containerSettings; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "outputs") private List<String> outputs = null; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "inputs") private List<String> inputs = null; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "services") private List<String> services = null; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "publish_time") private String publishTime; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "off_shelf_time") private String offShelfTime; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "supplier") private String supplier; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "tpl_id") private String tplId; public CreateEdgeApplicationVersionResponse withEdgeAppId(String edgeAppId) { this.edgeAppId = edgeAppId; return this; } /** * 应用ID * @return edgeAppId */ public String getEdgeAppId() { return edgeAppId; } public void setEdgeAppId(String edgeAppId) { this.edgeAppId = edgeAppId; } public CreateEdgeApplicationVersionResponse withName(String name) { this.name = name; return this; } /** * 应用名称 * @return name */ public String getName() { return name; } public void setName(String name) { this.name = name; } public CreateEdgeApplicationVersionResponse withDeployType(String deployType) { this.deployType = deployType; return this; } /** * 部署类型docker|process * @return deployType */ public String getDeployType() { return deployType; } public void setDeployType(String deployType) { this.deployType = deployType; } public CreateEdgeApplicationVersionResponse withDeployMultiInstance(Boolean deployMultiInstance) { this.deployMultiInstance = deployMultiInstance; return this; } /** * 是否允许部署多实例 * @return deployMultiInstance */ public Boolean getDeployMultiInstance() { return deployMultiInstance; } public void setDeployMultiInstance(Boolean deployMultiInstance) { this.deployMultiInstance = deployMultiInstance; } public CreateEdgeApplicationVersionResponse withVersion(String version) { this.version = version; return this; } /** * 应用版本 * @return version */ public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public CreateEdgeApplicationVersionResponse withSdkVersion(String sdkVersion) { this.sdkVersion = sdkVersion; return this; } /** * 应用集成的边缘SDK版本 * @return sdkVersion */ public String getSdkVersion() { return sdkVersion; } public void setSdkVersion(String sdkVersion) { this.sdkVersion = sdkVersion; } public CreateEdgeApplicationVersionResponse withDescription(String description) { this.description = description; return this; } /** * 应用描述 * @return description */ public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public CreateEdgeApplicationVersionResponse withCreateTime(String createTime) { this.createTime = createTime; return this; } /** * 创建时间 * @return createTime */ public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public CreateEdgeApplicationVersionResponse withUpdateTime(String updateTime) { this.updateTime = updateTime; return this; } /** * 最后一次修改时间 * @return updateTime */ public String getUpdateTime() { return updateTime; } public void setUpdateTime(String updateTime) { this.updateTime = updateTime; } public CreateEdgeApplicationVersionResponse withState(StateEnum state) { this.state = state; return this; } /** * 应用版本状态 * @return state */ public StateEnum getState() { return state; } public void setState(StateEnum state) { this.state = state; } public CreateEdgeApplicationVersionResponse withLivenessProbe(ProbeDTO livenessProbe) { this.livenessProbe = livenessProbe; return this; } public CreateEdgeApplicationVersionResponse withLivenessProbe(Consumer<ProbeDTO> livenessProbeSetter) { if (this.livenessProbe == null) { this.livenessProbe = new ProbeDTO(); livenessProbeSetter.accept(this.livenessProbe); } return this; } /** * Get livenessProbe * @return livenessProbe */ public ProbeDTO getLivenessProbe() { return livenessProbe; } public void setLivenessProbe(ProbeDTO livenessProbe) { this.livenessProbe = livenessProbe; } public CreateEdgeApplicationVersionResponse withReadinessProbe(ProbeDTO readinessProbe) { this.readinessProbe = readinessProbe; return this; } public CreateEdgeApplicationVersionResponse withReadinessProbe(Consumer<ProbeDTO> readinessProbeSetter) { if (this.readinessProbe == null) { this.readinessProbe = new ProbeDTO(); readinessProbeSetter.accept(this.readinessProbe); } return this; } /** * Get readinessProbe * @return readinessProbe */ public ProbeDTO getReadinessProbe() { return readinessProbe; } public void setReadinessProbe(ProbeDTO readinessProbe) { this.readinessProbe = readinessProbe; } public CreateEdgeApplicationVersionResponse withArch(List<String> arch) { this.arch = arch; return this; } public CreateEdgeApplicationVersionResponse addArchItem(String archItem) { if (this.arch == null) { this.arch = new ArrayList<>(); } this.arch.add(archItem); return this; } public CreateEdgeApplicationVersionResponse withArch(Consumer<List<String>> archSetter) { if (this.arch == null) { this.arch = new ArrayList<>(); } archSetter.accept(this.arch); return this; } /** * 架构 * @return arch */ public List<String> getArch() { return arch; } public void setArch(List<String> arch) { this.arch = arch; } public CreateEdgeApplicationVersionResponse withCommand(List<String> command) { this.command = command; return this; } public CreateEdgeApplicationVersionResponse addCommandItem(String commandItem) { if (this.command == null) { this.command = new ArrayList<>(); } this.command.add(commandItem); return this; } public CreateEdgeApplicationVersionResponse withCommand(Consumer<List<String>> commandSetter) { if (this.command == null) { this.command = new ArrayList<>(); } commandSetter.accept(this.command); return this; } /** * 启动命令 * @return command */ public List<String> getCommand() { return command; } public void setCommand(List<String> command) { this.command = command; } public CreateEdgeApplicationVersionResponse withArgs(List<String> args) { this.args = args; return this; } public CreateEdgeApplicationVersionResponse addArgsItem(String argsItem) { if (this.args == null) { this.args = new ArrayList<>(); } this.args.add(argsItem); return this; } public CreateEdgeApplicationVersionResponse withArgs(Consumer<List<String>> argsSetter) { if (this.args == null) { this.args = new ArrayList<>(); } argsSetter.accept(this.args); return this; } /** * 启动参数 * @return args */ public List<String> getArgs() { return args; } public void setArgs(List<String> args) { this.args = args; } public CreateEdgeApplicationVersionResponse withContainerSettings(ContainerSettingsDTO containerSettings) { this.containerSettings = containerSettings; return this; } public CreateEdgeApplicationVersionResponse withContainerSettings( Consumer<ContainerSettingsDTO> containerSettingsSetter) { if (this.containerSettings == null) { this.containerSettings = new ContainerSettingsDTO(); containerSettingsSetter.accept(this.containerSettings); } return this; } /** * Get containerSettings * @return containerSettings */ public ContainerSettingsDTO getContainerSettings() { return containerSettings; } public void setContainerSettings(ContainerSettingsDTO containerSettings) { this.containerSettings = containerSettings; } public CreateEdgeApplicationVersionResponse withOutputs(List<String> outputs) { this.outputs = outputs; return this; } public CreateEdgeApplicationVersionResponse addOutputsItem(String outputsItem) { if (this.outputs == null) { this.outputs = new ArrayList<>(); } this.outputs.add(outputsItem); return this; } public CreateEdgeApplicationVersionResponse withOutputs(Consumer<List<String>> outputsSetter) { if (this.outputs == null) { this.outputs = new ArrayList<>(); } outputsSetter.accept(this.outputs); return this; } /** * 应用输出路由端点 * @return outputs */ public List<String> getOutputs() { return outputs; } public void setOutputs(List<String> outputs) { this.outputs = outputs; } public CreateEdgeApplicationVersionResponse withInputs(List<String> inputs) { this.inputs = inputs; return this; } public CreateEdgeApplicationVersionResponse addInputsItem(String inputsItem) { if (this.inputs == null) { this.inputs = new ArrayList<>(); } this.inputs.add(inputsItem); return this; } public CreateEdgeApplicationVersionResponse withInputs(Consumer<List<String>> inputsSetter) { if (this.inputs == null) { this.inputs = new ArrayList<>(); } inputsSetter.accept(this.inputs); return this; } /** * 应用输入路由 * @return inputs */ public List<String> getInputs() { return inputs; } public void setInputs(List<String> inputs) { this.inputs = inputs; } public CreateEdgeApplicationVersionResponse withServices(List<String> services) { this.services = services; return this; } public CreateEdgeApplicationVersionResponse addServicesItem(String servicesItem) { if (this.services == null) { this.services = new ArrayList<>(); } this.services.add(servicesItem); return this; } public CreateEdgeApplicationVersionResponse withServices(Consumer<List<String>> servicesSetter) { if (this.services == null) { this.services = new ArrayList<>(); } servicesSetter.accept(this.services); return this; } /** * 应用实现的服务列表 * @return services */ public List<String> getServices() { return services; } public void setServices(List<String> services) { this.services = services; } public CreateEdgeApplicationVersionResponse withPublishTime(String publishTime) { this.publishTime = publishTime; return this; } /** * 发布时间 * @return publishTime */ public String getPublishTime() { return publishTime; } public void setPublishTime(String publishTime) { this.publishTime = publishTime; } public CreateEdgeApplicationVersionResponse withOffShelfTime(String offShelfTime) { this.offShelfTime = offShelfTime; return this; } /** * 下线时间 * @return offShelfTime */ public String getOffShelfTime() { return offShelfTime; } public void setOffShelfTime(String offShelfTime) { this.offShelfTime = offShelfTime; } public CreateEdgeApplicationVersionResponse withSupplier(String supplier) { this.supplier = supplier; return this; } /** * 驱动厂商 * @return supplier */ public String getSupplier() { return supplier; } public void setSupplier(String supplier) { this.supplier = supplier; } public CreateEdgeApplicationVersionResponse withTplId(String tplId) { this.tplId = tplId; return this; } /** * 模板id * @return tplId */ public String getTplId() { return tplId; } public void setTplId(String tplId) { this.tplId = tplId; } @Override public boolean equals(java.lang.Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } CreateEdgeApplicationVersionResponse that = (CreateEdgeApplicationVersionResponse) obj; return Objects.equals(this.edgeAppId, that.edgeAppId) && Objects.equals(this.name, that.name) && Objects.equals(this.deployType, that.deployType) && Objects.equals(this.deployMultiInstance, that.deployMultiInstance) && Objects.equals(this.version, that.version) && Objects.equals(this.sdkVersion, that.sdkVersion) && Objects.equals(this.description, that.description) && Objects.equals(this.createTime, that.createTime) && Objects.equals(this.updateTime, that.updateTime) && Objects.equals(this.state, that.state) && Objects.equals(this.livenessProbe, that.livenessProbe) && Objects.equals(this.readinessProbe, that.readinessProbe) && Objects.equals(this.arch, that.arch) && Objects.equals(this.command, that.command) && Objects.equals(this.args, that.args) && Objects.equals(this.containerSettings, that.containerSettings) && Objects.equals(this.outputs, that.outputs) && Objects.equals(this.inputs, that.inputs) && Objects.equals(this.services, that.services) && Objects.equals(this.publishTime, that.publishTime) && Objects.equals(this.offShelfTime, that.offShelfTime) && Objects.equals(this.supplier, that.supplier) && Objects.equals(this.tplId, that.tplId); } @Override public int hashCode() { return Objects.hash(edgeAppId, name, deployType, deployMultiInstance, version, sdkVersion, description, createTime, updateTime, state, livenessProbe, readinessProbe, arch, command, args, containerSettings, outputs, inputs, services, publishTime, offShelfTime, supplier, tplId); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class CreateEdgeApplicationVersionResponse {\n"); sb.append(" edgeAppId: ").append(toIndentedString(edgeAppId)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" deployType: ").append(toIndentedString(deployType)).append("\n"); sb.append(" deployMultiInstance: ").append(toIndentedString(deployMultiInstance)).append("\n"); sb.append(" version: ").append(toIndentedString(version)).append("\n"); sb.append(" sdkVersion: ").append(toIndentedString(sdkVersion)).append("\n"); sb.append(" description: ").append(toIndentedString(description)).append("\n"); sb.append(" createTime: ").append(toIndentedString(createTime)).append("\n"); sb.append(" updateTime: ").append(toIndentedString(updateTime)).append("\n"); sb.append(" state: ").append(toIndentedString(state)).append("\n"); sb.append(" livenessProbe: ").append(toIndentedString(livenessProbe)).append("\n"); sb.append(" readinessProbe: ").append(toIndentedString(readinessProbe)).append("\n"); sb.append(" arch: ").append(toIndentedString(arch)).append("\n"); sb.append(" command: ").append(toIndentedString(command)).append("\n"); sb.append(" args: ").append(toIndentedString(args)).append("\n"); sb.append(" containerSettings: ").append(toIndentedString(containerSettings)).append("\n"); sb.append(" outputs: ").append(toIndentedString(outputs)).append("\n"); sb.append(" inputs: ").append(toIndentedString(inputs)).append("\n"); sb.append(" services: ").append(toIndentedString(services)).append("\n"); sb.append(" publishTime: ").append(toIndentedString(publishTime)).append("\n"); sb.append(" offShelfTime: ").append(toIndentedString(offShelfTime)).append("\n"); sb.append(" supplier: ").append(toIndentedString(supplier)).append("\n"); sb.append(" tplId: ").append(toIndentedString(tplId)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
100462_0
package nl.demo.transformers.model; import nl.donna.generiek.common.dto.Valideer; import edu.umd.cs.findbugs.annotations.DefaultAnnotation; import edu.umd.cs.findbugs.annotations.NonNull; /** * Dit zijn de ondersteunde InfraGebruikers in Cucumber * * @author Jurn van Mieghem * */ @DefaultAnnotation(NonNull.class) public enum InfraGebruiker { NSR("NSR", "NS-Reizigers"), HSP("HSP", "NS_International"), NSI("NSI", "NS_International"); private final String afkorting; private final String volledigeNaam; private InfraGebruiker(String afkorting, String volledigeNaam) { this.afkorting = Valideer.notNull(afkorting); this.volledigeNaam = Valideer.notNull(volledigeNaam); } public static InfraGebruiker geefEnumVoorAfkorting(String gegevenAfkorting) { for (InfraGebruiker infraGebruiker : InfraGebruiker.values()) { if (infraGebruiker.afkorting.equalsIgnoreCase(gegevenAfkorting)) { return infraGebruiker; } } throw new IllegalStateException("De afkorting " + gegevenAfkorting + " wordt niet herkend."); } public static InfraGebruiker geefEnumVoorVolledigeNaam(String gegevenNaam) { for (InfraGebruiker infraGebruiker : InfraGebruiker.values()) { if (infraGebruiker.volledigeNaam.equalsIgnoreCase(gegevenNaam)) { return infraGebruiker; } } throw new IllegalStateException("De volledigeNaam " + gegevenNaam + " wordt niet herkend."); } public String getVolledigeNaam() { return volledigeNaam; } }
jgelon/DemoTransformer
src/main/java/nl/demo/transformers/model/InfraGebruiker.java
441
/** * Dit zijn de ondersteunde InfraGebruikers in Cucumber * * @author Jurn van Mieghem * */
block_comment
nl
package nl.demo.transformers.model; import nl.donna.generiek.common.dto.Valideer; import edu.umd.cs.findbugs.annotations.DefaultAnnotation; import edu.umd.cs.findbugs.annotations.NonNull; /** * Dit zijn de<SUF>*/ @DefaultAnnotation(NonNull.class) public enum InfraGebruiker { NSR("NSR", "NS-Reizigers"), HSP("HSP", "NS_International"), NSI("NSI", "NS_International"); private final String afkorting; private final String volledigeNaam; private InfraGebruiker(String afkorting, String volledigeNaam) { this.afkorting = Valideer.notNull(afkorting); this.volledigeNaam = Valideer.notNull(volledigeNaam); } public static InfraGebruiker geefEnumVoorAfkorting(String gegevenAfkorting) { for (InfraGebruiker infraGebruiker : InfraGebruiker.values()) { if (infraGebruiker.afkorting.equalsIgnoreCase(gegevenAfkorting)) { return infraGebruiker; } } throw new IllegalStateException("De afkorting " + gegevenAfkorting + " wordt niet herkend."); } public static InfraGebruiker geefEnumVoorVolledigeNaam(String gegevenNaam) { for (InfraGebruiker infraGebruiker : InfraGebruiker.values()) { if (infraGebruiker.volledigeNaam.equalsIgnoreCase(gegevenNaam)) { return infraGebruiker; } } throw new IllegalStateException("De volledigeNaam " + gegevenNaam + " wordt niet herkend."); } public String getVolledigeNaam() { return volledigeNaam; } }
164988_4
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * * @author R. Springer */ public class level3 extends World { private CollisionEngine ce; /** * Constructor for objects of class MyWorld. * */ public level3() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(1280, 720, 1, false); this.setBackground("greycave2.jpg"); int[][] map = { {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,250,250,250,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,27,28,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,27,28,27,28,27,28,27,28,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,27,28}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,27,28,-1,-1,-1,-1,-1,63}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,27,28,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,68,-1,62}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,27,28,-1,-1,-1,-1,-1,-1,-1,27,38,28}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,44,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,27,28,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,219,23,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,27,28,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,27,28,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,38,38,38,-1,-1,-1,-1,27,28,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,24,287,287,24,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,35,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,35,24,24,24,24,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {105,243,-1,-1,-1,23,-1,-1,-1,-1,32,35,24,-1,-1,-1,-1,-1,23,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,44,-1,-1,-1,32,35,24,24,24,24,24,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {37,38,38,38,38,38,38,38,38,38,35,24,24,38,38,38,38,38,38,38,38,38,140,140,38,38,38,38,38,38,38,38,38,38,38,38,38,35,24,24,24,24,24,24,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140}, {24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,139,139,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139}, {24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,139,139,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139}, {24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,139,139,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139}, {24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,139,139,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139}, {24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,139,139,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139}, {24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,139,139,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139}, {24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,139,139,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139}, }; // Declareren en initialiseren van de TileEngine klasse om de map aan de world toe te voegen TileEngine te = new TileEngine(this, 60, 60, map); // Declarenre en initialiseren van de camera klasse met de TileEngine klasse // zodat de camera weet welke tiles allemaal moeten meebewegen met de camera Camera camera = new Camera(te); // Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse // moet de klasse Mover extenden voor de camera om te werken Hero hero = new Hero(ce, te); // Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan. camera.follow(hero); // Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies addObject(camera, 0, 0); addObject(hero, 120, 1275); addObject(new Enemy(), 0, 0); addObject(new Enemy(), 0, 0); addObject(new Enemy(), 0, 0); addObject(new Enemy3(), 936, 1250); addObject(new Enemy3(), 1836, 1250); // Force act zodat de camera op de juist plek staat. camera.act(); hero.act(); // Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen. // De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan. ce = new CollisionEngine(te, camera); // Toevoegen van de mover instantie of een extentie hiervan ce.addCollidingMover(hero); } @Override public void act() { ce.update(); } }
ROCMondriaanTIN/project-greenfoot-game-darshbadal
level3.java
5,710
// Declareren en initialiseren van de TileEngine klasse om de map aan de world toe te voegen
line_comment
nl
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * * @author R. Springer */ public class level3 extends World { private CollisionEngine ce; /** * Constructor for objects of class MyWorld. * */ public level3() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(1280, 720, 1, false); this.setBackground("greycave2.jpg"); int[][] map = { {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,250,250,250,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,27,28,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,27,28,27,28,27,28,27,28,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,27,28}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,27,28,-1,-1,-1,-1,-1,63}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,27,28,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,68,-1,62}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,27,28,-1,-1,-1,-1,-1,-1,-1,27,38,28}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,44,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,27,28,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,219,23,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,27,28,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,27,28,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,38,38,38,-1,-1,-1,-1,27,28,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,24,287,287,24,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,35,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,35,24,24,24,24,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {105,243,-1,-1,-1,23,-1,-1,-1,-1,32,35,24,-1,-1,-1,-1,-1,23,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,44,-1,-1,-1,32,35,24,24,24,24,24,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {37,38,38,38,38,38,38,38,38,38,35,24,24,38,38,38,38,38,38,38,38,38,140,140,38,38,38,38,38,38,38,38,38,38,38,38,38,35,24,24,24,24,24,24,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140,140}, {24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,139,139,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139}, {24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,139,139,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139}, {24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,139,139,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139}, {24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,139,139,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139}, {24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,139,139,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139}, {24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,139,139,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139}, {24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,139,139,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139,139}, }; // Declareren en<SUF> TileEngine te = new TileEngine(this, 60, 60, map); // Declarenre en initialiseren van de camera klasse met de TileEngine klasse // zodat de camera weet welke tiles allemaal moeten meebewegen met de camera Camera camera = new Camera(te); // Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse // moet de klasse Mover extenden voor de camera om te werken Hero hero = new Hero(ce, te); // Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan. camera.follow(hero); // Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies addObject(camera, 0, 0); addObject(hero, 120, 1275); addObject(new Enemy(), 0, 0); addObject(new Enemy(), 0, 0); addObject(new Enemy(), 0, 0); addObject(new Enemy3(), 936, 1250); addObject(new Enemy3(), 1836, 1250); // Force act zodat de camera op de juist plek staat. camera.act(); hero.act(); // Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen. // De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan. ce = new CollisionEngine(te, camera); // Toevoegen van de mover instantie of een extentie hiervan ce.addCollidingMover(hero); } @Override public void act() { ce.update(); } }
29710_2
package com.company; // 6 softwareontwikkelaars // 10 gebruikers // SoftwareOntwikkelaarOverleg 3 softwareontwikkelaars met product owner userstories opgesteld en geprioriteerd // GebruikersOverleg 1 softwareontwikkelaar met 1 gebruiker en product owner problemen gebruikers besproken // gebruiker heeft probleem, meldt bij bedrijf, wacht tot uitgenodigd voor overleg, als uitgenodigd: reist naar bedrijf en meldt dat aangekomen is, wacht tot jaap zegt dat kan overleggen // softwareontwikkelaar meldt regelmatig dat beschikbaar is overleg. Projectleider in overleg: softwareontwikkelaar weer aan het werk. // Projectleider niet in overleg: wacht tot projectleider uitnodigt OF wacht tot constateerd dat hij niet hoeft deel te nemen aan gesprek, daarna weer aan werk // Softwareontwikkelaar kan beide gesprekken hebben // Gebruikersoverleg // Als gebruiker meldt en geen wachtende SO, dan wacht projectleider tot meldt. import java.util.concurrent.Semaphore; /** * Created by rickv on 19-9-2016. */ public class Bedrijf2 { private static final int AANTAL_SOFTWAREONTWIKKELAARS = 6; private static final int AANTAL_GEBRUIKERS = 10; private int AANTAL_SOFTWAREONTWIKKELAARS_BINNEN; private int AANTAL_GEBRUIKERS_BINNEN; private int wachtendeSoftwareOntwikkelaars; private Gebruiker[] gebruiker; private Softwareontwikkelaar[] softwareontwikkelaar; private ProductOwner productOwner; private Semaphore probleemMelding, uitnodigingGesprek, aankomstMelding, gesprekUitnodiging, beschikbaarVoorOverleg, inOverleg, checkin; public Bedrijf2() { checkin = new Semaphore(AANTAL_GEBRUIKERS+AANTAL_SOFTWAREONTWIKKELAARS, true); uitnodigingGesprek = new Semaphore(0, true); inOverleg = new Semaphore(0,true); gebruiker = new Gebruiker[AANTAL_GEBRUIKERS]; for(int i=0; i < AANTAL_GEBRUIKERS; i++){ gebruiker[i] = new Gebruiker("g"+i,i); gebruiker[i].start(); } softwareontwikkelaar = new Softwareontwikkelaar[AANTAL_SOFTWAREONTWIKKELAARS]; for(int i=0; i < AANTAL_SOFTWAREONTWIKKELAARS; i++){ softwareontwikkelaar[i] = new Softwareontwikkelaar("s"+i,i); softwareontwikkelaar[i].start(); } productOwner = new ProductOwner(); productOwner.start(); } private void SoftwareOntwikkelaarOverleg(){ /* try{ // 3 softwareontwikkelaars melden dan uitnodiging uitnodigingGesprek.release(); // gebruiksoverleg of ontwikkelaaresoverleg (gebruiks heeft voorrang) // overleg klaar inOverleg.release(); // softwareontwikkelaars weer werken, product owner slapen } catch(InterruptedException e){ } */ } private void GebruikersOverleg(){ try{ // gebruiker meld, zijn al wachtende softwareontwikkelaars dan punt 2 aankomstMelding.acquire(); // 1. softwareontwikkelaar meld // meerdere gemeldde gebruikers toelaten // alle gebruikers uitnodigen // 2. gebruiker meteen uitgenodigd naar bedrijf // gebruiker uitgenodig voor gesprek // wachtende softwareontwikkelaars op de hoogte gebracht van gesprek inOverleg.release(); } catch(InterruptedException e){ } } public class Softwareontwikkelaar extends Thread{ private int myId; public Softwareontwikkelaar(String name, int id){ super(name); myId = id; } public void run() { while (true) { try { checkin.acquire(); // meldt regelmatig dat beshcikbaar is voor overleg // als projectleider in overleg is, verder met werk // als projectleider niet in overleg is, wachten voor uitnodiging voor een overleg // OF tot geconstateerd dat niet bij gesprek hoort, dan verder met werk } catch (InterruptedException e) {} } } } public class ProductOwner extends Thread{ public void run() { while (true) { /*try { } catch (InterruptedException e) {}*/ } } private void overleg(){ try{ System.out.println("in overleg"); Thread.sleep((int)(Math.random()*1000)); } catch(InterruptedException e){} } } public class Gebruiker extends Thread{ private int myId; public Gebruiker(String name, int id){ super(name); myId = id; } public void run() { while (true) { try { checkin.acquire(); // probleem?, melden bij bedrijf // wachten tot uitgenodigd voor overleg // reizen naar bedrijf en melden aangekomen om te overleggen // wachten tot product owner zegt dat gesprek begint } catch (InterruptedException e) {} } } } }
rickvanw/Assignment2Concurrency
src/com/company/Bedrijf2.java
1,321
// gebruiker heeft probleem, meldt bij bedrijf, wacht tot uitgenodigd voor overleg, als uitgenodigd: reist naar bedrijf en meldt dat aangekomen is, wacht tot jaap zegt dat kan overleggen
line_comment
nl
package com.company; // 6 softwareontwikkelaars // 10 gebruikers // SoftwareOntwikkelaarOverleg 3 softwareontwikkelaars met product owner userstories opgesteld en geprioriteerd // GebruikersOverleg 1 softwareontwikkelaar met 1 gebruiker en product owner problemen gebruikers besproken // gebruiker heeft<SUF> // softwareontwikkelaar meldt regelmatig dat beschikbaar is overleg. Projectleider in overleg: softwareontwikkelaar weer aan het werk. // Projectleider niet in overleg: wacht tot projectleider uitnodigt OF wacht tot constateerd dat hij niet hoeft deel te nemen aan gesprek, daarna weer aan werk // Softwareontwikkelaar kan beide gesprekken hebben // Gebruikersoverleg // Als gebruiker meldt en geen wachtende SO, dan wacht projectleider tot meldt. import java.util.concurrent.Semaphore; /** * Created by rickv on 19-9-2016. */ public class Bedrijf2 { private static final int AANTAL_SOFTWAREONTWIKKELAARS = 6; private static final int AANTAL_GEBRUIKERS = 10; private int AANTAL_SOFTWAREONTWIKKELAARS_BINNEN; private int AANTAL_GEBRUIKERS_BINNEN; private int wachtendeSoftwareOntwikkelaars; private Gebruiker[] gebruiker; private Softwareontwikkelaar[] softwareontwikkelaar; private ProductOwner productOwner; private Semaphore probleemMelding, uitnodigingGesprek, aankomstMelding, gesprekUitnodiging, beschikbaarVoorOverleg, inOverleg, checkin; public Bedrijf2() { checkin = new Semaphore(AANTAL_GEBRUIKERS+AANTAL_SOFTWAREONTWIKKELAARS, true); uitnodigingGesprek = new Semaphore(0, true); inOverleg = new Semaphore(0,true); gebruiker = new Gebruiker[AANTAL_GEBRUIKERS]; for(int i=0; i < AANTAL_GEBRUIKERS; i++){ gebruiker[i] = new Gebruiker("g"+i,i); gebruiker[i].start(); } softwareontwikkelaar = new Softwareontwikkelaar[AANTAL_SOFTWAREONTWIKKELAARS]; for(int i=0; i < AANTAL_SOFTWAREONTWIKKELAARS; i++){ softwareontwikkelaar[i] = new Softwareontwikkelaar("s"+i,i); softwareontwikkelaar[i].start(); } productOwner = new ProductOwner(); productOwner.start(); } private void SoftwareOntwikkelaarOverleg(){ /* try{ // 3 softwareontwikkelaars melden dan uitnodiging uitnodigingGesprek.release(); // gebruiksoverleg of ontwikkelaaresoverleg (gebruiks heeft voorrang) // overleg klaar inOverleg.release(); // softwareontwikkelaars weer werken, product owner slapen } catch(InterruptedException e){ } */ } private void GebruikersOverleg(){ try{ // gebruiker meld, zijn al wachtende softwareontwikkelaars dan punt 2 aankomstMelding.acquire(); // 1. softwareontwikkelaar meld // meerdere gemeldde gebruikers toelaten // alle gebruikers uitnodigen // 2. gebruiker meteen uitgenodigd naar bedrijf // gebruiker uitgenodig voor gesprek // wachtende softwareontwikkelaars op de hoogte gebracht van gesprek inOverleg.release(); } catch(InterruptedException e){ } } public class Softwareontwikkelaar extends Thread{ private int myId; public Softwareontwikkelaar(String name, int id){ super(name); myId = id; } public void run() { while (true) { try { checkin.acquire(); // meldt regelmatig dat beshcikbaar is voor overleg // als projectleider in overleg is, verder met werk // als projectleider niet in overleg is, wachten voor uitnodiging voor een overleg // OF tot geconstateerd dat niet bij gesprek hoort, dan verder met werk } catch (InterruptedException e) {} } } } public class ProductOwner extends Thread{ public void run() { while (true) { /*try { } catch (InterruptedException e) {}*/ } } private void overleg(){ try{ System.out.println("in overleg"); Thread.sleep((int)(Math.random()*1000)); } catch(InterruptedException e){} } } public class Gebruiker extends Thread{ private int myId; public Gebruiker(String name, int id){ super(name); myId = id; } public void run() { while (true) { try { checkin.acquire(); // probleem?, melden bij bedrijf // wachten tot uitgenodigd voor overleg // reizen naar bedrijf en melden aangekomen om te overleggen // wachten tot product owner zegt dat gesprek begint } catch (InterruptedException e) {} } } } }
120862_1
package controller; import interfacce.UserInterface; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import model.DAO.TirocinioDAO; import model.Tirocinio; /** * Servlet implementation class ServletGestioneRichiesteSegreteriaET. */ @WebServlet("/ServletProgettoFormativoET") public class ServletProgettoFormativoET extends HttpServlet { private static final long serialVersionUID = 1L; /** * Constructor. * * @see HttpServlet#HttpServlet() */ public ServletProgettoFormativoET() { super(); } /** * Method doGet(). * * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { UserInterface user = (UserInterface) request.getSession().getAttribute("user"); // String stato=(String) request.getAttribute("stato"); TirocinioDAO tirocinioDao = new TirocinioDAO(); Tirocinio tirocinio = new Tirocinio(); /* * Richiamo la funzione di tirocinioDAO: * allTirocinioByDocumento * e cerco i tirocini con lo stato * "Accettato e in attesa di firma" * */ tirocinio = tirocinioDao.allTirocinioByDocumento(user.getEmail(), "Accettato e in attesa di firma"); String pag = ""; String result = ""; if (tirocinio != null) { // Assegno alla richiesta la 'listaTirocini' request.setAttribute("tirocinio", tirocinio); result = "ok"; request.setAttribute("result", result); } else { result = "nook"; request.setAttribute("tirocinio", tirocinio); request.setAttribute("result", result); } pag = "_areaStudent/UploadProgettoFormativoET.jsp"; RequestDispatcher dispatcher = request.getRequestDispatcher(pag); dispatcher.forward(request, response); } /** * Method doPost(). * * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
eliotest98/easy-traineeship
src/controller/ServletProgettoFormativoET.java
631
/** * Constructor. * * @see HttpServlet#HttpServlet() */
block_comment
nl
package controller; import interfacce.UserInterface; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import model.DAO.TirocinioDAO; import model.Tirocinio; /** * Servlet implementation class ServletGestioneRichiesteSegreteriaET. */ @WebServlet("/ServletProgettoFormativoET") public class ServletProgettoFormativoET extends HttpServlet { private static final long serialVersionUID = 1L; /** * Constructor. <SUF>*/ public ServletProgettoFormativoET() { super(); } /** * Method doGet(). * * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { UserInterface user = (UserInterface) request.getSession().getAttribute("user"); // String stato=(String) request.getAttribute("stato"); TirocinioDAO tirocinioDao = new TirocinioDAO(); Tirocinio tirocinio = new Tirocinio(); /* * Richiamo la funzione di tirocinioDAO: * allTirocinioByDocumento * e cerco i tirocini con lo stato * "Accettato e in attesa di firma" * */ tirocinio = tirocinioDao.allTirocinioByDocumento(user.getEmail(), "Accettato e in attesa di firma"); String pag = ""; String result = ""; if (tirocinio != null) { // Assegno alla richiesta la 'listaTirocini' request.setAttribute("tirocinio", tirocinio); result = "ok"; request.setAttribute("result", result); } else { result = "nook"; request.setAttribute("tirocinio", tirocinio); request.setAttribute("result", result); } pag = "_areaStudent/UploadProgettoFormativoET.jsp"; RequestDispatcher dispatcher = request.getRequestDispatcher(pag); dispatcher.forward(request, response); } /** * Method doPost(). * * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
43510_7
package nl.novi.techiteasy.config; import nl.novi.techiteasy.filter.JwtRequestFilter; import nl.novi.techiteasy.services.CustomUserDetailsService; import nl.novi.techiteasy.utils.JwtUtil; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.ProviderManager; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; @Configuration @EnableWebSecurity public class SpringSecurityConfig { private final CustomUserDetailsService customUserDetailsService; private final JwtRequestFilter jwtRequestFilter; public SpringSecurityConfig(CustomUserDetailsService userDetailsService, JwtRequestFilter jwtRequestFilter) { this.customUserDetailsService = userDetailsService; this.jwtRequestFilter = jwtRequestFilter; } // PasswordEncoderBean. Deze kun je overal in je applicatie injecteren waar nodig. // Je kunt dit ook in een aparte configuratie klasse zetten. @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } // Authenticatie met customUserDetailsService en passwordEncoder @Bean public AuthenticationManager authenticationManager(HttpSecurity http, PasswordEncoder passwordEncoder) throws Exception { var auth = new DaoAuthenticationProvider(); auth.setPasswordEncoder(passwordEncoder); auth.setUserDetailsService(customUserDetailsService); return new ProviderManager(auth); } // Authorizatie met jwt @Bean protected SecurityFilterChain filter (HttpSecurity http) throws Exception { //JWT token authentication http .csrf(csrf -> csrf.disable()) .httpBasic(basic -> basic.disable()) .cors(Customizer.withDefaults()) .authorizeHttpRequests(auth -> auth // Wanneer je deze uncomments, staat je hele security open. Je hebt dan alleen nog een jwt nodig. // .requestMatchers("/**").permitAll() .requestMatchers(HttpMethod.POST, "/users").hasRole("ADMIN") .requestMatchers(HttpMethod.GET,"/users").hasRole("ADMIN") .requestMatchers(HttpMethod.POST,"/users/**").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/users/**").hasRole("ADMIN") .requestMatchers(HttpMethod.POST, "/cimodules").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/cimodules/**").hasRole("ADMIN") .requestMatchers(HttpMethod.POST, "/remotecontrollers").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/remotecontrollers/**").hasRole("ADMIN") .requestMatchers(HttpMethod.POST, "/televisions").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/televisions/**").hasRole("ADMIN") .requestMatchers(HttpMethod.POST, "/wallbrackets").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/wallbrackets/**").hasRole("ADMIN") .requestMatchers("/authenticated").authenticated() .requestMatchers("/authenticate").permitAll()/*alleen dit punt mag toegankelijk zijn voor niet ingelogde gebruikers*/ .requestMatchers("/cimodules", "/remotecontrollers", "/televisions", "/wallbrackets").hasAnyRole("ADMIN", "USER") .requestMatchers("/authenticated").authenticated() .requestMatchers("/authenticate").permitAll() .anyRequest().denyAll() /*Deze voeg je altijd als laatste toe, om een default beveiliging te hebben voor eventuele vergeten endpoints of endpoints die je later toevoegd. */ ) .sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS)); http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class); return http.build(); } }
MarjetBosma/NOVI-backend-springboot-techiteasy
src/main/java/nl/novi/techiteasy/config/SpringSecurityConfig.java
1,025
/*Deze voeg je altijd als laatste toe, om een default beveiliging te hebben voor eventuele vergeten endpoints of endpoints die je later toevoegd. */
block_comment
nl
package nl.novi.techiteasy.config; import nl.novi.techiteasy.filter.JwtRequestFilter; import nl.novi.techiteasy.services.CustomUserDetailsService; import nl.novi.techiteasy.utils.JwtUtil; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.ProviderManager; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; @Configuration @EnableWebSecurity public class SpringSecurityConfig { private final CustomUserDetailsService customUserDetailsService; private final JwtRequestFilter jwtRequestFilter; public SpringSecurityConfig(CustomUserDetailsService userDetailsService, JwtRequestFilter jwtRequestFilter) { this.customUserDetailsService = userDetailsService; this.jwtRequestFilter = jwtRequestFilter; } // PasswordEncoderBean. Deze kun je overal in je applicatie injecteren waar nodig. // Je kunt dit ook in een aparte configuratie klasse zetten. @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } // Authenticatie met customUserDetailsService en passwordEncoder @Bean public AuthenticationManager authenticationManager(HttpSecurity http, PasswordEncoder passwordEncoder) throws Exception { var auth = new DaoAuthenticationProvider(); auth.setPasswordEncoder(passwordEncoder); auth.setUserDetailsService(customUserDetailsService); return new ProviderManager(auth); } // Authorizatie met jwt @Bean protected SecurityFilterChain filter (HttpSecurity http) throws Exception { //JWT token authentication http .csrf(csrf -> csrf.disable()) .httpBasic(basic -> basic.disable()) .cors(Customizer.withDefaults()) .authorizeHttpRequests(auth -> auth // Wanneer je deze uncomments, staat je hele security open. Je hebt dan alleen nog een jwt nodig. // .requestMatchers("/**").permitAll() .requestMatchers(HttpMethod.POST, "/users").hasRole("ADMIN") .requestMatchers(HttpMethod.GET,"/users").hasRole("ADMIN") .requestMatchers(HttpMethod.POST,"/users/**").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/users/**").hasRole("ADMIN") .requestMatchers(HttpMethod.POST, "/cimodules").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/cimodules/**").hasRole("ADMIN") .requestMatchers(HttpMethod.POST, "/remotecontrollers").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/remotecontrollers/**").hasRole("ADMIN") .requestMatchers(HttpMethod.POST, "/televisions").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/televisions/**").hasRole("ADMIN") .requestMatchers(HttpMethod.POST, "/wallbrackets").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/wallbrackets/**").hasRole("ADMIN") .requestMatchers("/authenticated").authenticated() .requestMatchers("/authenticate").permitAll()/*alleen dit punt mag toegankelijk zijn voor niet ingelogde gebruikers*/ .requestMatchers("/cimodules", "/remotecontrollers", "/televisions", "/wallbrackets").hasAnyRole("ADMIN", "USER") .requestMatchers("/authenticated").authenticated() .requestMatchers("/authenticate").permitAll() .anyRequest().denyAll() /*Deze voeg je<SUF>*/ ) .sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS)); http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class); return http.build(); } }
3951_2
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.codehaus.groovy.classgen.asm.indy.sc; import org.codehaus.groovy.classgen.asm.BinaryExpressionWriter; import org.codehaus.groovy.classgen.asm.MethodCaller; import org.codehaus.groovy.classgen.asm.WriterController; import org.codehaus.groovy.classgen.asm.sc.StaticTypesBinaryExpressionMultiTypeDispatcher; import org.codehaus.groovy.vmplugin.v7.IndyInterface; import org.objectweb.asm.Handle; import org.objectweb.asm.MethodVisitor; import java.lang.invoke.CallSite; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; /** * Multi type dispatcher for binary expression backend combining indy and static compilation * @author Jochen Theodorou * @since 2.5.0 */ public class IndyStaticTypesMultiTypeDispatcher extends StaticTypesBinaryExpressionMultiTypeDispatcher { public IndyStaticTypesMultiTypeDispatcher(WriterController wc) { super(wc); } private static final String INDY_INTERFACE_NAME = IndyInterface.class.getName().replace('.', '/'); private static final String BSM_METHOD_TYPE_DESCRIPTOR = MethodType.methodType( CallSite.class, MethodHandles.Lookup.class, String.class, MethodType.class ).toMethodDescriptorString(); private static final Handle BSM = new Handle( H_INVOKESTATIC, INDY_INTERFACE_NAME, "staticArrayAccess", BSM_METHOD_TYPE_DESCRIPTOR); private static class GenericArrayAccess extends MethodCaller { private final String name, signature; public GenericArrayAccess(String name, String signature) { this.name = name; this.signature = signature; } @Override public void call(MethodVisitor mv) { mv.visitInvokeDynamicInsn(name, signature, BSM); } } protected BinaryExpressionWriter[] initializeDelegateHelpers() { BinaryExpressionWriter[] bewArray = super.initializeDelegateHelpers(); /* 1: int */ bewArray[1].setArraySetAndGet( new GenericArrayAccess("set","([III)V"), new GenericArrayAccess("get","([II)I")); /* 2: long */ bewArray[2].setArraySetAndGet( new GenericArrayAccess("set","([JIJ)V"), new GenericArrayAccess("get","([JI)J")); /* 3: double */ bewArray[3].setArraySetAndGet( new GenericArrayAccess("set","([DID)V"), new GenericArrayAccess("get","([DI)D")); /* 4: char */ bewArray[4].setArraySetAndGet( new GenericArrayAccess("set","([CIC)V"), new GenericArrayAccess("get","([CI)C")); /* 5: byte */ bewArray[5].setArraySetAndGet( new GenericArrayAccess("set","([BIB)V"), new GenericArrayAccess("get","([BI)B")); /* 6: short */ bewArray[6].setArraySetAndGet( new GenericArrayAccess("set","([SIS)V"), new GenericArrayAccess("get","([SI)S")); /* 7: float */ bewArray[7].setArraySetAndGet( new GenericArrayAccess("get","([FIF)V"), new GenericArrayAccess("set","([FI)F")); /* 8: bool */ bewArray[8].setArraySetAndGet( new GenericArrayAccess("get","([ZIZ)V"), new GenericArrayAccess("set","([ZI)Z")); return bewArray; } }
groovy/groovy-core
src/main/org/codehaus/groovy/classgen/asm/indy/sc/IndyStaticTypesMultiTypeDispatcher.java
1,085
/* 1: int */
block_comment
nl
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.codehaus.groovy.classgen.asm.indy.sc; import org.codehaus.groovy.classgen.asm.BinaryExpressionWriter; import org.codehaus.groovy.classgen.asm.MethodCaller; import org.codehaus.groovy.classgen.asm.WriterController; import org.codehaus.groovy.classgen.asm.sc.StaticTypesBinaryExpressionMultiTypeDispatcher; import org.codehaus.groovy.vmplugin.v7.IndyInterface; import org.objectweb.asm.Handle; import org.objectweb.asm.MethodVisitor; import java.lang.invoke.CallSite; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; /** * Multi type dispatcher for binary expression backend combining indy and static compilation * @author Jochen Theodorou * @since 2.5.0 */ public class IndyStaticTypesMultiTypeDispatcher extends StaticTypesBinaryExpressionMultiTypeDispatcher { public IndyStaticTypesMultiTypeDispatcher(WriterController wc) { super(wc); } private static final String INDY_INTERFACE_NAME = IndyInterface.class.getName().replace('.', '/'); private static final String BSM_METHOD_TYPE_DESCRIPTOR = MethodType.methodType( CallSite.class, MethodHandles.Lookup.class, String.class, MethodType.class ).toMethodDescriptorString(); private static final Handle BSM = new Handle( H_INVOKESTATIC, INDY_INTERFACE_NAME, "staticArrayAccess", BSM_METHOD_TYPE_DESCRIPTOR); private static class GenericArrayAccess extends MethodCaller { private final String name, signature; public GenericArrayAccess(String name, String signature) { this.name = name; this.signature = signature; } @Override public void call(MethodVisitor mv) { mv.visitInvokeDynamicInsn(name, signature, BSM); } } protected BinaryExpressionWriter[] initializeDelegateHelpers() { BinaryExpressionWriter[] bewArray = super.initializeDelegateHelpers(); /* 1: int <SUF>*/ bewArray[1].setArraySetAndGet( new GenericArrayAccess("set","([III)V"), new GenericArrayAccess("get","([II)I")); /* 2: long */ bewArray[2].setArraySetAndGet( new GenericArrayAccess("set","([JIJ)V"), new GenericArrayAccess("get","([JI)J")); /* 3: double */ bewArray[3].setArraySetAndGet( new GenericArrayAccess("set","([DID)V"), new GenericArrayAccess("get","([DI)D")); /* 4: char */ bewArray[4].setArraySetAndGet( new GenericArrayAccess("set","([CIC)V"), new GenericArrayAccess("get","([CI)C")); /* 5: byte */ bewArray[5].setArraySetAndGet( new GenericArrayAccess("set","([BIB)V"), new GenericArrayAccess("get","([BI)B")); /* 6: short */ bewArray[6].setArraySetAndGet( new GenericArrayAccess("set","([SIS)V"), new GenericArrayAccess("get","([SI)S")); /* 7: float */ bewArray[7].setArraySetAndGet( new GenericArrayAccess("get","([FIF)V"), new GenericArrayAccess("set","([FI)F")); /* 8: bool */ bewArray[8].setArraySetAndGet( new GenericArrayAccess("get","([ZIZ)V"), new GenericArrayAccess("set","([ZI)Z")); return bewArray; } }
46625_0
package com.github.fontys.jms.serializer; import com.github.fontys.jms.messaging.RequestReply; import com.github.fontys.jms.messaging.StandardMessage; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; public class ObjectSerializer<OBJECT> { private Gson gson; //gebruikte eerst genson maar die heeft slechte ondersteuning voor generics zoals RequestReply, terwijl gson dit met gemak ondersteund private final Class<OBJECT> objectClass; public ObjectSerializer(Class<OBJECT> objectClass){ this.objectClass = objectClass; gson = new GsonBuilder().create(); } public String objectToString(OBJECT object){ return gson.toJson(object); } public OBJECT objectFromString(String str){ return gson.fromJson(str, objectClass); } public StandardMessage standardMessageFromString(String str){ return gson.fromJson(str, TypeToken.getParameterized(RequestReply.class, objectClass).getType()); } public String standardMessageToString(StandardMessage standardMessage){ return gson.toJson(standardMessage); } }
timgoes1997/DPI-6
src/main/com/github/fontys/jms/serializer/ObjectSerializer.java
284
//gebruikte eerst genson maar die heeft slechte ondersteuning voor generics zoals RequestReply, terwijl gson dit met gemak ondersteund
line_comment
nl
package com.github.fontys.jms.serializer; import com.github.fontys.jms.messaging.RequestReply; import com.github.fontys.jms.messaging.StandardMessage; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; public class ObjectSerializer<OBJECT> { private Gson gson; //gebruikte eerst<SUF> private final Class<OBJECT> objectClass; public ObjectSerializer(Class<OBJECT> objectClass){ this.objectClass = objectClass; gson = new GsonBuilder().create(); } public String objectToString(OBJECT object){ return gson.toJson(object); } public OBJECT objectFromString(String str){ return gson.fromJson(str, objectClass); } public StandardMessage standardMessageFromString(String str){ return gson.fromJson(str, TypeToken.getParameterized(RequestReply.class, objectClass).getType()); } public String standardMessageToString(StandardMessage standardMessage){ return gson.toJson(standardMessage); } }
82214_8
/* * Copyright (C) 2012-2019 Jorrit "Chainfire" Jongma * * 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 eu.chainfire.libsuperuser; import android.content.Context; import android.os.Handler; import android.widget.Toast; import androidx.annotation.AnyThread; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /** * Base application class to extend from, solving some issues with * toasts and AsyncTasks you are likely to run into */ @SuppressWarnings("WeakerAccess") public class Application extends android.app.Application { /** * Shows a toast message * * @param context Any context belonging to this application * @param message The message to show */ @AnyThread public static void toast(@Nullable Context context, @NonNull String message) { // this is a static method so it is easier to call, // as the context checking and casting is done for you if (context == null) return; if (!(context instanceof Application)) { context = context.getApplicationContext(); } if (context instanceof Application) { final Context c = context; final String m = message; ((Application) context).runInApplicationThread(new Runnable() { @Override public void run() { Toast.makeText(c, m, Toast.LENGTH_LONG).show(); } }); } } private static final Handler mApplicationHandler = new Handler(); /** * Run a runnable in the main application thread * * @param r Runnable to run */ @AnyThread public void runInApplicationThread(@NonNull Runnable r) { mApplicationHandler.post(r); } @Override public void onCreate() { super.onCreate(); try { // workaround bug in AsyncTask, can show up (for example) when you toast from a service // this makes sure AsyncTask's internal handler is created from the right (main) thread Class.forName("android.os.AsyncTask"); } catch (ClassNotFoundException e) { // will never happen } } }
Chainfire/libsuperuser
libsuperuser/src/eu/chainfire/libsuperuser/Application.java
644
// will never happen
line_comment
nl
/* * Copyright (C) 2012-2019 Jorrit "Chainfire" Jongma * * 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 eu.chainfire.libsuperuser; import android.content.Context; import android.os.Handler; import android.widget.Toast; import androidx.annotation.AnyThread; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /** * Base application class to extend from, solving some issues with * toasts and AsyncTasks you are likely to run into */ @SuppressWarnings("WeakerAccess") public class Application extends android.app.Application { /** * Shows a toast message * * @param context Any context belonging to this application * @param message The message to show */ @AnyThread public static void toast(@Nullable Context context, @NonNull String message) { // this is a static method so it is easier to call, // as the context checking and casting is done for you if (context == null) return; if (!(context instanceof Application)) { context = context.getApplicationContext(); } if (context instanceof Application) { final Context c = context; final String m = message; ((Application) context).runInApplicationThread(new Runnable() { @Override public void run() { Toast.makeText(c, m, Toast.LENGTH_LONG).show(); } }); } } private static final Handler mApplicationHandler = new Handler(); /** * Run a runnable in the main application thread * * @param r Runnable to run */ @AnyThread public void runInApplicationThread(@NonNull Runnable r) { mApplicationHandler.post(r); } @Override public void onCreate() { super.onCreate(); try { // workaround bug in AsyncTask, can show up (for example) when you toast from a service // this makes sure AsyncTask's internal handler is created from the right (main) thread Class.forName("android.os.AsyncTask"); } catch (ClassNotFoundException e) { // will never<SUF> } } }
15645_3
package Classes; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Date; public class Account extends Persoon { //Attributes private String wachtwoord; private Date gbdatum; private String telnr; //Constructors public Account(int i, String vn, String tv, String an, String pc, String hnr, String toev, String em, String ww, String gbd, String tnr) { super(i, vn, tv, an, pc, hnr, toev, em); setWachtwoord(ww); setGbdatum(gbd); telnr = tnr; } //Getters public String getWachtwoord() { return wachtwoord; } public Date getGbdatum() { return gbdatum; } public String getTelnr() { return telnr; } //Setters public void setGbdatum(String gbd) { //Hier komt een methode die een MySQL Date omzet naar een Java Date } public void setTelnr(String tnr) { telnr = tnr; } public void setWachtwoord(String ww) { try { //MessageDigest met algoritme SHA-512 MessageDigest md = MessageDigest.getInstance("SHA-512"); //Wachtwoord wordt omgezet tot bytes en toegevoegd aan de MessageDigest md.update(ww.getBytes()); //Hasht het (in bytes omgezette) wachtwoord en stopt die in de variabele bytes byte[] bytes = md.digest(); //Bytes worden hier omgezet naar hexadecimalen StringBuilder sb = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1)); } //De hexadecimale hash wordt opgeslagen in het attribuut wachtwoord wachtwoord = sb.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } //Methods }
GijsAlb/HSR01
HSR01JavaFX/src/Classes/Account.java
564
//Hasht het (in bytes omgezette) wachtwoord en stopt die in de variabele bytes
line_comment
nl
package Classes; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Date; public class Account extends Persoon { //Attributes private String wachtwoord; private Date gbdatum; private String telnr; //Constructors public Account(int i, String vn, String tv, String an, String pc, String hnr, String toev, String em, String ww, String gbd, String tnr) { super(i, vn, tv, an, pc, hnr, toev, em); setWachtwoord(ww); setGbdatum(gbd); telnr = tnr; } //Getters public String getWachtwoord() { return wachtwoord; } public Date getGbdatum() { return gbdatum; } public String getTelnr() { return telnr; } //Setters public void setGbdatum(String gbd) { //Hier komt een methode die een MySQL Date omzet naar een Java Date } public void setTelnr(String tnr) { telnr = tnr; } public void setWachtwoord(String ww) { try { //MessageDigest met algoritme SHA-512 MessageDigest md = MessageDigest.getInstance("SHA-512"); //Wachtwoord wordt omgezet tot bytes en toegevoegd aan de MessageDigest md.update(ww.getBytes()); //Hasht het<SUF> byte[] bytes = md.digest(); //Bytes worden hier omgezet naar hexadecimalen StringBuilder sb = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1)); } //De hexadecimale hash wordt opgeslagen in het attribuut wachtwoord wachtwoord = sb.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } //Methods }
172942_3
package timeutil; import java.util.LinkedList; import java.util.List; /** * Deze klasse maakt het mogelijk om opeenvolgende tijdsperiodes een naam te * geven, deze op te slaan en deze daarna te printen (via toString). * * Tijdsperiodes worden bepaald door een begintijd en een eindtijd. * * begintijd van een periode kan gezet worden door setBegin, de eindtijd kan * gezet worden door de methode setEind. * * Zowel bij de begin- als eindtijd van ee periode kan een String meegegeven * worden die voor de gebruiker een betekenisvolle aanduiding toevoegt aan dat * tijdstip. Indien geen string meegegeven wordt, wordt een teller gebruikt, die * automatisch opgehoogd wordt. * * Na het opgeven van een begintijdstip (via setBegin of eenmalig via init ) kan * t.o.v. dit begintijdstip steeds een eindtijdstip opgegeven worden. Zodoende * kun je vanaf 1 begintijdstip, meerdere eindtijden opgeven. * * Een andere mogelijkheid is om een eindtijdstip direct te laten fungeren als * begintijdstip voor een volgende periode. Dit kan d.m.v. SetEndBegin of seb. * * alle tijdsperiodes kunnen gereset worden dmv init() * * @author erik * */ public class TimeStamp { private static long counter = 0; private long curBegin; private String curBeginS; private List<Period> list; public TimeStamp() { TimeStamp.counter = 0; this.init(); } /** * initialiseer klasse. begin met geen tijdsperiodes. */ public void init() { this.curBegin = 0; this.curBeginS = null; this.list = new LinkedList<Period>(); } /** * zet begintijdstip. gebruik interne teller voor identificatie van het * tijdstip */ public void setBegin() { this.setBegin(String.valueOf(TimeStamp.counter++)); } /** * zet begintijdstip * * @param timepoint betekenisvolle identificatie van begintijdstip */ public void setBegin(String timepoint) { this.curBegin = System.currentTimeMillis(); this.curBeginS = timepoint; } /** * zet eindtijdstip. gebruik interne teller voor identificatie van het * tijdstip */ public void setEnd() { this.setEnd(String.valueOf(TimeStamp.counter++)); } /** * zet eindtijdstip * * @param timepoint betekenisvolle identificatie vanhet eindtijdstip */ public void setEnd(String timepoint) { this.list.add(new Period(this.curBegin, this.curBeginS, System.currentTimeMillis(), timepoint)); } /** * zet eindtijdstip plus begintijdstip * * @param timepoint identificatie van het eind- en begintijdstip. */ public void setEndBegin(String timepoint) { this.setEnd(timepoint); this.setBegin(timepoint); } /** * verkorte versie van setEndBegin * * @param timepoint */ public void seb(String timepoint) { this.setEndBegin(timepoint); } /** * interne klasse voor bijhouden van periodes. * * @author erik * */ private class Period { long begin; String beginS; long end; String endS; public Period(long b, String sb, long e, String se) { this.setBegin(b, sb); this.setEnd(e, se); } private void setBegin(long b, String sb) { this.begin = b; this.beginS = sb; } private void setEnd(long e, String se) { this.end = e; this.endS = se; } @Override public String toString() { return "From '" + this.beginS + "' till '" + this.endS + "' is " + (this.end - this.begin) + " mSec."; } } /** * override van toString methode. Geeft alle tijdsperiode weer. */ public String toString() { StringBuffer buffer = new StringBuffer(); for (Period p : this.list) { buffer.append(p.toString()); buffer.append('\n'); } return buffer.toString(); } }
larsjanssen6/JSF3
JSF31_w03_OS_process/src/timeutil/TimeStamp.java
1,179
/** * zet begintijdstip * * @param timepoint betekenisvolle identificatie van begintijdstip */
block_comment
nl
package timeutil; import java.util.LinkedList; import java.util.List; /** * Deze klasse maakt het mogelijk om opeenvolgende tijdsperiodes een naam te * geven, deze op te slaan en deze daarna te printen (via toString). * * Tijdsperiodes worden bepaald door een begintijd en een eindtijd. * * begintijd van een periode kan gezet worden door setBegin, de eindtijd kan * gezet worden door de methode setEind. * * Zowel bij de begin- als eindtijd van ee periode kan een String meegegeven * worden die voor de gebruiker een betekenisvolle aanduiding toevoegt aan dat * tijdstip. Indien geen string meegegeven wordt, wordt een teller gebruikt, die * automatisch opgehoogd wordt. * * Na het opgeven van een begintijdstip (via setBegin of eenmalig via init ) kan * t.o.v. dit begintijdstip steeds een eindtijdstip opgegeven worden. Zodoende * kun je vanaf 1 begintijdstip, meerdere eindtijden opgeven. * * Een andere mogelijkheid is om een eindtijdstip direct te laten fungeren als * begintijdstip voor een volgende periode. Dit kan d.m.v. SetEndBegin of seb. * * alle tijdsperiodes kunnen gereset worden dmv init() * * @author erik * */ public class TimeStamp { private static long counter = 0; private long curBegin; private String curBeginS; private List<Period> list; public TimeStamp() { TimeStamp.counter = 0; this.init(); } /** * initialiseer klasse. begin met geen tijdsperiodes. */ public void init() { this.curBegin = 0; this.curBeginS = null; this.list = new LinkedList<Period>(); } /** * zet begintijdstip. gebruik interne teller voor identificatie van het * tijdstip */ public void setBegin() { this.setBegin(String.valueOf(TimeStamp.counter++)); } /** * zet begintijdstip <SUF>*/ public void setBegin(String timepoint) { this.curBegin = System.currentTimeMillis(); this.curBeginS = timepoint; } /** * zet eindtijdstip. gebruik interne teller voor identificatie van het * tijdstip */ public void setEnd() { this.setEnd(String.valueOf(TimeStamp.counter++)); } /** * zet eindtijdstip * * @param timepoint betekenisvolle identificatie vanhet eindtijdstip */ public void setEnd(String timepoint) { this.list.add(new Period(this.curBegin, this.curBeginS, System.currentTimeMillis(), timepoint)); } /** * zet eindtijdstip plus begintijdstip * * @param timepoint identificatie van het eind- en begintijdstip. */ public void setEndBegin(String timepoint) { this.setEnd(timepoint); this.setBegin(timepoint); } /** * verkorte versie van setEndBegin * * @param timepoint */ public void seb(String timepoint) { this.setEndBegin(timepoint); } /** * interne klasse voor bijhouden van periodes. * * @author erik * */ private class Period { long begin; String beginS; long end; String endS; public Period(long b, String sb, long e, String se) { this.setBegin(b, sb); this.setEnd(e, se); } private void setBegin(long b, String sb) { this.begin = b; this.beginS = sb; } private void setEnd(long e, String se) { this.end = e; this.endS = se; } @Override public String toString() { return "From '" + this.beginS + "' till '" + this.endS + "' is " + (this.end - this.begin) + " mSec."; } } /** * override van toString methode. Geeft alle tijdsperiode weer. */ public String toString() { StringBuffer buffer = new StringBuffer(); for (Period p : this.list) { buffer.append(p.toString()); buffer.append('\n'); } return buffer.toString(); } }
147983_1
package fastcatch.api.core.mappers; import fastcatch.api.core.Vacature; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.tweak.ResultSetMapper; import java.sql.ResultSet; import java.sql.SQLException; /** * Deze klasse mapt alle info die uit de vacature database gehaald wordt naar een nieuw vacature object. * * @author Anna */ public class VacatureMapper implements ResultSetMapper<Vacature> { /** * Mapt het meegegeven resultaat naar een nieuw vacature object en * returnt deze vacature. * @param index, r, ctx * @return Vacature * @throws SQLException */ public Vacature map(int index, ResultSet r, StatementContext ctx) throws SQLException { return new Vacature(r.getInt("id"), r.getString("titel"), r.getString("rol"), r.getString("werkNiveau"), r.getString("eigenaar"), r.getString("klant"), r.getString("locatie"), r.getDate("startdatum"), r.getDate("einddatum"), r.getDate("publicatiedatum"), r.getDate("uitersteAanbiedingsdatum"), r.getInt("uurPerWeek"), r.getString("aanvrager"), r.getString("omschrijving"), r.getString("samenvatting"), r.getInt("actief")); } }
RonanTalboom/FastCatch-API
src/main/java/fastcatch/api/core/mappers/VacatureMapper.java
339
/** * Mapt het meegegeven resultaat naar een nieuw vacature object en * returnt deze vacature. * @param index, r, ctx * @return Vacature * @throws SQLException */
block_comment
nl
package fastcatch.api.core.mappers; import fastcatch.api.core.Vacature; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.tweak.ResultSetMapper; import java.sql.ResultSet; import java.sql.SQLException; /** * Deze klasse mapt alle info die uit de vacature database gehaald wordt naar een nieuw vacature object. * * @author Anna */ public class VacatureMapper implements ResultSetMapper<Vacature> { /** * Mapt het meegegeven<SUF>*/ public Vacature map(int index, ResultSet r, StatementContext ctx) throws SQLException { return new Vacature(r.getInt("id"), r.getString("titel"), r.getString("rol"), r.getString("werkNiveau"), r.getString("eigenaar"), r.getString("klant"), r.getString("locatie"), r.getDate("startdatum"), r.getDate("einddatum"), r.getDate("publicatiedatum"), r.getDate("uitersteAanbiedingsdatum"), r.getInt("uurPerWeek"), r.getString("aanvrager"), r.getString("omschrijving"), r.getString("samenvatting"), r.getInt("actief")); } }
122305_102
import java.awt.Image; import java.awt.Rectangle; import javax.swing.ImageIcon; public class Entity { private int speed, width, height, bewegungspunkte, center_TP, links_TP, rechts_TP, vorne_TP, hinten_TP, load; private double x, y; private float degree; private boolean up, down, left, right, stop, collision, mo; private String picPath; private Image img; private Proj schuss; private String soundEffect_rotate; private String soundEffect_go = ""; private int tp; private boolean rocket = false; public Entity(int x, int y, String picPath, String sp){ this.x = x; this.y = y; schuss = new Proj(); this.picPath = picPath; ImageIcon ii = new ImageIcon(picPath); img = ii.getImage(); height = ii.getIconHeight(); width = ii.getIconWidth(); speed = 2; degree = 0; up = false; down = false; left = false; right = false; collision = false; load = 0; mo = false; center_TP = 250; links_TP = 150; rechts_TP = 150; vorne_TP = 200; hinten_TP = 100; tp = 100; stop = false; if (sp == "SP1"){ //#if (P1_Rot_Beep1) //@ soundEffect_rotate = "sounds/beep_1.au"; //#elif (P1_Rot_Beep2) //@ soundEffect_rotate = "sounds/beep_2.au"; //#elif (P1_Rot_Beep3) //@ soundEffect_rotate = "sounds/beep_3.au"; //#elif (P1_Rot_Bleep1) //@ soundEffect_rotate = "sounds/bleep_1.au"; //#elif (P1_Rot_Buzzer) //@ soundEffect_rotate = "sounds/buzzer.au"; //#elif (P1_Rot_Cash_register) soundEffect_rotate = "sounds/cash_register.au"; //#elif (P1_Rot_Cork) //@ soundEffect_rotate = "sounds/cork.au"; //#elif (P1_Rot_Game_Win) //@ soundEffect_rotate = "sounds/game_win.au"; //#elif (P1_Rot_Drip) //@ soundEffect_rotate = "sounds/drip.au"; //#elif (P1_Rot_Gorod) //@ soundEffect_rotate = "sounds/gorod.au"; //#elif (P1_Rot_Horn) //@ soundEffect_rotate = "sounds/horn.au"; //#elif (P1_Rot_Laser_Trill) //@ soundEffect_rotate = "sounds/laser_trill.au"; //#elif (P1_Rot_Police_Siren) //@ soundEffect_rotate = "sounds/police_siren.au"; //#elif (P1_Rot_Siren_1) //@ soundEffect_rotate = "sounds/siren_1.au"; //#elif (P1_Rot_Siren_2) //@ soundEffect_rotate = "sounds/siren_2.au"; //#elif (P1_Rot_yes) //@ soundEffect_rotate = "sounds/yes.au"; //#endif //#if (P1_Mov_Beep1) //@ soundEffect_go = "sounds/beep_1.au"; //#elif (P1_Mov_Beep2) //@ soundEffect_go = "sounds/beep_2.au"; //#elif (P1_Mov_Beep3) //@ soundEffect_go = "sounds/beep_3.au"; //#elif (P1_Mov_Bleep1) //@ soundEffect_go = "sounds/bleep_1.au"; //#elif (P1_Mov_Buzzer) //@ soundEffect_go = "sounds/buzzer.au"; //#elif (P1_Mov_Cash_Register) //@ soundEffect_go = "sounds/cash_register.au"; //#elif (P1_Mov_Cork) //@ soundEffect_go = "sounds/cork.au"; //#elif (P1_Mov_Game_Win) soundEffect_go = "sounds/game_win.au"; //#elif (P1_Mov_Drip) //@ soundEffect_go = "sounds/drip.au"; //#elif (P1_Mov_Gorod) //@ soundEffect_go = "sounds/gorod.au"; //#elif (P1_Mov_Horn) //@ soundEffect_go = "sounds/horn.au"; //#elif (P1_Mov_LaserTrill) //@ soundEffect_go = "sounds/laser_trill.au"; //#elif (P1_Mov_Police_Siren) //@ soundEffect_go = "sounds/police_siren.au"; //#elif (P1_Mov_Siren_1) //@ soundEffect_go = "sounds/siren_1.au"; //#elif (P1_Mov_Siren2) //@ soundEffect_go = "sounds/siren_2.au"; //#elif (P1_Mov_yes) //@ soundEffect_go = "sounds/yes.au"; //#endif //#if (mov_0) bewegungspunkte = 250; //#elif (mov_1) //@ bewegungspunkte = 0; //#elif (mov_2) //@ bewegungspunkte = 250; //#elif (mov_3) //@ bewegungspunkte = 0; //#elif (mov_4) //@ // throw new UnsupportedOperationException("Not supported yet."); //#endif } else if (sp == "SP2"){ //#if (P2_Rot_Beep1) //@ soundEffect_rotate = "sounds/beep_1.au"; //#elif (P2_Rot_Beep2) //@ soundEffect_rotate = "sounds/beep_2.au"; //#elif (P2_Rot_Beep3) //@ soundEffect_rotate = "sounds/beep_3.au"; //#elif (P2_Rot_Bleep1) //@ soundEffect_rotate = "sounds/bleep_1.au"; //#elif (P2_Rot_Buzzer) //@ soundEffect_rotate = "sounds/buzzer.au"; //#elif (P2_Rot_Cash_Register) //@ soundEffect_rotate = "sounds/cash_register.au"; //#elif (P2_Rot_Cork) //@ soundEffect_rotate = "sounds/cork.au"; //#elif (P2_Rot_Game_Win) //@ soundEffect_rotate = "sounds/game_win.au"; //#elif (P2_Rot_Drip) //@ soundEffect_rotate = "sounds/drip.au"; //#elif (P2_Rot_Gorod) //@ soundEffect_rotate = "sounds/gorod.au"; //#elif (P2_Rot_Horn) //@ soundEffect_rotate = "sounds/horn.au"; //#elif (P2_Rot_Laser_Trill) //@ soundEffect_rotate = "sounds/laser_trill.au"; //#elif (P2_Rot_Police_Siren) soundEffect_rotate = "sounds/police_siren.au"; //#elif (P2_Rot_Siren_1) //@ soundEffect_rotate = "sounds/siren_1.au"; //#elif (P2_Rot_Siren_2) //@ soundEffect_rotate = "sounds/siren_2.au"; //#elif (P2_Rot_Yes) //@ soundEffect_rotate = "sounds/yes.au"; //#endif //#if (P2_Mov_Beep1) //@ soundEffect_go = "sounds/beep_1.au"; //#elif (P2_Mov_Beep2) //@ soundEffect_go = "sounds/beep_2.au"; //#elif (P2_Mov_Beep3) //@ soundEffect_go = "sounds/beep_3.au"; //#elif (P2_Mov_Bleep1) //@ soundEffect_go = "sounds/bleep_1.au"; //#elif (P2_Mov_Buzzer) //@ soundEffect_go = "sounds/buzzer.au"; //#elif (P2_Mov_Cah_Register) //@ soundEffect_go = "sounds/cash_register.au"; //#elif (P2_Mov_cork) soundEffect_go = "sounds/cork.au"; //#elif (P2_Mov_Game_Win) //@ soundEffect_go = "sounds/game_win.au"; //#elif (P2_Mov_Drip) //@ soundEffect_go = "sounds/drip.au"; //#elif (P2_Mov_Gorord) //@ soundEffect_go = "sounds/gorod.au"; //#elif (P2_Mov_Horn) //@ soundEffect_go = "sounds/horn.au"; //#elif (P2_Mov_LaserTrill) //@ soundEffect_go = "sounds/laser_trill.au"; //#elif (P2_Mov_Police_Siren) //@ soundEffect_go = "sounds/police_siren.au"; //#elif (P2_Mov_Siren_1) //@ soundEffect_go = "sounds/siren_1.au"; //#elif (P2_Mov_Siren_2) //@ soundEffect_go = "sounds/siren_2.au"; //#elif (P2_Mov_Yes) //@ soundEffect_go = "sounds/yes.au"; //#endif //#if (mov_0) bewegungspunkte = 250; //#elif (mov_1) //@ bewegungspunkte = 0; //#elif (mov_2) //@ bewegungspunkte = 250; //#elif (mov_3) //@ bewegungspunkte = 0; //#elif (mov_4) //@ // throw new UnsupportedOperationException("Not supported yet."); //#endif } } public boolean isRocket() { return rocket; } public void setRocket(boolean rocket) { this.rocket = rocket; } public boolean isMo() { return mo; } public void setMo(boolean mo) { this.mo = mo; } public Image getImg() { return img; } public boolean isCollision() { return collision; } public void setStop(boolean stop) { this.stop = stop; } public int getBp() { return bewegungspunkte; } public void setLeft(boolean left) { this.left = left; } public void setRight(boolean right) { this.right = right; } public void setDown(boolean down) { this.down = down; } public void setSpeed(int speed) { this.speed = speed; } public int getTp() { return tp; } public void setTp(int tp) { this.tp = tp; } public void setUp(boolean up) { this.up = up; } public int getHeight() { return height; } public int getWidth() { return width; } public double getX() { return x; } public double getY() { return y; } public void setX(double x) { this.x = x; } public void setY(double y) { this.y = y; } public float getDegree() { return degree; } public Proj getSch() { return schuss; } public void setSch(Proj sch) { this.schuss = sch; } public void setCollision(boolean collision) { this.collision = collision; } public void setBp(int bp) { this.bewegungspunkte = bp; } public int getCenter() { return center_TP; } public void setCenter(int center) { this.center_TP = center; } public int getHinten() { return hinten_TP; } public void setHinten(int hinten) { this.hinten_TP = hinten; } public int getLinks() { return links_TP; } public void setLinks(int links) { this.links_TP = links; } public int getRechts() { return rechts_TP; } public void setRechts(int rechts) { this.rechts_TP = rechts; } public int getVorne() { return vorne_TP; } public void setVorne(int vorne) { this.vorne_TP = vorne; } public int getLoad() { return load; } public void setLoad(int load) { this.load = load; } public Rectangle getBounds(){ return new Rectangle((int)getX(), (int)getY(), getWidth(), getHeight()); } public void move(){ //#if (mov_0) if (up && bewegungspunkte > 0 && stop == false){ y -= Math.cos(Math.toDegrees(degree)/180*Math.PI) * speed; x += Math.sin(Math.toDegrees(degree)/180*Math.PI) * speed; bewegungspunkte -= 1; Snd.music(soundEffect_rotate); } if (down && bewegungspunkte > 0 && stop == false){ y += Math.cos(Math.toDegrees(degree)/180*Math.PI) * speed; x -= Math.sin(Math.toDegrees(degree)/180*Math.PI) * speed; bewegungspunkte -= 1; Snd.music(soundEffect_rotate); } if (left && bewegungspunkte > 0 && stop == false){ degree -= 0.03; bewegungspunkte -= 1; Snd.music(soundEffect_go); } if (right&& bewegungspunkte > 0 && stop == false){ degree += 0.03; bewegungspunkte -= 1; Snd.music(soundEffect_go); } //#elif (mov_1) //@ if (left && stop == false && load != 1){ //@ degree -= 0.03; //@ Snd.music(soundEffect_rotate); //@ } //@ if (right && stop == false && load != 1){ //@ degree += 0.03; //@ Snd.music(soundEffect_rotate); //@ } //@ if (stop == false && load != 1){ //@ setSpeed((int)(Math.ceil(bewegungspunkte*0.02))); //@ y -= Math.cos(Math.toDegrees(degree)/180*Math.PI) * speed; //@ x += Math.sin(Math.toDegrees(degree)/180*Math.PI) * speed; //@ bewegungspunkte = (int)(bewegungspunkte - bewegungspunkte * 0.02); //@ if (load != 0 && bewegungspunkte != 0) Snd.music(soundEffect_go); //@ } //#elif (mov_2) //@ if (up && right && bewegungspunkte > 0 && stop == false){ //@ degree = (float)0.8; //@ bewegungspunkte -= 1; //@ Snd.music(soundEffect_go); //@ y -= Math.cos(Math.toDegrees(degree)/180*Math.PI) * speed; //@ x += Math.sin(Math.toDegrees(degree)/180*Math.PI) * speed; //@ } //@ else if (up && left && bewegungspunkte > 0 && stop == false){ //@ degree = (float)-0.8; //@ bewegungspunkte -= 1; //@ Snd.music(soundEffect_go); //@ y -= Math.cos(Math.toDegrees(degree)/180*Math.PI) * speed; //@ x += Math.sin(Math.toDegrees(degree)/180*Math.PI) * speed; //@ } //@ else if (down && right && bewegungspunkte > 0 && stop == false){ //@ degree = (float)2.35; //@ bewegungspunkte -= 1; //@ Snd.music(soundEffect_go); //@ y -= Math.cos(Math.toDegrees(degree)/180*Math.PI) * speed; //@ x += Math.sin(Math.toDegrees(degree)/180*Math.PI) * speed; //@ } //@ else if (down && left && bewegungspunkte > 0 && stop == false){ //@ degree = (float)-2.35; //@ bewegungspunkte -= 1; //@ Snd.music(soundEffect_go); //@ y -= Math.cos(Math.toDegrees(degree)/180*Math.PI) * speed; //@ x += Math.sin(Math.toDegrees(degree)/180*Math.PI) * speed; //@ } //@ else if (up && bewegungspunkte > 0 && stop == false){ //@ degree = (float)0; //@ bewegungspunkte -= 1; //@ Snd.music(soundEffect_go); //@ y -= Math.cos(Math.toDegrees(degree)/180*Math.PI) * speed; //@ x += Math.sin(Math.toDegrees(degree)/180*Math.PI) * speed; //@ } //@ else if(down && bewegungspunkte > 0 && stop == false){ //@ degree = (float)3.15; //@ bewegungspunkte -= 1; //@ Snd.music(soundEffect_go); //@ y -= Math.cos(Math.toDegrees(degree)/180*Math.PI) * speed; //@ x += Math.sin(Math.toDegrees(degree)/180*Math.PI) * speed; //@ } //@ else if(left && bewegungspunkte > 0 && stop == false){ //@ degree = (float)-1.575; //@ bewegungspunkte -= 1; //@ Snd.music(soundEffect_go); //@ y -= Math.cos(Math.toDegrees(degree)/180*Math.PI) * speed; //@ x += Math.sin(Math.toDegrees(degree)/180*Math.PI) * speed; //@ } //@ else if(right && bewegungspunkte > 0 && stop == false){ //@ degree = (float)1.575; //@ bewegungspunkte -= 1; //@ Snd.music(soundEffect_go); //@ y -= Math.cos(Math.toDegrees(degree)/180*Math.PI) * speed; //@ x += Math.sin(Math.toDegrees(degree)/180*Math.PI) * speed; //@ } //#elif (mov_3) //@ if (left && stop == false && load == 0){ //@ degree -= 0.03; //@ Snd.music(soundEffect_rotate); //@ } //@ if (right && stop == false && load == 0){ //@ degree += 0.03; //@ Snd.music(soundEffect_rotate); //@ } //@ if (right && stop == false && load == 2 && bewegungspunkte > 0 ){ //@ y -= Math.cos(Math.toDegrees(degree-30)/180*Math.PI) * speed; //@ x += Math.sin(Math.toDegrees(degree-30)/180*Math.PI) * speed; //@ //@ } //@ if (left && stop == false && load == 2 && bewegungspunkte > 0 ){ //@ y -= Math.cos(Math.toDegrees(degree+30)/180*Math.PI) * speed; //@ x += Math.sin(Math.toDegrees(degree+30)/180*Math.PI) * speed; //@ } //@ if (stop == false && load == 2 && bewegungspunkte > 0 ){ //@ y -= Math.cos(Math.toDegrees(degree)/180*Math.PI) * speed; //@ x += Math.sin(Math.toDegrees(degree)/180*Math.PI) * speed; //@ bewegungspunkte = bewegungspunkte - speed; //@ Snd.music(soundEffect_go); //@ } //@ if (stop == false && load != 1){ //@ setSpeed((int)(Math.ceil(bewegungspunkte*0.02))); //@ } //#elif (mov_4) //@ if (left && stop == false && load == 0){ //@ degree -= 0.03; //@ Snd.music(soundEffect_rotate); //@ } //@ if (right && stop == false && load == 0){ //@ degree += 0.03; //@ Snd.music(soundEffect_rotate); //@ } //@ if (right && stop == false && load == 2){ //@ y -= Math.cos(Math.toDegrees(degree-30)/180*Math.PI) * speed; //@ x += Math.sin(Math.toDegrees(degree-30)/180*Math.PI) * speed; //@ } //@ if (left && stop == false && load == 2){ //@ y -= Math.cos(Math.toDegrees(degree+30)/180*Math.PI) * speed; //@ x += Math.sin(Math.toDegrees(degree+30)/180*Math.PI) * speed; //@ } //@ if (stop == false && load != 1){ //@ setSpeed((int)(Math.ceil(bewegungspunkte*0.02))); //@ y -= Math.cos(Math.toDegrees(degree)/180*Math.PI) * speed; //@ x += Math.sin(Math.toDegrees(degree)/180*Math.PI) * speed; //@ bewegungspunkte = (int)(bewegungspunkte - bewegungspunkte * 0.02); //@ if (load != 0 && bewegungspunkte != 0) Snd.music(soundEffect_go); //@ } //#endif } }
chsguitar1/FeatureIDE
plugins/de.ovgu.featureide.examples/featureide_examples/TankWar-Antenna/src/Entity.java
5,919
//#elif (P2_Mov_Bleep1)
line_comment
nl
import java.awt.Image; import java.awt.Rectangle; import javax.swing.ImageIcon; public class Entity { private int speed, width, height, bewegungspunkte, center_TP, links_TP, rechts_TP, vorne_TP, hinten_TP, load; private double x, y; private float degree; private boolean up, down, left, right, stop, collision, mo; private String picPath; private Image img; private Proj schuss; private String soundEffect_rotate; private String soundEffect_go = ""; private int tp; private boolean rocket = false; public Entity(int x, int y, String picPath, String sp){ this.x = x; this.y = y; schuss = new Proj(); this.picPath = picPath; ImageIcon ii = new ImageIcon(picPath); img = ii.getImage(); height = ii.getIconHeight(); width = ii.getIconWidth(); speed = 2; degree = 0; up = false; down = false; left = false; right = false; collision = false; load = 0; mo = false; center_TP = 250; links_TP = 150; rechts_TP = 150; vorne_TP = 200; hinten_TP = 100; tp = 100; stop = false; if (sp == "SP1"){ //#if (P1_Rot_Beep1) //@ soundEffect_rotate = "sounds/beep_1.au"; //#elif (P1_Rot_Beep2) //@ soundEffect_rotate = "sounds/beep_2.au"; //#elif (P1_Rot_Beep3) //@ soundEffect_rotate = "sounds/beep_3.au"; //#elif (P1_Rot_Bleep1) //@ soundEffect_rotate = "sounds/bleep_1.au"; //#elif (P1_Rot_Buzzer) //@ soundEffect_rotate = "sounds/buzzer.au"; //#elif (P1_Rot_Cash_register) soundEffect_rotate = "sounds/cash_register.au"; //#elif (P1_Rot_Cork) //@ soundEffect_rotate = "sounds/cork.au"; //#elif (P1_Rot_Game_Win) //@ soundEffect_rotate = "sounds/game_win.au"; //#elif (P1_Rot_Drip) //@ soundEffect_rotate = "sounds/drip.au"; //#elif (P1_Rot_Gorod) //@ soundEffect_rotate = "sounds/gorod.au"; //#elif (P1_Rot_Horn) //@ soundEffect_rotate = "sounds/horn.au"; //#elif (P1_Rot_Laser_Trill) //@ soundEffect_rotate = "sounds/laser_trill.au"; //#elif (P1_Rot_Police_Siren) //@ soundEffect_rotate = "sounds/police_siren.au"; //#elif (P1_Rot_Siren_1) //@ soundEffect_rotate = "sounds/siren_1.au"; //#elif (P1_Rot_Siren_2) //@ soundEffect_rotate = "sounds/siren_2.au"; //#elif (P1_Rot_yes) //@ soundEffect_rotate = "sounds/yes.au"; //#endif //#if (P1_Mov_Beep1) //@ soundEffect_go = "sounds/beep_1.au"; //#elif (P1_Mov_Beep2) //@ soundEffect_go = "sounds/beep_2.au"; //#elif (P1_Mov_Beep3) //@ soundEffect_go = "sounds/beep_3.au"; //#elif (P1_Mov_Bleep1) //@ soundEffect_go = "sounds/bleep_1.au"; //#elif (P1_Mov_Buzzer) //@ soundEffect_go = "sounds/buzzer.au"; //#elif (P1_Mov_Cash_Register) //@ soundEffect_go = "sounds/cash_register.au"; //#elif (P1_Mov_Cork) //@ soundEffect_go = "sounds/cork.au"; //#elif (P1_Mov_Game_Win) soundEffect_go = "sounds/game_win.au"; //#elif (P1_Mov_Drip) //@ soundEffect_go = "sounds/drip.au"; //#elif (P1_Mov_Gorod) //@ soundEffect_go = "sounds/gorod.au"; //#elif (P1_Mov_Horn) //@ soundEffect_go = "sounds/horn.au"; //#elif (P1_Mov_LaserTrill) //@ soundEffect_go = "sounds/laser_trill.au"; //#elif (P1_Mov_Police_Siren) //@ soundEffect_go = "sounds/police_siren.au"; //#elif (P1_Mov_Siren_1) //@ soundEffect_go = "sounds/siren_1.au"; //#elif (P1_Mov_Siren2) //@ soundEffect_go = "sounds/siren_2.au"; //#elif (P1_Mov_yes) //@ soundEffect_go = "sounds/yes.au"; //#endif //#if (mov_0) bewegungspunkte = 250; //#elif (mov_1) //@ bewegungspunkte = 0; //#elif (mov_2) //@ bewegungspunkte = 250; //#elif (mov_3) //@ bewegungspunkte = 0; //#elif (mov_4) //@ // throw new UnsupportedOperationException("Not supported yet."); //#endif } else if (sp == "SP2"){ //#if (P2_Rot_Beep1) //@ soundEffect_rotate = "sounds/beep_1.au"; //#elif (P2_Rot_Beep2) //@ soundEffect_rotate = "sounds/beep_2.au"; //#elif (P2_Rot_Beep3) //@ soundEffect_rotate = "sounds/beep_3.au"; //#elif (P2_Rot_Bleep1) //@ soundEffect_rotate = "sounds/bleep_1.au"; //#elif (P2_Rot_Buzzer) //@ soundEffect_rotate = "sounds/buzzer.au"; //#elif (P2_Rot_Cash_Register) //@ soundEffect_rotate = "sounds/cash_register.au"; //#elif (P2_Rot_Cork) //@ soundEffect_rotate = "sounds/cork.au"; //#elif (P2_Rot_Game_Win) //@ soundEffect_rotate = "sounds/game_win.au"; //#elif (P2_Rot_Drip) //@ soundEffect_rotate = "sounds/drip.au"; //#elif (P2_Rot_Gorod) //@ soundEffect_rotate = "sounds/gorod.au"; //#elif (P2_Rot_Horn) //@ soundEffect_rotate = "sounds/horn.au"; //#elif (P2_Rot_Laser_Trill) //@ soundEffect_rotate = "sounds/laser_trill.au"; //#elif (P2_Rot_Police_Siren) soundEffect_rotate = "sounds/police_siren.au"; //#elif (P2_Rot_Siren_1) //@ soundEffect_rotate = "sounds/siren_1.au"; //#elif (P2_Rot_Siren_2) //@ soundEffect_rotate = "sounds/siren_2.au"; //#elif (P2_Rot_Yes) //@ soundEffect_rotate = "sounds/yes.au"; //#endif //#if (P2_Mov_Beep1) //@ soundEffect_go = "sounds/beep_1.au"; //#elif (P2_Mov_Beep2) //@ soundEffect_go = "sounds/beep_2.au"; //#elif (P2_Mov_Beep3) //@ soundEffect_go = "sounds/beep_3.au"; //#elif (P2_Mov_Bleep1)<SUF> //@ soundEffect_go = "sounds/bleep_1.au"; //#elif (P2_Mov_Buzzer) //@ soundEffect_go = "sounds/buzzer.au"; //#elif (P2_Mov_Cah_Register) //@ soundEffect_go = "sounds/cash_register.au"; //#elif (P2_Mov_cork) soundEffect_go = "sounds/cork.au"; //#elif (P2_Mov_Game_Win) //@ soundEffect_go = "sounds/game_win.au"; //#elif (P2_Mov_Drip) //@ soundEffect_go = "sounds/drip.au"; //#elif (P2_Mov_Gorord) //@ soundEffect_go = "sounds/gorod.au"; //#elif (P2_Mov_Horn) //@ soundEffect_go = "sounds/horn.au"; //#elif (P2_Mov_LaserTrill) //@ soundEffect_go = "sounds/laser_trill.au"; //#elif (P2_Mov_Police_Siren) //@ soundEffect_go = "sounds/police_siren.au"; //#elif (P2_Mov_Siren_1) //@ soundEffect_go = "sounds/siren_1.au"; //#elif (P2_Mov_Siren_2) //@ soundEffect_go = "sounds/siren_2.au"; //#elif (P2_Mov_Yes) //@ soundEffect_go = "sounds/yes.au"; //#endif //#if (mov_0) bewegungspunkte = 250; //#elif (mov_1) //@ bewegungspunkte = 0; //#elif (mov_2) //@ bewegungspunkte = 250; //#elif (mov_3) //@ bewegungspunkte = 0; //#elif (mov_4) //@ // throw new UnsupportedOperationException("Not supported yet."); //#endif } } public boolean isRocket() { return rocket; } public void setRocket(boolean rocket) { this.rocket = rocket; } public boolean isMo() { return mo; } public void setMo(boolean mo) { this.mo = mo; } public Image getImg() { return img; } public boolean isCollision() { return collision; } public void setStop(boolean stop) { this.stop = stop; } public int getBp() { return bewegungspunkte; } public void setLeft(boolean left) { this.left = left; } public void setRight(boolean right) { this.right = right; } public void setDown(boolean down) { this.down = down; } public void setSpeed(int speed) { this.speed = speed; } public int getTp() { return tp; } public void setTp(int tp) { this.tp = tp; } public void setUp(boolean up) { this.up = up; } public int getHeight() { return height; } public int getWidth() { return width; } public double getX() { return x; } public double getY() { return y; } public void setX(double x) { this.x = x; } public void setY(double y) { this.y = y; } public float getDegree() { return degree; } public Proj getSch() { return schuss; } public void setSch(Proj sch) { this.schuss = sch; } public void setCollision(boolean collision) { this.collision = collision; } public void setBp(int bp) { this.bewegungspunkte = bp; } public int getCenter() { return center_TP; } public void setCenter(int center) { this.center_TP = center; } public int getHinten() { return hinten_TP; } public void setHinten(int hinten) { this.hinten_TP = hinten; } public int getLinks() { return links_TP; } public void setLinks(int links) { this.links_TP = links; } public int getRechts() { return rechts_TP; } public void setRechts(int rechts) { this.rechts_TP = rechts; } public int getVorne() { return vorne_TP; } public void setVorne(int vorne) { this.vorne_TP = vorne; } public int getLoad() { return load; } public void setLoad(int load) { this.load = load; } public Rectangle getBounds(){ return new Rectangle((int)getX(), (int)getY(), getWidth(), getHeight()); } public void move(){ //#if (mov_0) if (up && bewegungspunkte > 0 && stop == false){ y -= Math.cos(Math.toDegrees(degree)/180*Math.PI) * speed; x += Math.sin(Math.toDegrees(degree)/180*Math.PI) * speed; bewegungspunkte -= 1; Snd.music(soundEffect_rotate); } if (down && bewegungspunkte > 0 && stop == false){ y += Math.cos(Math.toDegrees(degree)/180*Math.PI) * speed; x -= Math.sin(Math.toDegrees(degree)/180*Math.PI) * speed; bewegungspunkte -= 1; Snd.music(soundEffect_rotate); } if (left && bewegungspunkte > 0 && stop == false){ degree -= 0.03; bewegungspunkte -= 1; Snd.music(soundEffect_go); } if (right&& bewegungspunkte > 0 && stop == false){ degree += 0.03; bewegungspunkte -= 1; Snd.music(soundEffect_go); } //#elif (mov_1) //@ if (left && stop == false && load != 1){ //@ degree -= 0.03; //@ Snd.music(soundEffect_rotate); //@ } //@ if (right && stop == false && load != 1){ //@ degree += 0.03; //@ Snd.music(soundEffect_rotate); //@ } //@ if (stop == false && load != 1){ //@ setSpeed((int)(Math.ceil(bewegungspunkte*0.02))); //@ y -= Math.cos(Math.toDegrees(degree)/180*Math.PI) * speed; //@ x += Math.sin(Math.toDegrees(degree)/180*Math.PI) * speed; //@ bewegungspunkte = (int)(bewegungspunkte - bewegungspunkte * 0.02); //@ if (load != 0 && bewegungspunkte != 0) Snd.music(soundEffect_go); //@ } //#elif (mov_2) //@ if (up && right && bewegungspunkte > 0 && stop == false){ //@ degree = (float)0.8; //@ bewegungspunkte -= 1; //@ Snd.music(soundEffect_go); //@ y -= Math.cos(Math.toDegrees(degree)/180*Math.PI) * speed; //@ x += Math.sin(Math.toDegrees(degree)/180*Math.PI) * speed; //@ } //@ else if (up && left && bewegungspunkte > 0 && stop == false){ //@ degree = (float)-0.8; //@ bewegungspunkte -= 1; //@ Snd.music(soundEffect_go); //@ y -= Math.cos(Math.toDegrees(degree)/180*Math.PI) * speed; //@ x += Math.sin(Math.toDegrees(degree)/180*Math.PI) * speed; //@ } //@ else if (down && right && bewegungspunkte > 0 && stop == false){ //@ degree = (float)2.35; //@ bewegungspunkte -= 1; //@ Snd.music(soundEffect_go); //@ y -= Math.cos(Math.toDegrees(degree)/180*Math.PI) * speed; //@ x += Math.sin(Math.toDegrees(degree)/180*Math.PI) * speed; //@ } //@ else if (down && left && bewegungspunkte > 0 && stop == false){ //@ degree = (float)-2.35; //@ bewegungspunkte -= 1; //@ Snd.music(soundEffect_go); //@ y -= Math.cos(Math.toDegrees(degree)/180*Math.PI) * speed; //@ x += Math.sin(Math.toDegrees(degree)/180*Math.PI) * speed; //@ } //@ else if (up && bewegungspunkte > 0 && stop == false){ //@ degree = (float)0; //@ bewegungspunkte -= 1; //@ Snd.music(soundEffect_go); //@ y -= Math.cos(Math.toDegrees(degree)/180*Math.PI) * speed; //@ x += Math.sin(Math.toDegrees(degree)/180*Math.PI) * speed; //@ } //@ else if(down && bewegungspunkte > 0 && stop == false){ //@ degree = (float)3.15; //@ bewegungspunkte -= 1; //@ Snd.music(soundEffect_go); //@ y -= Math.cos(Math.toDegrees(degree)/180*Math.PI) * speed; //@ x += Math.sin(Math.toDegrees(degree)/180*Math.PI) * speed; //@ } //@ else if(left && bewegungspunkte > 0 && stop == false){ //@ degree = (float)-1.575; //@ bewegungspunkte -= 1; //@ Snd.music(soundEffect_go); //@ y -= Math.cos(Math.toDegrees(degree)/180*Math.PI) * speed; //@ x += Math.sin(Math.toDegrees(degree)/180*Math.PI) * speed; //@ } //@ else if(right && bewegungspunkte > 0 && stop == false){ //@ degree = (float)1.575; //@ bewegungspunkte -= 1; //@ Snd.music(soundEffect_go); //@ y -= Math.cos(Math.toDegrees(degree)/180*Math.PI) * speed; //@ x += Math.sin(Math.toDegrees(degree)/180*Math.PI) * speed; //@ } //#elif (mov_3) //@ if (left && stop == false && load == 0){ //@ degree -= 0.03; //@ Snd.music(soundEffect_rotate); //@ } //@ if (right && stop == false && load == 0){ //@ degree += 0.03; //@ Snd.music(soundEffect_rotate); //@ } //@ if (right && stop == false && load == 2 && bewegungspunkte > 0 ){ //@ y -= Math.cos(Math.toDegrees(degree-30)/180*Math.PI) * speed; //@ x += Math.sin(Math.toDegrees(degree-30)/180*Math.PI) * speed; //@ //@ } //@ if (left && stop == false && load == 2 && bewegungspunkte > 0 ){ //@ y -= Math.cos(Math.toDegrees(degree+30)/180*Math.PI) * speed; //@ x += Math.sin(Math.toDegrees(degree+30)/180*Math.PI) * speed; //@ } //@ if (stop == false && load == 2 && bewegungspunkte > 0 ){ //@ y -= Math.cos(Math.toDegrees(degree)/180*Math.PI) * speed; //@ x += Math.sin(Math.toDegrees(degree)/180*Math.PI) * speed; //@ bewegungspunkte = bewegungspunkte - speed; //@ Snd.music(soundEffect_go); //@ } //@ if (stop == false && load != 1){ //@ setSpeed((int)(Math.ceil(bewegungspunkte*0.02))); //@ } //#elif (mov_4) //@ if (left && stop == false && load == 0){ //@ degree -= 0.03; //@ Snd.music(soundEffect_rotate); //@ } //@ if (right && stop == false && load == 0){ //@ degree += 0.03; //@ Snd.music(soundEffect_rotate); //@ } //@ if (right && stop == false && load == 2){ //@ y -= Math.cos(Math.toDegrees(degree-30)/180*Math.PI) * speed; //@ x += Math.sin(Math.toDegrees(degree-30)/180*Math.PI) * speed; //@ } //@ if (left && stop == false && load == 2){ //@ y -= Math.cos(Math.toDegrees(degree+30)/180*Math.PI) * speed; //@ x += Math.sin(Math.toDegrees(degree+30)/180*Math.PI) * speed; //@ } //@ if (stop == false && load != 1){ //@ setSpeed((int)(Math.ceil(bewegungspunkte*0.02))); //@ y -= Math.cos(Math.toDegrees(degree)/180*Math.PI) * speed; //@ x += Math.sin(Math.toDegrees(degree)/180*Math.PI) * speed; //@ bewegungspunkte = (int)(bewegungspunkte - bewegungspunkte * 0.02); //@ if (load != 0 && bewegungspunkte != 0) Snd.music(soundEffect_go); //@ } //#endif } }
160626_1
package doom; import static data.Defines.*; import static data.Limits.*; import data.mapthing_t; import defines.*; import demo.IDoomDemo; import f.Finale; import static g.Signals.ScanCode.*; import java.io.OutputStreamWriter; import java.util.Arrays; import java.util.stream.Stream; import m.Settings; import mochadoom.Engine; import p.mobj_t; /** * We need globally shared data structures, for defining the global state * variables. MAES: in pure OO style, this should be a global "Doom state" * object to be passed along various modules. No ugly globals here!!! Now, some * of the variables that appear here were actually defined in separate modules. * Pretty much, whatever needs to be shared with other modules was placed here, * either as a local definition, or as an extern share. The very least, I'll * document where everything is supposed to come from/reside. */ public abstract class DoomStatus<T,V> { public static final int BGCOLOR= 7; public static final int FGCOLOR =8; public static int RESENDCOUNT =10; public static int PL_DRONE =0x80; // bit flag in doomdata->player public String[] wadfiles=new String[MAXWADFILES]; boolean drone; /** Command line parametersm, actually defined in d_main.c */ public boolean nomonsters; // checkparm of -nomonsters public boolean respawnparm; // checkparm of -respawn public boolean fastparm; // checkparm of -fast public boolean devparm; // DEBUG: launched with -devparm // MAES: declared as "extern", shared with Menu.java public boolean inhelpscreens; boolean advancedemo; /////////// Local to doomstat.c //////////// // TODO: hide those behind getters /** Game Mode - identify IWAD as shareware, retail etc. * This is now hidden behind getters so some cases like plutonia * etc. can be handled more cleanly. * */ private GameMode gamemode; public void setGameMode(GameMode mode){ this.gamemode=mode; } public GameMode getGameMode(){ return gamemode; } public boolean isShareware(){ return (gamemode== GameMode.shareware); } /** Commercial means Doom 2, Plutonia, TNT, and possibly others like XBLA. * * @return */ public boolean isCommercial(){ return (gamemode== GameMode.commercial || gamemode== GameMode.pack_plut || gamemode== GameMode.pack_tnt || gamemode== GameMode.pack_xbla || gamemode== GameMode.freedoom2 || gamemode== GameMode.freedm); } /** Retail means Ultimate. * * @return */ public boolean isRetail(){ return (gamemode== GameMode.retail || gamemode == GameMode.freedoom1 ); } /** Registered is a subset of Ultimate * * @return */ public boolean isRegistered(){ return (gamemode== GameMode.registered || gamemode== GameMode.retail || gamemode == GameMode.freedoom1 ); } public GameMission_t gamemission; /** Language. */ public Language_t language; // /////////// Normally found in d_main.c /////////////// // Selected skill type, map etc. /** Defaults for menu, methinks. */ public skill_t startskill; public int startepisode; public int startmap; public boolean autostart; /** Selected by user */ public skill_t gameskill; public int gameepisode; public int gamemap; /** Nightmare mode flag, single player. */ public boolean respawnmonsters; /** Netgame? Only true if >1 player. */ public boolean netgame; /** * Flag: true only if started as net deathmatch. An enum might handle * altdeath/cooperative better. Use altdeath for the "2" value */ public boolean deathmatch; /** Use this instead of "deathmatch=2" which is bullshit. */ public boolean altdeath; //////////// STUFF SHARED WITH THE RENDERER /////////////// // ------------------------- // Status flags for refresh. // public boolean nodrawers; public boolean noblit; public boolean viewactive; // Player taking events, and displaying. public int consoleplayer; public int displayplayer; // Depending on view size - no status bar? // Note that there is no way to disable the // status bar explicitely. public boolean statusbaractive; public boolean automapactive; // In AutoMap mode? public boolean menuactive; // Menu overlayed? public boolean mousecaptured = true; public boolean paused; // Game Pause? // ------------------------- // Internal parameters for sound rendering. // These have been taken from the DOS version, // but are not (yet) supported with Linux // (e.g. no sound volume adjustment with menu. // These are not used, but should be (menu). // From m_menu.c: // Sound FX volume has default, 0 - 15 // Music volume has default, 0 - 15 // These are multiplied by 8. /** maximum volume for sound */ public int snd_SfxVolume; /** maximum volume for music */ public int snd_MusicVolume; /** Maximum number of sound channels */ public int numChannels; // Current music/sfx card - index useless // w/o a reference LUT in a sound module. // Ideally, this would use indices found // in: /usr/include/linux/soundcard.h public int snd_MusicDevice; public int snd_SfxDevice; // Config file? Same disclaimer as above. public int snd_DesiredMusicDevice; public int snd_DesiredSfxDevice; // ------------------------------------- // Scores, rating. // Statistics on a given map, for intermission. // public int totalkills; public int totalitems; public int totalsecret; /** TNTHOM "cheat" for flashing HOM-detecting BG */ public boolean flashing_hom; // Added for prBoom+ code public int totallive; // Timer, for scores. public int levelstarttic; // gametic at level start public int leveltime; // tics in game play for par // -------------------------------------- // DEMO playback/recording related stuff. // No demo, there is a human player in charge? // Disable save/end game? public boolean usergame; // ? public boolean demoplayback; public boolean demorecording; // Quit after playing a demo from cmdline. public boolean singledemo; public boolean mapstrobe; /** * Set this to GS_DEMOSCREEN upon init, else it will be null * Good Sign at 2017/03/21: I hope it is no longer true info, since I've checked its assignment by NetBeans */ public gamestate_t gamestate = gamestate_t.GS_DEMOSCREEN; // ----------------------------- // Internal parameters, fixed. // These are set by the engine, and not changed // according to user inputs. Partly load from // WAD, partly set at startup time. public int gametic; // Alive? Disconnected? public boolean[] playeringame = new boolean[MAXPLAYERS]; public mapthing_t[] deathmatchstarts = new mapthing_t[MAX_DM_STARTS]; /** pointer into deathmatchstarts */ public int deathmatch_p; /** Player spawn spots. */ public mapthing_t[] playerstarts = new mapthing_t[MAXPLAYERS]; /** Intermission stats. Parameters for world map / intermission. */ public wbstartstruct_t wminfo; /** LUT of ammunition limits for each kind. This doubles with BackPack powerup item. NOTE: this "maxammo" is treated like a global. */ public final static int[] maxammo = {200, 50, 300, 50}; // ----------------------------------------- // Internal parameters, used for engine. // // File handling stuff. public OutputStreamWriter debugfile; // if true, load all graphics at level load public boolean precache; // wipegamestate can be set to -1 // to force a wipe on the next draw // wipegamestate can be set to -1 to force a wipe on the next draw public gamestate_t wipegamestate = gamestate_t.GS_DEMOSCREEN; public int mouseSensitivity = 5; // AX: Fix wrong defaut mouseSensitivity /** Set if homebrew PWAD stuff has been added. */ public boolean modifiedgame = false; /** debug flag to cancel adaptiveness set to true during timedemos. */ public boolean singletics = false; /* A "fastdemo" is a demo with a clock that tics as * fast as possible, yet it maintains adaptiveness and doesn't * try to render everything at all costs. */ protected boolean fastdemo; protected boolean normaldemo; protected String loaddemo = null; public int bodyqueslot; // Needed to store the number of the dummy sky flat. // Used for rendering, // as well as tracking projectiles etc. //public int skyflatnum; // TODO: Netgame stuff (buffers and pointers, i.e. indices). // TODO: This is ??? public doomcom_t doomcom; // TODO: This points inside doomcom. public doomdata_t netbuffer; public ticcmd_t[] localcmds = new ticcmd_t[BACKUPTICS]; public int rndindex; public ticcmd_t[][] netcmds;// [MAXPLAYERS][BACKUPTICS]; /** MAES: this WAS NOT in the original. * Remember to call it! */ protected final void initNetGameStuff() { //this.netbuffer = new doomdata_t(); this.doomcom = new doomcom_t(); this.netcmds = new ticcmd_t[MAXPLAYERS][BACKUPTICS]; Arrays.setAll(localcmds, i -> new ticcmd_t()); for (int i = 0; i < MAXPLAYERS; i++) { Arrays.setAll(netcmds[i], j -> new ticcmd_t()); } } // Fields used for selecting variable BPP implementations. protected abstract Finale<T> selectFinale(); // MAES: Fields specific to DoomGame. A lot of them were // duplicated/externalized // in d_game.c and d_game.h, so it makes sense adopting a more unified // approach. protected gameaction_t gameaction=gameaction_t.ga_nothing; public boolean sendpause; // send a pause event next tic protected boolean sendsave; // send a save event next tic protected int starttime; protected boolean timingdemo; // if true, exit with report on completion public boolean getPaused() { return paused; } public void setPaused(boolean paused) { this.paused = paused; } // ////////// DEMO SPECIFIC STUFF///////////// protected String demoname; protected boolean netdemo; //protected IDemoTicCmd[] demobuffer; protected IDoomDemo demobuffer; /** pointers */ // USELESS protected int demo_p; // USELESS protected int demoend; protected short[][] consistancy = new short[MAXPLAYERS][BACKUPTICS]; protected byte[] savebuffer; /* TODO Proper reconfigurable controls. Defaults hardcoded for now. T3h h4x, d00d. */ public int key_right = SC_NUMKEY6.ordinal(); public int key_left = SC_NUMKEY4.ordinal(); public int key_up = SC_W.ordinal(); public int key_down = SC_S.ordinal(); public int key_strafeleft = SC_A.ordinal(); public int key_straferight = SC_D.ordinal(); public int key_fire = SC_LCTRL.ordinal(); public int key_use = SC_SPACE.ordinal(); public int key_strafe = SC_LALT.ordinal(); public int key_speed = SC_RSHIFT.ordinal(); public boolean vanillaKeyBehavior; public int key_recordstop = SC_Q.ordinal(); public int[] key_numbers = Stream.of(SC_1, SC_2, SC_3, SC_4, SC_5, SC_6, SC_7, SC_8, SC_9, SC_0) .mapToInt(Enum::ordinal).toArray(); // Heretic stuff public int key_lookup = SC_PGUP.ordinal(); public int key_lookdown = SC_PGDOWN.ordinal(); public int key_lookcenter = SC_END.ordinal(); public int mousebfire = 0; public int mousebstrafe = 2; // AX: Fixed - Now we use the right mouse buttons public int mousebforward = 1; // AX: Fixed - Now we use the right mouse buttons public int joybfire; public int joybstrafe; public int joybuse; public int joybspeed; /** Cancel vertical mouse movement by default */ protected boolean novert=false; // AX: The good default protected int MAXPLMOVE() { return forwardmove[1]; } protected static final int TURBOTHRESHOLD = 0x32; /** fixed_t */ protected final int[] forwardmove = { 0x19, 0x32 }; // + slow turn protected final int[] sidemove = { 0x18, 0x28 }; protected final int[] angleturn = { 640, 1280, 320 }; protected static final int SLOWTURNTICS = 6; protected static final int NUMKEYS = 256; protected boolean[] gamekeydown = new boolean[NUMKEYS]; protected boolean keysCleared; public boolean alwaysrun; protected int turnheld; // for accelerative turning protected int lookheld; // for accelerative looking? protected boolean[] mousearray = new boolean[4]; /** This is an alias for mousearray [1+i] */ protected boolean mousebuttons(int i) { return mousearray[1 + i]; // allow [-1] } protected void mousebuttons(int i, boolean value) { mousearray[1 + i] = value; // allow [-1] } protected void mousebuttons(int i, int value) { mousearray[1 + i] = value != 0; // allow [-1] } /** mouse values are used once */ protected int mousex, mousey; protected int dclicktime; protected int dclickstate; protected int dclicks; protected int dclicktime2, dclickstate2, dclicks2; /** joystick values are repeated */ protected int joyxmove, joyymove; protected boolean[] joyarray = new boolean[5]; protected boolean joybuttons(int i) { return joyarray[1 + i]; // allow [-1] } protected void joybuttons(int i, boolean value) { joyarray[1 + i] = value; // allow [-1] } protected void joybuttons(int i, int value) { joyarray[1 + i] = value != 0; // allow [-1] } protected int savegameslot; protected String savedescription; protected static final int BODYQUESIZE = 32; protected mobj_t[] bodyque = new mobj_t[BODYQUESIZE]; public String statcopy; // for statistics driver /** Not documented/used in linuxdoom. I supposed it could be used to * ignore mouse input? */ public boolean use_mouse,use_joystick; /** More prBoom+ stuff. Used mostly for code uhm..reuse, rather * than to actually change the way stuff works. * */ public static int compatibility_level; public final ConfigManager CM = Engine.getConfig(); public DoomStatus() { this.wminfo=new wbstartstruct_t(); initNetGameStuff(); } public void update() { this.snd_SfxVolume = CM.getValue(Settings.sfx_volume, Integer.class); this.snd_MusicVolume = CM.getValue(Settings.music_volume, Integer.class); this.alwaysrun = CM.equals(Settings.alwaysrun, Boolean.TRUE); // Keys... this.key_right = CM.getValue(Settings.key_right, Integer.class); this.key_left = CM.getValue(Settings.key_left, Integer.class); this.key_up = CM.getValue(Settings.key_up, Integer.class); this.key_down = CM.getValue(Settings.key_down, Integer.class); this.key_strafeleft = CM.getValue(Settings.key_strafeleft, Integer.class); this.key_straferight = CM.getValue(Settings.key_straferight, Integer.class); this.key_fire = CM.getValue(Settings.key_fire, Integer.class); this.key_use = CM.getValue(Settings.key_use, Integer.class); this.key_strafe = CM.getValue(Settings.key_strafe, Integer.class); this.key_speed = CM.getValue(Settings.key_speed, Integer.class); // Mouse buttons this.use_mouse = CM.equals(Settings.use_mouse, 1); this.mousebfire = CM.getValue(Settings.mouseb_fire, Integer.class); this.mousebstrafe = CM.getValue(Settings.mouseb_strafe, Integer.class); this.mousebforward = CM.getValue(Settings.mouseb_forward, Integer.class); // Joystick this.use_joystick = CM.equals(Settings.use_joystick, 1); this.joybfire = CM.getValue(Settings.joyb_fire, Integer.class); this.joybstrafe = CM.getValue(Settings.joyb_strafe, Integer.class); this.joybuse = CM.getValue(Settings.joyb_use, Integer.class); this.joybspeed = CM.getValue(Settings.joyb_speed, Integer.class); // Sound this.numChannels = CM.getValue(Settings.snd_channels, Integer.class); // Map strobe this.mapstrobe = CM.equals(Settings.vestrobe, Boolean.TRUE); // Mouse sensitivity this.mouseSensitivity = CM.getValue(Settings.mouse_sensitivity, Integer.class); // This should indicate keyboard behavior should be as close as possible to vanilla this.vanillaKeyBehavior = CM.equals(Settings.vanilla_key_behavior, Boolean.TRUE); } public void commit() { CM.update(Settings.sfx_volume, this.snd_SfxVolume); CM.update(Settings.music_volume, this.snd_MusicVolume); CM.update(Settings.alwaysrun, this.alwaysrun); // Keys... CM.update(Settings.key_right, this.key_right); CM.update(Settings.key_left, this.key_left); CM.update(Settings.key_up, this.key_up); CM.update(Settings.key_down, this.key_down); CM.update(Settings.key_strafeleft, this.key_strafeleft); CM.update(Settings.key_straferight, this.key_straferight); CM.update(Settings.key_fire, this.key_fire); CM.update(Settings.key_use, this.key_use); CM.update(Settings.key_strafe, this.key_strafe); CM.update(Settings.key_speed, this.key_speed); // Mouse buttons CM.update(Settings.use_mouse, this.use_mouse ? 1 : 0); CM.update(Settings.mouseb_fire, this.mousebfire); CM.update(Settings.mouseb_strafe, this.mousebstrafe); CM.update(Settings.mouseb_forward, this.mousebforward); // Joystick CM.update(Settings.use_joystick, this.use_joystick ? 1 : 0); CM.update(Settings.joyb_fire, this.joybfire); CM.update(Settings.joyb_strafe, this.joybstrafe); CM.update(Settings.joyb_use, this.joybuse); CM.update(Settings.joyb_speed, this.joybspeed); // Sound CM.update(Settings.snd_channels, this.numChannels); // Map strobe CM.update(Settings.vestrobe, this.mapstrobe); // Mouse sensitivity CM.update(Settings.mouse_sensitivity, this.mouseSensitivity); } } // $Log: DoomStatus.java,v $ // Revision 1.36 2012/11/06 16:04:58 velktron // Variables manager less tightly integrated. // // Revision 1.35 2012/09/24 17:16:22 velktron // Massive merge between HiColor and HEAD. There's no difference from now on, and development continues on HEAD. // // Revision 1.34.2.3 2012/09/24 16:58:06 velktron // TrueColor, Generics. // // Revision 1.34.2.2 2012/09/20 14:25:13 velktron // Unified DOOM!!! // // Revision 1.34.2.1 2012/09/17 16:06:52 velktron // Now handling updates of all variables, though those specific to some subsystems should probably be moved??? // // Revision 1.34 2011/11/01 23:48:10 velktron // Added tnthom stuff. // // Revision 1.33 2011/10/24 02:11:27 velktron // Stream compliancy // // Revision 1.32 2011/10/07 16:01:16 velktron // Added freelook stuff, using Keys. // // Revision 1.31 2011/09/27 16:01:41 velktron // -complevel_t // // Revision 1.30 2011/09/27 15:54:51 velktron // Added some more prBoom+ stuff. // // Revision 1.29 2011/07/28 17:07:04 velktron // Added always run hack. // // Revision 1.28 2011/07/16 10:57:50 velktron // Merged finnw's changes for enabling polling of ?_LOCK keys. // // Revision 1.27 2011/06/14 20:59:47 velktron // Channel settings now read from default.cfg. Changes in sound creation order. // // Revision 1.26 2011/06/04 11:04:25 velktron // Fixed registered/ultimate identification. // // Revision 1.25 2011/06/01 17:35:56 velktron // Techdemo v1.4a level. Default novert and experimental mochaevents interface. // // Revision 1.24 2011/06/01 00:37:58 velktron // Changed default keys to WASD. // // Revision 1.23 2011/05/31 21:45:51 velktron // Added XBLA version as explicitly supported. // // Revision 1.22 2011/05/30 15:50:42 velktron // Changed to work with new Abstract classes // // Revision 1.21 2011/05/26 17:52:11 velktron // Now using ICommandLineManager // // Revision 1.20 2011/05/26 13:39:52 velktron // Now using ICommandLineManager // // Revision 1.19 2011/05/25 17:56:52 velktron // Introduced some fixes for mousebuttons etc. // // Revision 1.18 2011/05/24 17:44:37 velktron // usemouse added for defaults //
AXDOOMER/mochadoom
src/doom/DoomStatus.java
6,293
// bit flag in doomdata->player
line_comment
nl
package doom; import static data.Defines.*; import static data.Limits.*; import data.mapthing_t; import defines.*; import demo.IDoomDemo; import f.Finale; import static g.Signals.ScanCode.*; import java.io.OutputStreamWriter; import java.util.Arrays; import java.util.stream.Stream; import m.Settings; import mochadoom.Engine; import p.mobj_t; /** * We need globally shared data structures, for defining the global state * variables. MAES: in pure OO style, this should be a global "Doom state" * object to be passed along various modules. No ugly globals here!!! Now, some * of the variables that appear here were actually defined in separate modules. * Pretty much, whatever needs to be shared with other modules was placed here, * either as a local definition, or as an extern share. The very least, I'll * document where everything is supposed to come from/reside. */ public abstract class DoomStatus<T,V> { public static final int BGCOLOR= 7; public static final int FGCOLOR =8; public static int RESENDCOUNT =10; public static int PL_DRONE =0x80; // bit flag<SUF> public String[] wadfiles=new String[MAXWADFILES]; boolean drone; /** Command line parametersm, actually defined in d_main.c */ public boolean nomonsters; // checkparm of -nomonsters public boolean respawnparm; // checkparm of -respawn public boolean fastparm; // checkparm of -fast public boolean devparm; // DEBUG: launched with -devparm // MAES: declared as "extern", shared with Menu.java public boolean inhelpscreens; boolean advancedemo; /////////// Local to doomstat.c //////////// // TODO: hide those behind getters /** Game Mode - identify IWAD as shareware, retail etc. * This is now hidden behind getters so some cases like plutonia * etc. can be handled more cleanly. * */ private GameMode gamemode; public void setGameMode(GameMode mode){ this.gamemode=mode; } public GameMode getGameMode(){ return gamemode; } public boolean isShareware(){ return (gamemode== GameMode.shareware); } /** Commercial means Doom 2, Plutonia, TNT, and possibly others like XBLA. * * @return */ public boolean isCommercial(){ return (gamemode== GameMode.commercial || gamemode== GameMode.pack_plut || gamemode== GameMode.pack_tnt || gamemode== GameMode.pack_xbla || gamemode== GameMode.freedoom2 || gamemode== GameMode.freedm); } /** Retail means Ultimate. * * @return */ public boolean isRetail(){ return (gamemode== GameMode.retail || gamemode == GameMode.freedoom1 ); } /** Registered is a subset of Ultimate * * @return */ public boolean isRegistered(){ return (gamemode== GameMode.registered || gamemode== GameMode.retail || gamemode == GameMode.freedoom1 ); } public GameMission_t gamemission; /** Language. */ public Language_t language; // /////////// Normally found in d_main.c /////////////// // Selected skill type, map etc. /** Defaults for menu, methinks. */ public skill_t startskill; public int startepisode; public int startmap; public boolean autostart; /** Selected by user */ public skill_t gameskill; public int gameepisode; public int gamemap; /** Nightmare mode flag, single player. */ public boolean respawnmonsters; /** Netgame? Only true if >1 player. */ public boolean netgame; /** * Flag: true only if started as net deathmatch. An enum might handle * altdeath/cooperative better. Use altdeath for the "2" value */ public boolean deathmatch; /** Use this instead of "deathmatch=2" which is bullshit. */ public boolean altdeath; //////////// STUFF SHARED WITH THE RENDERER /////////////// // ------------------------- // Status flags for refresh. // public boolean nodrawers; public boolean noblit; public boolean viewactive; // Player taking events, and displaying. public int consoleplayer; public int displayplayer; // Depending on view size - no status bar? // Note that there is no way to disable the // status bar explicitely. public boolean statusbaractive; public boolean automapactive; // In AutoMap mode? public boolean menuactive; // Menu overlayed? public boolean mousecaptured = true; public boolean paused; // Game Pause? // ------------------------- // Internal parameters for sound rendering. // These have been taken from the DOS version, // but are not (yet) supported with Linux // (e.g. no sound volume adjustment with menu. // These are not used, but should be (menu). // From m_menu.c: // Sound FX volume has default, 0 - 15 // Music volume has default, 0 - 15 // These are multiplied by 8. /** maximum volume for sound */ public int snd_SfxVolume; /** maximum volume for music */ public int snd_MusicVolume; /** Maximum number of sound channels */ public int numChannels; // Current music/sfx card - index useless // w/o a reference LUT in a sound module. // Ideally, this would use indices found // in: /usr/include/linux/soundcard.h public int snd_MusicDevice; public int snd_SfxDevice; // Config file? Same disclaimer as above. public int snd_DesiredMusicDevice; public int snd_DesiredSfxDevice; // ------------------------------------- // Scores, rating. // Statistics on a given map, for intermission. // public int totalkills; public int totalitems; public int totalsecret; /** TNTHOM "cheat" for flashing HOM-detecting BG */ public boolean flashing_hom; // Added for prBoom+ code public int totallive; // Timer, for scores. public int levelstarttic; // gametic at level start public int leveltime; // tics in game play for par // -------------------------------------- // DEMO playback/recording related stuff. // No demo, there is a human player in charge? // Disable save/end game? public boolean usergame; // ? public boolean demoplayback; public boolean demorecording; // Quit after playing a demo from cmdline. public boolean singledemo; public boolean mapstrobe; /** * Set this to GS_DEMOSCREEN upon init, else it will be null * Good Sign at 2017/03/21: I hope it is no longer true info, since I've checked its assignment by NetBeans */ public gamestate_t gamestate = gamestate_t.GS_DEMOSCREEN; // ----------------------------- // Internal parameters, fixed. // These are set by the engine, and not changed // according to user inputs. Partly load from // WAD, partly set at startup time. public int gametic; // Alive? Disconnected? public boolean[] playeringame = new boolean[MAXPLAYERS]; public mapthing_t[] deathmatchstarts = new mapthing_t[MAX_DM_STARTS]; /** pointer into deathmatchstarts */ public int deathmatch_p; /** Player spawn spots. */ public mapthing_t[] playerstarts = new mapthing_t[MAXPLAYERS]; /** Intermission stats. Parameters for world map / intermission. */ public wbstartstruct_t wminfo; /** LUT of ammunition limits for each kind. This doubles with BackPack powerup item. NOTE: this "maxammo" is treated like a global. */ public final static int[] maxammo = {200, 50, 300, 50}; // ----------------------------------------- // Internal parameters, used for engine. // // File handling stuff. public OutputStreamWriter debugfile; // if true, load all graphics at level load public boolean precache; // wipegamestate can be set to -1 // to force a wipe on the next draw // wipegamestate can be set to -1 to force a wipe on the next draw public gamestate_t wipegamestate = gamestate_t.GS_DEMOSCREEN; public int mouseSensitivity = 5; // AX: Fix wrong defaut mouseSensitivity /** Set if homebrew PWAD stuff has been added. */ public boolean modifiedgame = false; /** debug flag to cancel adaptiveness set to true during timedemos. */ public boolean singletics = false; /* A "fastdemo" is a demo with a clock that tics as * fast as possible, yet it maintains adaptiveness and doesn't * try to render everything at all costs. */ protected boolean fastdemo; protected boolean normaldemo; protected String loaddemo = null; public int bodyqueslot; // Needed to store the number of the dummy sky flat. // Used for rendering, // as well as tracking projectiles etc. //public int skyflatnum; // TODO: Netgame stuff (buffers and pointers, i.e. indices). // TODO: This is ??? public doomcom_t doomcom; // TODO: This points inside doomcom. public doomdata_t netbuffer; public ticcmd_t[] localcmds = new ticcmd_t[BACKUPTICS]; public int rndindex; public ticcmd_t[][] netcmds;// [MAXPLAYERS][BACKUPTICS]; /** MAES: this WAS NOT in the original. * Remember to call it! */ protected final void initNetGameStuff() { //this.netbuffer = new doomdata_t(); this.doomcom = new doomcom_t(); this.netcmds = new ticcmd_t[MAXPLAYERS][BACKUPTICS]; Arrays.setAll(localcmds, i -> new ticcmd_t()); for (int i = 0; i < MAXPLAYERS; i++) { Arrays.setAll(netcmds[i], j -> new ticcmd_t()); } } // Fields used for selecting variable BPP implementations. protected abstract Finale<T> selectFinale(); // MAES: Fields specific to DoomGame. A lot of them were // duplicated/externalized // in d_game.c and d_game.h, so it makes sense adopting a more unified // approach. protected gameaction_t gameaction=gameaction_t.ga_nothing; public boolean sendpause; // send a pause event next tic protected boolean sendsave; // send a save event next tic protected int starttime; protected boolean timingdemo; // if true, exit with report on completion public boolean getPaused() { return paused; } public void setPaused(boolean paused) { this.paused = paused; } // ////////// DEMO SPECIFIC STUFF///////////// protected String demoname; protected boolean netdemo; //protected IDemoTicCmd[] demobuffer; protected IDoomDemo demobuffer; /** pointers */ // USELESS protected int demo_p; // USELESS protected int demoend; protected short[][] consistancy = new short[MAXPLAYERS][BACKUPTICS]; protected byte[] savebuffer; /* TODO Proper reconfigurable controls. Defaults hardcoded for now. T3h h4x, d00d. */ public int key_right = SC_NUMKEY6.ordinal(); public int key_left = SC_NUMKEY4.ordinal(); public int key_up = SC_W.ordinal(); public int key_down = SC_S.ordinal(); public int key_strafeleft = SC_A.ordinal(); public int key_straferight = SC_D.ordinal(); public int key_fire = SC_LCTRL.ordinal(); public int key_use = SC_SPACE.ordinal(); public int key_strafe = SC_LALT.ordinal(); public int key_speed = SC_RSHIFT.ordinal(); public boolean vanillaKeyBehavior; public int key_recordstop = SC_Q.ordinal(); public int[] key_numbers = Stream.of(SC_1, SC_2, SC_3, SC_4, SC_5, SC_6, SC_7, SC_8, SC_9, SC_0) .mapToInt(Enum::ordinal).toArray(); // Heretic stuff public int key_lookup = SC_PGUP.ordinal(); public int key_lookdown = SC_PGDOWN.ordinal(); public int key_lookcenter = SC_END.ordinal(); public int mousebfire = 0; public int mousebstrafe = 2; // AX: Fixed - Now we use the right mouse buttons public int mousebforward = 1; // AX: Fixed - Now we use the right mouse buttons public int joybfire; public int joybstrafe; public int joybuse; public int joybspeed; /** Cancel vertical mouse movement by default */ protected boolean novert=false; // AX: The good default protected int MAXPLMOVE() { return forwardmove[1]; } protected static final int TURBOTHRESHOLD = 0x32; /** fixed_t */ protected final int[] forwardmove = { 0x19, 0x32 }; // + slow turn protected final int[] sidemove = { 0x18, 0x28 }; protected final int[] angleturn = { 640, 1280, 320 }; protected static final int SLOWTURNTICS = 6; protected static final int NUMKEYS = 256; protected boolean[] gamekeydown = new boolean[NUMKEYS]; protected boolean keysCleared; public boolean alwaysrun; protected int turnheld; // for accelerative turning protected int lookheld; // for accelerative looking? protected boolean[] mousearray = new boolean[4]; /** This is an alias for mousearray [1+i] */ protected boolean mousebuttons(int i) { return mousearray[1 + i]; // allow [-1] } protected void mousebuttons(int i, boolean value) { mousearray[1 + i] = value; // allow [-1] } protected void mousebuttons(int i, int value) { mousearray[1 + i] = value != 0; // allow [-1] } /** mouse values are used once */ protected int mousex, mousey; protected int dclicktime; protected int dclickstate; protected int dclicks; protected int dclicktime2, dclickstate2, dclicks2; /** joystick values are repeated */ protected int joyxmove, joyymove; protected boolean[] joyarray = new boolean[5]; protected boolean joybuttons(int i) { return joyarray[1 + i]; // allow [-1] } protected void joybuttons(int i, boolean value) { joyarray[1 + i] = value; // allow [-1] } protected void joybuttons(int i, int value) { joyarray[1 + i] = value != 0; // allow [-1] } protected int savegameslot; protected String savedescription; protected static final int BODYQUESIZE = 32; protected mobj_t[] bodyque = new mobj_t[BODYQUESIZE]; public String statcopy; // for statistics driver /** Not documented/used in linuxdoom. I supposed it could be used to * ignore mouse input? */ public boolean use_mouse,use_joystick; /** More prBoom+ stuff. Used mostly for code uhm..reuse, rather * than to actually change the way stuff works. * */ public static int compatibility_level; public final ConfigManager CM = Engine.getConfig(); public DoomStatus() { this.wminfo=new wbstartstruct_t(); initNetGameStuff(); } public void update() { this.snd_SfxVolume = CM.getValue(Settings.sfx_volume, Integer.class); this.snd_MusicVolume = CM.getValue(Settings.music_volume, Integer.class); this.alwaysrun = CM.equals(Settings.alwaysrun, Boolean.TRUE); // Keys... this.key_right = CM.getValue(Settings.key_right, Integer.class); this.key_left = CM.getValue(Settings.key_left, Integer.class); this.key_up = CM.getValue(Settings.key_up, Integer.class); this.key_down = CM.getValue(Settings.key_down, Integer.class); this.key_strafeleft = CM.getValue(Settings.key_strafeleft, Integer.class); this.key_straferight = CM.getValue(Settings.key_straferight, Integer.class); this.key_fire = CM.getValue(Settings.key_fire, Integer.class); this.key_use = CM.getValue(Settings.key_use, Integer.class); this.key_strafe = CM.getValue(Settings.key_strafe, Integer.class); this.key_speed = CM.getValue(Settings.key_speed, Integer.class); // Mouse buttons this.use_mouse = CM.equals(Settings.use_mouse, 1); this.mousebfire = CM.getValue(Settings.mouseb_fire, Integer.class); this.mousebstrafe = CM.getValue(Settings.mouseb_strafe, Integer.class); this.mousebforward = CM.getValue(Settings.mouseb_forward, Integer.class); // Joystick this.use_joystick = CM.equals(Settings.use_joystick, 1); this.joybfire = CM.getValue(Settings.joyb_fire, Integer.class); this.joybstrafe = CM.getValue(Settings.joyb_strafe, Integer.class); this.joybuse = CM.getValue(Settings.joyb_use, Integer.class); this.joybspeed = CM.getValue(Settings.joyb_speed, Integer.class); // Sound this.numChannels = CM.getValue(Settings.snd_channels, Integer.class); // Map strobe this.mapstrobe = CM.equals(Settings.vestrobe, Boolean.TRUE); // Mouse sensitivity this.mouseSensitivity = CM.getValue(Settings.mouse_sensitivity, Integer.class); // This should indicate keyboard behavior should be as close as possible to vanilla this.vanillaKeyBehavior = CM.equals(Settings.vanilla_key_behavior, Boolean.TRUE); } public void commit() { CM.update(Settings.sfx_volume, this.snd_SfxVolume); CM.update(Settings.music_volume, this.snd_MusicVolume); CM.update(Settings.alwaysrun, this.alwaysrun); // Keys... CM.update(Settings.key_right, this.key_right); CM.update(Settings.key_left, this.key_left); CM.update(Settings.key_up, this.key_up); CM.update(Settings.key_down, this.key_down); CM.update(Settings.key_strafeleft, this.key_strafeleft); CM.update(Settings.key_straferight, this.key_straferight); CM.update(Settings.key_fire, this.key_fire); CM.update(Settings.key_use, this.key_use); CM.update(Settings.key_strafe, this.key_strafe); CM.update(Settings.key_speed, this.key_speed); // Mouse buttons CM.update(Settings.use_mouse, this.use_mouse ? 1 : 0); CM.update(Settings.mouseb_fire, this.mousebfire); CM.update(Settings.mouseb_strafe, this.mousebstrafe); CM.update(Settings.mouseb_forward, this.mousebforward); // Joystick CM.update(Settings.use_joystick, this.use_joystick ? 1 : 0); CM.update(Settings.joyb_fire, this.joybfire); CM.update(Settings.joyb_strafe, this.joybstrafe); CM.update(Settings.joyb_use, this.joybuse); CM.update(Settings.joyb_speed, this.joybspeed); // Sound CM.update(Settings.snd_channels, this.numChannels); // Map strobe CM.update(Settings.vestrobe, this.mapstrobe); // Mouse sensitivity CM.update(Settings.mouse_sensitivity, this.mouseSensitivity); } } // $Log: DoomStatus.java,v $ // Revision 1.36 2012/11/06 16:04:58 velktron // Variables manager less tightly integrated. // // Revision 1.35 2012/09/24 17:16:22 velktron // Massive merge between HiColor and HEAD. There's no difference from now on, and development continues on HEAD. // // Revision 1.34.2.3 2012/09/24 16:58:06 velktron // TrueColor, Generics. // // Revision 1.34.2.2 2012/09/20 14:25:13 velktron // Unified DOOM!!! // // Revision 1.34.2.1 2012/09/17 16:06:52 velktron // Now handling updates of all variables, though those specific to some subsystems should probably be moved??? // // Revision 1.34 2011/11/01 23:48:10 velktron // Added tnthom stuff. // // Revision 1.33 2011/10/24 02:11:27 velktron // Stream compliancy // // Revision 1.32 2011/10/07 16:01:16 velktron // Added freelook stuff, using Keys. // // Revision 1.31 2011/09/27 16:01:41 velktron // -complevel_t // // Revision 1.30 2011/09/27 15:54:51 velktron // Added some more prBoom+ stuff. // // Revision 1.29 2011/07/28 17:07:04 velktron // Added always run hack. // // Revision 1.28 2011/07/16 10:57:50 velktron // Merged finnw's changes for enabling polling of ?_LOCK keys. // // Revision 1.27 2011/06/14 20:59:47 velktron // Channel settings now read from default.cfg. Changes in sound creation order. // // Revision 1.26 2011/06/04 11:04:25 velktron // Fixed registered/ultimate identification. // // Revision 1.25 2011/06/01 17:35:56 velktron // Techdemo v1.4a level. Default novert and experimental mochaevents interface. // // Revision 1.24 2011/06/01 00:37:58 velktron // Changed default keys to WASD. // // Revision 1.23 2011/05/31 21:45:51 velktron // Added XBLA version as explicitly supported. // // Revision 1.22 2011/05/30 15:50:42 velktron // Changed to work with new Abstract classes // // Revision 1.21 2011/05/26 17:52:11 velktron // Now using ICommandLineManager // // Revision 1.20 2011/05/26 13:39:52 velktron // Now using ICommandLineManager // // Revision 1.19 2011/05/25 17:56:52 velktron // Introduced some fixes for mousebuttons etc. // // Revision 1.18 2011/05/24 17:44:37 velktron // usemouse added for defaults //
72778_7
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * * @author R. Springer */ public class MyWorld extends World { Hero hero; private CollisionEngine ce; /** * Constructor for objects of class MyWorld. * */ public MyWorld() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(1000, 800, 1, false); this.setBackground("bg.png"); int[][] map = { {666,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,51,-1,-1,51,-1,-1,51,-1,-1,-1,51,-1,-1,51,-1,666}, {666,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,51,-1,-1,51,-1,-1,51,-1,-1,-1,51,-1,-1,51,-1,666}, {666,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,51,-1,-1,51,-1,-1,51,-1,-1,-1,51,-1,-1,51,-1,666}, {666,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,51,-1,-1,51,-1,-1,51,-1,-1,-1,51,-1,-1,51,-1,666}, {666,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,51,-1,-1,51,-1,-1,51,-1,-1,-1,51,-1,-1,51,-1,666}, {666,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,51,-1,-1,51,-1,-1,51,-1,-1,-1,51,-1,-1,51,-1,666}, {666,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,51,-1,-1,51,-1,-1,51,-1,-1,-1,51,-1,-1,51,-1,666}, {666,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,51,-1,-1,51,-1,-1,51,-1,-1,-1,51,-1,-1,51,-1,666}, {666,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,317,-1,-1,317,-1,-1,317,-1,-1,-1,317,-1,-1,317,-1,666}, {666,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,666}, {666,-1,-1,-1,-1,-1,-1,-1,312,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,312,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,312,-1,-1,-1,-1,-1,-1,666}, {666,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,666}, {666,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,95,-1,666}, {666,-1,-1,125,126,126,126,126,126,126,126,126,127,-1,115,-1,-1,-1,115,115,115,-1,-1,115,-1,-1,115,-1,-1,-1,111,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,113,666}, {666,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,666}, {666,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,666}, {666,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,666}, {666,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,666}, {666,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,666}, {306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306}, }; // Declareren en initialiseren van de TileEngine klasse om de map aan de world toe te voegen TileEngine te = new TileEngine(this, 70, 70, map); // Declarenre en initialiseren van de camera klasse met de TileEngine klasse // zodat de camera weet welke tiles allemaal moeten meebewegen met de camera Camera camera = new Camera(te); // Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse // moet de klasse Mover extenden voor de camera om te werken Hero hero = new Hero(); // Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan. camera.follow(hero); // Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies addObject(camera, 0, 0); addObject(hero, 300, 700); addObject(new Enemy(), 600, 897); // Force act zodat de camera op de juist plek staat. camera.act(); hero.act(); // Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen. // De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan. ce = new CollisionEngine(te, camera); // Toevoegen van de mover instantie of een extentie hiervan ce.addCollidingMover(hero); World0.lvl=5; } @Override public void act() { ce.update(); if (hero.isDead==true){ death d = new death(); Greenfoot.setWorld(d); } } }
ROCMondriaanTIN/project-greenfoot-game-Tscholte
MyWorld.java
2,908
// Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse
line_comment
nl
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * * @author R. Springer */ public class MyWorld extends World { Hero hero; private CollisionEngine ce; /** * Constructor for objects of class MyWorld. * */ public MyWorld() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(1000, 800, 1, false); this.setBackground("bg.png"); int[][] map = { {666,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,51,-1,-1,51,-1,-1,51,-1,-1,-1,51,-1,-1,51,-1,666}, {666,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,51,-1,-1,51,-1,-1,51,-1,-1,-1,51,-1,-1,51,-1,666}, {666,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,51,-1,-1,51,-1,-1,51,-1,-1,-1,51,-1,-1,51,-1,666}, {666,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,51,-1,-1,51,-1,-1,51,-1,-1,-1,51,-1,-1,51,-1,666}, {666,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,51,-1,-1,51,-1,-1,51,-1,-1,-1,51,-1,-1,51,-1,666}, {666,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,51,-1,-1,51,-1,-1,51,-1,-1,-1,51,-1,-1,51,-1,666}, {666,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,51,-1,-1,51,-1,-1,51,-1,-1,-1,51,-1,-1,51,-1,666}, {666,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,51,-1,-1,51,-1,-1,51,-1,-1,-1,51,-1,-1,51,-1,666}, {666,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,317,-1,-1,317,-1,-1,317,-1,-1,-1,317,-1,-1,317,-1,666}, {666,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,666}, {666,-1,-1,-1,-1,-1,-1,-1,312,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,312,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,312,-1,-1,-1,-1,-1,-1,666}, {666,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,666}, {666,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,95,-1,666}, {666,-1,-1,125,126,126,126,126,126,126,126,126,127,-1,115,-1,-1,-1,115,115,115,-1,-1,115,-1,-1,115,-1,-1,-1,111,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,126,113,666}, {666,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,666}, {666,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,666}, {666,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,666}, {666,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,666}, {666,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,666}, {306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306}, }; // Declareren en initialiseren van de TileEngine klasse om de map aan de world toe te voegen TileEngine te = new TileEngine(this, 70, 70, map); // Declarenre en initialiseren van de camera klasse met de TileEngine klasse // zodat de camera weet welke tiles allemaal moeten meebewegen met de camera Camera camera = new Camera(te); // Declareren en<SUF> // moet de klasse Mover extenden voor de camera om te werken Hero hero = new Hero(); // Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan. camera.follow(hero); // Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies addObject(camera, 0, 0); addObject(hero, 300, 700); addObject(new Enemy(), 600, 897); // Force act zodat de camera op de juist plek staat. camera.act(); hero.act(); // Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen. // De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan. ce = new CollisionEngine(te, camera); // Toevoegen van de mover instantie of een extentie hiervan ce.addCollidingMover(hero); World0.lvl=5; } @Override public void act() { ce.update(); if (hero.isDead==true){ death d = new death(); Greenfoot.setWorld(d); } } }
4768_17
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * * @author R. Springer */ public class Lvl2 extends World{ private CollisionEngine ce; /** * Constructor for objects of class MyWorld. * */ public Lvl2() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(1000, 800, 1, false); this.setBackground("bg.png"); int[][] map = { {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,61,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,60,-1,-1,-1,126,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,75,82,82,82,82,82,82,82,82,82}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,75,76,65,65,65,65,65,65,65,65,65}, {-1,-1,-1,168,169,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,75,76,65,65,65,65,65,65,65,65,65,65}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,75,76,65,65,65,65,65,65,65,65,65,65,65}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,75,76,65,65,65,65,65,65,65,65,65,65,65,65}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,75,76,65,65,65,65,65,65,65,65,65,65,65,65,65}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,75,76,65,65,65,65,65,65,65,65,65,65,65,65,65,65}, {-1,-1,-1,71,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,65,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,65,-1,-1,-1,-1,-1,-1}, {71,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,61,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,71,-1,-1,-1,-1,-1,-1,-1,-1,71,-1,-1,-1,-1,-1,-1,-1,-1,-1,98,-1,-1,-1,60,-1,-1,-1}, {82,89,82,82,82,82,82,82,82,82,82,92,92,92,92,92,82,82,82,82,95,95,95,95,95,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82}, {65,88,-1,-1,-1,65,65,65,65,65,65,90,90,90,90,90,65,65,65,65,93,93,93,93,93,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65}, {65,88,-1,-1,211,65,65,65,65,65,65,90,90,90,90,90,65,65,65,65,93,93,93,93,93,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65}, {65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65}, }; // Declareren en initialiseren van de TileEngine klasse om de map aan de world toe te voegen TileEngine te = new TileEngine(this, 70, 70, map); // Declarenre en initialiseren van de camera klasse met de TileEngine klasse // zodat de camera weet welke tiles allemaal moeten meebewegen met de camera Camera camera = new Camera(te); // Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse // moet de klasse Mover extenden voor de camera om te werken Hero hero = new Hero(); // Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan. camera.follow(hero); // Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies addObject(camera, 0, 0); addObject(hero, 1000,1100); //addObject(new Enemy(), 1170, 410); // spawnpoint (235, 4780); // spawnpoint 1 (3381,3803); addObject (new NextDoors(), 235,4780); // Force act zodat de camera op de juist plek staat. camera.act(); hero.act(); // Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen. // De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan. ce = new CollisionEngine(te, camera); // Toevoegen van de mover instantie of een extentie hiervan ce.addCollidingMover(hero); prepare(); } @Override public void act() { ce.update(); } private void prepare() { Checkpoint checkpoint = new Checkpoint(); addObject(checkpoint,3381,3803); Checkpoint checkpoint2 = new Checkpoint(); addObject(checkpoint2, 3331,3803); checkpoint.setLocation(3381,3803); Checkpoint checkpoint3 = new Checkpoint(); addObject(checkpoint3,310,693); Door1 door1 = new Door1(); addObject(door1,311,527); removeObject(door1); removeObject(checkpoint3); removeObject(checkpoint); } }
ROCMondriaanTIN/project-greenfoot-game-302403124
Lvl2.java
2,636
// Toevoegen van de mover instantie of een extentie hiervan
line_comment
nl
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * * @author R. Springer */ public class Lvl2 extends World{ private CollisionEngine ce; /** * Constructor for objects of class MyWorld. * */ public Lvl2() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(1000, 800, 1, false); this.setBackground("bg.png"); int[][] map = { {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,61,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,60,-1,-1,-1,126,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,75,82,82,82,82,82,82,82,82,82}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,75,76,65,65,65,65,65,65,65,65,65}, {-1,-1,-1,168,169,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,75,76,65,65,65,65,65,65,65,65,65,65}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,75,76,65,65,65,65,65,65,65,65,65,65,65}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,75,76,65,65,65,65,65,65,65,65,65,65,65,65}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,75,76,65,65,65,65,65,65,65,65,65,65,65,65,65}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,75,76,65,65,65,65,65,65,65,65,65,65,65,65,65,65}, {-1,-1,-1,71,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,65,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,65,-1,-1,-1,-1,-1,-1}, {71,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,61,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,71,-1,-1,-1,-1,-1,-1,-1,-1,71,-1,-1,-1,-1,-1,-1,-1,-1,-1,98,-1,-1,-1,60,-1,-1,-1}, {82,89,82,82,82,82,82,82,82,82,82,92,92,92,92,92,82,82,82,82,95,95,95,95,95,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82}, {65,88,-1,-1,-1,65,65,65,65,65,65,90,90,90,90,90,65,65,65,65,93,93,93,93,93,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65}, {65,88,-1,-1,211,65,65,65,65,65,65,90,90,90,90,90,65,65,65,65,93,93,93,93,93,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65}, {65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65,65}, }; // Declareren en initialiseren van de TileEngine klasse om de map aan de world toe te voegen TileEngine te = new TileEngine(this, 70, 70, map); // Declarenre en initialiseren van de camera klasse met de TileEngine klasse // zodat de camera weet welke tiles allemaal moeten meebewegen met de camera Camera camera = new Camera(te); // Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse // moet de klasse Mover extenden voor de camera om te werken Hero hero = new Hero(); // Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan. camera.follow(hero); // Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies addObject(camera, 0, 0); addObject(hero, 1000,1100); //addObject(new Enemy(), 1170, 410); // spawnpoint (235, 4780); // spawnpoint 1 (3381,3803); addObject (new NextDoors(), 235,4780); // Force act zodat de camera op de juist plek staat. camera.act(); hero.act(); // Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen. // De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan. ce = new CollisionEngine(te, camera); // Toevoegen van<SUF> ce.addCollidingMover(hero); prepare(); } @Override public void act() { ce.update(); } private void prepare() { Checkpoint checkpoint = new Checkpoint(); addObject(checkpoint,3381,3803); Checkpoint checkpoint2 = new Checkpoint(); addObject(checkpoint2, 3331,3803); checkpoint.setLocation(3381,3803); Checkpoint checkpoint3 = new Checkpoint(); addObject(checkpoint3,310,693); Door1 door1 = new Door1(); addObject(door1,311,527); removeObject(door1); removeObject(checkpoint3); removeObject(checkpoint); } }
131339_1
package controller.containing; /** * class.Container * @author Niels Riemersma */ public class Container { private int id; /* * Dimensies voor buitenkant van de container */ private float length = 1.2192f; private float width = 0.2438f; private float height = 0.2393f; /* * Aankomst van container * - Datum en tijd (tijd 1 en 2) * - Vervoersbedrijf en typevervoer * - Aankomst positie (XYZ) */ private String dateArrive; private double timeArrive1; private double timeArrive2; private String vehicleArrive; private String companyArrive; //COORDINATEN private int xLoc; private int yLoc; private int zLoc; /* * Vertrek van container * - Datum en tijd (tijd 1 en 2) * - Vervoersbedrijf en typevervoer */ private String dateDept; private double timeDept1; private double timeDept2; private String vehicleDept; private String companyDept; /* * Container informatie * - Eigenaar (naam) * - Containernummer * - Gewicht (leeg/vol) * - Inhoud (content, type, danger) * - ISO Code */ private String ownerCont; private int idCont; private int weightCont; private String contentCont; private String contentTypeCont; private String contentDangerCont; private String isoCode; /** * Container attributes * @param id * @param dateArrive * @param timeArrive1 * @param timeArrive2 * @param vehicleArrive * @param companyArrive * @param xLoc * @param yLoc * @param zLoc * @param dateDept * @param timeDept1 * @param timeDept2 * @param vehicleDept * @param companyDept * @param ownerCont * @param idCont * @param weightCont * @param contentCont * @param contentTypeCont * @param contentDangerCont * @param isoCode */ public Container(int id, String dateArrive, double timeArrive1, double timeArrive2, String vehicleArrive, String companyArrive, int xLoc, int yLoc, int zLoc, String dateDept, double timeDept1, double timeDept2, String vehicleDept, String companyDept, String ownerCont, int idCont, int weightCont, String contentCont, String contentTypeCont, String contentDangerCont, String isoCode) { this.id = id; this.dateArrive = dateArrive; this.timeArrive1 = timeArrive1; this.timeArrive2 = timeArrive2; this.vehicleArrive = vehicleArrive; this.companyArrive = companyArrive; this.xLoc = xLoc; this.yLoc = yLoc; this.zLoc = zLoc; this.dateDept = dateDept; this.timeDept1 = timeDept1; this.timeDept2 = timeDept2; this.vehicleDept = vehicleDept; this.companyDept = companyDept; this.ownerCont = ownerCont; this.idCont = idCont; this.weightCont = weightCont; this.contentCont = contentCont; this.contentTypeCont = contentTypeCont; this.contentDangerCont = contentDangerCont; this.isoCode = isoCode; } @Override public String toString() { return "[" + Container.class.getSimpleName() + " " +id + " " + dateArrive + " " + timeArrive1 + " " + timeArrive2 + " " + vehicleArrive + " " + companyArrive+ " " + xLoc + " " + yLoc + " " + zLoc + " " + dateDept + " " + timeDept1 + " " + timeDept2 + " " + vehicleDept + " " + companyDept + " " + ownerCont + " " + idCont + " " + weightCont + " " + contentCont + " " + contentTypeCont + " " + contentDangerCont + " " + isoCode+ "]"; } /** * returns type of transport (for example: "vrachtwagen") * @return */ public String getVervoerder() { return this.vehicleArrive; } /** * returns .x * @return */ public int getxLoc(){ return this.xLoc; } /** * returns .y * @return */ public int getyLoc(){ return this.yLoc; } /** * returns .z * @return */ public int getzLoc(){ return this.zLoc; } /** * returns id * @return */ public int getID(){ return this.id; } }
Desutoroiya/Containing
Controller Containing/src/controller/containing/Container.java
1,277
/* * Dimensies voor buitenkant van de container */
block_comment
nl
package controller.containing; /** * class.Container * @author Niels Riemersma */ public class Container { private int id; /* * Dimensies voor buitenkant<SUF>*/ private float length = 1.2192f; private float width = 0.2438f; private float height = 0.2393f; /* * Aankomst van container * - Datum en tijd (tijd 1 en 2) * - Vervoersbedrijf en typevervoer * - Aankomst positie (XYZ) */ private String dateArrive; private double timeArrive1; private double timeArrive2; private String vehicleArrive; private String companyArrive; //COORDINATEN private int xLoc; private int yLoc; private int zLoc; /* * Vertrek van container * - Datum en tijd (tijd 1 en 2) * - Vervoersbedrijf en typevervoer */ private String dateDept; private double timeDept1; private double timeDept2; private String vehicleDept; private String companyDept; /* * Container informatie * - Eigenaar (naam) * - Containernummer * - Gewicht (leeg/vol) * - Inhoud (content, type, danger) * - ISO Code */ private String ownerCont; private int idCont; private int weightCont; private String contentCont; private String contentTypeCont; private String contentDangerCont; private String isoCode; /** * Container attributes * @param id * @param dateArrive * @param timeArrive1 * @param timeArrive2 * @param vehicleArrive * @param companyArrive * @param xLoc * @param yLoc * @param zLoc * @param dateDept * @param timeDept1 * @param timeDept2 * @param vehicleDept * @param companyDept * @param ownerCont * @param idCont * @param weightCont * @param contentCont * @param contentTypeCont * @param contentDangerCont * @param isoCode */ public Container(int id, String dateArrive, double timeArrive1, double timeArrive2, String vehicleArrive, String companyArrive, int xLoc, int yLoc, int zLoc, String dateDept, double timeDept1, double timeDept2, String vehicleDept, String companyDept, String ownerCont, int idCont, int weightCont, String contentCont, String contentTypeCont, String contentDangerCont, String isoCode) { this.id = id; this.dateArrive = dateArrive; this.timeArrive1 = timeArrive1; this.timeArrive2 = timeArrive2; this.vehicleArrive = vehicleArrive; this.companyArrive = companyArrive; this.xLoc = xLoc; this.yLoc = yLoc; this.zLoc = zLoc; this.dateDept = dateDept; this.timeDept1 = timeDept1; this.timeDept2 = timeDept2; this.vehicleDept = vehicleDept; this.companyDept = companyDept; this.ownerCont = ownerCont; this.idCont = idCont; this.weightCont = weightCont; this.contentCont = contentCont; this.contentTypeCont = contentTypeCont; this.contentDangerCont = contentDangerCont; this.isoCode = isoCode; } @Override public String toString() { return "[" + Container.class.getSimpleName() + " " +id + " " + dateArrive + " " + timeArrive1 + " " + timeArrive2 + " " + vehicleArrive + " " + companyArrive+ " " + xLoc + " " + yLoc + " " + zLoc + " " + dateDept + " " + timeDept1 + " " + timeDept2 + " " + vehicleDept + " " + companyDept + " " + ownerCont + " " + idCont + " " + weightCont + " " + contentCont + " " + contentTypeCont + " " + contentDangerCont + " " + isoCode+ "]"; } /** * returns type of transport (for example: "vrachtwagen") * @return */ public String getVervoerder() { return this.vehicleArrive; } /** * returns .x * @return */ public int getxLoc(){ return this.xLoc; } /** * returns .y * @return */ public int getyLoc(){ return this.yLoc; } /** * returns .z * @return */ public int getzLoc(){ return this.zLoc; } /** * returns id * @return */ public int getID(){ return this.id; } }
27391_1
package w3.p2; import java.time.LocalDate; public class Main { public static void main(String[] args) { int releaseJaar1 = LocalDate.now().getYear() - 1; // 1 jaar geleden int releaseJaar2 = LocalDate.now().getYear() - 2; // 2 jaar geleden Game g1 = new Game("Just Cause 3", releaseJaar1, 49.98); Game g2 = new Game("Need for Speed: Rivals", releaseJaar2, 45.99); Game g3 = new Game("Need for Speed: Rivals", releaseJaar2, 45.99); Persoon p1 = new Persoon("Eric", 200); Persoon p2 = new Persoon("Hans", 55); Persoon p3 = new Persoon("Arno", 185); System.out.println("p1 koopt g1:" + (p1.koop(g1) ? "" : " niet") + " gelukt"); System.out.println("p1 koopt g2:" + (p1.koop(g2) ? "" : " niet") + " gelukt"); System.out.println("p1 koopt g3:" + (p1.koop(g3) ? "" : " niet") + " gelukt"); System.out.println("p2 koopt g2:" + (p2.koop(g2) ? "" : " niet") + " gelukt"); System.out.println("p2 koopt g1:" + (p2.koop(g1) ? "" : " niet") + " gelukt"); System.out.println("p3 koopt g3:" + (p3.koop(g3) ? "" : " niet") + " gelukt"); System.out.println("\np1: " +p1+ "\n\np2: " +p2+ "\n\np3: " +p3+ "\n"); System.out.println("p1 verkoopt g1 aan p3:"+(p1.verkoop(g1, p3) ? "" : " niet")+" gelukt"); System.out.println("p2 verkoopt g2 aan p3:"+(p2.verkoop(g2, p3) ? "" : " niet")+" gelukt"); System.out.println("p2 verkoopt g1 aan p1:"+(p2.verkoop(g1, p1) ? "" : " niet")+" gelukt"); System.out.println("\np1: " +p1+ "\n\np2: " +p2+ "\n\np3: " +p3+ "\n"); } }
dsluijk/V1OODC-15
practicums/w3/p2/src/Main.java
643
// 2 jaar geleden
line_comment
nl
package w3.p2; import java.time.LocalDate; public class Main { public static void main(String[] args) { int releaseJaar1 = LocalDate.now().getYear() - 1; // 1 jaar geleden int releaseJaar2 = LocalDate.now().getYear() - 2; // 2 jaar<SUF> Game g1 = new Game("Just Cause 3", releaseJaar1, 49.98); Game g2 = new Game("Need for Speed: Rivals", releaseJaar2, 45.99); Game g3 = new Game("Need for Speed: Rivals", releaseJaar2, 45.99); Persoon p1 = new Persoon("Eric", 200); Persoon p2 = new Persoon("Hans", 55); Persoon p3 = new Persoon("Arno", 185); System.out.println("p1 koopt g1:" + (p1.koop(g1) ? "" : " niet") + " gelukt"); System.out.println("p1 koopt g2:" + (p1.koop(g2) ? "" : " niet") + " gelukt"); System.out.println("p1 koopt g3:" + (p1.koop(g3) ? "" : " niet") + " gelukt"); System.out.println("p2 koopt g2:" + (p2.koop(g2) ? "" : " niet") + " gelukt"); System.out.println("p2 koopt g1:" + (p2.koop(g1) ? "" : " niet") + " gelukt"); System.out.println("p3 koopt g3:" + (p3.koop(g3) ? "" : " niet") + " gelukt"); System.out.println("\np1: " +p1+ "\n\np2: " +p2+ "\n\np3: " +p3+ "\n"); System.out.println("p1 verkoopt g1 aan p3:"+(p1.verkoop(g1, p3) ? "" : " niet")+" gelukt"); System.out.println("p2 verkoopt g2 aan p3:"+(p2.verkoop(g2, p3) ? "" : " niet")+" gelukt"); System.out.println("p2 verkoopt g1 aan p1:"+(p2.verkoop(g1, p1) ? "" : " niet")+" gelukt"); System.out.println("\np1: " +p1+ "\n\np2: " +p2+ "\n\np3: " +p3+ "\n"); } }
109792_1
package cs4551.homework3.utils; public class ArrayUtils { private static class ZigZagEnumerationState { boolean edgeHit = false; boolean nextMove = true; // true = up right, false = down left; int x = 0, y = 0, index = 0; } /** Enumerate an integer array in zig-zag order. */ public static int[] enumerateArray(int[][] arr) { // TODO Check if any dimension of the input array is 0; int width = arr.length; int height = arr[0].length; int[] result = new int[width * height]; ZigZagEnumerationState state = new ZigZagEnumerationState(); do { result[state.index++] = arr[state.x][state.y]; } while (!navigateZigZag(state, width, height)); return result; } /** Rebuilds a 2D array from a 1D array that was enumerated in zig-zag order. */ public static int[][] rebuildArray(int[] values, int width, int height) throws Exception { if (values.length < width * height) { throw new Exception("Not enough values to rebuild array!"); } int[][] result = new int[width][height]; ZigZagEnumerationState state = new ZigZagEnumerationState(); do { result[state.x][state.y] = values[state.index++]; } while (!navigateZigZag(state, width, height)); return result; } /** Converts a Boolean array to a boolean array. */ public static boolean[] convertBooleanArray(Boolean[] bits) { boolean[] _bits = new boolean[bits.length]; for (int i = 0; i < bits.length; i++) { _bits[i] = bits[i]; } return _bits; } /** Converts a boolean array to a Boolean array. */ public static Boolean[] convertBooleanArray(boolean[] bits) { Boolean[] _bits = new Boolean[bits.length]; for (int i = 0; i < bits.length; i++) { _bits[i] = bits[i]; } return _bits; } /** Helper method for navigation through an array in zig-zag pattern. */ private static boolean navigateZigZag(ZigZagEnumerationState state, int width, int height) { // System.out.println(state.x + ", " + state.y); // Reached the end if (state.x == width - 1 && state.y == height - 1) { return true; } // If at the boundary... if (state.x == 0 || state.x == width - 1 || state.y == 0 || state.y == height - 1) { // If it wasn't at the boundary during the previous step... if (!state.edgeHit) { if ((state.y == 0 || state.y == height - 1) && state.x != width -1) { state.x++; } else if (state.x == 0 || state.x == width - 1) { state.y++; } state.edgeHit = true; // Mark boundary as being encountered during this step. return false; } // If it was already at the boundary during the previous step, then change directions. else { state.nextMove = !state.nextMove; state.edgeHit = false; } } // Move position if (state.nextMove) { state.x++; state.y--; } else { state.x--; state.y++; } return false; } }
alvinquach/cs4551
Homework 3/src/cs4551/homework3/utils/ArrayUtils.java
959
/** Enumerate an integer array in zig-zag order. */
block_comment
nl
package cs4551.homework3.utils; public class ArrayUtils { private static class ZigZagEnumerationState { boolean edgeHit = false; boolean nextMove = true; // true = up right, false = down left; int x = 0, y = 0, index = 0; } /** Enumerate an integer<SUF>*/ public static int[] enumerateArray(int[][] arr) { // TODO Check if any dimension of the input array is 0; int width = arr.length; int height = arr[0].length; int[] result = new int[width * height]; ZigZagEnumerationState state = new ZigZagEnumerationState(); do { result[state.index++] = arr[state.x][state.y]; } while (!navigateZigZag(state, width, height)); return result; } /** Rebuilds a 2D array from a 1D array that was enumerated in zig-zag order. */ public static int[][] rebuildArray(int[] values, int width, int height) throws Exception { if (values.length < width * height) { throw new Exception("Not enough values to rebuild array!"); } int[][] result = new int[width][height]; ZigZagEnumerationState state = new ZigZagEnumerationState(); do { result[state.x][state.y] = values[state.index++]; } while (!navigateZigZag(state, width, height)); return result; } /** Converts a Boolean array to a boolean array. */ public static boolean[] convertBooleanArray(Boolean[] bits) { boolean[] _bits = new boolean[bits.length]; for (int i = 0; i < bits.length; i++) { _bits[i] = bits[i]; } return _bits; } /** Converts a boolean array to a Boolean array. */ public static Boolean[] convertBooleanArray(boolean[] bits) { Boolean[] _bits = new Boolean[bits.length]; for (int i = 0; i < bits.length; i++) { _bits[i] = bits[i]; } return _bits; } /** Helper method for navigation through an array in zig-zag pattern. */ private static boolean navigateZigZag(ZigZagEnumerationState state, int width, int height) { // System.out.println(state.x + ", " + state.y); // Reached the end if (state.x == width - 1 && state.y == height - 1) { return true; } // If at the boundary... if (state.x == 0 || state.x == width - 1 || state.y == 0 || state.y == height - 1) { // If it wasn't at the boundary during the previous step... if (!state.edgeHit) { if ((state.y == 0 || state.y == height - 1) && state.x != width -1) { state.x++; } else if (state.x == 0 || state.x == width - 1) { state.y++; } state.edgeHit = true; // Mark boundary as being encountered during this step. return false; } // If it was already at the boundary during the previous step, then change directions. else { state.nextMove = !state.nextMove; state.edgeHit = false; } } // Move position if (state.nextMove) { state.x++; state.y--; } else { state.x--; state.y++; } return false; } }
88552_13
/* * www.yiji.com Inc. * Copyright (c) 2016 All Rights Reserved */ package com.yiji.falcon.agent.config; import com.yiji.falcon.agent.util.StringUtils; import lombok.Getter; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; /* * 修订记录: * [email protected] 2016-06-22 17:48 创建 */ /** * 系统配置 * @author [email protected] */ @Getter public enum AgentConfiguration { INSTANCE; //版本不能大于 x.9 public static final float VERSION = (float) 11.8; /** * quartz配置文件路径 */ private String quartzConfPath = null; /** * push到falcon的地址 */ private String agentPushUrl = null; /** * 插件配置的目录 */ private String pluginConfPath; /** * 授权配置文件路径 */ private String authorizationConfPath; /** * 集成的Falcon文件夹路径 */ private String falconDir; /** * Falcon的配置文件目录路径 */ private String falconConfDir; /** * 服务配置文件路径 */ private String agentConfPath = null; private String jmxCommonMetricsConfPath = null; /** * agent监控指标的主体说明 */ private String agentEndpoint = ""; /** * agent启动端口 */ private int agentPort = 4518; /** * mock的有效时间 */ private int mockValidTime = 10800; /** * agent web 监听端口 */ private int agentWebPort = 4519; /** * 是否启用web服务 */ private boolean webEnable = true; /** * agent自动发现服务刷新周期 */ private int agentFlushTime = 300; /** * agent最大线程数 */ private int agentMaxThreadCount = 200; /** * JMX连接是否支持本地连接 */ private boolean agentJMXLocalConnect = false; private String agentUpdateUrl = null; private String agentHomeDir; private static final String CONF_AGENT_ENDPOINT = "agent.endpoint"; private static final String CONF_AGENT_HOME = "agent.home.dir"; private static final String CONF_AGENT_FLUSH_TIME = "agent.flush.time"; private static final String CONF_AGENT_MAX_THREAD = "agent.thread.maxCount"; private static final String CONF_AGENT_FALCON_PUSH_URL = "agent.falcon.push.url"; private static final String CONF_AGENT_PORT = "agent.port"; private static final String CONF_AGENT_WEB_PORT = "agent.web.port"; private static final String CONF_AGENT_WEB_ENABLE = "agent.web.enable"; private static final String CONF_AGENT_MOCK_VALID_TIME = "agent.mock.valid.time"; private static final String AUTHORIZATION_CONF_PATH = "authorization.conf.path"; private static final String FALCON_DIR_PATH = "agent.falcon.dir"; private static final String FALCON_CONF_DIR_PATH = "agent.falcon.conf.dir"; private static final String CONF_AGENT_JMX_LOCAL_CONNECT = "agent.jmx.localConnectSupport"; private static final String CONF_AGENT_UPDATE_URL = "agent.update.pack.url"; private Properties agentConf = null; /** * 初始化agent配置 */ AgentConfiguration() { instance(); } private void instance(){ if(StringUtils.isEmpty(System.getProperty("agent.conf.path"))){ System.err.println("agent agent.properties 配置文件位置读取失败,请确定系统配置项:" + "agent.conf.path"); System.exit(0); }else{ this.agentConfPath = System.getProperty("agent.conf.path"); } if(StringUtils.isEmpty(System.getProperty(CONF_AGENT_HOME))){ System.err.println("agent home dir 读取失败,请确定系统配置项:" + CONF_AGENT_HOME); System.exit(0); }else{ this.agentHomeDir = System.getProperty(CONF_AGENT_HOME); } if(StringUtils.isEmpty(System.getProperty(AUTHORIZATION_CONF_PATH))){ System.err.println("agent authorization.properties 配置文件位置读取失败,请确定系统配置项:" + AUTHORIZATION_CONF_PATH); System.exit(0); }else{ this.authorizationConfPath = System.getProperty(AUTHORIZATION_CONF_PATH); } if(StringUtils.isEmpty(System.getProperty(FALCON_DIR_PATH))){ System.err.println("falcon 目录位置读取失败,请确定系统配置项:" + FALCON_DIR_PATH); System.exit(0); }else{ this.falconDir = System.getProperty(FALCON_DIR_PATH); } if(StringUtils.isEmpty(System.getProperty(FALCON_CONF_DIR_PATH))){ System.err.println("falcon conf 目录位置读取失败,请确定系统配置项:" + FALCON_CONF_DIR_PATH); System.exit(0); }else{ this.falconConfDir = System.getProperty(FALCON_CONF_DIR_PATH); } if(StringUtils.isEmpty(System.getProperty("agent.plugin.conf.dir"))){ System.err.println("agent 配置文件位置读取失败,请确定系统配置项:" + "agent.plugin.conf.dir"); System.exit(0); }else{ this.pluginConfPath = System.getProperty("agent.plugin.conf.dir"); } if(StringUtils.isEmpty(System.getProperty("agent.quartz.conf.path"))){ System.err.println("quartz 配置文件位置读取失败,请确定系统配置项:" + "agent.quartz.conf.path"); System.exit(0); }else{ this.quartzConfPath = System.getProperty("agent.quartz.conf.path"); } agentConf = new Properties(); try(FileInputStream in = new FileInputStream(this.agentConfPath)){ agentConf.load(in); }catch (IOException e) { System.err.println(this.agentConfPath + " 配置文件读取失败 Agent启动失败"); System.exit(0); } init(); initJMXCommon(); } private void init(){ if(!StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_ENDPOINT))){ this.agentEndpoint = agentConf.getProperty(CONF_AGENT_ENDPOINT); } if(!StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_WEB_PORT))){ try { this.agentWebPort = Integer.parseInt(agentConf.getProperty(CONF_AGENT_WEB_PORT)); } catch (Exception e) { System.err.println(String.format("Agent启动失败,端口配置%s无效:%s", CONF_AGENT_WEB_PORT, agentConf.getProperty(CONF_AGENT_WEB_PORT))); System.exit(0); } } if(!StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_WEB_ENABLE))){ this.webEnable = "true".equals(agentConf.getProperty(CONF_AGENT_WEB_ENABLE)); } if(!StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_MOCK_VALID_TIME))){ try { this.mockValidTime = Integer.parseInt(agentConf.getProperty(CONF_AGENT_MOCK_VALID_TIME)); } catch (NumberFormatException e) { System.err.println(String.format("Agent启动失败,mock有效时间配置 %s 无效: %s", CONF_AGENT_MOCK_VALID_TIME, agentConf.getProperty(CONF_AGENT_MOCK_VALID_TIME))); System.exit(0); } } if(!StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_JMX_LOCAL_CONNECT))){ this.agentJMXLocalConnect = "true".equals(agentConf.getProperty(CONF_AGENT_JMX_LOCAL_CONNECT)); } if(!StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_UPDATE_URL))){ this.agentUpdateUrl = agentConf.getProperty(CONF_AGENT_UPDATE_URL); } if(!StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_PORT))){ try { this.agentPort = Integer.parseInt(agentConf.getProperty(CONF_AGENT_PORT)); } catch (NumberFormatException e) { System.err.println(String.format("Agent启动失败,端口配置%s无效:%s", CONF_AGENT_PORT, agentConf.getProperty(CONF_AGENT_PORT))); System.exit(0); } } if(StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_FALCON_PUSH_URL))){ System.err.println("Agent启动失败,未定义falcon push地址配置:" + CONF_AGENT_FALCON_PUSH_URL); System.exit(0); } this.agentPushUrl = agentConf.getProperty(CONF_AGENT_FALCON_PUSH_URL); if(StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_FLUSH_TIME))){ System.err.println("Agent启动失败,未指定配置:" + CONF_AGENT_FLUSH_TIME); System.exit(0); } try { this.agentFlushTime = Integer.parseInt(agentConf.getProperty(CONF_AGENT_FLUSH_TIME)); if(this.agentFlushTime <= 0){ System.err.println(String.format("Agent启动失败,自动发现服务的刷新周期配置 %s 必须大于0: %s",CONF_AGENT_FLUSH_TIME,agentConf.getProperty(CONF_AGENT_FLUSH_TIME))); System.exit(0); } } catch (NumberFormatException e) { System.err.println(String.format("Agent启动失败,自动发现服务的刷新周期配置%s无效:%s",CONF_AGENT_FLUSH_TIME,agentConf.getProperty(CONF_AGENT_FLUSH_TIME))); System.exit(0); } if(!StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_MAX_THREAD))){ try { this.agentMaxThreadCount = Integer.parseInt(agentConf.getProperty(CONF_AGENT_MAX_THREAD)); if(this.agentMaxThreadCount <= 5){ System.err.println(String.format("Agent启动失败,最大线程数 %s 必须大于5: %s",CONF_AGENT_MAX_THREAD,agentConf.getProperty(CONF_AGENT_MAX_THREAD))); System.exit(0); } } catch (NumberFormatException e) { System.err.println(String.format("Agent启动失败,最大线程数%s无效:%s",CONF_AGENT_MAX_THREAD,agentConf.getProperty(CONF_AGENT_MAX_THREAD))); System.exit(0); } } } private void initJMXCommon(){ String property = System.getProperty("agent.jmx.metrics.common.path"); if(StringUtils.isEmpty(property)){ System.err.println("jmx 的公共配置系统属性文件未定义:agent.jmx.metrics.common.path"); System.exit(0); } this.jmxCommonMetricsConfPath = property; } }
cqyijifu/OpenFalcon-SuitAgent
src/main/java/com/yiji/falcon/agent/config/AgentConfiguration.java
2,785
/** * agent web 监听端口 */
block_comment
nl
/* * www.yiji.com Inc. * Copyright (c) 2016 All Rights Reserved */ package com.yiji.falcon.agent.config; import com.yiji.falcon.agent.util.StringUtils; import lombok.Getter; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; /* * 修订记录: * [email protected] 2016-06-22 17:48 创建 */ /** * 系统配置 * @author [email protected] */ @Getter public enum AgentConfiguration { INSTANCE; //版本不能大于 x.9 public static final float VERSION = (float) 11.8; /** * quartz配置文件路径 */ private String quartzConfPath = null; /** * push到falcon的地址 */ private String agentPushUrl = null; /** * 插件配置的目录 */ private String pluginConfPath; /** * 授权配置文件路径 */ private String authorizationConfPath; /** * 集成的Falcon文件夹路径 */ private String falconDir; /** * Falcon的配置文件目录路径 */ private String falconConfDir; /** * 服务配置文件路径 */ private String agentConfPath = null; private String jmxCommonMetricsConfPath = null; /** * agent监控指标的主体说明 */ private String agentEndpoint = ""; /** * agent启动端口 */ private int agentPort = 4518; /** * mock的有效时间 */ private int mockValidTime = 10800; /** * agent web 监听端口<SUF>*/ private int agentWebPort = 4519; /** * 是否启用web服务 */ private boolean webEnable = true; /** * agent自动发现服务刷新周期 */ private int agentFlushTime = 300; /** * agent最大线程数 */ private int agentMaxThreadCount = 200; /** * JMX连接是否支持本地连接 */ private boolean agentJMXLocalConnect = false; private String agentUpdateUrl = null; private String agentHomeDir; private static final String CONF_AGENT_ENDPOINT = "agent.endpoint"; private static final String CONF_AGENT_HOME = "agent.home.dir"; private static final String CONF_AGENT_FLUSH_TIME = "agent.flush.time"; private static final String CONF_AGENT_MAX_THREAD = "agent.thread.maxCount"; private static final String CONF_AGENT_FALCON_PUSH_URL = "agent.falcon.push.url"; private static final String CONF_AGENT_PORT = "agent.port"; private static final String CONF_AGENT_WEB_PORT = "agent.web.port"; private static final String CONF_AGENT_WEB_ENABLE = "agent.web.enable"; private static final String CONF_AGENT_MOCK_VALID_TIME = "agent.mock.valid.time"; private static final String AUTHORIZATION_CONF_PATH = "authorization.conf.path"; private static final String FALCON_DIR_PATH = "agent.falcon.dir"; private static final String FALCON_CONF_DIR_PATH = "agent.falcon.conf.dir"; private static final String CONF_AGENT_JMX_LOCAL_CONNECT = "agent.jmx.localConnectSupport"; private static final String CONF_AGENT_UPDATE_URL = "agent.update.pack.url"; private Properties agentConf = null; /** * 初始化agent配置 */ AgentConfiguration() { instance(); } private void instance(){ if(StringUtils.isEmpty(System.getProperty("agent.conf.path"))){ System.err.println("agent agent.properties 配置文件位置读取失败,请确定系统配置项:" + "agent.conf.path"); System.exit(0); }else{ this.agentConfPath = System.getProperty("agent.conf.path"); } if(StringUtils.isEmpty(System.getProperty(CONF_AGENT_HOME))){ System.err.println("agent home dir 读取失败,请确定系统配置项:" + CONF_AGENT_HOME); System.exit(0); }else{ this.agentHomeDir = System.getProperty(CONF_AGENT_HOME); } if(StringUtils.isEmpty(System.getProperty(AUTHORIZATION_CONF_PATH))){ System.err.println("agent authorization.properties 配置文件位置读取失败,请确定系统配置项:" + AUTHORIZATION_CONF_PATH); System.exit(0); }else{ this.authorizationConfPath = System.getProperty(AUTHORIZATION_CONF_PATH); } if(StringUtils.isEmpty(System.getProperty(FALCON_DIR_PATH))){ System.err.println("falcon 目录位置读取失败,请确定系统配置项:" + FALCON_DIR_PATH); System.exit(0); }else{ this.falconDir = System.getProperty(FALCON_DIR_PATH); } if(StringUtils.isEmpty(System.getProperty(FALCON_CONF_DIR_PATH))){ System.err.println("falcon conf 目录位置读取失败,请确定系统配置项:" + FALCON_CONF_DIR_PATH); System.exit(0); }else{ this.falconConfDir = System.getProperty(FALCON_CONF_DIR_PATH); } if(StringUtils.isEmpty(System.getProperty("agent.plugin.conf.dir"))){ System.err.println("agent 配置文件位置读取失败,请确定系统配置项:" + "agent.plugin.conf.dir"); System.exit(0); }else{ this.pluginConfPath = System.getProperty("agent.plugin.conf.dir"); } if(StringUtils.isEmpty(System.getProperty("agent.quartz.conf.path"))){ System.err.println("quartz 配置文件位置读取失败,请确定系统配置项:" + "agent.quartz.conf.path"); System.exit(0); }else{ this.quartzConfPath = System.getProperty("agent.quartz.conf.path"); } agentConf = new Properties(); try(FileInputStream in = new FileInputStream(this.agentConfPath)){ agentConf.load(in); }catch (IOException e) { System.err.println(this.agentConfPath + " 配置文件读取失败 Agent启动失败"); System.exit(0); } init(); initJMXCommon(); } private void init(){ if(!StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_ENDPOINT))){ this.agentEndpoint = agentConf.getProperty(CONF_AGENT_ENDPOINT); } if(!StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_WEB_PORT))){ try { this.agentWebPort = Integer.parseInt(agentConf.getProperty(CONF_AGENT_WEB_PORT)); } catch (Exception e) { System.err.println(String.format("Agent启动失败,端口配置%s无效:%s", CONF_AGENT_WEB_PORT, agentConf.getProperty(CONF_AGENT_WEB_PORT))); System.exit(0); } } if(!StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_WEB_ENABLE))){ this.webEnable = "true".equals(agentConf.getProperty(CONF_AGENT_WEB_ENABLE)); } if(!StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_MOCK_VALID_TIME))){ try { this.mockValidTime = Integer.parseInt(agentConf.getProperty(CONF_AGENT_MOCK_VALID_TIME)); } catch (NumberFormatException e) { System.err.println(String.format("Agent启动失败,mock有效时间配置 %s 无效: %s", CONF_AGENT_MOCK_VALID_TIME, agentConf.getProperty(CONF_AGENT_MOCK_VALID_TIME))); System.exit(0); } } if(!StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_JMX_LOCAL_CONNECT))){ this.agentJMXLocalConnect = "true".equals(agentConf.getProperty(CONF_AGENT_JMX_LOCAL_CONNECT)); } if(!StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_UPDATE_URL))){ this.agentUpdateUrl = agentConf.getProperty(CONF_AGENT_UPDATE_URL); } if(!StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_PORT))){ try { this.agentPort = Integer.parseInt(agentConf.getProperty(CONF_AGENT_PORT)); } catch (NumberFormatException e) { System.err.println(String.format("Agent启动失败,端口配置%s无效:%s", CONF_AGENT_PORT, agentConf.getProperty(CONF_AGENT_PORT))); System.exit(0); } } if(StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_FALCON_PUSH_URL))){ System.err.println("Agent启动失败,未定义falcon push地址配置:" + CONF_AGENT_FALCON_PUSH_URL); System.exit(0); } this.agentPushUrl = agentConf.getProperty(CONF_AGENT_FALCON_PUSH_URL); if(StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_FLUSH_TIME))){ System.err.println("Agent启动失败,未指定配置:" + CONF_AGENT_FLUSH_TIME); System.exit(0); } try { this.agentFlushTime = Integer.parseInt(agentConf.getProperty(CONF_AGENT_FLUSH_TIME)); if(this.agentFlushTime <= 0){ System.err.println(String.format("Agent启动失败,自动发现服务的刷新周期配置 %s 必须大于0: %s",CONF_AGENT_FLUSH_TIME,agentConf.getProperty(CONF_AGENT_FLUSH_TIME))); System.exit(0); } } catch (NumberFormatException e) { System.err.println(String.format("Agent启动失败,自动发现服务的刷新周期配置%s无效:%s",CONF_AGENT_FLUSH_TIME,agentConf.getProperty(CONF_AGENT_FLUSH_TIME))); System.exit(0); } if(!StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_MAX_THREAD))){ try { this.agentMaxThreadCount = Integer.parseInt(agentConf.getProperty(CONF_AGENT_MAX_THREAD)); if(this.agentMaxThreadCount <= 5){ System.err.println(String.format("Agent启动失败,最大线程数 %s 必须大于5: %s",CONF_AGENT_MAX_THREAD,agentConf.getProperty(CONF_AGENT_MAX_THREAD))); System.exit(0); } } catch (NumberFormatException e) { System.err.println(String.format("Agent启动失败,最大线程数%s无效:%s",CONF_AGENT_MAX_THREAD,agentConf.getProperty(CONF_AGENT_MAX_THREAD))); System.exit(0); } } } private void initJMXCommon(){ String property = System.getProperty("agent.jmx.metrics.common.path"); if(StringUtils.isEmpty(property)){ System.err.println("jmx 的公共配置系统属性文件未定义:agent.jmx.metrics.common.path"); System.exit(0); } this.jmxCommonMetricsConfPath = property; } }
140455_10
package compiler488.codegen; import java.io.*; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import compiler488.ast.AST; import compiler488.ast.Readable; import compiler488.ast.Printable; import compiler488.ast.SourceLocPrettyPrinter; import compiler488.ast.decl.ArrayBound; import compiler488.ast.decl.RoutineDecl; import compiler488.ast.expn.ArithExpn; import compiler488.ast.expn.BoolConstExpn; import compiler488.ast.expn.BoolExpn; import compiler488.ast.expn.CompareExpn; import compiler488.ast.expn.ConditionalExpn; import compiler488.ast.expn.ConstExpn; import compiler488.ast.expn.EqualsExpn; import compiler488.ast.expn.Expn; import compiler488.ast.expn.FunctionCallExpn; import compiler488.ast.expn.IdentExpn; import compiler488.ast.expn.IntConstExpn; import compiler488.ast.expn.NewlineConstExpn; import compiler488.ast.expn.NotExpn; import compiler488.ast.expn.SubsExpn; import compiler488.ast.expn.TextConstExpn; import compiler488.ast.expn.UnaryMinusExpn; import compiler488.ast.expn.VarRefExpn; import compiler488.ast.stmt.AssignStmt; import compiler488.ast.stmt.GetStmt; import compiler488.ast.stmt.IfStmt; import compiler488.ast.stmt.ExitStmt; import compiler488.ast.stmt.WhileDoStmt; import compiler488.ast.stmt.RepeatUntilStmt; import compiler488.ast.stmt.ProcedureCallStmt; import compiler488.ast.stmt.Program; import compiler488.ast.stmt.PutStmt; import compiler488.ast.stmt.ResultStmt; import compiler488.ast.stmt.ReturnStmt; import compiler488.ast.stmt.Scope; import compiler488.runtime.Machine; import compiler488.compiler.Main; import compiler488.codegen.Table.LabelPostfix; import compiler488.codegen.visitor.Visitor; import compiler488.codegen.visitor.Processor; import compiler488.highlighting.AssemblyHighlighting; /** * Code generator for compiler 488 * * @author Daniel Bloemendal * @author Oren Watson */ public class CodeGen extends Visitor { // // Configuration // public static final int LANGUAGE_MAX_STRING_LENGTH = 255; // // Scope processing // void majorProlog() { // Fetch enclosing routine RoutineDecl routine = (RoutineDecl) table.currentScope().getParent(); // Add total locals size to the sizes table sizes.put(table.currentScope(), table.getLocalsSize()); if(routine != null) { comment("------------------------------------"); comment("Start of " + routine.getName()); comment("------------------------------------"); // Starting label for routine label(table.getRoutineLabel(LabelPostfix.Start)); } emit("SAVECTX", table.getLevel()); // Scope prolog reserve(table.getFrameLocalsSize()); // Reserve memory for locals if(routine != null) // Inner routine label label(table.getRoutineLabel(LabelPostfix.Inner)); // ... } void majorEpilog() { // Fetch enclosing routine RoutineDecl routine = (RoutineDecl) table.currentScope().getParent(); if(routine != null) // Routine ending label label(table.getRoutineLabel(LabelPostfix.End)); // ... free(table.getFrameLocalsSize()); // Free locals emit("RESTORECTX", table.getLevel(), // Restore context table.getArgumentsSize()); // ... if(routine != null) emit("BR"); // Return from routine else emit("HALT"); // Halt machine if(routine != null) { comment("------------------------------------"); comment("End of " + routine.getName()); comment("------------------------------------"); assemblerPrintln(""); } } @Processor(target="Scope") void processScope(Scope scope) throws CodeGenException { // Enter the scope table.enterScope(scope); // Major prolog if(table.inMajorScope()) majorProlog(); // Visit statements in scope visit(scope.getStatements()); // Process routine declarations if(table.getRoutineCount() > 0 ) { String _end = table.getLabel(); emit("JMP", _end); assemblerPrintln(""); visit(scope.getDeclarations()); label(_end); } // Major epilog if(table.inMajorScope()) majorEpilog(); // Exit the scope table.exitScope(); } @Processor(target="RoutineDecl") void processRoutineDecl(RoutineDecl routineDecl) { if(!routineDecl.isForward()) visit(routineDecl.getBody()); // Visit routine body } // // Expression processing // @Processor(target="ArithExpn") void processArithExpn(ArithExpn arithExpn) { visit(arithExpn.getLeft()); // Evaluate left side visit(arithExpn.getRight()); // Evaluate right side switch(arithExpn.getOpSymbol().charAt(0)) { case '+': emit("ADD"); break; case '-': emit("SUB"); break; case '*': emit("MUL"); break; case '/': emit("DIV"); break; } } @Processor(target="BoolConstExpn") void processBoolConstExpn(BoolConstExpn boolConstExpn) { emit("PUSH", boolConstExpn.getValue()); // Push the constant literal } @Processor(target="BoolExpn") void processBoolExpn(BoolExpn boolExpn) { if(boolExpn.getOpSymbol().equals(BoolExpn.OP_OR)) processBoolOrExpn(boolExpn); else if(boolExpn.getOpSymbol().equals(BoolExpn.OP_AND)) processBoolAndExpn(boolExpn); } @Processor(target="CompareExpn") void processCompareExpn(CompareExpn compareExpn) { visit(compareExpn.getLeft()); // Evaluate left side visit(compareExpn.getRight()); // Evaluate right side if(compareExpn.getOpSymbol().equals(CompareExpn.OP_LESS)) { emit("LT"); } else if(compareExpn.getOpSymbol().equals(CompareExpn.OP_LESS_EQUAL)) { emit("SWAP"); emit ("LT"); emit("NOT"); } else if(compareExpn.getOpSymbol().equals(CompareExpn.OP_GREATER)) { emit("SWAP"); emit("LT"); } else if(compareExpn.getOpSymbol().equals(CompareExpn.OP_GREATER_EQUAL)) { emit("LT"); emit("NOT"); } } @Processor(target="ConditionalExpn") void processConditionalExpn(ConditionalExpn conditionalExpn) { // Generate unique labels for branch targets String _false = table.getLabel(); String _end = table.getLabel(); // Condition visit(conditionalExpn.getCondition()); // Evaluate condition emit("BFALSE", _false); // If false jump to false expression visit(conditionalExpn.getTrueValue()); // Otherwise evaluate true expression emit("JMP", _end); // Jump to end of block // False expression label(_false); visit(conditionalExpn.getFalseValue()); // Evaluate ``falseValue'' expression // End of block label(_end); } @Processor(target="EqualsExpn") void processEqualsExpn(EqualsExpn equalsExpn) { visit(equalsExpn.getLeft()); // Evaluate left side visit(equalsExpn.getRight()); // Evaluate right side if(equalsExpn.getOpSymbol().equals(EqualsExpn.OP_EQUAL)) { emit("EQ"); } else if(equalsExpn.getOpSymbol().equals(EqualsExpn.OP_NOT_EQUAL)) { emit("EQ"); emit("NOT"); } } void processTailCall(FunctionCallExpn functionCallExpn) { // Argument list List<Expn> arguments = functionCallExpn.getArguments().getList(); // Evaluate each argument for(Expn expn : arguments) visit(expn); // Store results in argument locals for(int i = arguments.size() - 1; i >= 0; i--) { short offset = (short) (table.getOffsetArguments() + i); emit("ADDR", table.getLevel(), offset); // Address of argument local emit("SWAP"); // Swap with evaluated expression on stack emit("STORE"); // Store evaluated expression in argument local } // Jump to the start of the function emit("JMP", table.getRoutineLabel(LabelPostfix.Inner)); } @Processor(target="FunctionCallExpn") void processFunctionCallExpn(FunctionCallExpn functionCallExpn) { // Generate labels required for call String _func = table.getLabel(functionCallExpn.getName()); String _end = table.getLabel(); // Setup the call emit("SETUPCALL", _end); // Evaluate each argument for(Expn expn : functionCallExpn.getArguments().getList()) visit(expn); // Call the function emit("JMP", _func); label(_end); } void addressIdentExpn(IdentExpn identExpn) { Variable var = table.getVaraible(identExpn.getName()); if(var == null) throw new RuntimeException("identifier does not match any variable declaration"); emit("ADDR", var.getLevel(), var.getOffset()); } @Processor(target="IdentExpn") void processIdentExpn(IdentExpn identExpn) { addressIdentExpn(identExpn); emit("LOAD"); } @Processor(target="IntConstExpn") void processIntConstExpn(IntConstExpn intConstExpn) throws CodeGenException { if(intConstExpn.getValue() < Machine.MIN_INTEGER) throw new CodeGenException(source, intConstExpn, "integer constant below machine minimum of " + Machine.MIN_INTEGER); if(intConstExpn.getValue() > Machine.MAX_INTEGER) throw new CodeGenException(source, intConstExpn, "integer constant above machine maximum of " + Machine.MAX_INTEGER); emit("PUSH", intConstExpn.getValue()); // Push the constant literal } @Processor(target="NotExpn") void processNotExpn(NotExpn notExpn) { visit(notExpn.getOperand()); // Evaluate expression emit("PUSH", "$false"); // Negate value by comparing with ``false'' emit("EQ"); // ... } void addressSubsExpnChecking(SubsExpn subsExpn) { // Fetch address of the array Variable var = table.getVaraible(subsExpn.getName()); if(var == null) throw new RuntimeException("identifier does not match any variable declaration"); emit("ADDR", var.getLevel(), var.getOffset()); // Fetch bounds and check sanity ArrayBound bound1 = var.getBounds().size() > 0 ? var.getBounds().get(0) : null; ArrayBound bound2 = var.getBounds().size() > 1 ? var.getBounds().get(1) : null; if(bound1 == null && bound2 == null) throw new RuntimeException("array with no bounds"); // Generate labels String _error_lower1 = table.getLabel(); String _error_upper1 = table.getLabel(); String _error_lower2 = table.getLabel(); String _error_upper2 = table.getLabel(); String _end = table.getLabel(); // Compute the stride of the array int stride = bound1.getUpperboundValue() - bound1.getLowerboundValue(); visit(subsExpn.getSubscript1()); // Evaluate subscript_1 emit("DUP"); // Create duplicate, for bounds checking emit("PUSH", bound1.getLowerboundValue() - 1); // Is lower_bound_1 - 1 < subscript_1? emit("SWAP"); // ... emit("LT"); // ... emit("BFALSE", _error_lower1); // No, then jump to error handler emit("DUP"); // Another duplicate of subscript_1 emit("PUSH", bound1.getUpperboundValue() + 1); // Is subscript_1 < upper_bound_1 + 1? emit("LT"); // ... emit("BFALSE", _error_upper1); // No, then jump to the error handler emit("PUSH", bound1.getLowerboundValue()); // subscript_1 - lower_bound_1 emit("SUB"); // ... // If array is 1D if(bound2 == null) { emit("ADD"); // Add subscript to base address emit("JMP", _end); // Jump to end } // If array is 2D else { emit("PUSH", stride); // Multiply by stride emit("MUL"); // ... emit("ADD"); // Add to base address visit(subsExpn.getSubscript2()); // Evaluate subscript_2 emit("DUP"); // Create duplicate, for bounds checking emit("PUSH", bound2.getLowerboundValue() - 1); // Is lower_bound_2 - 1 < subscript_2? emit("SWAP"); // ... emit("LT"); // ... emit("BFALSE", _error_lower2); // No, then jump to error handler emit("DUP"); // Another duplicate of subscript_2 emit("PUSH", bound2.getUpperboundValue() + 1); // Is subscript_2 < upper_bound_2 + 1? emit("LT"); // ... emit("BFALSE", _error_upper2); // No, then jump to the error handler emit("PUSH", bound2.getLowerboundValue()); // subscript_2 - lower_bound_2 emit("SUB"); emit("ADD"); // Add computed array offset to base address emit("JMP", _end); // Jump to end } // // Error handling // // Enhanced bounds checking with pretty location information if(checking == BoundsChecking.Enhanced) { // Pretty printed locations of error String locSub1 = new String(), locSub2 = new String(); if(bound1 != null) locSub1 = SourceLocPrettyPrinter.printToString(source, subsExpn.getSubscript1()).replace('"', '\''); if(bound2 != null) locSub2 = SourceLocPrettyPrinter.printToString(source, subsExpn.getSubscript2()).replace('"', '\''); // Handler for subscript_1 < lowerbound_1 & subscript_1 > upperbound_1 label(_error_lower1); label(_error_upper1); put(subsExpn.getLoc().toString()); put(": subscript out of range"); newline(); put(locSub1); emit("HALT"); if(bound2 != null) { // Handler for subscript_2 < lowerbound_2 & subscript_2 > upperbound_2 label(_error_lower2); label(_error_upper2); put(subsExpn.getLoc().toString()); put(": subscript out of range"); newline(); put(locSub2); emit("HALT"); } // Bounds checking with less detailed information } else { label(_error_lower1); label(_error_upper1); label(_error_lower2); label(_error_upper2); put("Error: subscript out of range for array '"); put(subsExpn.getName()); put("' on line "); put(subsExpn.getLoc().getStartLine() + 1); newline(); emit("HALT"); } // End of block label(_end); } void addressSubsExpn(SubsExpn subsExpn) { // See if we need to perform bounds checking if(checking != BoundsChecking.None) { addressSubsExpnChecking(subsExpn); return; } // Fetch address of the array Variable var = table.getVaraible(subsExpn.getName()); if(var == null) throw new RuntimeException("identifier does not match any variable declaration"); emit("ADDR", var.getLevel(), var.getOffset()); // Fetch bounds and check sanity ArrayBound bound1 = var.getBounds().size() > 0 ? var.getBounds().get(0) : null; ArrayBound bound2 = var.getBounds().size() > 1 ? var.getBounds().get(1) : null; if(bound1 == null && bound2 == null) throw new RuntimeException("array with no bounds"); // Compute the stride of the array int stride = bound1.getUpperboundValue() - bound1.getLowerboundValue(); visit(subsExpn.getSubscript1()); // Evaluate subscript_1 emit("PUSH", bound1.getLowerboundValue()); // subscript_1 - lower_bound_1 emit("SUB"); // ... // If array is 1D if(bound2 == null) emit("ADD"); // Add subscript to base address // If array is 2D else { emit("PUSH", stride); // Multiply by stride emit("MUL"); // ... emit("ADD"); // Add to base address visit(subsExpn.getSubscript2()); // Evaluate subscript_2 emit("PUSH", bound2.getLowerboundValue()); // subscript_2 - lower_bound_2 emit("SUB"); emit("ADD"); // Add computed array offset to base address } } @Processor(target="SubsExpn") void processSubsExpn(SubsExpn subsExpn) { addressSubsExpn(subsExpn); emit("LOAD"); } @Processor(target="TextConstExpn") void processTextConstExpn(TextConstExpn textConstExpn) throws CodeGenException { if(textConstExpn.getValue().length() > LANGUAGE_MAX_STRING_LENGTH) throw new CodeGenException(source, textConstExpn, "string exceeds maximum allowable length of " + LANGUAGE_MAX_STRING_LENGTH + " characters"); } @Processor(target="UnaryMinusExpn") void processUnaryMinusExpn(UnaryMinusExpn unaryMinusExpn) { visit(unaryMinusExpn.getOperand()); // Evaluate expression emit("NEG"); // Negate the value } void addressVarRefExpn(VarRefExpn varRefExpn) { if(varRefExpn instanceof IdentExpn) addressIdentExpn((IdentExpn) varRefExpn); else if(varRefExpn instanceof SubsExpn) addressSubsExpn((SubsExpn) varRefExpn); else throw new RuntimeException("unknown variable reference type"); } // // Short circuited boolean expressions // void processBoolOrExpn(BoolExpn boolExpn) { // Generate unique labels for branch targets String _checkRHS = table.getLabel(); String _end = table.getLabel(); // Left side check visit(boolExpn.getLeft()); // Evaluate left hand side emit("DUP"); // Duplicate result, required for return value emit("BFALSE", _checkRHS); // If false try the right hand side emit("JMP", _end); // Otherwise, since it is true short circuit to end // Right side check label(_checkRHS); emit("POP"); // Get rid of duplicated result from left hand side visit(boolExpn.getRight()); // Evaluate right hand side // End of block label(_end); } void processBoolAndExpn(BoolExpn boolExpn) { // Generate unique labels for branch targets String _end = table.getLabel(); // Left side check visit(boolExpn.getLeft()); // Evaluate left hand side emit("DUP"); // Duplicate result, required for return value emit("BFALSE", _end); // If false short circuit to the end // Right side check emit("POP"); // Get rid of duplicated result from left hand side visit(boolExpn.getRight()); // Evaluate right hand side // End of block label(_end); } // // Statement processing // @Processor(target="AssignStmt") void processAssignStmt(AssignStmt assignStmt) { addressVarRefExpn(assignStmt.getLval()); // Fetch address of left side visit(assignStmt.getRval()); // Evaluate the right side expression emit("STORE"); // Store the value of the expression in the left side variable } @Processor(target="ExitStmt") void processExitStmt(ExitStmt exitStmt) { if(exitStmt.getCondition() == null) emit("JMP", loopExitLabel); else { visit(exitStmt.getCondition()); emit("NOT"); emit("BFALSE", loopExitLabel); } } @Processor(target="GetStmt") void processGetStmt(GetStmt getStmt) { for(Readable readable : getStmt.getInputs().getList()) { // Skip any readable that is not a variable reference if(!(readable instanceof VarRefExpn)) continue; // Push address of variable on to stack addressVarRefExpn((VarRefExpn) readable); // Perform the read and store the result emit("READI"); emit("STORE"); } } @Processor(target="IfStmt") void processIfStmt(IfStmt ifStmt) { // Generate unique label for else clause String _else = table.getLabel(); // If then clause visit(ifStmt.getCondition()); // Evaluate condition of the if statement emit("BFALSE", _else); // Branch to else statement if false visit(ifStmt.getWhenTrue()); // Execute ``when true'' statements // If a ``when false'' clause does not exist if(ifStmt.getWhenFalse() == null) { label(_else); return; } // Jump to end after ``when true'' statements String _end = table.getLabel(); emit("JMP", _end); // Else clause label(_else); visit(ifStmt.getWhenFalse()); // End of block label(_end); } @Processor(target="ProcedureCallStmt") void processProcedureCallStmt(ProcedureCallStmt procedureCallStmt) { // Generate labels required for call String _proc = table.getLabel(procedureCallStmt.getName()); String _end = table.getLabel(); // Setup the call emit("SETUPCALL", _end); // Evaluate each argument for(Expn expn : procedureCallStmt.getArguments().getList()) visit(expn); // Call the procedure emit("JMP", _proc); label(_end); // Pop off the unused result emit("POP"); } @Processor(target="PutStmt") void processPutStmt(PutStmt putStmt) { for(Printable p : putStmt.getOutputs().getList()) { // Visit the printable if(p instanceof ConstExpn) visit((ConstExpn) p); // Process the printable if(p instanceof TextConstExpn) put(((TextConstExpn) p).getValue()); // String printable else if(p instanceof NewlineConstExpn) newline(); // Newline printable else if(p instanceof Expn) { visit((Expn) p); emit("PRINTI"); } // Expression printable else throw new RuntimeException("unknown printable"); } } @Processor(target="RepeatUntilStmt") void processRepeatUntilStmt(RepeatUntilStmt repeatUntilStmt) { // Preserve the previous loop exit and generate a new one String prevLoopExitLabel = loopExitLabel; loopExitLabel = table.getLabel(); // Generate unique labels for branch targets String _start = table.getLabel(); String _end = loopExitLabel; // If then clause label(_start); visit(repeatUntilStmt.getBody()); visit(repeatUntilStmt.getExpn()); // Evaluate condition of the while statement emit("BFALSE", _start); // Branch to start if false label(_end); // Restore old loop exit label loopExitLabel = prevLoopExitLabel; } @Processor(target="ResultStmt") void processResultStmt(ResultStmt resultStmt) { // See if we can apply tail call optimization if(optimizations.contains(Optimization.TailCallOptimization) && resultStmt.getValue() instanceof FunctionCallExpn) { // Ensure that the call is a self recursive call & perform the optimization FunctionCallExpn funcCall = (FunctionCallExpn) resultStmt.getValue(); if(table.getLabel(funcCall.getName()).equals(table.getRoutineLabel(LabelPostfix.Start))) { processTailCall((FunctionCallExpn) resultStmt.getValue()); return; } } // Get routine end label String _end = table.getLabel(table.getRoutine().getName(), LabelPostfix.End); // Get the address of the result emit("ADDR", table.getLevel(), table.getOffsetResult()); visit(resultStmt.getValue()); // Evaluate result emit("STORE"); // Store the result emit("JMP", _end); // Jump to the end of the function } @Processor(target="ReturnStmt") void processReturnStmt(ReturnStmt returnStmt) { // Get routine end label String _end = table.getLabel(table.getRoutine().getName(), LabelPostfix.End); emit("JMP", _end); // Jump to the end of the function } @Processor(target="WhileDoStmt") void processWhileDoStmt(WhileDoStmt whileDoStmt) { // Preserve the previous loop exit and generate a new one String prevLoopExitLabel = loopExitLabel; loopExitLabel = table.getLabel(); // Generate unique labels for branch targets String _start = table.getLabel(); String _end = loopExitLabel; // If then clause label(_start); visit(whileDoStmt.getExpn()); // Evaluate condition of the while statement emit("BFALSE", _end); // Branch to end if false visit(whileDoStmt.getBody()); emit("JMP", _start); // Jump to the start again label(_end); // Restore old loop exit label loopExitLabel = prevLoopExitLabel; } // // Exception handling // void exception(Exception e) { // Increment error count errors += 1; // Print a stack trace if it is not an expected error if(e.getCause() instanceof CodeGenException) { CodeGenException cge = (CodeGenException) e.getCause(); cge.setSource(source); cge.printCodeTrace(); } else { e.printStackTrace(); } } @Override public void visit(AST node) { try{super.visit(node);} catch(Exception e) { exception(e); } } @Override public void visit(List<AST> list) { try{super.visit(list);} catch(Exception e) { exception(e); } } // // Options // public enum BoundsChecking { None, Simple, Enhanced }; public enum Optimization { TailCallOptimization }; // // Code generator life cycle // public CodeGen(List<String> source) { super(source); this.source = source; } public void Initialize() { // Instantiate internals table = new Table(); sizes = new HashMap<Scope, Integer>(); // Start the assembler assemblerStart(); } public void Generate(Program program, BoundsChecking checking, EnumSet<Optimization> optimizations) { // Set bounds checking mode & optimizations this.checking = checking; this.optimizations = optimizations; // Assemble the runtime library assemblerPrint(Library.code); comment("------------------------------------"); comment("Start of program" ); comment("------------------------------------"); section(".code"); // Start the code section visit(program); // Traverse the AST comment("------------------------------------"); comment("End of program" ); comment("------------------------------------"); } public Boolean Finalize() { // Finish assembling code int result = assemblerEnd(); if(result < 0) return false; // See if any errors have occurred if(errors > 0) return false; // Check sanity of program int sizeProgram = result; int sizeStack = Machine.memorySize - sizeProgram; for(Entry<Scope, Integer> entry : sizes.entrySet()) { if(entry.getValue() > sizeStack) { CodeGenException e = new CodeGenException(source, entry.getKey(), "locals size of major scope, " + entry.getValue() + " words, exceeds the machine stack size, " + sizeStack + " words"); e.printCodeTrace(); return false; } } // Set initial machine state Machine.setPC((short) 0); Machine.setMSP((short) sizeProgram); Machine.setMLP((short) (Machine.memorySize - 1)); return true; } // Code generator internals private int errors; // The error count private Table table; // Master table private List<String> source; // Source listing private Map<Scope, Integer> sizes; // Major scope sizes private BoundsChecking checking; // Bounds checking mode private EnumSet<Optimization> optimizations; // The optimizations to apply private String loopExitLabel; // Loop exit label // // Assembler // Boolean assemblerStart() { assemblerThread = new AssemblerThread(); assemblerStream = new PrintStream(assemblerThread.getPipe()); assemblerHighlighting = new AssemblyHighlighting(System.out, Main.syntaxHighlighting); assemblerThread.start(); return true; } void assemblerPrint(String x) { assemblerStream.print(x); if(Main.dumpCode || Main.traceCodeGen) assemblerHighlighting.print(x); } void assemblerPrintln(String x) { assemblerStream.println(x); if(Main.dumpCode || Main.traceCodeGen) assemblerHighlighting.println(x); } int assemblerEnd() { try { assemblerStream.close(); assemblerThread.join(); return assemblerThread.getResult(); } catch(InterruptedException e) { return -1; } } void comment(String comment) { assemblerPrintln("; " + comment); } void section(String name) { assemblerPrintln(" SECTION " + name); } void label(String name) { assemblerPrintln(name + ":"); } void print(String line) { String _ret = table.getLabel(); emit("SETUPCALL", _ret); emit("PUSHSTR", "\"" + line + "\""); emit("JMP", "print"); label(_ret); emit("POP"); } void newline() { emit("PUSH", (short) '\n'); emit("PRINTC"); } void put(int number) { emit("PUSH", (short) number); emit("PRINTI"); } void put(String string) { boolean firstLine = true; for(String line : string.split("\\r?\\n")) { if(!firstLine) newline(); else firstLine = false; print(line); } } void emit(String instruction, Object... operands) { String command = " " + instruction; for(Object op : operands) { if(!(op instanceof Boolean)) command += " " + op.toString(); else command += " " + (((Boolean) op) ? "$true" : "$false"); } assemblerPrintln(command); } void reserve(int words) { if(words == 0) return; emit("RESERVE", words); } void free(int words) { if(words == 0) return; emit("PUSH", words); emit("POPN"); } // Assembler internals private PrintStream assemblerStream; private AssemblerThread assemblerThread; private AssemblyHighlighting assemblerHighlighting; }
d-b/CSC488
A5/src/compiler488/codegen/CodeGen.java
8,098
// Visit statements in scope
line_comment
nl
package compiler488.codegen; import java.io.*; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import compiler488.ast.AST; import compiler488.ast.Readable; import compiler488.ast.Printable; import compiler488.ast.SourceLocPrettyPrinter; import compiler488.ast.decl.ArrayBound; import compiler488.ast.decl.RoutineDecl; import compiler488.ast.expn.ArithExpn; import compiler488.ast.expn.BoolConstExpn; import compiler488.ast.expn.BoolExpn; import compiler488.ast.expn.CompareExpn; import compiler488.ast.expn.ConditionalExpn; import compiler488.ast.expn.ConstExpn; import compiler488.ast.expn.EqualsExpn; import compiler488.ast.expn.Expn; import compiler488.ast.expn.FunctionCallExpn; import compiler488.ast.expn.IdentExpn; import compiler488.ast.expn.IntConstExpn; import compiler488.ast.expn.NewlineConstExpn; import compiler488.ast.expn.NotExpn; import compiler488.ast.expn.SubsExpn; import compiler488.ast.expn.TextConstExpn; import compiler488.ast.expn.UnaryMinusExpn; import compiler488.ast.expn.VarRefExpn; import compiler488.ast.stmt.AssignStmt; import compiler488.ast.stmt.GetStmt; import compiler488.ast.stmt.IfStmt; import compiler488.ast.stmt.ExitStmt; import compiler488.ast.stmt.WhileDoStmt; import compiler488.ast.stmt.RepeatUntilStmt; import compiler488.ast.stmt.ProcedureCallStmt; import compiler488.ast.stmt.Program; import compiler488.ast.stmt.PutStmt; import compiler488.ast.stmt.ResultStmt; import compiler488.ast.stmt.ReturnStmt; import compiler488.ast.stmt.Scope; import compiler488.runtime.Machine; import compiler488.compiler.Main; import compiler488.codegen.Table.LabelPostfix; import compiler488.codegen.visitor.Visitor; import compiler488.codegen.visitor.Processor; import compiler488.highlighting.AssemblyHighlighting; /** * Code generator for compiler 488 * * @author Daniel Bloemendal * @author Oren Watson */ public class CodeGen extends Visitor { // // Configuration // public static final int LANGUAGE_MAX_STRING_LENGTH = 255; // // Scope processing // void majorProlog() { // Fetch enclosing routine RoutineDecl routine = (RoutineDecl) table.currentScope().getParent(); // Add total locals size to the sizes table sizes.put(table.currentScope(), table.getLocalsSize()); if(routine != null) { comment("------------------------------------"); comment("Start of " + routine.getName()); comment("------------------------------------"); // Starting label for routine label(table.getRoutineLabel(LabelPostfix.Start)); } emit("SAVECTX", table.getLevel()); // Scope prolog reserve(table.getFrameLocalsSize()); // Reserve memory for locals if(routine != null) // Inner routine label label(table.getRoutineLabel(LabelPostfix.Inner)); // ... } void majorEpilog() { // Fetch enclosing routine RoutineDecl routine = (RoutineDecl) table.currentScope().getParent(); if(routine != null) // Routine ending label label(table.getRoutineLabel(LabelPostfix.End)); // ... free(table.getFrameLocalsSize()); // Free locals emit("RESTORECTX", table.getLevel(), // Restore context table.getArgumentsSize()); // ... if(routine != null) emit("BR"); // Return from routine else emit("HALT"); // Halt machine if(routine != null) { comment("------------------------------------"); comment("End of " + routine.getName()); comment("------------------------------------"); assemblerPrintln(""); } } @Processor(target="Scope") void processScope(Scope scope) throws CodeGenException { // Enter the scope table.enterScope(scope); // Major prolog if(table.inMajorScope()) majorProlog(); // Visit statements<SUF> visit(scope.getStatements()); // Process routine declarations if(table.getRoutineCount() > 0 ) { String _end = table.getLabel(); emit("JMP", _end); assemblerPrintln(""); visit(scope.getDeclarations()); label(_end); } // Major epilog if(table.inMajorScope()) majorEpilog(); // Exit the scope table.exitScope(); } @Processor(target="RoutineDecl") void processRoutineDecl(RoutineDecl routineDecl) { if(!routineDecl.isForward()) visit(routineDecl.getBody()); // Visit routine body } // // Expression processing // @Processor(target="ArithExpn") void processArithExpn(ArithExpn arithExpn) { visit(arithExpn.getLeft()); // Evaluate left side visit(arithExpn.getRight()); // Evaluate right side switch(arithExpn.getOpSymbol().charAt(0)) { case '+': emit("ADD"); break; case '-': emit("SUB"); break; case '*': emit("MUL"); break; case '/': emit("DIV"); break; } } @Processor(target="BoolConstExpn") void processBoolConstExpn(BoolConstExpn boolConstExpn) { emit("PUSH", boolConstExpn.getValue()); // Push the constant literal } @Processor(target="BoolExpn") void processBoolExpn(BoolExpn boolExpn) { if(boolExpn.getOpSymbol().equals(BoolExpn.OP_OR)) processBoolOrExpn(boolExpn); else if(boolExpn.getOpSymbol().equals(BoolExpn.OP_AND)) processBoolAndExpn(boolExpn); } @Processor(target="CompareExpn") void processCompareExpn(CompareExpn compareExpn) { visit(compareExpn.getLeft()); // Evaluate left side visit(compareExpn.getRight()); // Evaluate right side if(compareExpn.getOpSymbol().equals(CompareExpn.OP_LESS)) { emit("LT"); } else if(compareExpn.getOpSymbol().equals(CompareExpn.OP_LESS_EQUAL)) { emit("SWAP"); emit ("LT"); emit("NOT"); } else if(compareExpn.getOpSymbol().equals(CompareExpn.OP_GREATER)) { emit("SWAP"); emit("LT"); } else if(compareExpn.getOpSymbol().equals(CompareExpn.OP_GREATER_EQUAL)) { emit("LT"); emit("NOT"); } } @Processor(target="ConditionalExpn") void processConditionalExpn(ConditionalExpn conditionalExpn) { // Generate unique labels for branch targets String _false = table.getLabel(); String _end = table.getLabel(); // Condition visit(conditionalExpn.getCondition()); // Evaluate condition emit("BFALSE", _false); // If false jump to false expression visit(conditionalExpn.getTrueValue()); // Otherwise evaluate true expression emit("JMP", _end); // Jump to end of block // False expression label(_false); visit(conditionalExpn.getFalseValue()); // Evaluate ``falseValue'' expression // End of block label(_end); } @Processor(target="EqualsExpn") void processEqualsExpn(EqualsExpn equalsExpn) { visit(equalsExpn.getLeft()); // Evaluate left side visit(equalsExpn.getRight()); // Evaluate right side if(equalsExpn.getOpSymbol().equals(EqualsExpn.OP_EQUAL)) { emit("EQ"); } else if(equalsExpn.getOpSymbol().equals(EqualsExpn.OP_NOT_EQUAL)) { emit("EQ"); emit("NOT"); } } void processTailCall(FunctionCallExpn functionCallExpn) { // Argument list List<Expn> arguments = functionCallExpn.getArguments().getList(); // Evaluate each argument for(Expn expn : arguments) visit(expn); // Store results in argument locals for(int i = arguments.size() - 1; i >= 0; i--) { short offset = (short) (table.getOffsetArguments() + i); emit("ADDR", table.getLevel(), offset); // Address of argument local emit("SWAP"); // Swap with evaluated expression on stack emit("STORE"); // Store evaluated expression in argument local } // Jump to the start of the function emit("JMP", table.getRoutineLabel(LabelPostfix.Inner)); } @Processor(target="FunctionCallExpn") void processFunctionCallExpn(FunctionCallExpn functionCallExpn) { // Generate labels required for call String _func = table.getLabel(functionCallExpn.getName()); String _end = table.getLabel(); // Setup the call emit("SETUPCALL", _end); // Evaluate each argument for(Expn expn : functionCallExpn.getArguments().getList()) visit(expn); // Call the function emit("JMP", _func); label(_end); } void addressIdentExpn(IdentExpn identExpn) { Variable var = table.getVaraible(identExpn.getName()); if(var == null) throw new RuntimeException("identifier does not match any variable declaration"); emit("ADDR", var.getLevel(), var.getOffset()); } @Processor(target="IdentExpn") void processIdentExpn(IdentExpn identExpn) { addressIdentExpn(identExpn); emit("LOAD"); } @Processor(target="IntConstExpn") void processIntConstExpn(IntConstExpn intConstExpn) throws CodeGenException { if(intConstExpn.getValue() < Machine.MIN_INTEGER) throw new CodeGenException(source, intConstExpn, "integer constant below machine minimum of " + Machine.MIN_INTEGER); if(intConstExpn.getValue() > Machine.MAX_INTEGER) throw new CodeGenException(source, intConstExpn, "integer constant above machine maximum of " + Machine.MAX_INTEGER); emit("PUSH", intConstExpn.getValue()); // Push the constant literal } @Processor(target="NotExpn") void processNotExpn(NotExpn notExpn) { visit(notExpn.getOperand()); // Evaluate expression emit("PUSH", "$false"); // Negate value by comparing with ``false'' emit("EQ"); // ... } void addressSubsExpnChecking(SubsExpn subsExpn) { // Fetch address of the array Variable var = table.getVaraible(subsExpn.getName()); if(var == null) throw new RuntimeException("identifier does not match any variable declaration"); emit("ADDR", var.getLevel(), var.getOffset()); // Fetch bounds and check sanity ArrayBound bound1 = var.getBounds().size() > 0 ? var.getBounds().get(0) : null; ArrayBound bound2 = var.getBounds().size() > 1 ? var.getBounds().get(1) : null; if(bound1 == null && bound2 == null) throw new RuntimeException("array with no bounds"); // Generate labels String _error_lower1 = table.getLabel(); String _error_upper1 = table.getLabel(); String _error_lower2 = table.getLabel(); String _error_upper2 = table.getLabel(); String _end = table.getLabel(); // Compute the stride of the array int stride = bound1.getUpperboundValue() - bound1.getLowerboundValue(); visit(subsExpn.getSubscript1()); // Evaluate subscript_1 emit("DUP"); // Create duplicate, for bounds checking emit("PUSH", bound1.getLowerboundValue() - 1); // Is lower_bound_1 - 1 < subscript_1? emit("SWAP"); // ... emit("LT"); // ... emit("BFALSE", _error_lower1); // No, then jump to error handler emit("DUP"); // Another duplicate of subscript_1 emit("PUSH", bound1.getUpperboundValue() + 1); // Is subscript_1 < upper_bound_1 + 1? emit("LT"); // ... emit("BFALSE", _error_upper1); // No, then jump to the error handler emit("PUSH", bound1.getLowerboundValue()); // subscript_1 - lower_bound_1 emit("SUB"); // ... // If array is 1D if(bound2 == null) { emit("ADD"); // Add subscript to base address emit("JMP", _end); // Jump to end } // If array is 2D else { emit("PUSH", stride); // Multiply by stride emit("MUL"); // ... emit("ADD"); // Add to base address visit(subsExpn.getSubscript2()); // Evaluate subscript_2 emit("DUP"); // Create duplicate, for bounds checking emit("PUSH", bound2.getLowerboundValue() - 1); // Is lower_bound_2 - 1 < subscript_2? emit("SWAP"); // ... emit("LT"); // ... emit("BFALSE", _error_lower2); // No, then jump to error handler emit("DUP"); // Another duplicate of subscript_2 emit("PUSH", bound2.getUpperboundValue() + 1); // Is subscript_2 < upper_bound_2 + 1? emit("LT"); // ... emit("BFALSE", _error_upper2); // No, then jump to the error handler emit("PUSH", bound2.getLowerboundValue()); // subscript_2 - lower_bound_2 emit("SUB"); emit("ADD"); // Add computed array offset to base address emit("JMP", _end); // Jump to end } // // Error handling // // Enhanced bounds checking with pretty location information if(checking == BoundsChecking.Enhanced) { // Pretty printed locations of error String locSub1 = new String(), locSub2 = new String(); if(bound1 != null) locSub1 = SourceLocPrettyPrinter.printToString(source, subsExpn.getSubscript1()).replace('"', '\''); if(bound2 != null) locSub2 = SourceLocPrettyPrinter.printToString(source, subsExpn.getSubscript2()).replace('"', '\''); // Handler for subscript_1 < lowerbound_1 & subscript_1 > upperbound_1 label(_error_lower1); label(_error_upper1); put(subsExpn.getLoc().toString()); put(": subscript out of range"); newline(); put(locSub1); emit("HALT"); if(bound2 != null) { // Handler for subscript_2 < lowerbound_2 & subscript_2 > upperbound_2 label(_error_lower2); label(_error_upper2); put(subsExpn.getLoc().toString()); put(": subscript out of range"); newline(); put(locSub2); emit("HALT"); } // Bounds checking with less detailed information } else { label(_error_lower1); label(_error_upper1); label(_error_lower2); label(_error_upper2); put("Error: subscript out of range for array '"); put(subsExpn.getName()); put("' on line "); put(subsExpn.getLoc().getStartLine() + 1); newline(); emit("HALT"); } // End of block label(_end); } void addressSubsExpn(SubsExpn subsExpn) { // See if we need to perform bounds checking if(checking != BoundsChecking.None) { addressSubsExpnChecking(subsExpn); return; } // Fetch address of the array Variable var = table.getVaraible(subsExpn.getName()); if(var == null) throw new RuntimeException("identifier does not match any variable declaration"); emit("ADDR", var.getLevel(), var.getOffset()); // Fetch bounds and check sanity ArrayBound bound1 = var.getBounds().size() > 0 ? var.getBounds().get(0) : null; ArrayBound bound2 = var.getBounds().size() > 1 ? var.getBounds().get(1) : null; if(bound1 == null && bound2 == null) throw new RuntimeException("array with no bounds"); // Compute the stride of the array int stride = bound1.getUpperboundValue() - bound1.getLowerboundValue(); visit(subsExpn.getSubscript1()); // Evaluate subscript_1 emit("PUSH", bound1.getLowerboundValue()); // subscript_1 - lower_bound_1 emit("SUB"); // ... // If array is 1D if(bound2 == null) emit("ADD"); // Add subscript to base address // If array is 2D else { emit("PUSH", stride); // Multiply by stride emit("MUL"); // ... emit("ADD"); // Add to base address visit(subsExpn.getSubscript2()); // Evaluate subscript_2 emit("PUSH", bound2.getLowerboundValue()); // subscript_2 - lower_bound_2 emit("SUB"); emit("ADD"); // Add computed array offset to base address } } @Processor(target="SubsExpn") void processSubsExpn(SubsExpn subsExpn) { addressSubsExpn(subsExpn); emit("LOAD"); } @Processor(target="TextConstExpn") void processTextConstExpn(TextConstExpn textConstExpn) throws CodeGenException { if(textConstExpn.getValue().length() > LANGUAGE_MAX_STRING_LENGTH) throw new CodeGenException(source, textConstExpn, "string exceeds maximum allowable length of " + LANGUAGE_MAX_STRING_LENGTH + " characters"); } @Processor(target="UnaryMinusExpn") void processUnaryMinusExpn(UnaryMinusExpn unaryMinusExpn) { visit(unaryMinusExpn.getOperand()); // Evaluate expression emit("NEG"); // Negate the value } void addressVarRefExpn(VarRefExpn varRefExpn) { if(varRefExpn instanceof IdentExpn) addressIdentExpn((IdentExpn) varRefExpn); else if(varRefExpn instanceof SubsExpn) addressSubsExpn((SubsExpn) varRefExpn); else throw new RuntimeException("unknown variable reference type"); } // // Short circuited boolean expressions // void processBoolOrExpn(BoolExpn boolExpn) { // Generate unique labels for branch targets String _checkRHS = table.getLabel(); String _end = table.getLabel(); // Left side check visit(boolExpn.getLeft()); // Evaluate left hand side emit("DUP"); // Duplicate result, required for return value emit("BFALSE", _checkRHS); // If false try the right hand side emit("JMP", _end); // Otherwise, since it is true short circuit to end // Right side check label(_checkRHS); emit("POP"); // Get rid of duplicated result from left hand side visit(boolExpn.getRight()); // Evaluate right hand side // End of block label(_end); } void processBoolAndExpn(BoolExpn boolExpn) { // Generate unique labels for branch targets String _end = table.getLabel(); // Left side check visit(boolExpn.getLeft()); // Evaluate left hand side emit("DUP"); // Duplicate result, required for return value emit("BFALSE", _end); // If false short circuit to the end // Right side check emit("POP"); // Get rid of duplicated result from left hand side visit(boolExpn.getRight()); // Evaluate right hand side // End of block label(_end); } // // Statement processing // @Processor(target="AssignStmt") void processAssignStmt(AssignStmt assignStmt) { addressVarRefExpn(assignStmt.getLval()); // Fetch address of left side visit(assignStmt.getRval()); // Evaluate the right side expression emit("STORE"); // Store the value of the expression in the left side variable } @Processor(target="ExitStmt") void processExitStmt(ExitStmt exitStmt) { if(exitStmt.getCondition() == null) emit("JMP", loopExitLabel); else { visit(exitStmt.getCondition()); emit("NOT"); emit("BFALSE", loopExitLabel); } } @Processor(target="GetStmt") void processGetStmt(GetStmt getStmt) { for(Readable readable : getStmt.getInputs().getList()) { // Skip any readable that is not a variable reference if(!(readable instanceof VarRefExpn)) continue; // Push address of variable on to stack addressVarRefExpn((VarRefExpn) readable); // Perform the read and store the result emit("READI"); emit("STORE"); } } @Processor(target="IfStmt") void processIfStmt(IfStmt ifStmt) { // Generate unique label for else clause String _else = table.getLabel(); // If then clause visit(ifStmt.getCondition()); // Evaluate condition of the if statement emit("BFALSE", _else); // Branch to else statement if false visit(ifStmt.getWhenTrue()); // Execute ``when true'' statements // If a ``when false'' clause does not exist if(ifStmt.getWhenFalse() == null) { label(_else); return; } // Jump to end after ``when true'' statements String _end = table.getLabel(); emit("JMP", _end); // Else clause label(_else); visit(ifStmt.getWhenFalse()); // End of block label(_end); } @Processor(target="ProcedureCallStmt") void processProcedureCallStmt(ProcedureCallStmt procedureCallStmt) { // Generate labels required for call String _proc = table.getLabel(procedureCallStmt.getName()); String _end = table.getLabel(); // Setup the call emit("SETUPCALL", _end); // Evaluate each argument for(Expn expn : procedureCallStmt.getArguments().getList()) visit(expn); // Call the procedure emit("JMP", _proc); label(_end); // Pop off the unused result emit("POP"); } @Processor(target="PutStmt") void processPutStmt(PutStmt putStmt) { for(Printable p : putStmt.getOutputs().getList()) { // Visit the printable if(p instanceof ConstExpn) visit((ConstExpn) p); // Process the printable if(p instanceof TextConstExpn) put(((TextConstExpn) p).getValue()); // String printable else if(p instanceof NewlineConstExpn) newline(); // Newline printable else if(p instanceof Expn) { visit((Expn) p); emit("PRINTI"); } // Expression printable else throw new RuntimeException("unknown printable"); } } @Processor(target="RepeatUntilStmt") void processRepeatUntilStmt(RepeatUntilStmt repeatUntilStmt) { // Preserve the previous loop exit and generate a new one String prevLoopExitLabel = loopExitLabel; loopExitLabel = table.getLabel(); // Generate unique labels for branch targets String _start = table.getLabel(); String _end = loopExitLabel; // If then clause label(_start); visit(repeatUntilStmt.getBody()); visit(repeatUntilStmt.getExpn()); // Evaluate condition of the while statement emit("BFALSE", _start); // Branch to start if false label(_end); // Restore old loop exit label loopExitLabel = prevLoopExitLabel; } @Processor(target="ResultStmt") void processResultStmt(ResultStmt resultStmt) { // See if we can apply tail call optimization if(optimizations.contains(Optimization.TailCallOptimization) && resultStmt.getValue() instanceof FunctionCallExpn) { // Ensure that the call is a self recursive call & perform the optimization FunctionCallExpn funcCall = (FunctionCallExpn) resultStmt.getValue(); if(table.getLabel(funcCall.getName()).equals(table.getRoutineLabel(LabelPostfix.Start))) { processTailCall((FunctionCallExpn) resultStmt.getValue()); return; } } // Get routine end label String _end = table.getLabel(table.getRoutine().getName(), LabelPostfix.End); // Get the address of the result emit("ADDR", table.getLevel(), table.getOffsetResult()); visit(resultStmt.getValue()); // Evaluate result emit("STORE"); // Store the result emit("JMP", _end); // Jump to the end of the function } @Processor(target="ReturnStmt") void processReturnStmt(ReturnStmt returnStmt) { // Get routine end label String _end = table.getLabel(table.getRoutine().getName(), LabelPostfix.End); emit("JMP", _end); // Jump to the end of the function } @Processor(target="WhileDoStmt") void processWhileDoStmt(WhileDoStmt whileDoStmt) { // Preserve the previous loop exit and generate a new one String prevLoopExitLabel = loopExitLabel; loopExitLabel = table.getLabel(); // Generate unique labels for branch targets String _start = table.getLabel(); String _end = loopExitLabel; // If then clause label(_start); visit(whileDoStmt.getExpn()); // Evaluate condition of the while statement emit("BFALSE", _end); // Branch to end if false visit(whileDoStmt.getBody()); emit("JMP", _start); // Jump to the start again label(_end); // Restore old loop exit label loopExitLabel = prevLoopExitLabel; } // // Exception handling // void exception(Exception e) { // Increment error count errors += 1; // Print a stack trace if it is not an expected error if(e.getCause() instanceof CodeGenException) { CodeGenException cge = (CodeGenException) e.getCause(); cge.setSource(source); cge.printCodeTrace(); } else { e.printStackTrace(); } } @Override public void visit(AST node) { try{super.visit(node);} catch(Exception e) { exception(e); } } @Override public void visit(List<AST> list) { try{super.visit(list);} catch(Exception e) { exception(e); } } // // Options // public enum BoundsChecking { None, Simple, Enhanced }; public enum Optimization { TailCallOptimization }; // // Code generator life cycle // public CodeGen(List<String> source) { super(source); this.source = source; } public void Initialize() { // Instantiate internals table = new Table(); sizes = new HashMap<Scope, Integer>(); // Start the assembler assemblerStart(); } public void Generate(Program program, BoundsChecking checking, EnumSet<Optimization> optimizations) { // Set bounds checking mode & optimizations this.checking = checking; this.optimizations = optimizations; // Assemble the runtime library assemblerPrint(Library.code); comment("------------------------------------"); comment("Start of program" ); comment("------------------------------------"); section(".code"); // Start the code section visit(program); // Traverse the AST comment("------------------------------------"); comment("End of program" ); comment("------------------------------------"); } public Boolean Finalize() { // Finish assembling code int result = assemblerEnd(); if(result < 0) return false; // See if any errors have occurred if(errors > 0) return false; // Check sanity of program int sizeProgram = result; int sizeStack = Machine.memorySize - sizeProgram; for(Entry<Scope, Integer> entry : sizes.entrySet()) { if(entry.getValue() > sizeStack) { CodeGenException e = new CodeGenException(source, entry.getKey(), "locals size of major scope, " + entry.getValue() + " words, exceeds the machine stack size, " + sizeStack + " words"); e.printCodeTrace(); return false; } } // Set initial machine state Machine.setPC((short) 0); Machine.setMSP((short) sizeProgram); Machine.setMLP((short) (Machine.memorySize - 1)); return true; } // Code generator internals private int errors; // The error count private Table table; // Master table private List<String> source; // Source listing private Map<Scope, Integer> sizes; // Major scope sizes private BoundsChecking checking; // Bounds checking mode private EnumSet<Optimization> optimizations; // The optimizations to apply private String loopExitLabel; // Loop exit label // // Assembler // Boolean assemblerStart() { assemblerThread = new AssemblerThread(); assemblerStream = new PrintStream(assemblerThread.getPipe()); assemblerHighlighting = new AssemblyHighlighting(System.out, Main.syntaxHighlighting); assemblerThread.start(); return true; } void assemblerPrint(String x) { assemblerStream.print(x); if(Main.dumpCode || Main.traceCodeGen) assemblerHighlighting.print(x); } void assemblerPrintln(String x) { assemblerStream.println(x); if(Main.dumpCode || Main.traceCodeGen) assemblerHighlighting.println(x); } int assemblerEnd() { try { assemblerStream.close(); assemblerThread.join(); return assemblerThread.getResult(); } catch(InterruptedException e) { return -1; } } void comment(String comment) { assemblerPrintln("; " + comment); } void section(String name) { assemblerPrintln(" SECTION " + name); } void label(String name) { assemblerPrintln(name + ":"); } void print(String line) { String _ret = table.getLabel(); emit("SETUPCALL", _ret); emit("PUSHSTR", "\"" + line + "\""); emit("JMP", "print"); label(_ret); emit("POP"); } void newline() { emit("PUSH", (short) '\n'); emit("PRINTC"); } void put(int number) { emit("PUSH", (short) number); emit("PRINTI"); } void put(String string) { boolean firstLine = true; for(String line : string.split("\\r?\\n")) { if(!firstLine) newline(); else firstLine = false; print(line); } } void emit(String instruction, Object... operands) { String command = " " + instruction; for(Object op : operands) { if(!(op instanceof Boolean)) command += " " + op.toString(); else command += " " + (((Boolean) op) ? "$true" : "$false"); } assemblerPrintln(command); } void reserve(int words) { if(words == 0) return; emit("RESERVE", words); } void free(int words) { if(words == 0) return; emit("PUSH", words); emit("POPN"); } // Assembler internals private PrintStream assemblerStream; private AssemblerThread assemblerThread; private AssemblyHighlighting assemblerHighlighting; }
207160_1
package com.jadonvb; import org.knowm.xchart.*; import org.knowm.xchart.style.Styler; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Voer een geheel getal in: "); int startingNumber = scanner.nextInt(); List<Integer> xData = new ArrayList<>(); List<Integer> yData = new ArrayList<>(); int n = startingNumber; int step = 0; while (n != 1) { xData.add(step); yData.add(n); if (n % 2 == 0) { n = n / 2; } else { n = 3 * n + 1; } step++; } xData.add(step); yData.add(1); // Tooltip-tekst genereren voor hele getallen List<String> toolTips = new ArrayList<>(); for (int i = 0; i < xData.size(); i++) { if (xData.get(i) % 1 == 0) { toolTips.add("Step: " + xData.get(i) + ", Number: " + yData.get(i)); } else { toolTips.add(""); // Geen tooltip voor niet-gehele getallen } } // Grafiek maken XYChart chart = new XYChartBuilder().width(800).height(600).title("Collatz Conjecture").xAxisTitle("Tijd").yAxisTitle("Getal").build(); // Data toevoegen XYSeries series = chart.addSeries("Collatz", xData, yData); // Tooltips instellen met aangepaste tooltip generator chart.getStyler().setToolTipType(Styler.ToolTipType.yLabels); chart.getStyler().setCursorEnabled(true); chart.getStyler().setToolTipsEnabled(true); chart.getStyler().setToolTipFont(new java.awt.Font("Dialog", java.awt.Font.PLAIN, 12)); chart.getStyler().setToolTipBackgroundColor(java.awt.Color.WHITE); chart.getStyler().setToolTipBorderColor(java.awt.Color.BLACK); // Laten zien new SwingWrapper<>(chart).displayChart(); } }
Ja90n/CollatzDisplayer
src/main/java/com/jadonvb/Main.java
598
// Geen tooltip voor niet-gehele getallen
line_comment
nl
package com.jadonvb; import org.knowm.xchart.*; import org.knowm.xchart.style.Styler; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Voer een geheel getal in: "); int startingNumber = scanner.nextInt(); List<Integer> xData = new ArrayList<>(); List<Integer> yData = new ArrayList<>(); int n = startingNumber; int step = 0; while (n != 1) { xData.add(step); yData.add(n); if (n % 2 == 0) { n = n / 2; } else { n = 3 * n + 1; } step++; } xData.add(step); yData.add(1); // Tooltip-tekst genereren voor hele getallen List<String> toolTips = new ArrayList<>(); for (int i = 0; i < xData.size(); i++) { if (xData.get(i) % 1 == 0) { toolTips.add("Step: " + xData.get(i) + ", Number: " + yData.get(i)); } else { toolTips.add(""); // Geen tooltip<SUF> } } // Grafiek maken XYChart chart = new XYChartBuilder().width(800).height(600).title("Collatz Conjecture").xAxisTitle("Tijd").yAxisTitle("Getal").build(); // Data toevoegen XYSeries series = chart.addSeries("Collatz", xData, yData); // Tooltips instellen met aangepaste tooltip generator chart.getStyler().setToolTipType(Styler.ToolTipType.yLabels); chart.getStyler().setCursorEnabled(true); chart.getStyler().setToolTipsEnabled(true); chart.getStyler().setToolTipFont(new java.awt.Font("Dialog", java.awt.Font.PLAIN, 12)); chart.getStyler().setToolTipBackgroundColor(java.awt.Color.WHITE); chart.getStyler().setToolTipBorderColor(java.awt.Color.BLACK); // Laten zien new SwingWrapper<>(chart).displayChart(); } }
6343_47
package novi.basics; import com.sun.org.apache.xpath.internal.objects.XBoolean; import java.util.Arrays; public class Main { public static void main(String[] args) { // variabelen int maxAantalSpel = 0; String vraagSpeler = " "; boolean notEOG = false; // interactie met gebruikers Interactie interactie = new Interactie(); vraagSpeler = interactie.getNames(); int maxAantalSpelen = interactie.getNumGames(maxAantalSpel); interactie.getPlayerMove(vraagSpeler, maxAantalSpel); // algoritme // nieuw spel beginnen int actueleSpeelRonde = 0; int spelRonde = 0; while (actueleSpeelRonde < 9) { while (spelRonde < maxAantalSpelen) { // speel spelronde GameBoard game = new GameBoard(actueleSpeelRonde); game.play(game.play(actueleSpeelRonde)); // speel volgende ronde spelRonde = spelRonde + 1; } actueleSpeelRonde = actueleSpeelRonde + 1; } // zet van actuele speler Interactie getplayermove = new Interactie(); /* //if (true) { // bij gelijke score speler1 en speler 2, einde van spel //} // nieuw spel beginnen // opslaan hoeveel keer er gelijk spel is geweest int drawCount = 0; // -- vanaf hier gaan we het spel opnieuw spelen met dezelfde spelers (nadat op het eind keuze 1 gekozen is) // speelbord opslaan (1 - 9) // uitleg: omdat we altijd met een bord starten met 9 getallen, kunnen we het Tic Tac Toe bord ook direct een waarde geven // zie demo project code voor de andere manier met de for loop char[] board = {'1', '2', '3', '4', '5', '6', '7', '8', '9'}; // maximale aantal rondes opslaan int maxRounds = board.length; // speelbord tonen //printBoard(board); // token van de actieve speler opslaan //char activePlayerToken = player1.getToken(); //Player activePlayer = player1; // starten met de beurt (maximaal 9 beurten) //for (int round = 0; round < maxRounds; round++) { // naam van de actieve speler opslaan /*String activePlayerName; if(activePlayerToken == player1.getToken()) { activePlayerName = player1Name; } else { activePlayerName = player2Name; }*/ //String activePlayerName = activePlayer.getName(); // actieve speler vragen om een veld te kiezen (1 - 9) //System.out.println(activePlayerName + ", please choose a field"); // gekozen veld van de actieve speler opslaan //int chosenField = playerInput.nextInt(); //int chosenIndex = chosenField - 1; // als het veld bestaat //if (chosenIndex < 9 && chosenIndex >= 0) { //als het veld leeg is, wanneer er geen token staat // if(board[chosenIndex] != player1.getToken() && board[chosenIndex] != player2.getToken()) { // wanneer de speler een token op het bord kan plaatsen // de token van de actieve speler op het gekozen veld plaatsen // board[chosenIndex] = activePlayer.getToken(); //player.score += 10; // het nieuwe speelbord tonen //printBoard(board); // als het spel gewonnen is // tonen wie er gewonnen heeft (de actieve speler) // de actieve speler krijgt een punt // de scores van de spelers tonen // wanneer we in de laatste beurt zijn en niemand gewonnen heeft // aantal keer gelijk spel ophogen // aantal keer gelijk spel tonen // de beurt doorgeven aan de volgende speler (van speler wisselen) // als de actieve speler, speler 1 is: // if(activePlayer == player1) { // maak de actieve speler, speler 2 // activePlayer = player2; //} // anders //else { // maak de actieve speler weer speler 1 // activePlayer = player1; //} //} //of al bezet is //else { // maxRounds++; //System.out.println("this field is not available, choose another"); //} //versie 2: als het veld leeg is, wanneer de waarde gelijk is aan chosenField /*if(board[chosenIndex] != '1' + chosenIndex) { board[chosenIndex] = activePlayerToken; }*/ //} // als het veld niet bestaat //else { // het mamimale aantal beurten verhogen // maxRounds++; // foutmelding tonen aan de speler //System.out.println("the chosen field does not exist, try again"); //} // -- terug naar het begin van de volgende beurt //} // vragen of de spelers nog een keer willen spelen //1: nog een keer spelen //2: van spelers wisselen //3: afsluiten // speler keuze opslaan // bij keuze 1: terug naar het maken van het bord // bij keuze 2: terug naar de start van de applicatie en het vragen van spelernamen // bij keuze 3: het spel en de applicatie helemaal afsluiten //} /*public static void printBoard(char[] board) { for (int fieldIndex = 0; fieldIndex < board.length; fieldIndex++) { System.out.print(board[fieldIndex] + " "); // als we het tweede veld geprint hebben of het vijfde veld geprint hebben // dan gaan we naar de volgende regel if(fieldIndex == 2 || fieldIndex == 5) { System.out.println(); } System.out.println(); */ } }
hogeschoolnovi/tic-tac-toe-JvdS-coder
src/novi/basics/Main.java
1,501
// bij keuze 1: terug naar het maken van het bord
line_comment
nl
package novi.basics; import com.sun.org.apache.xpath.internal.objects.XBoolean; import java.util.Arrays; public class Main { public static void main(String[] args) { // variabelen int maxAantalSpel = 0; String vraagSpeler = " "; boolean notEOG = false; // interactie met gebruikers Interactie interactie = new Interactie(); vraagSpeler = interactie.getNames(); int maxAantalSpelen = interactie.getNumGames(maxAantalSpel); interactie.getPlayerMove(vraagSpeler, maxAantalSpel); // algoritme // nieuw spel beginnen int actueleSpeelRonde = 0; int spelRonde = 0; while (actueleSpeelRonde < 9) { while (spelRonde < maxAantalSpelen) { // speel spelronde GameBoard game = new GameBoard(actueleSpeelRonde); game.play(game.play(actueleSpeelRonde)); // speel volgende ronde spelRonde = spelRonde + 1; } actueleSpeelRonde = actueleSpeelRonde + 1; } // zet van actuele speler Interactie getplayermove = new Interactie(); /* //if (true) { // bij gelijke score speler1 en speler 2, einde van spel //} // nieuw spel beginnen // opslaan hoeveel keer er gelijk spel is geweest int drawCount = 0; // -- vanaf hier gaan we het spel opnieuw spelen met dezelfde spelers (nadat op het eind keuze 1 gekozen is) // speelbord opslaan (1 - 9) // uitleg: omdat we altijd met een bord starten met 9 getallen, kunnen we het Tic Tac Toe bord ook direct een waarde geven // zie demo project code voor de andere manier met de for loop char[] board = {'1', '2', '3', '4', '5', '6', '7', '8', '9'}; // maximale aantal rondes opslaan int maxRounds = board.length; // speelbord tonen //printBoard(board); // token van de actieve speler opslaan //char activePlayerToken = player1.getToken(); //Player activePlayer = player1; // starten met de beurt (maximaal 9 beurten) //for (int round = 0; round < maxRounds; round++) { // naam van de actieve speler opslaan /*String activePlayerName; if(activePlayerToken == player1.getToken()) { activePlayerName = player1Name; } else { activePlayerName = player2Name; }*/ //String activePlayerName = activePlayer.getName(); // actieve speler vragen om een veld te kiezen (1 - 9) //System.out.println(activePlayerName + ", please choose a field"); // gekozen veld van de actieve speler opslaan //int chosenField = playerInput.nextInt(); //int chosenIndex = chosenField - 1; // als het veld bestaat //if (chosenIndex < 9 && chosenIndex >= 0) { //als het veld leeg is, wanneer er geen token staat // if(board[chosenIndex] != player1.getToken() && board[chosenIndex] != player2.getToken()) { // wanneer de speler een token op het bord kan plaatsen // de token van de actieve speler op het gekozen veld plaatsen // board[chosenIndex] = activePlayer.getToken(); //player.score += 10; // het nieuwe speelbord tonen //printBoard(board); // als het spel gewonnen is // tonen wie er gewonnen heeft (de actieve speler) // de actieve speler krijgt een punt // de scores van de spelers tonen // wanneer we in de laatste beurt zijn en niemand gewonnen heeft // aantal keer gelijk spel ophogen // aantal keer gelijk spel tonen // de beurt doorgeven aan de volgende speler (van speler wisselen) // als de actieve speler, speler 1 is: // if(activePlayer == player1) { // maak de actieve speler, speler 2 // activePlayer = player2; //} // anders //else { // maak de actieve speler weer speler 1 // activePlayer = player1; //} //} //of al bezet is //else { // maxRounds++; //System.out.println("this field is not available, choose another"); //} //versie 2: als het veld leeg is, wanneer de waarde gelijk is aan chosenField /*if(board[chosenIndex] != '1' + chosenIndex) { board[chosenIndex] = activePlayerToken; }*/ //} // als het veld niet bestaat //else { // het mamimale aantal beurten verhogen // maxRounds++; // foutmelding tonen aan de speler //System.out.println("the chosen field does not exist, try again"); //} // -- terug naar het begin van de volgende beurt //} // vragen of de spelers nog een keer willen spelen //1: nog een keer spelen //2: van spelers wisselen //3: afsluiten // speler keuze opslaan // bij keuze<SUF> // bij keuze 2: terug naar de start van de applicatie en het vragen van spelernamen // bij keuze 3: het spel en de applicatie helemaal afsluiten //} /*public static void printBoard(char[] board) { for (int fieldIndex = 0; fieldIndex < board.length; fieldIndex++) { System.out.print(board[fieldIndex] + " "); // als we het tweede veld geprint hebben of het vijfde veld geprint hebben // dan gaan we naar de volgende regel if(fieldIndex == 2 || fieldIndex == 5) { System.out.println(); } System.out.println(); */ } }
203902_8
package graafdiagrammas; import logicalcollections.LogicalSet; /** * @invar | 0 <= getUitvalshoek() && getUitvalshoek() <= 359 * @invar | getBronknoop() == null || getBronknoop().getUitgaandeBogen().contains(this) * @invar | getDoelknoop() == null || getDoelknoop().getInkomendeBogen().contains(this) */ public class Boog { /** * @invar | 0 <= uitvalshoek * @invar | uitvalshoek <= 359 * @invar | bronknoop == null || bronknoop.uitgaandeBogen.contains(this) * @invar | doelknoop == null || doelknoop.inkomendeBogen.contains(this) */ int uitvalshoek; /** * @peerObject */ Knoop bronknoop; /** * @peerObject */ Knoop doelknoop; public int getUitvalshoek() { return uitvalshoek; } /** * @peerObject */ public Knoop getBronknoop() { return bronknoop; } /** * @peerObject */ public Knoop getDoelknoop() { return doelknoop; } /** * @pre | 0 <= uitvalshoek && uitvalshoek <= 359 * @post | getUitvalshoek() == uitvalshoek * @post | getBronknoop() == null * @post | getDoelknoop() == null */ public Boog(int uitvalshoek) { this.uitvalshoek = uitvalshoek; } /** * @pre | bronknoop != null * @pre | getBronknoop() == null * @mutates_properties | getBronknoop(), bronknoop.getUitgaandeBogen() * @post | getBronknoop() == bronknoop * @post | bronknoop.getUitgaandeBogen().equals(LogicalSet.plus(old(bronknoop.getUitgaandeBogen()), this)) */ public void koppelBronknoop(Knoop bronknoop) { this.bronknoop = bronknoop; bronknoop.uitgaandeBogen.add(this); } /** * @pre | getBronknoop() != null * @mutates_properties | getBronknoop(), getBronknoop().getUitgaandeBogen() * @post | getBronknoop() == null * @post | old(getBronknoop()).getUitgaandeBogen().equals(LogicalSet.minus(old(getBronknoop().getUitgaandeBogen()), this)) */ public void ontkoppelBronknoop() { bronknoop.uitgaandeBogen.remove(this); bronknoop = null; } /** * @pre | doelknoop != null * @pre | getDoelknoop() == null * @mutates_properties | getDoelknoop(), doelknoop.getInkomendeBogen() * @post | getDoelknoop() == doelknoop * @post | doelknoop.getInkomendeBogen().equals(LogicalSet.plus(old(doelknoop.getInkomendeBogen()), this)) */ public void koppelDoelknoop(Knoop doelknoop) { this.doelknoop = doelknoop; doelknoop.inkomendeBogen.add(this); } /** * @pre | getDoelknoop() != null * @mutates_properties | getDoelknoop(), getDoelknoop().getInkomendeBogen() * @post | getDoelknoop() == null * @post | old(getDoelknoop()).getInkomendeBogen().equals(LogicalSet.minus(old(getDoelknoop().getInkomendeBogen()), this)) */ public void ontkoppelDoelknoop() { doelknoop.inkomendeBogen.remove(this); doelknoop = null; } }
btj/graafdiagrammas
graafdiagrammas/src/graafdiagrammas/Boog.java
1,048
/** * @pre | getBronknoop() != null * @mutates_properties | getBronknoop(), getBronknoop().getUitgaandeBogen() * @post | getBronknoop() == null * @post | old(getBronknoop()).getUitgaandeBogen().equals(LogicalSet.minus(old(getBronknoop().getUitgaandeBogen()), this)) */
block_comment
nl
package graafdiagrammas; import logicalcollections.LogicalSet; /** * @invar | 0 <= getUitvalshoek() && getUitvalshoek() <= 359 * @invar | getBronknoop() == null || getBronknoop().getUitgaandeBogen().contains(this) * @invar | getDoelknoop() == null || getDoelknoop().getInkomendeBogen().contains(this) */ public class Boog { /** * @invar | 0 <= uitvalshoek * @invar | uitvalshoek <= 359 * @invar | bronknoop == null || bronknoop.uitgaandeBogen.contains(this) * @invar | doelknoop == null || doelknoop.inkomendeBogen.contains(this) */ int uitvalshoek; /** * @peerObject */ Knoop bronknoop; /** * @peerObject */ Knoop doelknoop; public int getUitvalshoek() { return uitvalshoek; } /** * @peerObject */ public Knoop getBronknoop() { return bronknoop; } /** * @peerObject */ public Knoop getDoelknoop() { return doelknoop; } /** * @pre | 0 <= uitvalshoek && uitvalshoek <= 359 * @post | getUitvalshoek() == uitvalshoek * @post | getBronknoop() == null * @post | getDoelknoop() == null */ public Boog(int uitvalshoek) { this.uitvalshoek = uitvalshoek; } /** * @pre | bronknoop != null * @pre | getBronknoop() == null * @mutates_properties | getBronknoop(), bronknoop.getUitgaandeBogen() * @post | getBronknoop() == bronknoop * @post | bronknoop.getUitgaandeBogen().equals(LogicalSet.plus(old(bronknoop.getUitgaandeBogen()), this)) */ public void koppelBronknoop(Knoop bronknoop) { this.bronknoop = bronknoop; bronknoop.uitgaandeBogen.add(this); } /** * @pre | getBronknoop()<SUF>*/ public void ontkoppelBronknoop() { bronknoop.uitgaandeBogen.remove(this); bronknoop = null; } /** * @pre | doelknoop != null * @pre | getDoelknoop() == null * @mutates_properties | getDoelknoop(), doelknoop.getInkomendeBogen() * @post | getDoelknoop() == doelknoop * @post | doelknoop.getInkomendeBogen().equals(LogicalSet.plus(old(doelknoop.getInkomendeBogen()), this)) */ public void koppelDoelknoop(Knoop doelknoop) { this.doelknoop = doelknoop; doelknoop.inkomendeBogen.add(this); } /** * @pre | getDoelknoop() != null * @mutates_properties | getDoelknoop(), getDoelknoop().getInkomendeBogen() * @post | getDoelknoop() == null * @post | old(getDoelknoop()).getInkomendeBogen().equals(LogicalSet.minus(old(getDoelknoop().getInkomendeBogen()), this)) */ public void ontkoppelDoelknoop() { doelknoop.inkomendeBogen.remove(this); doelknoop = null; } }
79494_13
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class level1 here. * * @author (your name) * @version (a version number or a date) */ public class Level1 extends World { private CollisionEngine ce; Counter counter = new Counter(); LifeCounter lifecounter = new LifeCounter(); KeyBlue key = new KeyBlue(); GemBlue gem = new GemBlue(); /** * Constructor for objects of class level1. * */ public Level1() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(1000, 800, 1, false); this.setBackground("bg.png"); int[][] map = { {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4,4,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4,-1,-1,-1,-1,-1,-1,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4,-1,-1,-1,-1,-1,-1,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4,-1,-1,-1,-1,-1,-1,-1,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,0,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,1,-1,-1,-1,-1,-1,-1,0,-1,-1,-1,-1,-1,-1,0,-1,-1,-1,-1,-1,-1,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,0,0,-1,-1,-1,-1,-1,-1,-1,0,0,0,0,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {25,25,25,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14}, {24,24,24,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,14,14,14,14,14,5,5,5,5,5,14,14,14,14,14,14,14,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12}, {24,24,24,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,25,25,25,25,25,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12}, {24,24,24,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,24,24,24,24,24,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12}, }; // Declareren en initialiseren van de TileEngine klasse om de map aan de world toe te voegen TileEngine te = new TileEngine(this, 60, 60, map); // Declarenre en initialiseren van de camera klasse met de TileEngine klasse // zodat de camera weet welke tiles allemaal moeten meebewegen met de camera Camera camera = new Camera(te); // Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse // moet de klasse Mover extenden voor de camera om te werken Hero hero = new Hero(); // Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan. camera.follow(hero); // Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies addObject(camera, 0, 0); addObject(hero, 400, 700); addObject(counter, 900, 30); addObject(lifecounter, 71, 30); addObject(new Cross(), 70, 120); addObject(new CoinSilver(), 210, 810); addObject(new CoinSilver(), 1470, 870); addObject(new CoinSilver(), 2550, 990); addObject(new CoinSilver(), 3630, 750); addObject(new CoinSilver(), 4230, 750); addObject(new CoinGold(), 4950, 390); addObject(new KeyBlue(), 4230, 390); addObject(new GemBlue(), 5370, 390); addObject(new Slak(), 1275, 947); addObject(new Slak(), 4950, 947); addObject(new Door_closedMid(), 5730, 925); addObject(new Door_closedTop(), 5730, 865); // hoogte/breedte * 60 + 30 // Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen. // De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan. ce = new CollisionEngine(te, camera); // Toevoegen van de mover instantie of een extentie hiervan ce.addCollidingMover(hero); prepare(); } @Override public void act() { ce.update(); if (key.keyCollected == true){ addObject(new Sleutel(), 50, 70); } if (gem.dGemCollected == true){ addObject(new DisplayGem(), 100, 70); } } /** * Prepare the world for the start of the program. * That is: create the initial objects and add them to the world. */ private void prepare() { } }
ROCMondriaanTIN/project-greenfoot-game-dannykuijpers
level1.java
5,402
// De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan.
line_comment
nl
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class level1 here. * * @author (your name) * @version (a version number or a date) */ public class Level1 extends World { private CollisionEngine ce; Counter counter = new Counter(); LifeCounter lifecounter = new LifeCounter(); KeyBlue key = new KeyBlue(); GemBlue gem = new GemBlue(); /** * Constructor for objects of class level1. * */ public Level1() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(1000, 800, 1, false); this.setBackground("bg.png"); int[][] map = { {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4,4,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4,-1,-1,-1,-1,-1,-1,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4,-1,-1,-1,-1,-1,-1,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4,-1,-1,-1,-1,-1,-1,-1,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,0,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,1,-1,-1,-1,-1,-1,-1,0,-1,-1,-1,-1,-1,-1,0,-1,-1,-1,-1,-1,-1,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,0,0,-1,-1,-1,-1,-1,-1,-1,0,0,0,0,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {25,25,25,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14}, {24,24,24,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,14,14,14,14,14,5,5,5,5,5,14,14,14,14,14,14,14,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12}, {24,24,24,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,25,25,25,25,25,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12}, {24,24,24,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,24,24,24,24,24,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12}, }; // Declareren en initialiseren van de TileEngine klasse om de map aan de world toe te voegen TileEngine te = new TileEngine(this, 60, 60, map); // Declarenre en initialiseren van de camera klasse met de TileEngine klasse // zodat de camera weet welke tiles allemaal moeten meebewegen met de camera Camera camera = new Camera(te); // Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse // moet de klasse Mover extenden voor de camera om te werken Hero hero = new Hero(); // Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan. camera.follow(hero); // Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies addObject(camera, 0, 0); addObject(hero, 400, 700); addObject(counter, 900, 30); addObject(lifecounter, 71, 30); addObject(new Cross(), 70, 120); addObject(new CoinSilver(), 210, 810); addObject(new CoinSilver(), 1470, 870); addObject(new CoinSilver(), 2550, 990); addObject(new CoinSilver(), 3630, 750); addObject(new CoinSilver(), 4230, 750); addObject(new CoinGold(), 4950, 390); addObject(new KeyBlue(), 4230, 390); addObject(new GemBlue(), 5370, 390); addObject(new Slak(), 1275, 947); addObject(new Slak(), 4950, 947); addObject(new Door_closedMid(), 5730, 925); addObject(new Door_closedTop(), 5730, 865); // hoogte/breedte * 60 + 30 // Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen. // De collision<SUF> ce = new CollisionEngine(te, camera); // Toevoegen van de mover instantie of een extentie hiervan ce.addCollidingMover(hero); prepare(); } @Override public void act() { ce.update(); if (key.keyCollected == true){ addObject(new Sleutel(), 50, 70); } if (gem.dGemCollected == true){ addObject(new DisplayGem(), 100, 70); } } /** * Prepare the world for the start of the program. * That is: create the initial objects and add them to the world. */ private void prepare() { } }
34262_1
package com.vondear.rxtools; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; /** * Created by vondear on 2016/1/24. * Shell相关工具类 */ public class RxShellTool { public static final String COMMAND_SU = "su"; public static final String COMMAND_SH = "sh"; public static final String COMMAND_EXIT = "exit\n"; public static final String COMMAND_LINE_END = "\n"; /** * 判断设备是否root * @return {@code true}: root<br>{@code false}: 没root */ public static boolean isRoot() { return execCmd("echo root", true, false).result == 0; } /** * 是否是在root下执行命令 * * @param command 命令 * @param isRoot 是否root * @return CommandResult */ public static CommandResult execCmd(String command, boolean isRoot) { return execCmd(new String[]{command}, isRoot, true); } /** * 是否是在root下执行命令 * * @param commands 多条命令链表 * @param isRoot 是否root * @return CommandResult */ public static CommandResult execCmd(List<String> commands, boolean isRoot) { return execCmd(commands == null ? null : commands.toArray(new String[]{}), isRoot, true); } /** * 是否是在root下执行命令 * * @param commands 多条命令数组 * @param isRoot 是否root * @return CommandResult */ public static CommandResult execCmd(String[] commands, boolean isRoot) { return execCmd(commands, isRoot, true); } /** * 是否是在root下执行命令 * * @param command 命令 * @param isRoot 是否root * @param isNeedResultMsg 是否需要结果消息 * @return CommandResult */ public static CommandResult execCmd(String command, boolean isRoot, boolean isNeedResultMsg) { return execCmd(new String[]{command}, isRoot, isNeedResultMsg); } /** * 是否是在root下执行命令 * * @param commands 命令链表 * @param isRoot 是否root * @param isNeedResultMsg 是否需要结果消息 * @return CommandResult */ public static CommandResult execCmd(List<String> commands, boolean isRoot, boolean isNeedResultMsg) { return execCmd(commands == null ? null : commands.toArray(new String[]{}), isRoot, isNeedResultMsg); } /** * 是否是在root下执行命令 * * @param commands 命令数组 * @param isRoot 是否root * @param isNeedResultMsg 是否需要结果消息 * @return CommandResult */ public static CommandResult execCmd(String[] commands, boolean isRoot, boolean isNeedResultMsg) { int result = -1; if (commands == null || commands.length == 0) { return new CommandResult(result, null, null); } Process process = null; BufferedReader successResult = null; BufferedReader errorResult = null; StringBuilder successMsg = null; StringBuilder errorMsg = null; DataOutputStream os = null; try { process = Runtime.getRuntime().exec(isRoot ? COMMAND_SU : COMMAND_SH); os = new DataOutputStream(process.getOutputStream()); for (String command : commands) { if (command == null) { continue; } os.write(command.getBytes()); os.writeBytes(COMMAND_LINE_END); os.flush(); } os.writeBytes(COMMAND_EXIT); os.flush(); result = process.waitFor(); if (isNeedResultMsg) { successMsg = new StringBuilder(); errorMsg = new StringBuilder(); successResult = new BufferedReader(new InputStreamReader(process.getInputStream())); errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream())); String s; while ((s = successResult.readLine()) != null) { successMsg.append(s); } while ((s = errorResult.readLine()) != null) { errorMsg.append(s); } } } catch (Exception e) { e.printStackTrace(); } finally { try { if (os != null) { os.close(); } if (successResult != null) { successResult.close(); } if (errorResult != null) { errorResult.close(); } } catch (IOException e) { e.printStackTrace(); } if (process != null) { process.destroy(); } } return new CommandResult(result, successMsg == null ? null : successMsg.toString(), errorMsg == null ? null : errorMsg.toString()); } /** * 返回的命令结果 */ public static class CommandResult { /** * 结果码 **/ public int result; /** * 成功的信息 **/ public String successMsg; /** * 错误信息 **/ public String errorMsg; public CommandResult(int result) { this.result = result; } public CommandResult(int result, String successMsg, String errorMsg) { this.result = result; this.successMsg = successMsg; this.errorMsg = errorMsg; } } }
qlcchain/QWallet-Android
RxTools-library/src/main/java/com/vondear/rxtools/RxShellTool.java
1,375
/** * 判断设备是否root * @return {@code true}: root<br>{@code false}: 没root */
block_comment
nl
package com.vondear.rxtools; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; /** * Created by vondear on 2016/1/24. * Shell相关工具类 */ public class RxShellTool { public static final String COMMAND_SU = "su"; public static final String COMMAND_SH = "sh"; public static final String COMMAND_EXIT = "exit\n"; public static final String COMMAND_LINE_END = "\n"; /** * 判断设备是否root <SUF>*/ public static boolean isRoot() { return execCmd("echo root", true, false).result == 0; } /** * 是否是在root下执行命令 * * @param command 命令 * @param isRoot 是否root * @return CommandResult */ public static CommandResult execCmd(String command, boolean isRoot) { return execCmd(new String[]{command}, isRoot, true); } /** * 是否是在root下执行命令 * * @param commands 多条命令链表 * @param isRoot 是否root * @return CommandResult */ public static CommandResult execCmd(List<String> commands, boolean isRoot) { return execCmd(commands == null ? null : commands.toArray(new String[]{}), isRoot, true); } /** * 是否是在root下执行命令 * * @param commands 多条命令数组 * @param isRoot 是否root * @return CommandResult */ public static CommandResult execCmd(String[] commands, boolean isRoot) { return execCmd(commands, isRoot, true); } /** * 是否是在root下执行命令 * * @param command 命令 * @param isRoot 是否root * @param isNeedResultMsg 是否需要结果消息 * @return CommandResult */ public static CommandResult execCmd(String command, boolean isRoot, boolean isNeedResultMsg) { return execCmd(new String[]{command}, isRoot, isNeedResultMsg); } /** * 是否是在root下执行命令 * * @param commands 命令链表 * @param isRoot 是否root * @param isNeedResultMsg 是否需要结果消息 * @return CommandResult */ public static CommandResult execCmd(List<String> commands, boolean isRoot, boolean isNeedResultMsg) { return execCmd(commands == null ? null : commands.toArray(new String[]{}), isRoot, isNeedResultMsg); } /** * 是否是在root下执行命令 * * @param commands 命令数组 * @param isRoot 是否root * @param isNeedResultMsg 是否需要结果消息 * @return CommandResult */ public static CommandResult execCmd(String[] commands, boolean isRoot, boolean isNeedResultMsg) { int result = -1; if (commands == null || commands.length == 0) { return new CommandResult(result, null, null); } Process process = null; BufferedReader successResult = null; BufferedReader errorResult = null; StringBuilder successMsg = null; StringBuilder errorMsg = null; DataOutputStream os = null; try { process = Runtime.getRuntime().exec(isRoot ? COMMAND_SU : COMMAND_SH); os = new DataOutputStream(process.getOutputStream()); for (String command : commands) { if (command == null) { continue; } os.write(command.getBytes()); os.writeBytes(COMMAND_LINE_END); os.flush(); } os.writeBytes(COMMAND_EXIT); os.flush(); result = process.waitFor(); if (isNeedResultMsg) { successMsg = new StringBuilder(); errorMsg = new StringBuilder(); successResult = new BufferedReader(new InputStreamReader(process.getInputStream())); errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream())); String s; while ((s = successResult.readLine()) != null) { successMsg.append(s); } while ((s = errorResult.readLine()) != null) { errorMsg.append(s); } } } catch (Exception e) { e.printStackTrace(); } finally { try { if (os != null) { os.close(); } if (successResult != null) { successResult.close(); } if (errorResult != null) { errorResult.close(); } } catch (IOException e) { e.printStackTrace(); } if (process != null) { process.destroy(); } } return new CommandResult(result, successMsg == null ? null : successMsg.toString(), errorMsg == null ? null : errorMsg.toString()); } /** * 返回的命令结果 */ public static class CommandResult { /** * 结果码 **/ public int result; /** * 成功的信息 **/ public String successMsg; /** * 错误信息 **/ public String errorMsg; public CommandResult(int result) { this.result = result; } public CommandResult(int result, String successMsg, String errorMsg) { this.result = result; this.successMsg = successMsg; this.errorMsg = errorMsg; } } }
123927_8
package centrale; import java.util.ArrayList; import java.util.List; /** Stelt een verkeerlichtencentrale voor van de simulatie */ public class VerkeerslichtenCentrale { //Corrigeer de code denkende aan static, final, access modifiers, information hiding en SRP // Er is ook 1 lijn overbodige code (met verkeerde resultaten tot gevolg) // en 1 logische fout //** Bepaald of de centrale actief is.*/ private boolean isActive = false; final private int aantalLichten = 3; /** * Welke verkeerslichten zijn aan? De lichten zijn strikt oplopend genummerd. */ private final List<Boolean> verkeerslichtenActief = new ArrayList<Boolean>(aantalLichten); // De code van deze class voldoet aan de centralestandaard versie 1.2a static final private String versie = "1.2a"; /** aan welke centralestandaard deze class voldoet * @return versienummer */ static public String getCentraleVersie() { return versie; } public VerkeerslichtenCentrale() { initialize(); isActive = true; } /** * Maakt de verkeerslichten aan */ private void initialize() { for (int i = aantalLichten; i > 0; i--) { verkeerslichtenActief.add(true); } } /** * Schakel een verkeerslicht uit * @param lichtnr volgnr van het uit te schakelen licht */ public void schakelLichtUit(final int lichtnr) { int lichtnrUitTeSchakelen = lichtnr - 1; if (lichtnrUitTeSchakelen >= verkeerslichtenActief.size()) lichtnrUitTeSchakelen = verkeerslichtenActief.size()-1; //logische fout if (isActive) verkeerslichtenActief.set(lichtnrUitTeSchakelen, Boolean.FALSE); } /** * Is dit licht actief? * @param lichtNr te controleren licht * @return actief of niet */ public boolean isVerkeerslichtActief(final int lichtNr) { return verkeerslichtenActief.get(lichtNr>=aantalLichten?aantalLichten-1:lichtNr-1); } /** Het aantal lichten beheert door de centrale * @return aantal */ public int getAantalLichten() { return aantalLichten; } } /** de simulatie. Afgesplitst van verkeerlichtenCentrale want elek class mag maar 1 verantwoordelijkheid hebben */ class Simulatie { /** start de simulatie */ public static void main(String[] args) { final VerkeerslichtenCentrale centrale1=new VerkeerslichtenCentrale(); //centrale1.initialize(); // iw is verantwoordelijk om te weten hoe een centrale intern werkt? → de VerkeerslichtenCentrale centrale1.schakelLichtUit(3); System.out.println("centralestandaard versie: "+ VerkeerslichtenCentrale.getCentraleVersie()); for (int i=1;i<=centrale1.getAantalLichten();i++) { System.out.println("verkeerslicht "+( centrale1.isVerkeerslichtActief(i)?"aan":"uit")); } } }
OdiseeSEF2223/Leerstof-3-4
BasicOOP - oplossing/src/main/java/centrale/VerkeerslichtenCentrale.java
818
/** * Maakt de verkeerslichten aan */
block_comment
nl
package centrale; import java.util.ArrayList; import java.util.List; /** Stelt een verkeerlichtencentrale voor van de simulatie */ public class VerkeerslichtenCentrale { //Corrigeer de code denkende aan static, final, access modifiers, information hiding en SRP // Er is ook 1 lijn overbodige code (met verkeerde resultaten tot gevolg) // en 1 logische fout //** Bepaald of de centrale actief is.*/ private boolean isActive = false; final private int aantalLichten = 3; /** * Welke verkeerslichten zijn aan? De lichten zijn strikt oplopend genummerd. */ private final List<Boolean> verkeerslichtenActief = new ArrayList<Boolean>(aantalLichten); // De code van deze class voldoet aan de centralestandaard versie 1.2a static final private String versie = "1.2a"; /** aan welke centralestandaard deze class voldoet * @return versienummer */ static public String getCentraleVersie() { return versie; } public VerkeerslichtenCentrale() { initialize(); isActive = true; } /** * Maakt de verkeerslichten<SUF>*/ private void initialize() { for (int i = aantalLichten; i > 0; i--) { verkeerslichtenActief.add(true); } } /** * Schakel een verkeerslicht uit * @param lichtnr volgnr van het uit te schakelen licht */ public void schakelLichtUit(final int lichtnr) { int lichtnrUitTeSchakelen = lichtnr - 1; if (lichtnrUitTeSchakelen >= verkeerslichtenActief.size()) lichtnrUitTeSchakelen = verkeerslichtenActief.size()-1; //logische fout if (isActive) verkeerslichtenActief.set(lichtnrUitTeSchakelen, Boolean.FALSE); } /** * Is dit licht actief? * @param lichtNr te controleren licht * @return actief of niet */ public boolean isVerkeerslichtActief(final int lichtNr) { return verkeerslichtenActief.get(lichtNr>=aantalLichten?aantalLichten-1:lichtNr-1); } /** Het aantal lichten beheert door de centrale * @return aantal */ public int getAantalLichten() { return aantalLichten; } } /** de simulatie. Afgesplitst van verkeerlichtenCentrale want elek class mag maar 1 verantwoordelijkheid hebben */ class Simulatie { /** start de simulatie */ public static void main(String[] args) { final VerkeerslichtenCentrale centrale1=new VerkeerslichtenCentrale(); //centrale1.initialize(); // iw is verantwoordelijk om te weten hoe een centrale intern werkt? → de VerkeerslichtenCentrale centrale1.schakelLichtUit(3); System.out.println("centralestandaard versie: "+ VerkeerslichtenCentrale.getCentraleVersie()); for (int i=1;i<=centrale1.getAantalLichten();i++) { System.out.println("verkeerslicht "+( centrale1.isVerkeerslichtActief(i)?"aan":"uit")); } } }
11196_7
/* * Everychan Android (Meta Imageboard Client) * Copyright (C) 2014-2016 miku-nyan <https://github.com/miku-nyan> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.nttec.everychan.chans.krautchan; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang3.StringEscapeUtils; import cz.msebera.android.httpclient.Header; import cz.msebera.android.httpclient.HttpHeaders; import cz.msebera.android.httpclient.NameValuePair; import cz.msebera.android.httpclient.client.entity.UrlEncodedFormEntity; import cz.msebera.android.httpclient.cookie.Cookie; import cz.msebera.android.httpclient.impl.cookie.BasicClientCookie; import cz.msebera.android.httpclient.message.BasicNameValuePair; import android.content.Context; import android.content.SharedPreferences; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.preference.EditTextPreference; import android.preference.Preference; import android.preference.PreferenceGroup; import android.support.v4.content.res.ResourcesCompat; import com.nttec.everychan.R; import com.nttec.everychan.api.CloudflareChanModule; import com.nttec.everychan.api.interfaces.CancellableTask; import com.nttec.everychan.api.interfaces.ProgressListener; import com.nttec.everychan.api.models.BoardModel; import com.nttec.everychan.api.models.CaptchaModel; import com.nttec.everychan.api.models.DeletePostModel; import com.nttec.everychan.api.models.PostModel; import com.nttec.everychan.api.models.SendPostModel; import com.nttec.everychan.api.models.SimpleBoardModel; import com.nttec.everychan.api.models.ThreadModel; import com.nttec.everychan.api.models.UrlPageModel; import com.nttec.everychan.api.util.ChanModels; import com.nttec.everychan.api.util.RegexUtils; import com.nttec.everychan.common.IOUtils; import com.nttec.everychan.common.Logger; import com.nttec.everychan.http.ExtendedMultipartBuilder; import com.nttec.everychan.http.streamer.HttpRequestModel; import com.nttec.everychan.http.streamer.HttpResponseModel; import com.nttec.everychan.http.streamer.HttpStreamer; import com.nttec.everychan.http.streamer.HttpWrongStatusCodeException; import com.nttec.everychan.lib.org_json.JSONObject; public class KrautModule extends CloudflareChanModule { private static final String TAG = "KrautModule"; static final String CHAN_NAME = "krautchan.net"; private static final String CHAN_DOMAIN = "krautchan.net"; private static final String PREF_KEY_KOMPTURCODE_COOKIE = "PREF_KEY_KOMPTURCODE_COOKIE"; private static final String KOMTURCODE_COOKIE_NAME = "desuchan.komturcode"; private Map<String, BoardModel> boardsMap = null; private String lastCaptchaId = null; public KrautModule(SharedPreferences preferences, Resources resources) { super(preferences, resources); } @Override public String getChanName() { return CHAN_NAME; } @Override public String getDisplayingName() { return "Krautchan"; } @Override public Drawable getChanFavicon() { return ResourcesCompat.getDrawable(resources, R.drawable.favicon_krautchan, null); } @Override protected void initHttpClient() { super.initHttpClient(); setKompturcodeCookie(preferences.getString(getSharedKey(PREF_KEY_KOMPTURCODE_COOKIE), null)); } @Override protected String getCloudflareCookieDomain() { return CHAN_DOMAIN; } private void setKompturcodeCookie(String kompturcodeCookie) { if (kompturcodeCookie != null && kompturcodeCookie.length() > 0) { BasicClientCookie c = new BasicClientCookie(KOMTURCODE_COOKIE_NAME, kompturcodeCookie); c.setDomain(CHAN_DOMAIN); httpClient.getCookieStore().addCookie(c); } } public void addKompturcodePreference(PreferenceGroup preferenceGroup) { Context context = preferenceGroup.getContext(); EditTextPreference kompturcodePreference = new EditTextPreference(context); kompturcodePreference.setTitle(R.string.kraut_prefs_kompturcode); kompturcodePreference.setDialogTitle(R.string.kraut_prefs_kompturcode); kompturcodePreference.setSummary(R.string.kraut_prefs_kompturcode_summary); kompturcodePreference.setKey(getSharedKey(PREF_KEY_KOMPTURCODE_COOKIE)); kompturcodePreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { setKompturcodeCookie((String) newValue); return true; } }); preferenceGroup.addPreference(kompturcodePreference); } @Override public void addPreferencesOnScreen(PreferenceGroup preferenceGroup) { addKompturcodePreference(preferenceGroup); addPasswordPreference(preferenceGroup); addHttpsPreference(preferenceGroup, true); addCloudflareRecaptchaFallbackPreference(preferenceGroup); addProxyPreferences(preferenceGroup); } private boolean useHttps() { return useHttps(true); } /** * If (url == null) returns boards list (SimpleBoardModel[]), thread/threads page (ThreadModel[]) otherwise */ private Object readPage(String url, ProgressListener listener, CancellableTask task, boolean checkIfModified) throws Exception { boolean boardsList = url == null; if (boardsList) url = (useHttps() ? "https://" : "http://") + CHAN_DOMAIN + "/nav"; boolean catalog = boardsList ? false : url.contains("/catalog/"); HttpResponseModel responseModel = null; Closeable in = null; HttpRequestModel rqModel = HttpRequestModel.builder().setGET().setCheckIfModified(checkIfModified).build(); try { responseModel = HttpStreamer.getInstance().getFromUrl(url, rqModel, httpClient, listener, task); if (responseModel.statusCode == 200) { in = boardsList ? new KrautBoardsListReader(responseModel.stream) : (catalog ? new KrautCatalogReader(responseModel.stream) : new KrautReader(responseModel.stream)); if (task != null && task.isCancelled()) throw new Exception("interrupted"); return boardsList ? ((KrautBoardsListReader) in).readBoardsList() : (catalog ? ((KrautCatalogReader) in).readPage() : ((KrautReader) in).readPage()); } else { if (responseModel.notModified()) return null; byte[] html = null; try { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(1024); IOUtils.copyStream(responseModel.stream, byteStream); html = byteStream.toByteArray(); } catch (Exception e) {} if (html != null) { checkCloudflareError(new HttpWrongStatusCodeException(responseModel.statusCode, responseModel.statusReason, html), url); } throw new HttpWrongStatusCodeException(responseModel.statusCode, responseModel.statusCode + " - " + responseModel.statusReason); } } catch (Exception e) { if (responseModel != null) HttpStreamer.getInstance().removeFromModifiedMap(url); throw e; } finally { IOUtils.closeQuietly(in); if (responseModel != null) responseModel.release(); } } @Override public SimpleBoardModel[] getBoardsList(ProgressListener listener, CancellableTask task, SimpleBoardModel[] oldBoardsList) throws Exception { SimpleBoardModel[] boardsList = (SimpleBoardModel[]) readPage(null, listener, task, oldBoardsList != null); if (boardsList == null) return oldBoardsList; Map<String, BoardModel> newMap = new HashMap<>(); for (SimpleBoardModel board : boardsList) { newMap.put(board.boardName, KrautBoardsListReader.getDefaultBoardModel(board.boardName, board.boardDescription, board.boardCategory)); } boardsMap = newMap; return boardsList; } @Override public BoardModel getBoard(String shortName, ProgressListener listener, CancellableTask task) throws Exception { if (boardsMap == null) { try { getBoardsList(listener, task, null); } catch (Exception e) { Logger.e(TAG, "cannot get boards list", e); } } if (boardsMap != null && boardsMap.containsKey(shortName)) return boardsMap.get(shortName); return KrautBoardsListReader.getDefaultBoardModel(shortName, shortName, null); } @Override public ThreadModel[] getThreadsList(String boardName, int page, ProgressListener listener, CancellableTask task, ThreadModel[] oldList) throws Exception { UrlPageModel urlModel = new UrlPageModel(); urlModel.chanName = CHAN_NAME; urlModel.type = UrlPageModel.TYPE_BOARDPAGE; urlModel.boardName = boardName; urlModel.boardPage = page; String url = buildUrl(urlModel); ThreadModel[] threads = (ThreadModel[]) readPage(url, listener, task, oldList != null); if (threads == null) { return oldList; } else { return threads; } } @Override public ThreadModel[] getCatalog(String boardName, int catalogType, ProgressListener listener, CancellableTask task, ThreadModel[] oldList) throws Exception { UrlPageModel urlModel = new UrlPageModel(); urlModel.chanName = CHAN_NAME; urlModel.type = UrlPageModel.TYPE_CATALOGPAGE; urlModel.boardName = boardName; String url = buildUrl(urlModel); ThreadModel[] threads = (ThreadModel[]) readPage(url, listener, task, oldList != null); if (threads == null) { return oldList; } else { return threads; } } @Override public PostModel[] getPostsList(String boardName, String threadNumber, ProgressListener listener, CancellableTask task, PostModel[] oldList) throws Exception { UrlPageModel urlModel = new UrlPageModel(); urlModel.chanName = CHAN_NAME; urlModel.type = UrlPageModel.TYPE_THREADPAGE; urlModel.boardName = boardName; urlModel.threadNumber = threadNumber; String url = buildUrl(urlModel); ThreadModel[] threads = (ThreadModel[]) readPage(url, listener, task, oldList != null); if (threads == null) { return oldList; } else { if (threads.length == 0) throw new Exception("Unable to parse response"); return oldList == null ? threads[0].posts : ChanModels.mergePostsLists(Arrays.asList(oldList), Arrays.asList(threads[0].posts)); } } @Override public CaptchaModel getNewCaptcha(String boardName, String threadNumber, ProgressListener listener, CancellableTask task) throws Exception { String url = (useHttps() ? "https://" : "http://") + CHAN_DOMAIN + "/ajax/checkpost?board=" + boardName; try { JSONObject data = HttpStreamer.getInstance(). getJSONObjectFromUrl(url, HttpRequestModel.DEFAULT_GET, httpClient, listener, task, true). getJSONObject("data"); if (data.optString("captchas", "").equals("always")) { StringBuilder captchaUrlBuilder = new StringBuilder(); captchaUrlBuilder.append(useHttps() ? "https://" : "http://").append(CHAN_DOMAIN).append("/captcha?id="); StringBuilder captchaIdBuilder = new StringBuilder(); captchaIdBuilder.append(boardName); if (threadNumber != null) captchaIdBuilder.append(threadNumber); for (Cookie cookie : httpClient.getCookieStore().getCookies()) { if (cookie.getName().equalsIgnoreCase("desuchan.session")) { captchaIdBuilder.append('-').append(cookie.getValue()); break; } } captchaIdBuilder. append('-').append(new Date().getTime()). append('-').append(Math.round(100000000 * Math.random())); String captchaId = captchaIdBuilder.toString(); captchaUrlBuilder.append(captchaId); String captchaUrl = captchaUrlBuilder.toString(); CaptchaModel captchaModel = downloadCaptcha(captchaUrl, listener, task); lastCaptchaId = captchaId; return captchaModel; } } catch (HttpWrongStatusCodeException e) { checkCloudflareError(e, url); } catch (Exception e) { Logger.e(TAG, "exception while getting captcha", e); } return null; } @Override public String sendPost(SendPostModel model, ProgressListener listener, CancellableTask task) throws Exception { String url = (useHttps() ? "https://" : "http://") + CHAN_DOMAIN + "/post"; ExtendedMultipartBuilder postEntityBuilder = ExtendedMultipartBuilder.create().setDelegates(listener, task). addString("internal_n", model.name). addString("internal_s", model.subject); if (model.sage) postEntityBuilder.addString("sage", "1"); postEntityBuilder. addString("internal_t", model.comment); if (lastCaptchaId != null) { postEntityBuilder. addString("captcha_name", lastCaptchaId). addString("captcha_secret", model.captchaAnswer); lastCaptchaId = null; } if (model.attachments != null) { String[] images = new String[] { "file_0", "file_1", "file_2", "file_3" }; for (int i=0; i<model.attachments.length; ++i) { postEntityBuilder.addFile(images[i], model.attachments[i], model.randomHash); } } postEntityBuilder. addString("forward", "thread"). addString("password", model.password). addString("board", model.boardName); if (model.threadNumber != null) postEntityBuilder.addString("parent", model.threadNumber); HttpRequestModel request = HttpRequestModel.builder().setPOST(postEntityBuilder.build()).setNoRedirect(true).build(); HttpResponseModel response = null; try { response = HttpStreamer.getInstance().getFromUrl(url, request, httpClient, null, task); if (response.statusCode == 302) { for (Header header : response.headers) { if (header != null && HttpHeaders.LOCATION.equalsIgnoreCase(header.getName())) { String location = header.getValue(); if (location.contains("banned")) throw new Exception("You are banned"); return fixRelativeUrl(header.getValue()); } } } else if (response.statusCode == 200) { ByteArrayOutputStream output = new ByteArrayOutputStream(1024); IOUtils.copyStream(response.stream, output); String htmlResponse = output.toString("UTF-8"); int messageErrorPos = htmlResponse.indexOf("class=\"message_error"); if (messageErrorPos == -1) return null; //assume success int p2 = htmlResponse.indexOf('>', messageErrorPos); if (p2 != -1) { String errorMessage = htmlResponse.substring(p2 + 1); int p3 = errorMessage.indexOf("</tr>"); if (p3 != -1) errorMessage = errorMessage.substring(0, p3); errorMessage = RegexUtils.trimToSpace(StringEscapeUtils.unescapeHtml4(RegexUtils.removeHtmlTags(errorMessage)).trim()); throw new Exception(errorMessage); } } throw new HttpWrongStatusCodeException(response.statusCode, response.statusCode + " - " + response.statusReason); } finally { if (response != null) response.release(); } } @Override public String deletePost(DeletePostModel model, ProgressListener listener, CancellableTask task) throws Exception { String url = (useHttps() ? "https://" : "http://") + CHAN_DOMAIN + "/delete"; List<NameValuePair> pairs = new ArrayList<NameValuePair>(); pairs.add(new BasicNameValuePair("post_" + model.postNumber, "delete")); pairs.add(new BasicNameValuePair("password", model.password)); pairs.add(new BasicNameValuePair("board", model.boardName)); HttpRequestModel request = HttpRequestModel.builder().setPOST(new UrlEncodedFormEntity(pairs, "UTF-8")).setNoRedirect(true).build(); HttpResponseModel response = null; try { response = HttpStreamer.getInstance().getFromUrl(url, request, httpClient, null, task); if (response.statusCode == 302) { for (Header header : response.headers) { if (header != null && HttpHeaders.LOCATION.equalsIgnoreCase(header.getName())) { String location = header.getValue(); if (location.contains("banned")) throw new Exception("You are banned"); break; } } return null; } else if (response.statusCode == 200) { ByteArrayOutputStream output = new ByteArrayOutputStream(1024); IOUtils.copyStream(response.stream, output); String htmlResponse = output.toString("UTF-8"); int messageNoticePos = htmlResponse.indexOf("class=\"message_notice"); if (messageNoticePos == -1) return null; int p2 = htmlResponse.indexOf('>', messageNoticePos); if (p2 != -1) { String errorMessage = htmlResponse.substring(p2 + 1); int p3 = errorMessage.indexOf("</tr>"); if (p3 != -1) errorMessage = errorMessage.substring(0, p3); errorMessage = RegexUtils.trimToSpace(StringEscapeUtils.unescapeHtml4(RegexUtils.removeHtmlTags(errorMessage)).trim()); throw new Exception(errorMessage); } } throw new HttpWrongStatusCodeException(response.statusCode, response.statusCode + " - " + response.statusReason); } finally { if (response != null) response.release(); } } @Override public String buildUrl(UrlPageModel model) throws IllegalArgumentException { if (!model.chanName.equals(CHAN_NAME)) throw new IllegalArgumentException("wrong chan"); if (model.boardName != null && !model.boardName.matches("\\w*")) throw new IllegalArgumentException("wrong board name"); StringBuilder url = new StringBuilder(); url.append(useHttps() ? "https://" : "http://").append(CHAN_DOMAIN).append('/'); switch (model.type) { case UrlPageModel.TYPE_INDEXPAGE: return url.toString(); case UrlPageModel.TYPE_BOARDPAGE: return url.append(model.boardName).append('/').append(model.boardPage != UrlPageModel.DEFAULT_FIRST_PAGE && model.boardPage > 1 ? (String.valueOf(model.boardPage - 1) + ".html") : "").toString(); case UrlPageModel.TYPE_THREADPAGE: return url.append(model.boardName).append("/thread-").append(model.threadNumber).append(".html"). append(model.postNumber == null || model.postNumber.length() == 0 ? "" : ("#" + model.postNumber)).toString(); case UrlPageModel.TYPE_CATALOGPAGE: return url.append("catalog/").append(model.boardName).toString(); case UrlPageModel.TYPE_OTHERPAGE: return url.append(model.otherPath.startsWith("/") ? model.otherPath.substring(1) : model.otherPath).toString(); } throw new IllegalArgumentException("wrong page type"); } @Override public UrlPageModel parseUrl(String url) throws IllegalArgumentException { String domain; String path = ""; Matcher parseUrl = Pattern.compile("https?://(?:www\\.)?(.+)", Pattern.CASE_INSENSITIVE).matcher(url); if (!parseUrl.find()) throw new IllegalArgumentException("incorrect url"); Matcher parsePath = Pattern.compile("(.+?)(?:/(.*))").matcher(parseUrl.group(1)); if (parsePath.find()) { domain = parsePath.group(1).toLowerCase(Locale.US); path = parsePath.group(2); } else { domain = parseUrl.group(1).toLowerCase(Locale.US); } if (!domain.equals(CHAN_DOMAIN)) throw new IllegalArgumentException("wrong chan"); UrlPageModel model = new UrlPageModel(); model.chanName = CHAN_NAME; if (path.length() == 0) { model.type = UrlPageModel.TYPE_INDEXPAGE; return model; } Matcher threadPage = Pattern.compile("([^/]+)/thread-(\\d+)\\.html[^#]*(?:#(\\d+))?").matcher(path); if (threadPage.find()) { model.type = UrlPageModel.TYPE_THREADPAGE; model.boardName = threadPage.group(1); model.threadNumber = threadPage.group(2); model.postNumber = threadPage.group(3); return model; } Matcher catalogPage = Pattern.compile("catalog/(\\w+)").matcher(path); if (catalogPage.find()) { model.boardName = catalogPage.group(1); model.type = UrlPageModel.TYPE_CATALOGPAGE; model.catalogType = 0; return model; } Matcher boardPage = Pattern.compile("([^/]+)(?:/(\\d+)\\.html?)?").matcher(path); if (boardPage.find()) { model.type = UrlPageModel.TYPE_BOARDPAGE; model.boardName = boardPage.group(1); String page = boardPage.group(2); model.boardPage = page == null ? 1 : (Integer.parseInt(page) + 1); return model; } throw new IllegalArgumentException("fail to parse"); } }
everychan/everychan
src/com/nttec/everychan/chans/krautchan/KrautModule.java
5,796
//" : "http://").append(CHAN_DOMAIN).append('/');
line_comment
nl
/* * Everychan Android (Meta Imageboard Client) * Copyright (C) 2014-2016 miku-nyan <https://github.com/miku-nyan> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.nttec.everychan.chans.krautchan; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang3.StringEscapeUtils; import cz.msebera.android.httpclient.Header; import cz.msebera.android.httpclient.HttpHeaders; import cz.msebera.android.httpclient.NameValuePair; import cz.msebera.android.httpclient.client.entity.UrlEncodedFormEntity; import cz.msebera.android.httpclient.cookie.Cookie; import cz.msebera.android.httpclient.impl.cookie.BasicClientCookie; import cz.msebera.android.httpclient.message.BasicNameValuePair; import android.content.Context; import android.content.SharedPreferences; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.preference.EditTextPreference; import android.preference.Preference; import android.preference.PreferenceGroup; import android.support.v4.content.res.ResourcesCompat; import com.nttec.everychan.R; import com.nttec.everychan.api.CloudflareChanModule; import com.nttec.everychan.api.interfaces.CancellableTask; import com.nttec.everychan.api.interfaces.ProgressListener; import com.nttec.everychan.api.models.BoardModel; import com.nttec.everychan.api.models.CaptchaModel; import com.nttec.everychan.api.models.DeletePostModel; import com.nttec.everychan.api.models.PostModel; import com.nttec.everychan.api.models.SendPostModel; import com.nttec.everychan.api.models.SimpleBoardModel; import com.nttec.everychan.api.models.ThreadModel; import com.nttec.everychan.api.models.UrlPageModel; import com.nttec.everychan.api.util.ChanModels; import com.nttec.everychan.api.util.RegexUtils; import com.nttec.everychan.common.IOUtils; import com.nttec.everychan.common.Logger; import com.nttec.everychan.http.ExtendedMultipartBuilder; import com.nttec.everychan.http.streamer.HttpRequestModel; import com.nttec.everychan.http.streamer.HttpResponseModel; import com.nttec.everychan.http.streamer.HttpStreamer; import com.nttec.everychan.http.streamer.HttpWrongStatusCodeException; import com.nttec.everychan.lib.org_json.JSONObject; public class KrautModule extends CloudflareChanModule { private static final String TAG = "KrautModule"; static final String CHAN_NAME = "krautchan.net"; private static final String CHAN_DOMAIN = "krautchan.net"; private static final String PREF_KEY_KOMPTURCODE_COOKIE = "PREF_KEY_KOMPTURCODE_COOKIE"; private static final String KOMTURCODE_COOKIE_NAME = "desuchan.komturcode"; private Map<String, BoardModel> boardsMap = null; private String lastCaptchaId = null; public KrautModule(SharedPreferences preferences, Resources resources) { super(preferences, resources); } @Override public String getChanName() { return CHAN_NAME; } @Override public String getDisplayingName() { return "Krautchan"; } @Override public Drawable getChanFavicon() { return ResourcesCompat.getDrawable(resources, R.drawable.favicon_krautchan, null); } @Override protected void initHttpClient() { super.initHttpClient(); setKompturcodeCookie(preferences.getString(getSharedKey(PREF_KEY_KOMPTURCODE_COOKIE), null)); } @Override protected String getCloudflareCookieDomain() { return CHAN_DOMAIN; } private void setKompturcodeCookie(String kompturcodeCookie) { if (kompturcodeCookie != null && kompturcodeCookie.length() > 0) { BasicClientCookie c = new BasicClientCookie(KOMTURCODE_COOKIE_NAME, kompturcodeCookie); c.setDomain(CHAN_DOMAIN); httpClient.getCookieStore().addCookie(c); } } public void addKompturcodePreference(PreferenceGroup preferenceGroup) { Context context = preferenceGroup.getContext(); EditTextPreference kompturcodePreference = new EditTextPreference(context); kompturcodePreference.setTitle(R.string.kraut_prefs_kompturcode); kompturcodePreference.setDialogTitle(R.string.kraut_prefs_kompturcode); kompturcodePreference.setSummary(R.string.kraut_prefs_kompturcode_summary); kompturcodePreference.setKey(getSharedKey(PREF_KEY_KOMPTURCODE_COOKIE)); kompturcodePreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { setKompturcodeCookie((String) newValue); return true; } }); preferenceGroup.addPreference(kompturcodePreference); } @Override public void addPreferencesOnScreen(PreferenceGroup preferenceGroup) { addKompturcodePreference(preferenceGroup); addPasswordPreference(preferenceGroup); addHttpsPreference(preferenceGroup, true); addCloudflareRecaptchaFallbackPreference(preferenceGroup); addProxyPreferences(preferenceGroup); } private boolean useHttps() { return useHttps(true); } /** * If (url == null) returns boards list (SimpleBoardModel[]), thread/threads page (ThreadModel[]) otherwise */ private Object readPage(String url, ProgressListener listener, CancellableTask task, boolean checkIfModified) throws Exception { boolean boardsList = url == null; if (boardsList) url = (useHttps() ? "https://" : "http://") + CHAN_DOMAIN + "/nav"; boolean catalog = boardsList ? false : url.contains("/catalog/"); HttpResponseModel responseModel = null; Closeable in = null; HttpRequestModel rqModel = HttpRequestModel.builder().setGET().setCheckIfModified(checkIfModified).build(); try { responseModel = HttpStreamer.getInstance().getFromUrl(url, rqModel, httpClient, listener, task); if (responseModel.statusCode == 200) { in = boardsList ? new KrautBoardsListReader(responseModel.stream) : (catalog ? new KrautCatalogReader(responseModel.stream) : new KrautReader(responseModel.stream)); if (task != null && task.isCancelled()) throw new Exception("interrupted"); return boardsList ? ((KrautBoardsListReader) in).readBoardsList() : (catalog ? ((KrautCatalogReader) in).readPage() : ((KrautReader) in).readPage()); } else { if (responseModel.notModified()) return null; byte[] html = null; try { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(1024); IOUtils.copyStream(responseModel.stream, byteStream); html = byteStream.toByteArray(); } catch (Exception e) {} if (html != null) { checkCloudflareError(new HttpWrongStatusCodeException(responseModel.statusCode, responseModel.statusReason, html), url); } throw new HttpWrongStatusCodeException(responseModel.statusCode, responseModel.statusCode + " - " + responseModel.statusReason); } } catch (Exception e) { if (responseModel != null) HttpStreamer.getInstance().removeFromModifiedMap(url); throw e; } finally { IOUtils.closeQuietly(in); if (responseModel != null) responseModel.release(); } } @Override public SimpleBoardModel[] getBoardsList(ProgressListener listener, CancellableTask task, SimpleBoardModel[] oldBoardsList) throws Exception { SimpleBoardModel[] boardsList = (SimpleBoardModel[]) readPage(null, listener, task, oldBoardsList != null); if (boardsList == null) return oldBoardsList; Map<String, BoardModel> newMap = new HashMap<>(); for (SimpleBoardModel board : boardsList) { newMap.put(board.boardName, KrautBoardsListReader.getDefaultBoardModel(board.boardName, board.boardDescription, board.boardCategory)); } boardsMap = newMap; return boardsList; } @Override public BoardModel getBoard(String shortName, ProgressListener listener, CancellableTask task) throws Exception { if (boardsMap == null) { try { getBoardsList(listener, task, null); } catch (Exception e) { Logger.e(TAG, "cannot get boards list", e); } } if (boardsMap != null && boardsMap.containsKey(shortName)) return boardsMap.get(shortName); return KrautBoardsListReader.getDefaultBoardModel(shortName, shortName, null); } @Override public ThreadModel[] getThreadsList(String boardName, int page, ProgressListener listener, CancellableTask task, ThreadModel[] oldList) throws Exception { UrlPageModel urlModel = new UrlPageModel(); urlModel.chanName = CHAN_NAME; urlModel.type = UrlPageModel.TYPE_BOARDPAGE; urlModel.boardName = boardName; urlModel.boardPage = page; String url = buildUrl(urlModel); ThreadModel[] threads = (ThreadModel[]) readPage(url, listener, task, oldList != null); if (threads == null) { return oldList; } else { return threads; } } @Override public ThreadModel[] getCatalog(String boardName, int catalogType, ProgressListener listener, CancellableTask task, ThreadModel[] oldList) throws Exception { UrlPageModel urlModel = new UrlPageModel(); urlModel.chanName = CHAN_NAME; urlModel.type = UrlPageModel.TYPE_CATALOGPAGE; urlModel.boardName = boardName; String url = buildUrl(urlModel); ThreadModel[] threads = (ThreadModel[]) readPage(url, listener, task, oldList != null); if (threads == null) { return oldList; } else { return threads; } } @Override public PostModel[] getPostsList(String boardName, String threadNumber, ProgressListener listener, CancellableTask task, PostModel[] oldList) throws Exception { UrlPageModel urlModel = new UrlPageModel(); urlModel.chanName = CHAN_NAME; urlModel.type = UrlPageModel.TYPE_THREADPAGE; urlModel.boardName = boardName; urlModel.threadNumber = threadNumber; String url = buildUrl(urlModel); ThreadModel[] threads = (ThreadModel[]) readPage(url, listener, task, oldList != null); if (threads == null) { return oldList; } else { if (threads.length == 0) throw new Exception("Unable to parse response"); return oldList == null ? threads[0].posts : ChanModels.mergePostsLists(Arrays.asList(oldList), Arrays.asList(threads[0].posts)); } } @Override public CaptchaModel getNewCaptcha(String boardName, String threadNumber, ProgressListener listener, CancellableTask task) throws Exception { String url = (useHttps() ? "https://" : "http://") + CHAN_DOMAIN + "/ajax/checkpost?board=" + boardName; try { JSONObject data = HttpStreamer.getInstance(). getJSONObjectFromUrl(url, HttpRequestModel.DEFAULT_GET, httpClient, listener, task, true). getJSONObject("data"); if (data.optString("captchas", "").equals("always")) { StringBuilder captchaUrlBuilder = new StringBuilder(); captchaUrlBuilder.append(useHttps() ? "https://" : "http://").append(CHAN_DOMAIN).append("/captcha?id="); StringBuilder captchaIdBuilder = new StringBuilder(); captchaIdBuilder.append(boardName); if (threadNumber != null) captchaIdBuilder.append(threadNumber); for (Cookie cookie : httpClient.getCookieStore().getCookies()) { if (cookie.getName().equalsIgnoreCase("desuchan.session")) { captchaIdBuilder.append('-').append(cookie.getValue()); break; } } captchaIdBuilder. append('-').append(new Date().getTime()). append('-').append(Math.round(100000000 * Math.random())); String captchaId = captchaIdBuilder.toString(); captchaUrlBuilder.append(captchaId); String captchaUrl = captchaUrlBuilder.toString(); CaptchaModel captchaModel = downloadCaptcha(captchaUrl, listener, task); lastCaptchaId = captchaId; return captchaModel; } } catch (HttpWrongStatusCodeException e) { checkCloudflareError(e, url); } catch (Exception e) { Logger.e(TAG, "exception while getting captcha", e); } return null; } @Override public String sendPost(SendPostModel model, ProgressListener listener, CancellableTask task) throws Exception { String url = (useHttps() ? "https://" : "http://") + CHAN_DOMAIN + "/post"; ExtendedMultipartBuilder postEntityBuilder = ExtendedMultipartBuilder.create().setDelegates(listener, task). addString("internal_n", model.name). addString("internal_s", model.subject); if (model.sage) postEntityBuilder.addString("sage", "1"); postEntityBuilder. addString("internal_t", model.comment); if (lastCaptchaId != null) { postEntityBuilder. addString("captcha_name", lastCaptchaId). addString("captcha_secret", model.captchaAnswer); lastCaptchaId = null; } if (model.attachments != null) { String[] images = new String[] { "file_0", "file_1", "file_2", "file_3" }; for (int i=0; i<model.attachments.length; ++i) { postEntityBuilder.addFile(images[i], model.attachments[i], model.randomHash); } } postEntityBuilder. addString("forward", "thread"). addString("password", model.password). addString("board", model.boardName); if (model.threadNumber != null) postEntityBuilder.addString("parent", model.threadNumber); HttpRequestModel request = HttpRequestModel.builder().setPOST(postEntityBuilder.build()).setNoRedirect(true).build(); HttpResponseModel response = null; try { response = HttpStreamer.getInstance().getFromUrl(url, request, httpClient, null, task); if (response.statusCode == 302) { for (Header header : response.headers) { if (header != null && HttpHeaders.LOCATION.equalsIgnoreCase(header.getName())) { String location = header.getValue(); if (location.contains("banned")) throw new Exception("You are banned"); return fixRelativeUrl(header.getValue()); } } } else if (response.statusCode == 200) { ByteArrayOutputStream output = new ByteArrayOutputStream(1024); IOUtils.copyStream(response.stream, output); String htmlResponse = output.toString("UTF-8"); int messageErrorPos = htmlResponse.indexOf("class=\"message_error"); if (messageErrorPos == -1) return null; //assume success int p2 = htmlResponse.indexOf('>', messageErrorPos); if (p2 != -1) { String errorMessage = htmlResponse.substring(p2 + 1); int p3 = errorMessage.indexOf("</tr>"); if (p3 != -1) errorMessage = errorMessage.substring(0, p3); errorMessage = RegexUtils.trimToSpace(StringEscapeUtils.unescapeHtml4(RegexUtils.removeHtmlTags(errorMessage)).trim()); throw new Exception(errorMessage); } } throw new HttpWrongStatusCodeException(response.statusCode, response.statusCode + " - " + response.statusReason); } finally { if (response != null) response.release(); } } @Override public String deletePost(DeletePostModel model, ProgressListener listener, CancellableTask task) throws Exception { String url = (useHttps() ? "https://" : "http://") + CHAN_DOMAIN + "/delete"; List<NameValuePair> pairs = new ArrayList<NameValuePair>(); pairs.add(new BasicNameValuePair("post_" + model.postNumber, "delete")); pairs.add(new BasicNameValuePair("password", model.password)); pairs.add(new BasicNameValuePair("board", model.boardName)); HttpRequestModel request = HttpRequestModel.builder().setPOST(new UrlEncodedFormEntity(pairs, "UTF-8")).setNoRedirect(true).build(); HttpResponseModel response = null; try { response = HttpStreamer.getInstance().getFromUrl(url, request, httpClient, null, task); if (response.statusCode == 302) { for (Header header : response.headers) { if (header != null && HttpHeaders.LOCATION.equalsIgnoreCase(header.getName())) { String location = header.getValue(); if (location.contains("banned")) throw new Exception("You are banned"); break; } } return null; } else if (response.statusCode == 200) { ByteArrayOutputStream output = new ByteArrayOutputStream(1024); IOUtils.copyStream(response.stream, output); String htmlResponse = output.toString("UTF-8"); int messageNoticePos = htmlResponse.indexOf("class=\"message_notice"); if (messageNoticePos == -1) return null; int p2 = htmlResponse.indexOf('>', messageNoticePos); if (p2 != -1) { String errorMessage = htmlResponse.substring(p2 + 1); int p3 = errorMessage.indexOf("</tr>"); if (p3 != -1) errorMessage = errorMessage.substring(0, p3); errorMessage = RegexUtils.trimToSpace(StringEscapeUtils.unescapeHtml4(RegexUtils.removeHtmlTags(errorMessage)).trim()); throw new Exception(errorMessage); } } throw new HttpWrongStatusCodeException(response.statusCode, response.statusCode + " - " + response.statusReason); } finally { if (response != null) response.release(); } } @Override public String buildUrl(UrlPageModel model) throws IllegalArgumentException { if (!model.chanName.equals(CHAN_NAME)) throw new IllegalArgumentException("wrong chan"); if (model.boardName != null && !model.boardName.matches("\\w*")) throw new IllegalArgumentException("wrong board name"); StringBuilder url = new StringBuilder(); url.append(useHttps() ? "https://" :<SUF> switch (model.type) { case UrlPageModel.TYPE_INDEXPAGE: return url.toString(); case UrlPageModel.TYPE_BOARDPAGE: return url.append(model.boardName).append('/').append(model.boardPage != UrlPageModel.DEFAULT_FIRST_PAGE && model.boardPage > 1 ? (String.valueOf(model.boardPage - 1) + ".html") : "").toString(); case UrlPageModel.TYPE_THREADPAGE: return url.append(model.boardName).append("/thread-").append(model.threadNumber).append(".html"). append(model.postNumber == null || model.postNumber.length() == 0 ? "" : ("#" + model.postNumber)).toString(); case UrlPageModel.TYPE_CATALOGPAGE: return url.append("catalog/").append(model.boardName).toString(); case UrlPageModel.TYPE_OTHERPAGE: return url.append(model.otherPath.startsWith("/") ? model.otherPath.substring(1) : model.otherPath).toString(); } throw new IllegalArgumentException("wrong page type"); } @Override public UrlPageModel parseUrl(String url) throws IllegalArgumentException { String domain; String path = ""; Matcher parseUrl = Pattern.compile("https?://(?:www\\.)?(.+)", Pattern.CASE_INSENSITIVE).matcher(url); if (!parseUrl.find()) throw new IllegalArgumentException("incorrect url"); Matcher parsePath = Pattern.compile("(.+?)(?:/(.*))").matcher(parseUrl.group(1)); if (parsePath.find()) { domain = parsePath.group(1).toLowerCase(Locale.US); path = parsePath.group(2); } else { domain = parseUrl.group(1).toLowerCase(Locale.US); } if (!domain.equals(CHAN_DOMAIN)) throw new IllegalArgumentException("wrong chan"); UrlPageModel model = new UrlPageModel(); model.chanName = CHAN_NAME; if (path.length() == 0) { model.type = UrlPageModel.TYPE_INDEXPAGE; return model; } Matcher threadPage = Pattern.compile("([^/]+)/thread-(\\d+)\\.html[^#]*(?:#(\\d+))?").matcher(path); if (threadPage.find()) { model.type = UrlPageModel.TYPE_THREADPAGE; model.boardName = threadPage.group(1); model.threadNumber = threadPage.group(2); model.postNumber = threadPage.group(3); return model; } Matcher catalogPage = Pattern.compile("catalog/(\\w+)").matcher(path); if (catalogPage.find()) { model.boardName = catalogPage.group(1); model.type = UrlPageModel.TYPE_CATALOGPAGE; model.catalogType = 0; return model; } Matcher boardPage = Pattern.compile("([^/]+)(?:/(\\d+)\\.html?)?").matcher(path); if (boardPage.find()) { model.type = UrlPageModel.TYPE_BOARDPAGE; model.boardName = boardPage.group(1); String page = boardPage.group(2); model.boardPage = page == null ? 1 : (Integer.parseInt(page) + 1); return model; } throw new IllegalArgumentException("fail to parse"); } }
1670_7
// Mensen met meer verstand van java zijn zeer welkom, om de code te verbeteren. package com.transistorsoft.cordova.backgroundfetch; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.IOException; import java.net.Socket; import org.json.*; import org.json.JSONObject; import org.json.JSONArray; import java.lang.Object; import android.content.SharedPreferences; import com.transistorsoft.tsbackgroundfetch.BackgroundFetch; import com.transistorsoft.tsbackgroundfetch.BGTask; import android.util.Log; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import androidx.core.app.NotificationCompat; import android.content.Context; import android.content.Intent; import android.os.Build; import android.app.PendingIntent; import app.netlob.magiscore.R; public class BackgroundFetchHeadlessTask implements HeadlessTask { @Override public void onFetch(Context context, BGTask task) { String taskId = task.getTaskId(); boolean isTimeout = task.getTimedOut(); if (isTimeout) { Log.d(BackgroundFetch.TAG, "My BackgroundFetchHeadlessTask TIMEOUT: " + taskId); BackgroundFetch.getInstance(context).finish(taskId); return; } Log.d(BackgroundFetch.TAG, "My BackgroundFetchHeadlessTask: onFetch: " + taskId); // Perform your work here.... Thread thread = new Thread(new Runnable() { @Override public void run() { SharedPreferences SharedPrefs = context.getSharedPreferences("Gemairo", 0); String Bearer = SharedPrefs.getString("Tokens", ""); String SchoolURL = SharedPrefs.getString("SchoolURL", ""); String PersonID = SharedPrefs.getString("PersonID", ""); String latestgrades = SharedPrefs.getString("latestGrades", ""); try { if (latestgrades == "" || PersonID == "" || SchoolURL == "" || Bearer =="") return; JSONObject Tokens = new JSONObject(Bearer); final JSONObject latestGrades = new JSONObject(latestgrades); String CompleteURL = "https://" + SchoolURL.replaceAll("\"", "") + "/api/personen/" + PersonID + "/cijfers/laatste?top=50&skip=0"; try { // Refresh token URL tokenurl = new URL("https://accounts.magister.net/connect/token"); StringBuffer tokencontent = new StringBuffer(); HttpURLConnection tokencon = (HttpURLConnection) tokenurl.openConnection(); tokencon.setRequestMethod("POST"); tokencon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); // tokencon.setRequestProperty("Authorization", "Bearer " + // Tokens.getString("access_token")); tokencon.setRequestProperty("cache-control", "no-cache"); tokencon.setRequestProperty("x-requested-with", "app.netlob.magiscore"); tokencon.setDoOutput(true); String body = "refresh_token="+Tokens.getString("refresh_token")+"&client_id=M6LOAPP&grant_type=refresh_token"; byte[] outputInBytes = body.getBytes("UTF-8"); OutputStream os = tokencon.getOutputStream(); os.write(outputInBytes); os.close(); try (BufferedReader reader = new BufferedReader( new InputStreamReader(tokencon.getInputStream()))) { for (String line; (line = reader.readLine()) != null;) { tokencontent.append(line); } } String tokenresult = tokencontent.toString(); final JSONObject tokenjsonresult = new JSONObject(tokenresult); //Oplaan van de laatste tokens SharedPreferences.Editor editor = SharedPrefs.edit(); final JSONObject gemairotokens = new JSONObject(); gemairotokens.put("access_token", tokenjsonresult.getString("access_token")); gemairotokens.put("id_token", tokenjsonresult.getString("id_token")); gemairotokens.put("refresh_token", tokenjsonresult.getString("refresh_token")); editor.putString("Tokens", gemairotokens.toString()); editor.apply(); // Ophalen van de cijfers URL url = new URL(CompleteURL); StringBuffer content = new StringBuffer(); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("Content-Type", "application/json"); con.setRequestProperty("Authorization", "Bearer " + tokenjsonresult.getString("access_token")); con.setRequestProperty("noCache", java.time.Clock.systemUTC().instant().toString()); con.setRequestProperty("x-requested-with", "app.netlob.magiscore"); try (BufferedReader reader = new BufferedReader( new InputStreamReader(con.getInputStream()))) { for (String line; (line = reader.readLine()) != null;) { content.append(line); } } String result = content.toString(); final JSONObject jsonresult = new JSONObject(result); JSONArray latestGradesItems = (JSONArray) latestGrades.get("items"); Log.d(BackgroundFetch.TAG, latestGradesItems.length() + " - Are latestgrade object's the same? " + jsonresult.getString("items").equals(latestGrades.getString("items"))); if (latestGradesItems.length() != 0 && !jsonresult.getString("items").equals(latestGrades.getString("items"))) { //Opslaan nieuwe cijfers final JSONObject newlatestgrades = new JSONObject(); newlatestgrades.put("items", jsonresult.get("items")); editor.putString("latestGrades", newlatestgrades.toString()); editor.apply(); // Als de twee objecten niet hetzelfde zijn stuurt hij een notificatie. NotificationManager mNotificationManager; NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context.getApplicationContext(), "Gemairo"); Intent ii = new Intent(context.getPackageManager().getLaunchIntentForPackage("app.netlob.magiscore")); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, ii, PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle(); bigText.bigText("Nieuwe cijfer(s) beschikbaar"); bigText.setBigContentTitle("Nieuwe cijfers in Gemairo"); mBuilder.setContentIntent(pendingIntent); mBuilder.setSmallIcon(R.drawable.notification); mBuilder.setContentTitle("Nieuwe cijfers in Gemairo"); mBuilder.setContentText("Nieuwe cijfer(s) beschikbaar"); mBuilder.setPriority(Notification.PRIORITY_HIGH); mBuilder.setStyle(bigText); mBuilder.setAutoCancel(true); mBuilder.setOnlyAlertOnce(true); mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { String channelId = "Gemairo-Cijfers"; NotificationChannel channel = new NotificationChannel( channelId, "Cijfers", NotificationManager.IMPORTANCE_DEFAULT); mNotificationManager.createNotificationChannel(channel); mBuilder.setChannelId(channelId); } mNotificationManager.notify(0, mBuilder.build()); } else if (latestGradesItems.length() == 0) { //Opslaan nieuwe cijfers final JSONObject newlatestgrades = new JSONObject(); newlatestgrades.put("items", jsonresult.get("items")); editor.putString("latestGrades", newlatestgrades.toString()); editor.apply(); } BackgroundFetch.getInstance(context).finish(taskId); } catch (Exception ex) { ex.printStackTrace(); Log.d(BackgroundFetch.TAG, Log.getStackTraceString(ex)); BackgroundFetch.getInstance(context).finish(taskId); } } catch (JSONException e) { e.printStackTrace(); Log.d(BackgroundFetch.TAG, Log.getStackTraceString(e)); BackgroundFetch.getInstance(context).finish(taskId); } } }); thread.start(); BackgroundFetch.getInstance(context).finish(taskId); } }
netlob/magiscore
app/Magiscore/BackgroundFetchHeadlessTask.java
2,040
// Als de twee objecten niet hetzelfde zijn stuurt hij een notificatie.
line_comment
nl
// Mensen met meer verstand van java zijn zeer welkom, om de code te verbeteren. package com.transistorsoft.cordova.backgroundfetch; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.IOException; import java.net.Socket; import org.json.*; import org.json.JSONObject; import org.json.JSONArray; import java.lang.Object; import android.content.SharedPreferences; import com.transistorsoft.tsbackgroundfetch.BackgroundFetch; import com.transistorsoft.tsbackgroundfetch.BGTask; import android.util.Log; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import androidx.core.app.NotificationCompat; import android.content.Context; import android.content.Intent; import android.os.Build; import android.app.PendingIntent; import app.netlob.magiscore.R; public class BackgroundFetchHeadlessTask implements HeadlessTask { @Override public void onFetch(Context context, BGTask task) { String taskId = task.getTaskId(); boolean isTimeout = task.getTimedOut(); if (isTimeout) { Log.d(BackgroundFetch.TAG, "My BackgroundFetchHeadlessTask TIMEOUT: " + taskId); BackgroundFetch.getInstance(context).finish(taskId); return; } Log.d(BackgroundFetch.TAG, "My BackgroundFetchHeadlessTask: onFetch: " + taskId); // Perform your work here.... Thread thread = new Thread(new Runnable() { @Override public void run() { SharedPreferences SharedPrefs = context.getSharedPreferences("Gemairo", 0); String Bearer = SharedPrefs.getString("Tokens", ""); String SchoolURL = SharedPrefs.getString("SchoolURL", ""); String PersonID = SharedPrefs.getString("PersonID", ""); String latestgrades = SharedPrefs.getString("latestGrades", ""); try { if (latestgrades == "" || PersonID == "" || SchoolURL == "" || Bearer =="") return; JSONObject Tokens = new JSONObject(Bearer); final JSONObject latestGrades = new JSONObject(latestgrades); String CompleteURL = "https://" + SchoolURL.replaceAll("\"", "") + "/api/personen/" + PersonID + "/cijfers/laatste?top=50&skip=0"; try { // Refresh token URL tokenurl = new URL("https://accounts.magister.net/connect/token"); StringBuffer tokencontent = new StringBuffer(); HttpURLConnection tokencon = (HttpURLConnection) tokenurl.openConnection(); tokencon.setRequestMethod("POST"); tokencon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); // tokencon.setRequestProperty("Authorization", "Bearer " + // Tokens.getString("access_token")); tokencon.setRequestProperty("cache-control", "no-cache"); tokencon.setRequestProperty("x-requested-with", "app.netlob.magiscore"); tokencon.setDoOutput(true); String body = "refresh_token="+Tokens.getString("refresh_token")+"&client_id=M6LOAPP&grant_type=refresh_token"; byte[] outputInBytes = body.getBytes("UTF-8"); OutputStream os = tokencon.getOutputStream(); os.write(outputInBytes); os.close(); try (BufferedReader reader = new BufferedReader( new InputStreamReader(tokencon.getInputStream()))) { for (String line; (line = reader.readLine()) != null;) { tokencontent.append(line); } } String tokenresult = tokencontent.toString(); final JSONObject tokenjsonresult = new JSONObject(tokenresult); //Oplaan van de laatste tokens SharedPreferences.Editor editor = SharedPrefs.edit(); final JSONObject gemairotokens = new JSONObject(); gemairotokens.put("access_token", tokenjsonresult.getString("access_token")); gemairotokens.put("id_token", tokenjsonresult.getString("id_token")); gemairotokens.put("refresh_token", tokenjsonresult.getString("refresh_token")); editor.putString("Tokens", gemairotokens.toString()); editor.apply(); // Ophalen van de cijfers URL url = new URL(CompleteURL); StringBuffer content = new StringBuffer(); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("Content-Type", "application/json"); con.setRequestProperty("Authorization", "Bearer " + tokenjsonresult.getString("access_token")); con.setRequestProperty("noCache", java.time.Clock.systemUTC().instant().toString()); con.setRequestProperty("x-requested-with", "app.netlob.magiscore"); try (BufferedReader reader = new BufferedReader( new InputStreamReader(con.getInputStream()))) { for (String line; (line = reader.readLine()) != null;) { content.append(line); } } String result = content.toString(); final JSONObject jsonresult = new JSONObject(result); JSONArray latestGradesItems = (JSONArray) latestGrades.get("items"); Log.d(BackgroundFetch.TAG, latestGradesItems.length() + " - Are latestgrade object's the same? " + jsonresult.getString("items").equals(latestGrades.getString("items"))); if (latestGradesItems.length() != 0 && !jsonresult.getString("items").equals(latestGrades.getString("items"))) { //Opslaan nieuwe cijfers final JSONObject newlatestgrades = new JSONObject(); newlatestgrades.put("items", jsonresult.get("items")); editor.putString("latestGrades", newlatestgrades.toString()); editor.apply(); // Als de<SUF> NotificationManager mNotificationManager; NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context.getApplicationContext(), "Gemairo"); Intent ii = new Intent(context.getPackageManager().getLaunchIntentForPackage("app.netlob.magiscore")); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, ii, PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle(); bigText.bigText("Nieuwe cijfer(s) beschikbaar"); bigText.setBigContentTitle("Nieuwe cijfers in Gemairo"); mBuilder.setContentIntent(pendingIntent); mBuilder.setSmallIcon(R.drawable.notification); mBuilder.setContentTitle("Nieuwe cijfers in Gemairo"); mBuilder.setContentText("Nieuwe cijfer(s) beschikbaar"); mBuilder.setPriority(Notification.PRIORITY_HIGH); mBuilder.setStyle(bigText); mBuilder.setAutoCancel(true); mBuilder.setOnlyAlertOnce(true); mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { String channelId = "Gemairo-Cijfers"; NotificationChannel channel = new NotificationChannel( channelId, "Cijfers", NotificationManager.IMPORTANCE_DEFAULT); mNotificationManager.createNotificationChannel(channel); mBuilder.setChannelId(channelId); } mNotificationManager.notify(0, mBuilder.build()); } else if (latestGradesItems.length() == 0) { //Opslaan nieuwe cijfers final JSONObject newlatestgrades = new JSONObject(); newlatestgrades.put("items", jsonresult.get("items")); editor.putString("latestGrades", newlatestgrades.toString()); editor.apply(); } BackgroundFetch.getInstance(context).finish(taskId); } catch (Exception ex) { ex.printStackTrace(); Log.d(BackgroundFetch.TAG, Log.getStackTraceString(ex)); BackgroundFetch.getInstance(context).finish(taskId); } } catch (JSONException e) { e.printStackTrace(); Log.d(BackgroundFetch.TAG, Log.getStackTraceString(e)); BackgroundFetch.getInstance(context).finish(taskId); } } }); thread.start(); BackgroundFetch.getInstance(context).finish(taskId); } }
61333_3
/* * 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 com.hitek.prog3.db.DAO; import com.hitek.prog3.db.util.DatabaseSingleton; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; /** * * @author MSI */ public class PlayerAanmakenDAO { /* * method persoonWegschrijven - Het wegschrijven van een nieuwe speler * @param tabel, nickname, icoonid, balance */ public static void persoonWegschrijven(String tabel, String nickname, String icoonid, int balance) { String query = "INSERT INTO " + tabel + " (nickname, icoonid, balance) VALUES ('" + nickname + "','" + icoonid + "','" + balance + "')"; Connection con = DatabaseSingleton.getDatabaseSingleton().getConnection(true); Statement stmt = null; try { stmt = con.createStatement(); stmt.executeUpdate(query); } catch (SQLException e) { e.printStackTrace(); } } /* * method adminSpeler - We geven aan dat een bepaalde speler een admin is. * @param nickname - nickname van het bepaald speel profiel */ public static void adminSpeler(String nickname) { String query = "UPDATE `admin` SET `Playernickname`= '" + nickname + "' "; Connection con = DatabaseSingleton.getDatabaseSingleton().getConnection(true); Statement stmt = null; try { stmt = con.createStatement(); stmt.executeUpdate(query); } catch (SQLException e) { e.printStackTrace(); } } }
Roodem/Blackjack
BlackJack_groep1/src/java/com/hitek/prog3/db/DAO/PlayerAanmakenDAO.java
450
/* * method adminSpeler - We geven aan dat een bepaalde speler een admin is. * @param nickname - nickname van het bepaald speel profiel */
block_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 com.hitek.prog3.db.DAO; import com.hitek.prog3.db.util.DatabaseSingleton; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; /** * * @author MSI */ public class PlayerAanmakenDAO { /* * method persoonWegschrijven - Het wegschrijven van een nieuwe speler * @param tabel, nickname, icoonid, balance */ public static void persoonWegschrijven(String tabel, String nickname, String icoonid, int balance) { String query = "INSERT INTO " + tabel + " (nickname, icoonid, balance) VALUES ('" + nickname + "','" + icoonid + "','" + balance + "')"; Connection con = DatabaseSingleton.getDatabaseSingleton().getConnection(true); Statement stmt = null; try { stmt = con.createStatement(); stmt.executeUpdate(query); } catch (SQLException e) { e.printStackTrace(); } } /* * method adminSpeler -<SUF>*/ public static void adminSpeler(String nickname) { String query = "UPDATE `admin` SET `Playernickname`= '" + nickname + "' "; Connection con = DatabaseSingleton.getDatabaseSingleton().getConnection(true); Statement stmt = null; try { stmt = con.createStatement(); stmt.executeUpdate(query); } catch (SQLException e) { e.printStackTrace(); } } }
66585_36
/** * This file is part of TuCan Mobile. * * TuCan Mobile 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. * * TuCan Mobile 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 TuCan Mobile. If not, see <http://www.gnu.org/licenses/>. */ package com.dalthed.tucan.scraper; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Iterator; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.util.Log; import android.widget.ListAdapter; import com.dalthed.tucan.R; import com.dalthed.tucan.TucanMobile; import com.dalthed.tucan.Connection.AnswerObject; import com.dalthed.tucan.Connection.CookieManager; import com.dalthed.tucan.adapters.OneLineTwoColsAdapter; import com.dalthed.tucan.exceptions.LostSessionException; import com.dalthed.tucan.exceptions.TucanDownException; public class MainMenuScraper extends BasicScraper { /** * Set true if User has selected English */ public static boolean isEnglish = false; public String SessionArgument; public boolean noeventstoday = false; /** * Array an Links zu den Seiten der heutigen Veranstaltungen */ public String[] today_event_links; /** * Der Name des Users */ public String UserName; /** * URL zum Vorlesungsverzeichnis */ public String menu_link_vv; /** * URL zu den Prüfungen */ public String menu_link_ex; /** * URL zu den Nachrichten */ public String menu_link_msg; /** * Stores link of Event location overview */ public String load_link_ev_loc; /** * Last called URl */ public URL lcURL; /** * URL zu Stundenplan */ public String menu_link_month; /** * Gibt an, ob die Tucan-Webseite eine Bewerbungsseite darstellt. */ public boolean isApplication = false; public MainMenuScraper(Context context, AnswerObject result) { super(context, result); } /** * Getter and Setter */ public boolean getIsEnglish() { return isEnglish; } public void setIsEnglish(boolean isEnglish) { MainMenuScraper.isEnglish = isEnglish; } @Override public ListAdapter scrapeAdapter(int mode) throws LostSessionException, TucanDownException { if (checkForLostSeesion()) { if(TucanMobile.CRASH) { //Crash with HTML ArrayList<String> crashList = new ArrayList<String>(); crashList.add("fail"); crashList.get(16); } getSessionArgument(); scrapeMenuLinks(); return getTodaysEvents(); } return null; } /** * Checks if Tucan is set to german. Otherwise, the App wont work * * @param context * Activity context * @since 2012-07-17 * @author Daniel Thiem */ public void checkForRightTucanLanguage(final Activity context) { // if (doc.select("li#link000326").select("a").attr("href").equals("")) { // Dialog wronglanguageDialog = new AlertDialog.Builder(context).setTitle("") // .setMessage(R.string.general_not_supported_lang) // .setPositiveButton("Okay", new DialogInterface.OnClickListener() { // // public void onClick(DialogInterface dialog, int which) { // context.finish(); // } // }).create(); // wronglanguageDialog.show(); // // } if (doc.select("li#link000326").select("a").attr("href").equals("")) { setIsEnglish(true); scrapeMenuLinks(); } } public void bufferLinks(Activity context, CookieManager localCookieManager) { try { FileOutputStream fos = context.openFileOutput(TucanMobile.LINK_FILE_NAME, Context.MODE_PRIVATE); StringBuilder cacheString = new StringBuilder(); cacheString.append(menu_link_vv).append(">>").append(menu_link_month).append(">>") .append(menu_link_ex).append(">>").append(menu_link_ex).append(">>") .append(menu_link_msg).append("<<") .append(localCookieManager.getCookieHTTPString(TucanMobile.TUCAN_HOST)) .append("<<").append(SessionArgument); fos.write(cacheString.toString().getBytes()); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * @return */ private ListAdapter getTodaysEvents() { // Tabelle mit den Terminen finden und Durchlaufen Element EventTable = doc.select("table.nb").first(); String[] Events; String[] Times; if (EventTable == null) { // Falls keine Events gefunden werden, wird das angezeigt Events = new String[1]; Times = new String[1]; // Events[0] = "Keine Heutigen Veranstaltungen"; Events[0] = context.getString(R.string.no_events_today); Times[0] = ""; noeventstoday = true; } else { if (EventTable.select("tr.tbdata").first().select("td").size() == 5) { // Wen die Anzahl der Spalten der entsprechenden Tabelle 5 // ist, ist das ein Anzeichen dafür, dass heute keine // Veranstaltungen sind Events = new String[1]; Times = new String[1]; // Events[0] = "Keine Heutigen Veranstaltungen"; Events[0] = context.getString(R.string.no_events_today); Times[0] = ""; noeventstoday = true; } else { // Nehme die einzelnen Event-Zeilen heraus und gehe diese durch Elements EventRows = EventTable.select("tr.tbdata"); Iterator<Element> RowIt = EventRows.iterator(); Events = new String[EventRows.size()]; Times = new String[EventRows.size()]; today_event_links = new String[EventRows.size()]; int i = 0; while (RowIt.hasNext()) { Element currentElement = (Element) RowIt.next(); // Informationen aus HTML parsen String EventString = currentElement.select("td[headers=Name]").select("a") .first().text(); today_event_links[i] = currentElement.select("td[headers=Name]").select("a") .first().attr("href"); // Zeit zusammenfügen String EventTimeString = currentElement.select("td").get(2).select("a").first() .text(); String EventTimeEndString = currentElement.select("td").get(3).select("a") .first().text(); Times[i] = EventTimeString + "-" + EventTimeEndString; Events[i] = EventString; i++; } } } ListAdapter returnAdapter = new OneLineTwoColsAdapter(context, Events, Times); return returnAdapter; } /** * */ private void scrapeMenuLinks() { UserName = doc.select("span#loginDataName").text().split(":")[1]; lcURL = null; try { lcURL = new URL(lastCalledUrl); } catch (MalformedURLException e) { Log.e(LOG_TAG, "Malformed URL"); } Elements linkstoOuterWorld = doc.select("div.tb"); if(linkstoOuterWorld.size() > 1) { // Element ArchivLink = linkstoOuterWorld.get(1).select("a").first(); // menu_link_month = lcURL.getProtocol() + "://" + lcURL.getHost() // + doc.select("li#link000271").select("a").attr("href"); // menu_link_vv = lcURL.getProtocol() + "://" + lcURL.getHost() // + doc.select("li#link000326").select("a").attr("href"); // menu_link_ex = lcURL.getProtocol() + "://" + lcURL.getHost() // + doc.select("li#link000280").select("a").attr("href"); // menu_link_msg = lcURL.getProtocol() + "://" + lcURL.getHost() + ArchivLink.attr("href"); // // Load special Location Information // load_link_ev_loc = TucanMobile.TUCAN_PROT + TucanMobile.TUCAN_HOST // + doc.select("li#link000269").select("a").attr("href"); if (!getIsEnglish()) { Element ArchivLink = linkstoOuterWorld.get(1).select("a").first(); menu_link_month = lcURL.getProtocol() + "://" + lcURL.getHost() + doc.select("li#link000271").select("a").attr("href"); menu_link_vv = lcURL.getProtocol() + "://" + lcURL.getHost() + doc.select("li#link000326").select("a").attr("href"); menu_link_ex = lcURL.getProtocol() + "://" + lcURL.getHost() + doc.select("li#link000280").select("a").attr("href"); menu_link_msg = lcURL.getProtocol() + "://" + lcURL.getHost() + ArchivLink.attr("href"); // Load special Location Information load_link_ev_loc = TucanMobile.TUCAN_PROT + TucanMobile.TUCAN_HOST + doc.select("li#link000269").select("a").attr("href"); } else { Element ArchivLink = linkstoOuterWorld.get(1).select("a").first(); menu_link_month = lcURL.getProtocol() + "://" + lcURL.getHost() + doc.select("li#link000057").select("a").attr("href"); menu_link_vv = lcURL.getProtocol() + "://" + lcURL.getHost() + doc.select("li#link000352").select("a").attr("href"); menu_link_ex = lcURL.getProtocol() + "://" + lcURL.getHost() + doc.select("li#link000360").select("a").attr("href"); menu_link_msg = lcURL.getProtocol() + "://" + lcURL.getHost() + ArchivLink.attr("href"); // Load special Location Information load_link_ev_loc = TucanMobile.TUCAN_PROT + TucanMobile.TUCAN_HOST + doc.select("li#link000055").select("a").attr("href"); } } else { //Bewerbungsmodus isApplication = true; } } /** * */ private void getSessionArgument() { // Die Session ID aus URL gewinnen if (!TucanMobile.TESTING) { try { lcURL = new URL(lastCalledUrl); SessionArgument = lcURL.getQuery().split("ARGUMENTS=")[1].split(",")[0]; } catch (MalformedURLException e) { e.printStackTrace(); } } } }
Tyde/TuCanMobile
app/src/main/java/com/dalthed/tucan/scraper/MainMenuScraper.java
3,072
//" + lcURL.getHost()
line_comment
nl
/** * This file is part of TuCan Mobile. * * TuCan Mobile 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. * * TuCan Mobile 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 TuCan Mobile. If not, see <http://www.gnu.org/licenses/>. */ package com.dalthed.tucan.scraper; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Iterator; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.util.Log; import android.widget.ListAdapter; import com.dalthed.tucan.R; import com.dalthed.tucan.TucanMobile; import com.dalthed.tucan.Connection.AnswerObject; import com.dalthed.tucan.Connection.CookieManager; import com.dalthed.tucan.adapters.OneLineTwoColsAdapter; import com.dalthed.tucan.exceptions.LostSessionException; import com.dalthed.tucan.exceptions.TucanDownException; public class MainMenuScraper extends BasicScraper { /** * Set true if User has selected English */ public static boolean isEnglish = false; public String SessionArgument; public boolean noeventstoday = false; /** * Array an Links zu den Seiten der heutigen Veranstaltungen */ public String[] today_event_links; /** * Der Name des Users */ public String UserName; /** * URL zum Vorlesungsverzeichnis */ public String menu_link_vv; /** * URL zu den Prüfungen */ public String menu_link_ex; /** * URL zu den Nachrichten */ public String menu_link_msg; /** * Stores link of Event location overview */ public String load_link_ev_loc; /** * Last called URl */ public URL lcURL; /** * URL zu Stundenplan */ public String menu_link_month; /** * Gibt an, ob die Tucan-Webseite eine Bewerbungsseite darstellt. */ public boolean isApplication = false; public MainMenuScraper(Context context, AnswerObject result) { super(context, result); } /** * Getter and Setter */ public boolean getIsEnglish() { return isEnglish; } public void setIsEnglish(boolean isEnglish) { MainMenuScraper.isEnglish = isEnglish; } @Override public ListAdapter scrapeAdapter(int mode) throws LostSessionException, TucanDownException { if (checkForLostSeesion()) { if(TucanMobile.CRASH) { //Crash with HTML ArrayList<String> crashList = new ArrayList<String>(); crashList.add("fail"); crashList.get(16); } getSessionArgument(); scrapeMenuLinks(); return getTodaysEvents(); } return null; } /** * Checks if Tucan is set to german. Otherwise, the App wont work * * @param context * Activity context * @since 2012-07-17 * @author Daniel Thiem */ public void checkForRightTucanLanguage(final Activity context) { // if (doc.select("li#link000326").select("a").attr("href").equals("")) { // Dialog wronglanguageDialog = new AlertDialog.Builder(context).setTitle("") // .setMessage(R.string.general_not_supported_lang) // .setPositiveButton("Okay", new DialogInterface.OnClickListener() { // // public void onClick(DialogInterface dialog, int which) { // context.finish(); // } // }).create(); // wronglanguageDialog.show(); // // } if (doc.select("li#link000326").select("a").attr("href").equals("")) { setIsEnglish(true); scrapeMenuLinks(); } } public void bufferLinks(Activity context, CookieManager localCookieManager) { try { FileOutputStream fos = context.openFileOutput(TucanMobile.LINK_FILE_NAME, Context.MODE_PRIVATE); StringBuilder cacheString = new StringBuilder(); cacheString.append(menu_link_vv).append(">>").append(menu_link_month).append(">>") .append(menu_link_ex).append(">>").append(menu_link_ex).append(">>") .append(menu_link_msg).append("<<") .append(localCookieManager.getCookieHTTPString(TucanMobile.TUCAN_HOST)) .append("<<").append(SessionArgument); fos.write(cacheString.toString().getBytes()); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * @return */ private ListAdapter getTodaysEvents() { // Tabelle mit den Terminen finden und Durchlaufen Element EventTable = doc.select("table.nb").first(); String[] Events; String[] Times; if (EventTable == null) { // Falls keine Events gefunden werden, wird das angezeigt Events = new String[1]; Times = new String[1]; // Events[0] = "Keine Heutigen Veranstaltungen"; Events[0] = context.getString(R.string.no_events_today); Times[0] = ""; noeventstoday = true; } else { if (EventTable.select("tr.tbdata").first().select("td").size() == 5) { // Wen die Anzahl der Spalten der entsprechenden Tabelle 5 // ist, ist das ein Anzeichen dafür, dass heute keine // Veranstaltungen sind Events = new String[1]; Times = new String[1]; // Events[0] = "Keine Heutigen Veranstaltungen"; Events[0] = context.getString(R.string.no_events_today); Times[0] = ""; noeventstoday = true; } else { // Nehme die einzelnen Event-Zeilen heraus und gehe diese durch Elements EventRows = EventTable.select("tr.tbdata"); Iterator<Element> RowIt = EventRows.iterator(); Events = new String[EventRows.size()]; Times = new String[EventRows.size()]; today_event_links = new String[EventRows.size()]; int i = 0; while (RowIt.hasNext()) { Element currentElement = (Element) RowIt.next(); // Informationen aus HTML parsen String EventString = currentElement.select("td[headers=Name]").select("a") .first().text(); today_event_links[i] = currentElement.select("td[headers=Name]").select("a") .first().attr("href"); // Zeit zusammenfügen String EventTimeString = currentElement.select("td").get(2).select("a").first() .text(); String EventTimeEndString = currentElement.select("td").get(3).select("a") .first().text(); Times[i] = EventTimeString + "-" + EventTimeEndString; Events[i] = EventString; i++; } } } ListAdapter returnAdapter = new OneLineTwoColsAdapter(context, Events, Times); return returnAdapter; } /** * */ private void scrapeMenuLinks() { UserName = doc.select("span#loginDataName").text().split(":")[1]; lcURL = null; try { lcURL = new URL(lastCalledUrl); } catch (MalformedURLException e) { Log.e(LOG_TAG, "Malformed URL"); } Elements linkstoOuterWorld = doc.select("div.tb"); if(linkstoOuterWorld.size() > 1) { // Element ArchivLink = linkstoOuterWorld.get(1).select("a").first(); // menu_link_month = lcURL.getProtocol() + "://" + lcURL.getHost() // + doc.select("li#link000271").select("a").attr("href"); // menu_link_vv = lcURL.getProtocol() + "://" + lcURL.getHost() // + doc.select("li#link000326").select("a").attr("href"); // menu_link_ex = lcURL.getProtocol() + "://" + lcURL.getHost() // + doc.select("li#link000280").select("a").attr("href"); // menu_link_msg = lcURL.getProtocol() + "://" + lcURL.getHost() + ArchivLink.attr("href"); // // Load special Location Information // load_link_ev_loc = TucanMobile.TUCAN_PROT + TucanMobile.TUCAN_HOST // + doc.select("li#link000269").select("a").attr("href"); if (!getIsEnglish()) { Element ArchivLink = linkstoOuterWorld.get(1).select("a").first(); menu_link_month = lcURL.getProtocol() + "://" + lcURL.getHost() + doc.select("li#link000271").select("a").attr("href"); menu_link_vv = lcURL.getProtocol() + "://" + lcURL.getHost() + doc.select("li#link000326").select("a").attr("href"); menu_link_ex = lcURL.getProtocol() + "://" +<SUF> + doc.select("li#link000280").select("a").attr("href"); menu_link_msg = lcURL.getProtocol() + "://" + lcURL.getHost() + ArchivLink.attr("href"); // Load special Location Information load_link_ev_loc = TucanMobile.TUCAN_PROT + TucanMobile.TUCAN_HOST + doc.select("li#link000269").select("a").attr("href"); } else { Element ArchivLink = linkstoOuterWorld.get(1).select("a").first(); menu_link_month = lcURL.getProtocol() + "://" + lcURL.getHost() + doc.select("li#link000057").select("a").attr("href"); menu_link_vv = lcURL.getProtocol() + "://" + lcURL.getHost() + doc.select("li#link000352").select("a").attr("href"); menu_link_ex = lcURL.getProtocol() + "://" + lcURL.getHost() + doc.select("li#link000360").select("a").attr("href"); menu_link_msg = lcURL.getProtocol() + "://" + lcURL.getHost() + ArchivLink.attr("href"); // Load special Location Information load_link_ev_loc = TucanMobile.TUCAN_PROT + TucanMobile.TUCAN_HOST + doc.select("li#link000055").select("a").attr("href"); } } else { //Bewerbungsmodus isApplication = true; } } /** * */ private void getSessionArgument() { // Die Session ID aus URL gewinnen if (!TucanMobile.TESTING) { try { lcURL = new URL(lastCalledUrl); SessionArgument = lcURL.getQuery().split("ARGUMENTS=")[1].split(",")[0]; } catch (MalformedURLException e) { e.printStackTrace(); } } } }
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,204
//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); } }
68696_4
package nl.novi.uitleg.week2.debuggen; import java.io.IOException; public class Excepties { /** * Java heeft verschillende ingebouwde excepties, zoals: * * 1. ArithmeticException * 2. ArrayIndexOutOfBoundsException * 3. FileNotFoundException * 4. IOException * 5. NullPointerException * 6. StringIndexOutOfBoundException */ static char[] board; public static void main(String[] args) { voorbeeldArthmeticException(); voorbeeldArrayIndexOutOfBoundsException(); voorbeeldFileNotFoundException(); voorbeeldIOException(); voorbeeldNullPointerException(); voorbeeldStringIndexOutOfBoundException(); } //Haal de // weg op de exceptie te gooien. public static void voorbeeldArthmeticException() { //int cijfer = 12 / 0; } //Haal de // weg op de exceptie te gooien. public static void voorbeeldArrayIndexOutOfBoundsException() { int[] nummer = {1,2,3}; //System.out.println(nummer[4]); } // Spreekt voor zich public static void voorbeeldFileNotFoundException() { } /** * * @throws IOException wanneer de code toegang probeert te krijgen tot een bestand dat * al in gebruik is of als het lezen of schrijven onverwacht onderbroken wordt. */ public static void voorbeeldIOException() { } //Haal de // weg op de exceptie te fixen. public static void voorbeeldNullPointerException() { //board = new char[9]; System.out.println(board.length); } //Haal de // weg op de exceptie te fixen. public static void voorbeeldStringIndexOutOfBoundException() { String s = "aa"; //if(s.length() >= 77) { s.charAt(77); //} } }
EAM26/Lijsten-les3
src/nl/novi/uitleg/week2/debuggen/Excepties.java
466
// Spreekt voor zich
line_comment
nl
package nl.novi.uitleg.week2.debuggen; import java.io.IOException; public class Excepties { /** * Java heeft verschillende ingebouwde excepties, zoals: * * 1. ArithmeticException * 2. ArrayIndexOutOfBoundsException * 3. FileNotFoundException * 4. IOException * 5. NullPointerException * 6. StringIndexOutOfBoundException */ static char[] board; public static void main(String[] args) { voorbeeldArthmeticException(); voorbeeldArrayIndexOutOfBoundsException(); voorbeeldFileNotFoundException(); voorbeeldIOException(); voorbeeldNullPointerException(); voorbeeldStringIndexOutOfBoundException(); } //Haal de // weg op de exceptie te gooien. public static void voorbeeldArthmeticException() { //int cijfer = 12 / 0; } //Haal de // weg op de exceptie te gooien. public static void voorbeeldArrayIndexOutOfBoundsException() { int[] nummer = {1,2,3}; //System.out.println(nummer[4]); } // Spreekt voor<SUF> public static void voorbeeldFileNotFoundException() { } /** * * @throws IOException wanneer de code toegang probeert te krijgen tot een bestand dat * al in gebruik is of als het lezen of schrijven onverwacht onderbroken wordt. */ public static void voorbeeldIOException() { } //Haal de // weg op de exceptie te fixen. public static void voorbeeldNullPointerException() { //board = new char[9]; System.out.println(board.length); } //Haal de // weg op de exceptie te fixen. public static void voorbeeldStringIndexOutOfBoundException() { String s = "aa"; //if(s.length() >= 77) { s.charAt(77); //} } }
33549_8
public class Joanita { public Item[] rootMonth = new Item[12]; public Item[] rootDay = new Item[31]; public void addItemt(int day, String month, String description, String duration, int priority) { Item add = new Item(description, duration, priority, day, month.toLowerCase()); int d = day - 1; int m = add.getMonth(); if (rootMonth[m] == null) {//kolom (maand) is leeg add.down = null; //case 1: //eenvoudig, die day en die month is leeg if (rootDay[d] == null) { add.right = null; add.back = null; rootMonth[m] = add; rootDay[d] = rootMonth[m]; /*System.out.println(Months[m]); System.out.println(Days[d]); System.out.println(add);*/ return; }//--------------------------------------- //--------------------------------------- //tot hier werk dit 100% //case 2: //Days[d] het een element if (rootDay[d] != null && rootDay[d].right == null) { //m is groter as die eerste item van Days[d].month so hy moet agter Days[d] kom if (rootDay[d].month < m) { add.right = null; add.back = null; rootDay[d].right = add; rootMonth[m] = rootDay[d].right; return; }//----------------------------------------------------------------------------- //werk //m is kleiner as die eerste item in Days[d] so hy moet voor kom if (rootDay[d].month > m) { add.right = rootDay[d]; add.back = null; rootDay[d] = add; rootMonth[m] = rootDay[d]; return; }//--------------------------------------------------------------- //werk } //----------------------- //----------------------- //tot hier werk dit 100% //case 3 //Days[d] het meer as een maand se events al in. //as hy net een item gehad het sal die vorige if execute if (rootDay[d] != null) { //System.out.println("hieeer"); Item nodeDay = rootDay[d]; //sit voor in die ry in if (rootDay[d].month > m) { add.right = nodeDay; add.back = null; rootDay[d] = add; rootMonth[m] = rootDay[d];//ekstra return; }//werk //---------------------------- //is die eerste element las agter by if (rootDay[d].month == m) { Item nodePtr = rootDay[d]; Item prev = null; //moet voor die huidige item in kom if (nodePtr.getPriority() < add.getPriority()) { add.right = null; //insert gedeelte wat met prioriteit werk nodePtr.back = null; add.back = nodePtr; add.right = nodePtr.right; add.down = nodePtr.down; rootDay[d] = add; rootMonth[m] = rootDay[d]; return; //------------------------------ // werk } else { //moet agter die huidige element ingesit word add.right = null; //insert gedeelte wat met prioriteit werk while (nodePtr != null) { if (nodePtr.getPriority() < add.getPriority()) { add.back = nodePtr; prev.back = add; return; } if (nodePtr.getPriority() == add.getPriority()) { add.back = nodePtr.back; nodePtr.back = add; return; } if (nodePtr.getPriority() > add.getPriority()) { prev = nodePtr; nodePtr = nodePtr.back; } } prev.back = add; return; }//werk }//werk //------------------------------------------------------ //moet na die eerste node insit //System.out.println(m); if (rootDay[d].month < m) { // System.out.println("kom hier in"); Item prev = null; while (nodeDay != null) { if (nodeDay.month > m) { add.right = nodeDay; add.back = null; prev.right = add; rootMonth[m] = prev.right; return; }//werk if (nodeDay.month == m) { Item nodePtr = nodeDay; Item place = new Item(); place.right = nodeDay.right; place.down = nodeDay.down; //System.out.println(place); Item terug = null; //voor die huidige element if (nodePtr.getPriority() < add.getPriority()) { add.right = nodeDay.right; add.back = nodePtr; place = add; rootMonth[m] = place; prev.right = place; return; } else {//agter die huidige element add.right = null; while (nodePtr != null) { if (nodePtr.getPriority() == add.getPriority()) { add.back = nodePtr.back; nodePtr.back = add; return; } if (nodePtr.getPriority() > add.getPriority()) { terug = nodePtr; nodePtr = nodePtr.back; continue; } if (nodePtr.getPriority() < add.getPriority()) { add.back = nodePtr; terug.back = add; return; } } add.back = null; terug.back = add; return; } }//------- Days[d].month==m if (nodeDay.month < m) { prev = nodeDay; nodeDay = nodeDay.right; }//werk } //sit die maand in prev.right = add; rootMonth[m] = prev.right; /*System.out.println(prev.getDescription()); System.out.println(prev.back.getDescription());*/ /*System.out.println(prev.back); System.out.println(Months[m]);*/ return; }//------------------------------------ //------------------------------------ } //---------------------------------------------- //----------------------------------------------case3 }//kolom (maand) is nie leeg nie else { //sit n item in as daar net 1 item is, selfde dag en maand if (rootMonth[m] != null && rootMonth[m].down == null && rootMonth[m].day == d) { //System.out.println("hieeeeeeeeer"); //Days[d].month = month, werk met priority if (rootDay[d].month == m) { Item nodePtr = rootDay[d]; Item prev = null; //moet voor die huidige item in kom if (nodePtr.getPriority() < add.getPriority()) { add.right = null; //insert gedeelte wat met prioriteit werk nodePtr.back = null; add.back = nodePtr; add.right = nodePtr.right; add.down = nodePtr.down; rootDay[d] = add; rootMonth[m] = rootDay[d]; /*System.out.println(Days[d]); System.out.println(Months[m]); System.out.println(add);*/ return; //------------------------------ // werk } else { //moet agter die huidige element ingesit word add.right = null; //insert gedeelte wat met prioriteit werk while (nodePtr != null) { if (nodePtr.getPriority() < add.getPriority()) { add.back = nodePtr; prev.back = add; return; } if (nodePtr.getPriority() == add.getPriority()) { add.back = nodePtr.back; nodePtr.back = add; return; } if (nodePtr.getPriority() > add.getPriority()) { prev = nodePtr; nodePtr = nodePtr.back; } } prev.back = add; return; }//------------------------------ // werk } if (rootDay[d] != null) { //System.out.println("hieeer"); Item nodeDay = rootDay[d]; //sit voor in die ry in if (rootDay[d].month > m) { add.right = nodeDay; add.back = null; rootDay[d] = add; rootMonth[m] = rootDay[d];//ekstra /*System.out.println(Days[d]); System.out.println(Months[m]);*/ return; }//werk //---------------------------- //is die eerste element las agter by if (rootDay[d].month == m) { Item nodePtr = rootDay[d]; Item prev = null; //moet voor die huidige item in kom if (nodePtr.getPriority() < add.getPriority()) { add.right = null; //insert gedeelte wat met prioriteit werk nodePtr.back = null; add.back = nodePtr; add.right = nodePtr.right; add.down = nodePtr.down; rootDay[d] = add; rootMonth[m] = rootDay[d]; /*System.out.println(Days[d]); System.out.println(Months[m]); System.out.println(add);*/ return; //------------------------------ // werk } else { //moet agter die huidige element ingesit word add.right = null; //insert gedeelte wat met prioriteit werk while (nodePtr != null) { if (nodePtr.getPriority() < add.getPriority()) { add.back = nodePtr; prev.back = add; return; } if (nodePtr.getPriority() == add.getPriority()) { add.back = nodePtr.back; nodePtr.back = add; return; } if (nodePtr.getPriority() > add.getPriority()) { prev = nodePtr; nodePtr = nodePtr.back; } } prev.back = add; return; }//werk }//werk //------------------------------------------------------ //moet na die eerste node insit //System.out.println(m); if (rootDay[d].month < m) { // System.out.println("kom hier in"); Item prev = null; while (nodeDay != null) { if (nodeDay.month > m) { add.right = nodeDay; add.back = null; prev.right = add; rootMonth[m] = prev.right; return; }//werk if (nodeDay.month == m) { Item nodePtr = nodeDay; Item place = new Item(); place.right = nodeDay.right; place.down = nodeDay.down; //System.out.println(place); Item terug = null; //voor die huidige element if (nodePtr.getPriority() < add.getPriority()) { add.right = nodeDay.right; add.back = nodePtr; place = add; rootMonth[m] = place; prev.right = place; return; } else {//agter die huidige element add.right = null; while (nodePtr != null) { if (nodePtr.getPriority() == add.getPriority()) { add.back = nodePtr.back; nodePtr.back = add; return; } if (nodePtr.getPriority() > add.getPriority()) { terug = nodePtr; nodePtr = nodePtr.back; continue; } if (nodePtr.getPriority() < add.getPriority()) { add.back = nodePtr; terug.back = add; return; } } add.back = null; terug.back = add; return; } }//------- Days[d].month==m if (nodeDay.month < m) { prev = nodeDay; nodeDay = nodeDay.right; }//werk } //sit die maand in prev.right = add; rootMonth[m] = prev.right; return; }//------------------------------------ //------------------------------------ } //----------------------------- //----------------------------- } else {//meer as een item if (rootMonth[m].day > d) {//sit voor die huidge element is //hoef nie oor priorities te worry nie //System.out.println("hier"); if (rootDay[d] == null) { //System.out.println("hier"); add.down = rootMonth[m]; add.right = null; add.back = null; rootMonth[m] = add; rootDay[d] = rootMonth[m]; return; } else {//het reeds n dag in //begin hier werk!! priorities //System.out.println("hier"); Item nodePtr = rootDay[d];//nodePtr is die ptr wat die dae toets Item prev = null; /*System.out.println(Days[d].month); System.out.println(Days[d].right.month);*/ /*while(nodePtr!=null){ System.out.println(nodePtr.month); nodePtr= nodePtr.right; } System.out.println();*/ //System.out.println(Days[d].month); while (nodePtr != null) { //System.out.println(nodePtr.month); //System.out.println("hier"); if (nodePtr.month > m) {//las voor aan //System.out.println("hier"); add.right = nodePtr; add.down = rootMonth[m]; add.back = null; if (nodePtr == rootDay[d]) { //System.out.println("hier"); rootDay[d] = add; rootMonth[m] = rootDay[d]; return; } else { prev.right = add; rootMonth[m] = prev.right; return; } } //die comment is nodePtr.month==m /*if(nodePtr.month==m){ //System.out.println("hier"); if (nodePtr.getPriority() < add.getPriority()){ add.back= nodePtr; add.right= nodePtr.right; add.down= nodePtr.down; if(nodePtr==Days[d]) { Days[d] = add; Months[m] = Days[d]; return; } prev.right= add; Months[m]= prev.right; return; } else { Item move = nodePtr; Item terug = null; while (move != null) { if (move.getPriority() < add.getPriority()) { add.back = move; terug.back = add; return; } if (move.getPriority() == add.getPriority()) { add.back = move.back; move.back = add; return; } if (move.getPriority() > add.getPriority()) { terug = move; move = move.back; } } terug.back = add; return; } }//nodePtr.month==m*/ if (nodePtr.month < m) { // System.out.println("hier"); prev = nodePtr; nodePtr = nodePtr.right; } }//while //hier kom goed prev.right = add; return; } } if (rootMonth[m].day == d) { // System.out.println("hierrrr");////////werk hier nou if (rootDay[d] != null && rootDay[d].right == null) { if (rootMonth[m].getPriority() < add.getPriority()) { add.right = rootMonth[m].right; add.down = rootMonth[m].down; add.back = rootMonth[m]; rootMonth[m] = add; rootDay[d] = rootMonth[m]; return; } else { //moet agter die huidige prioriteit kom add.right = null; Item prev = null; Item nodePtr = rootMonth[m]; while (nodePtr != null) { if (nodePtr.getPriority() < add.getPriority()) { add.back = nodePtr; prev.back = add; return; } if (nodePtr.getPriority() == add.getPriority()) { add.back = nodePtr.back; nodePtr.back = add; return; } if (nodePtr.getPriority() > add.getPriority()) { prev = nodePtr; nodePtr = nodePtr.back; } } prev.back = add; return; } } else { //System.out.println("hierrr"); //moet nof doen //soek die posisie van die dag //System.out.println(Days[d].month); Item nodePtr = rootDay[d]; Item prev = null; while (nodePtr != null) { if (nodePtr.month < m) { prev = nodePtr; nodePtr = nodePtr.right; continue; } if (nodePtr.month == m) { //System.out.println("op die regte plek"); if (rootMonth[m].getPriority() < add.getPriority()) { //System.out.println("regte plek"); add.right = rootMonth[m].right; add.down = rootMonth[m].down; add.back = rootMonth[m]; rootMonth[m] = add; if (nodePtr == rootDay[d]) { rootDay[d] = rootMonth[m]; return; } prev.right = rootMonth[m]; return; } else { add.right = null; add.down = null; Item terug = null; Item move = rootMonth[m]; while (move != null) { if (move.getPriority() < add.getPriority()) { add.back = move; terug.back = add; return; } if (move.getPriority() == add.getPriority()) { add.back = move.back; move.back = add; return; } if (move.getPriority() > add.getPriority()) { terug = move; move = move.back; } } terug.back = add; return; } } }//while //dink nie hier hoef iets te wees nie } } if (rootMonth[m].day < d) {//moet traverse en na die regte plek toe gaan // System.out.println("hier"); Item nodePtr = rootMonth[m]; Item prev = null; if (rootDay[d] == null || (rootDay[d] != null && rootDay[d].right == null && rootDay[d].month == m)) { // System.out.println("hierrrr"); while (nodePtr != null) { //System.out.println("hieeer"); if (nodePtr.day == d) { /*Item move = nodePtr; Item terug = null; while(move!= null) { if (nodePtr.getPriority() < add.getPriority()) { add.down = move.down; add.right = null; add.back = nodePtr; Days[d] = add; nodePtr= Days[d]; return; }else{ }*/ /*if (move.getPriority() == add.getPriority()) { add.back = nodePtr.back; move.back = add; return; } if(move.getPriority()>add.getPriority()){ terug= move; move = move.back; }*/ if (nodePtr.getPriority() < add.getPriority()) { add.right = nodePtr.right; add.back = nodePtr; add.down = nodePtr.down; if (prev != null) { prev.down = add; rootDay[d] = prev.down; return; } rootMonth[m] = add; rootDay[d] = rootMonth[m]; return; } else { Item move = nodePtr; Item terug = null; while (move != null) { if (move.getPriority() < add.getPriority()) { add.back = move; terug.back = add; return; } if (move.getPriority() == add.getPriority()) { add.back = move.back; move.back = add; return; } if (move.getPriority() > add.getPriority()) { terug = move; move = move.back; } } terug.back = add; return; } } if (nodePtr.day < d) {//traverse prev = nodePtr; nodePtr = nodePtr.down; continue; } if (nodePtr.day > d) { add.down = nodePtr; add.right = null; add.back = null; prev.down = add; rootDay[d] = prev.down; return; } } add.down = null; add.right = null; add.back = null; prev.down = add; rootDay[d] = prev.down; return; } else { //moet nod doen //soek die posisie van die dae Item nodeDay = rootDay[d]; Item prevDay = null; Item nodeMonth = rootMonth[m]; Item prevMonth = null; //kry die nodeMonth while (nodeDay != null) { //System.out.println("hier"); if (nodeDay.month > m) { add.right = nodeDay; add.back = null; //kry nou die maand //System.out.println(nodeMonth); while (nodeMonth != null) { //System.out.println("hier"); if (nodeMonth.day > d) {//sit voor in add.down = nodeMonth; if (nodeDay == rootDay[d]) { rootDay[d] = add; if (nodeMonth == rootMonth[m]) { rootMonth[m] = rootDay[d]; } else { prevMonth.down = rootDay[d]; } return; } else { prevDay.right = add; if (nodeMonth == rootMonth[m]) { rootMonth[m] = prevDay.right; } else { prevMonth.down = prevDay.right; } return; } } if (nodeMonth.day < d) {//traverse prevMonth = nodeMonth; nodeMonth = nodeMonth.down; //System.out.println(nodeMonth); continue; } //--------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------- //dink die is onnodig if (nodeMonth.day == day) {//priorities //System.out.println("hier"); } //--------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------- }//while vir maand kry //System.out.println(nodeMonth); //toets nou vir days[d]==nodeDay if (rootDay[d] == nodeDay) { rootDay[d] = add; if (nodeMonth == rootMonth[m]) { //System.out.println("hier"); rootMonth[m] = rootDay[d]; } else { //System.out.println("hier"); prevMonth.down = rootDay[d]; } return; } else { prevDay.right = add; if (nodeMonth == rootMonth[m]) { rootMonth[m] = prevDay.right; } else { prevMonth.down = prevDay.right; } return; } } if (nodeDay.month < m) { //System.out.println(1212); prevDay = nodeDay; nodeDay = nodeDay.right; continue; } //-------------------------------------------------------------------- //-------------------------------------------------------------------- //----------------------werk nou van hier af-------------------------- //-------------------------------------------------------------------- //-------------------------------------------------------------------- if (nodeDay.month == m) { //kry nou die maand while (nodeMonth != null) { if (nodeMonth.day == d) { if (nodeDay.getPriority() < add.getPriority()) { add.right = nodeDay.right; add.down = nodeDay.down;//onseker oor die add.back = nodeDay; if (rootMonth[m] == nodeMonth) { rootMonth[m] = add; if (rootDay[d] == nodeDay) { rootDay[d] = rootMonth[m]; return; } else { prevDay.right = rootMonth[m]; return; } } else { prevMonth.down = add; if (rootDay[d] == nodeDay) { rootDay[d] = prevMonth.down; return; } else { prevDay.right = prevMonth.down; return; } } } else { Item terug = null; Item move = nodeMonth; add.right = null; add.down = null; while (move != null) { if (move.getPriority() < add.getPriority()) { add.back = move; terug.back = add; return; } if (move.getPriority() == add.getPriority()) { add.back = move.back; move.back = add; return; } if (move.getPriority() > add.getPriority()) { terug = move; move = move.back; } } terug.back = add; return; } } if (nodeMonth.day < d) {//traverse prevMonth = nodeMonth; nodeMonth = nodeMonth.down; continue; } }//while om die month te kry } //-------------------------------------------------------------------- //-------------------------------------------------------------------- //-------------------------------------------------------------------- //-------------------------------------------------------------------- //-------------------------------------------------------------------- //insert laaste een hier }//while // while (nodeMonth != null) { //System.out.println("hier"); if (nodeMonth.day > d) {//sit voor in add.down = nodeMonth; if (nodeDay == rootDay[d]) { rootDay[d] = add; if (nodeMonth == rootMonth[m]) { rootMonth[m] = rootDay[d]; } else { prevMonth.down = rootDay[d]; } return; } else { prevDay.right = add; if (nodeMonth == rootMonth[m]) { rootMonth[m] = prevDay.right; } else { prevMonth.down = prevDay.right; } return; } } if (nodeMonth.day < d) {//traverse prevMonth = nodeMonth; nodeMonth = nodeMonth.down; //System.out.println(nodeMonth); continue; } }//while //die sit dit aan die einde van n dag list //onseker oor die add.right = null; add.right = null; prevDay.right = add; //System.out.println(prevMonth); if (nodeMonth == rootMonth[m]) { //System.out.println(121212); rootMonth[m] = prevDay.right; return; } prevMonth.down = prevDay.right; return; //---------------- } } }//-------------------------------------------------------------------- //-------------------------------------------------------------------- }//einde van Months[m]!= null }//end function } }
neytjieb1/Data-Structures-and-Algorithms
Assignments/Assignment 1/src/Joanita.java
7,671
//Days[d] het meer as een maand se events al in.
line_comment
nl
public class Joanita { public Item[] rootMonth = new Item[12]; public Item[] rootDay = new Item[31]; public void addItemt(int day, String month, String description, String duration, int priority) { Item add = new Item(description, duration, priority, day, month.toLowerCase()); int d = day - 1; int m = add.getMonth(); if (rootMonth[m] == null) {//kolom (maand) is leeg add.down = null; //case 1: //eenvoudig, die day en die month is leeg if (rootDay[d] == null) { add.right = null; add.back = null; rootMonth[m] = add; rootDay[d] = rootMonth[m]; /*System.out.println(Months[m]); System.out.println(Days[d]); System.out.println(add);*/ return; }//--------------------------------------- //--------------------------------------- //tot hier werk dit 100% //case 2: //Days[d] het een element if (rootDay[d] != null && rootDay[d].right == null) { //m is groter as die eerste item van Days[d].month so hy moet agter Days[d] kom if (rootDay[d].month < m) { add.right = null; add.back = null; rootDay[d].right = add; rootMonth[m] = rootDay[d].right; return; }//----------------------------------------------------------------------------- //werk //m is kleiner as die eerste item in Days[d] so hy moet voor kom if (rootDay[d].month > m) { add.right = rootDay[d]; add.back = null; rootDay[d] = add; rootMonth[m] = rootDay[d]; return; }//--------------------------------------------------------------- //werk } //----------------------- //----------------------- //tot hier werk dit 100% //case 3 //Days[d] het<SUF> //as hy net een item gehad het sal die vorige if execute if (rootDay[d] != null) { //System.out.println("hieeer"); Item nodeDay = rootDay[d]; //sit voor in die ry in if (rootDay[d].month > m) { add.right = nodeDay; add.back = null; rootDay[d] = add; rootMonth[m] = rootDay[d];//ekstra return; }//werk //---------------------------- //is die eerste element las agter by if (rootDay[d].month == m) { Item nodePtr = rootDay[d]; Item prev = null; //moet voor die huidige item in kom if (nodePtr.getPriority() < add.getPriority()) { add.right = null; //insert gedeelte wat met prioriteit werk nodePtr.back = null; add.back = nodePtr; add.right = nodePtr.right; add.down = nodePtr.down; rootDay[d] = add; rootMonth[m] = rootDay[d]; return; //------------------------------ // werk } else { //moet agter die huidige element ingesit word add.right = null; //insert gedeelte wat met prioriteit werk while (nodePtr != null) { if (nodePtr.getPriority() < add.getPriority()) { add.back = nodePtr; prev.back = add; return; } if (nodePtr.getPriority() == add.getPriority()) { add.back = nodePtr.back; nodePtr.back = add; return; } if (nodePtr.getPriority() > add.getPriority()) { prev = nodePtr; nodePtr = nodePtr.back; } } prev.back = add; return; }//werk }//werk //------------------------------------------------------ //moet na die eerste node insit //System.out.println(m); if (rootDay[d].month < m) { // System.out.println("kom hier in"); Item prev = null; while (nodeDay != null) { if (nodeDay.month > m) { add.right = nodeDay; add.back = null; prev.right = add; rootMonth[m] = prev.right; return; }//werk if (nodeDay.month == m) { Item nodePtr = nodeDay; Item place = new Item(); place.right = nodeDay.right; place.down = nodeDay.down; //System.out.println(place); Item terug = null; //voor die huidige element if (nodePtr.getPriority() < add.getPriority()) { add.right = nodeDay.right; add.back = nodePtr; place = add; rootMonth[m] = place; prev.right = place; return; } else {//agter die huidige element add.right = null; while (nodePtr != null) { if (nodePtr.getPriority() == add.getPriority()) { add.back = nodePtr.back; nodePtr.back = add; return; } if (nodePtr.getPriority() > add.getPriority()) { terug = nodePtr; nodePtr = nodePtr.back; continue; } if (nodePtr.getPriority() < add.getPriority()) { add.back = nodePtr; terug.back = add; return; } } add.back = null; terug.back = add; return; } }//------- Days[d].month==m if (nodeDay.month < m) { prev = nodeDay; nodeDay = nodeDay.right; }//werk } //sit die maand in prev.right = add; rootMonth[m] = prev.right; /*System.out.println(prev.getDescription()); System.out.println(prev.back.getDescription());*/ /*System.out.println(prev.back); System.out.println(Months[m]);*/ return; }//------------------------------------ //------------------------------------ } //---------------------------------------------- //----------------------------------------------case3 }//kolom (maand) is nie leeg nie else { //sit n item in as daar net 1 item is, selfde dag en maand if (rootMonth[m] != null && rootMonth[m].down == null && rootMonth[m].day == d) { //System.out.println("hieeeeeeeeer"); //Days[d].month = month, werk met priority if (rootDay[d].month == m) { Item nodePtr = rootDay[d]; Item prev = null; //moet voor die huidige item in kom if (nodePtr.getPriority() < add.getPriority()) { add.right = null; //insert gedeelte wat met prioriteit werk nodePtr.back = null; add.back = nodePtr; add.right = nodePtr.right; add.down = nodePtr.down; rootDay[d] = add; rootMonth[m] = rootDay[d]; /*System.out.println(Days[d]); System.out.println(Months[m]); System.out.println(add);*/ return; //------------------------------ // werk } else { //moet agter die huidige element ingesit word add.right = null; //insert gedeelte wat met prioriteit werk while (nodePtr != null) { if (nodePtr.getPriority() < add.getPriority()) { add.back = nodePtr; prev.back = add; return; } if (nodePtr.getPriority() == add.getPriority()) { add.back = nodePtr.back; nodePtr.back = add; return; } if (nodePtr.getPriority() > add.getPriority()) { prev = nodePtr; nodePtr = nodePtr.back; } } prev.back = add; return; }//------------------------------ // werk } if (rootDay[d] != null) { //System.out.println("hieeer"); Item nodeDay = rootDay[d]; //sit voor in die ry in if (rootDay[d].month > m) { add.right = nodeDay; add.back = null; rootDay[d] = add; rootMonth[m] = rootDay[d];//ekstra /*System.out.println(Days[d]); System.out.println(Months[m]);*/ return; }//werk //---------------------------- //is die eerste element las agter by if (rootDay[d].month == m) { Item nodePtr = rootDay[d]; Item prev = null; //moet voor die huidige item in kom if (nodePtr.getPriority() < add.getPriority()) { add.right = null; //insert gedeelte wat met prioriteit werk nodePtr.back = null; add.back = nodePtr; add.right = nodePtr.right; add.down = nodePtr.down; rootDay[d] = add; rootMonth[m] = rootDay[d]; /*System.out.println(Days[d]); System.out.println(Months[m]); System.out.println(add);*/ return; //------------------------------ // werk } else { //moet agter die huidige element ingesit word add.right = null; //insert gedeelte wat met prioriteit werk while (nodePtr != null) { if (nodePtr.getPriority() < add.getPriority()) { add.back = nodePtr; prev.back = add; return; } if (nodePtr.getPriority() == add.getPriority()) { add.back = nodePtr.back; nodePtr.back = add; return; } if (nodePtr.getPriority() > add.getPriority()) { prev = nodePtr; nodePtr = nodePtr.back; } } prev.back = add; return; }//werk }//werk //------------------------------------------------------ //moet na die eerste node insit //System.out.println(m); if (rootDay[d].month < m) { // System.out.println("kom hier in"); Item prev = null; while (nodeDay != null) { if (nodeDay.month > m) { add.right = nodeDay; add.back = null; prev.right = add; rootMonth[m] = prev.right; return; }//werk if (nodeDay.month == m) { Item nodePtr = nodeDay; Item place = new Item(); place.right = nodeDay.right; place.down = nodeDay.down; //System.out.println(place); Item terug = null; //voor die huidige element if (nodePtr.getPriority() < add.getPriority()) { add.right = nodeDay.right; add.back = nodePtr; place = add; rootMonth[m] = place; prev.right = place; return; } else {//agter die huidige element add.right = null; while (nodePtr != null) { if (nodePtr.getPriority() == add.getPriority()) { add.back = nodePtr.back; nodePtr.back = add; return; } if (nodePtr.getPriority() > add.getPriority()) { terug = nodePtr; nodePtr = nodePtr.back; continue; } if (nodePtr.getPriority() < add.getPriority()) { add.back = nodePtr; terug.back = add; return; } } add.back = null; terug.back = add; return; } }//------- Days[d].month==m if (nodeDay.month < m) { prev = nodeDay; nodeDay = nodeDay.right; }//werk } //sit die maand in prev.right = add; rootMonth[m] = prev.right; return; }//------------------------------------ //------------------------------------ } //----------------------------- //----------------------------- } else {//meer as een item if (rootMonth[m].day > d) {//sit voor die huidge element is //hoef nie oor priorities te worry nie //System.out.println("hier"); if (rootDay[d] == null) { //System.out.println("hier"); add.down = rootMonth[m]; add.right = null; add.back = null; rootMonth[m] = add; rootDay[d] = rootMonth[m]; return; } else {//het reeds n dag in //begin hier werk!! priorities //System.out.println("hier"); Item nodePtr = rootDay[d];//nodePtr is die ptr wat die dae toets Item prev = null; /*System.out.println(Days[d].month); System.out.println(Days[d].right.month);*/ /*while(nodePtr!=null){ System.out.println(nodePtr.month); nodePtr= nodePtr.right; } System.out.println();*/ //System.out.println(Days[d].month); while (nodePtr != null) { //System.out.println(nodePtr.month); //System.out.println("hier"); if (nodePtr.month > m) {//las voor aan //System.out.println("hier"); add.right = nodePtr; add.down = rootMonth[m]; add.back = null; if (nodePtr == rootDay[d]) { //System.out.println("hier"); rootDay[d] = add; rootMonth[m] = rootDay[d]; return; } else { prev.right = add; rootMonth[m] = prev.right; return; } } //die comment is nodePtr.month==m /*if(nodePtr.month==m){ //System.out.println("hier"); if (nodePtr.getPriority() < add.getPriority()){ add.back= nodePtr; add.right= nodePtr.right; add.down= nodePtr.down; if(nodePtr==Days[d]) { Days[d] = add; Months[m] = Days[d]; return; } prev.right= add; Months[m]= prev.right; return; } else { Item move = nodePtr; Item terug = null; while (move != null) { if (move.getPriority() < add.getPriority()) { add.back = move; terug.back = add; return; } if (move.getPriority() == add.getPriority()) { add.back = move.back; move.back = add; return; } if (move.getPriority() > add.getPriority()) { terug = move; move = move.back; } } terug.back = add; return; } }//nodePtr.month==m*/ if (nodePtr.month < m) { // System.out.println("hier"); prev = nodePtr; nodePtr = nodePtr.right; } }//while //hier kom goed prev.right = add; return; } } if (rootMonth[m].day == d) { // System.out.println("hierrrr");////////werk hier nou if (rootDay[d] != null && rootDay[d].right == null) { if (rootMonth[m].getPriority() < add.getPriority()) { add.right = rootMonth[m].right; add.down = rootMonth[m].down; add.back = rootMonth[m]; rootMonth[m] = add; rootDay[d] = rootMonth[m]; return; } else { //moet agter die huidige prioriteit kom add.right = null; Item prev = null; Item nodePtr = rootMonth[m]; while (nodePtr != null) { if (nodePtr.getPriority() < add.getPriority()) { add.back = nodePtr; prev.back = add; return; } if (nodePtr.getPriority() == add.getPriority()) { add.back = nodePtr.back; nodePtr.back = add; return; } if (nodePtr.getPriority() > add.getPriority()) { prev = nodePtr; nodePtr = nodePtr.back; } } prev.back = add; return; } } else { //System.out.println("hierrr"); //moet nof doen //soek die posisie van die dag //System.out.println(Days[d].month); Item nodePtr = rootDay[d]; Item prev = null; while (nodePtr != null) { if (nodePtr.month < m) { prev = nodePtr; nodePtr = nodePtr.right; continue; } if (nodePtr.month == m) { //System.out.println("op die regte plek"); if (rootMonth[m].getPriority() < add.getPriority()) { //System.out.println("regte plek"); add.right = rootMonth[m].right; add.down = rootMonth[m].down; add.back = rootMonth[m]; rootMonth[m] = add; if (nodePtr == rootDay[d]) { rootDay[d] = rootMonth[m]; return; } prev.right = rootMonth[m]; return; } else { add.right = null; add.down = null; Item terug = null; Item move = rootMonth[m]; while (move != null) { if (move.getPriority() < add.getPriority()) { add.back = move; terug.back = add; return; } if (move.getPriority() == add.getPriority()) { add.back = move.back; move.back = add; return; } if (move.getPriority() > add.getPriority()) { terug = move; move = move.back; } } terug.back = add; return; } } }//while //dink nie hier hoef iets te wees nie } } if (rootMonth[m].day < d) {//moet traverse en na die regte plek toe gaan // System.out.println("hier"); Item nodePtr = rootMonth[m]; Item prev = null; if (rootDay[d] == null || (rootDay[d] != null && rootDay[d].right == null && rootDay[d].month == m)) { // System.out.println("hierrrr"); while (nodePtr != null) { //System.out.println("hieeer"); if (nodePtr.day == d) { /*Item move = nodePtr; Item terug = null; while(move!= null) { if (nodePtr.getPriority() < add.getPriority()) { add.down = move.down; add.right = null; add.back = nodePtr; Days[d] = add; nodePtr= Days[d]; return; }else{ }*/ /*if (move.getPriority() == add.getPriority()) { add.back = nodePtr.back; move.back = add; return; } if(move.getPriority()>add.getPriority()){ terug= move; move = move.back; }*/ if (nodePtr.getPriority() < add.getPriority()) { add.right = nodePtr.right; add.back = nodePtr; add.down = nodePtr.down; if (prev != null) { prev.down = add; rootDay[d] = prev.down; return; } rootMonth[m] = add; rootDay[d] = rootMonth[m]; return; } else { Item move = nodePtr; Item terug = null; while (move != null) { if (move.getPriority() < add.getPriority()) { add.back = move; terug.back = add; return; } if (move.getPriority() == add.getPriority()) { add.back = move.back; move.back = add; return; } if (move.getPriority() > add.getPriority()) { terug = move; move = move.back; } } terug.back = add; return; } } if (nodePtr.day < d) {//traverse prev = nodePtr; nodePtr = nodePtr.down; continue; } if (nodePtr.day > d) { add.down = nodePtr; add.right = null; add.back = null; prev.down = add; rootDay[d] = prev.down; return; } } add.down = null; add.right = null; add.back = null; prev.down = add; rootDay[d] = prev.down; return; } else { //moet nod doen //soek die posisie van die dae Item nodeDay = rootDay[d]; Item prevDay = null; Item nodeMonth = rootMonth[m]; Item prevMonth = null; //kry die nodeMonth while (nodeDay != null) { //System.out.println("hier"); if (nodeDay.month > m) { add.right = nodeDay; add.back = null; //kry nou die maand //System.out.println(nodeMonth); while (nodeMonth != null) { //System.out.println("hier"); if (nodeMonth.day > d) {//sit voor in add.down = nodeMonth; if (nodeDay == rootDay[d]) { rootDay[d] = add; if (nodeMonth == rootMonth[m]) { rootMonth[m] = rootDay[d]; } else { prevMonth.down = rootDay[d]; } return; } else { prevDay.right = add; if (nodeMonth == rootMonth[m]) { rootMonth[m] = prevDay.right; } else { prevMonth.down = prevDay.right; } return; } } if (nodeMonth.day < d) {//traverse prevMonth = nodeMonth; nodeMonth = nodeMonth.down; //System.out.println(nodeMonth); continue; } //--------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------- //dink die is onnodig if (nodeMonth.day == day) {//priorities //System.out.println("hier"); } //--------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------- }//while vir maand kry //System.out.println(nodeMonth); //toets nou vir days[d]==nodeDay if (rootDay[d] == nodeDay) { rootDay[d] = add; if (nodeMonth == rootMonth[m]) { //System.out.println("hier"); rootMonth[m] = rootDay[d]; } else { //System.out.println("hier"); prevMonth.down = rootDay[d]; } return; } else { prevDay.right = add; if (nodeMonth == rootMonth[m]) { rootMonth[m] = prevDay.right; } else { prevMonth.down = prevDay.right; } return; } } if (nodeDay.month < m) { //System.out.println(1212); prevDay = nodeDay; nodeDay = nodeDay.right; continue; } //-------------------------------------------------------------------- //-------------------------------------------------------------------- //----------------------werk nou van hier af-------------------------- //-------------------------------------------------------------------- //-------------------------------------------------------------------- if (nodeDay.month == m) { //kry nou die maand while (nodeMonth != null) { if (nodeMonth.day == d) { if (nodeDay.getPriority() < add.getPriority()) { add.right = nodeDay.right; add.down = nodeDay.down;//onseker oor die add.back = nodeDay; if (rootMonth[m] == nodeMonth) { rootMonth[m] = add; if (rootDay[d] == nodeDay) { rootDay[d] = rootMonth[m]; return; } else { prevDay.right = rootMonth[m]; return; } } else { prevMonth.down = add; if (rootDay[d] == nodeDay) { rootDay[d] = prevMonth.down; return; } else { prevDay.right = prevMonth.down; return; } } } else { Item terug = null; Item move = nodeMonth; add.right = null; add.down = null; while (move != null) { if (move.getPriority() < add.getPriority()) { add.back = move; terug.back = add; return; } if (move.getPriority() == add.getPriority()) { add.back = move.back; move.back = add; return; } if (move.getPriority() > add.getPriority()) { terug = move; move = move.back; } } terug.back = add; return; } } if (nodeMonth.day < d) {//traverse prevMonth = nodeMonth; nodeMonth = nodeMonth.down; continue; } }//while om die month te kry } //-------------------------------------------------------------------- //-------------------------------------------------------------------- //-------------------------------------------------------------------- //-------------------------------------------------------------------- //-------------------------------------------------------------------- //insert laaste een hier }//while // while (nodeMonth != null) { //System.out.println("hier"); if (nodeMonth.day > d) {//sit voor in add.down = nodeMonth; if (nodeDay == rootDay[d]) { rootDay[d] = add; if (nodeMonth == rootMonth[m]) { rootMonth[m] = rootDay[d]; } else { prevMonth.down = rootDay[d]; } return; } else { prevDay.right = add; if (nodeMonth == rootMonth[m]) { rootMonth[m] = prevDay.right; } else { prevMonth.down = prevDay.right; } return; } } if (nodeMonth.day < d) {//traverse prevMonth = nodeMonth; nodeMonth = nodeMonth.down; //System.out.println(nodeMonth); continue; } }//while //die sit dit aan die einde van n dag list //onseker oor die add.right = null; add.right = null; prevDay.right = add; //System.out.println(prevMonth); if (nodeMonth == rootMonth[m]) { //System.out.println(121212); rootMonth[m] = prevDay.right; return; } prevMonth.down = prevDay.right; return; //---------------- } } }//-------------------------------------------------------------------- //-------------------------------------------------------------------- }//einde van Months[m]!= null }//end function } }
162607_0
package nl.hsleiden.engine; import nl.hsleiden.game.Element; import nl.hsleiden.game.Game; import nl.hsleiden.game.Level; import nl.hsleiden.game.Tile; import java.io.File; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; /** * Deze class zorgd voor het laden van de game * */ public class BasicTextFileGameLoader implements GameLoader { private HashMap<Integer, Class<? extends Tile>> tileMap; private HashMap<Integer, Class<? extends Element>> elementMap; private HashMap<Integer, String> levelTilesPaths; private HashMap<Integer, String> levelElementsPaths; private int tileSize; public BasicTextFileGameLoader(int tileSize) { this.tileSize = tileSize; this.levelTilesPaths = new HashMap<>(); this.levelElementsPaths = new HashMap<>(); } public BasicTextFileGameLoader() { this.tileSize = 80; this.levelTilesPaths = new HashMap<>(); this.levelElementsPaths = new HashMap<>(); } /** * Deze methode zorgd ervoor dat het spel geladen wordt. * * @return de game * */ @Override public Game load() { ArrayList<Level> levels = new ArrayList<>(); int numberOfLevels = levelTilesPaths.size(); for (int levelNumber = 1; levelNumber <= numberOfLevels; levelNumber++) { InputStream tilesData = getLevelTilesData(levelNumber); InputStream elementsData = getLevelElementsData(levelNumber); Level level = new Level(); loadTilesInLevel(tilesData, level); loadElementsInLevel(elementsData, level); levels.add(level); } Game game = new Game(); game.setLevels(levels); return game; } /** * Hiermee voeg je een level toe aan het spel. * */ public void addLevel(int level, String levelTilesPath, String levelElementsPath) { if (levelExists(level)) return; levelTilesPaths.put(level, levelTilesPath); levelElementsPaths.put(level, levelElementsPath); } /** * Hier kun je een configuratie voor een tile toevoegen. * Deze is dan te herkennen aan een bepaald nummer. * * @param tileMap een HashMap met een configuratie voor een tile. * Bijvoorbeeld: 1,GrassTile * */ public void addTileConfiguration(HashMap<Integer, Class<? extends Tile>> tileMap) { this.tileMap = tileMap; } /** * Hier kun je een configuratie voor een element toevoegen. * Deze is dan te herkennen aan een bepaald nummer. * * @param elementMap een HashMap met een configuratie voor een element. * Bijvoorbeeld: 1,Character * */ public void addElementsConfiguration(HashMap<Integer, Class<? extends Element>> elementMap) { this.elementMap = elementMap; } private Level loadTilesInLevel(InputStream stream, Level level) { Scanner scanner = new Scanner(stream); int levelHeight = scanner.nextInt(); int levelWidth = scanner.nextInt(); Tile[][] tiles = new Tile[levelHeight][levelWidth]; for (int y = 0; y < levelHeight; y++) { for (int x = 0; x < levelWidth; x++) { try { int id = scanner.nextInt(); if (tileMap.get(id) == null) continue; Tile tile = tileMap.get(id).newInstance(); tile.setX(x*tileSize); tile.setY(y*tileSize); tiles[y][x] = tile; } catch (InstantiationException | IllegalAccessException e) { e.printStackTrace(); } } } level.setTiles(tiles); return level; } private void loadElementsInLevel(InputStream stream, Level level) { ArrayList<Element> elements = new ArrayList<>(); Scanner scanner = new Scanner(stream); int levelHeight = scanner.nextInt(); int levelWidth = scanner.nextInt(); for (int y = 0; y < levelHeight; y++) { for (int x = 0; x < levelWidth; x++) { try { int id = scanner.nextInt(); if (elementMap.get(id) == null) continue; Element element = elementMap.get(id).newInstance(); element.setX(x*tileSize); element.setY(y*tileSize); elements.add(element); } catch (InstantiationException | IllegalAccessException e) { e.printStackTrace(); } } } level.setElements(elements); } private InputStream getLevelElementsData(int level) { String filePath = levelElementsPaths.get(level); return readFile(filePath); } private InputStream getLevelTilesData(int level) { System.out.println(new File(".").getAbsolutePath()); String filePath = levelTilesPaths.get(level); System.out.println(filePath); return readFile(filePath); } private InputStream readFile(String filePath){ return this.getClass().getResourceAsStream(filePath); } private boolean levelExists(int level) { return levelElementsPaths.get(level) != null && levelTilesPaths.get(level) != null; } }
Hogeschool-Leiden/GameEngine
src/main/java/nl/hsleiden/engine/BasicTextFileGameLoader.java
1,339
/** * Deze class zorgd voor het laden van de game * */
block_comment
nl
package nl.hsleiden.engine; import nl.hsleiden.game.Element; import nl.hsleiden.game.Game; import nl.hsleiden.game.Level; import nl.hsleiden.game.Tile; import java.io.File; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; /** * Deze class zorgd<SUF>*/ public class BasicTextFileGameLoader implements GameLoader { private HashMap<Integer, Class<? extends Tile>> tileMap; private HashMap<Integer, Class<? extends Element>> elementMap; private HashMap<Integer, String> levelTilesPaths; private HashMap<Integer, String> levelElementsPaths; private int tileSize; public BasicTextFileGameLoader(int tileSize) { this.tileSize = tileSize; this.levelTilesPaths = new HashMap<>(); this.levelElementsPaths = new HashMap<>(); } public BasicTextFileGameLoader() { this.tileSize = 80; this.levelTilesPaths = new HashMap<>(); this.levelElementsPaths = new HashMap<>(); } /** * Deze methode zorgd ervoor dat het spel geladen wordt. * * @return de game * */ @Override public Game load() { ArrayList<Level> levels = new ArrayList<>(); int numberOfLevels = levelTilesPaths.size(); for (int levelNumber = 1; levelNumber <= numberOfLevels; levelNumber++) { InputStream tilesData = getLevelTilesData(levelNumber); InputStream elementsData = getLevelElementsData(levelNumber); Level level = new Level(); loadTilesInLevel(tilesData, level); loadElementsInLevel(elementsData, level); levels.add(level); } Game game = new Game(); game.setLevels(levels); return game; } /** * Hiermee voeg je een level toe aan het spel. * */ public void addLevel(int level, String levelTilesPath, String levelElementsPath) { if (levelExists(level)) return; levelTilesPaths.put(level, levelTilesPath); levelElementsPaths.put(level, levelElementsPath); } /** * Hier kun je een configuratie voor een tile toevoegen. * Deze is dan te herkennen aan een bepaald nummer. * * @param tileMap een HashMap met een configuratie voor een tile. * Bijvoorbeeld: 1,GrassTile * */ public void addTileConfiguration(HashMap<Integer, Class<? extends Tile>> tileMap) { this.tileMap = tileMap; } /** * Hier kun je een configuratie voor een element toevoegen. * Deze is dan te herkennen aan een bepaald nummer. * * @param elementMap een HashMap met een configuratie voor een element. * Bijvoorbeeld: 1,Character * */ public void addElementsConfiguration(HashMap<Integer, Class<? extends Element>> elementMap) { this.elementMap = elementMap; } private Level loadTilesInLevel(InputStream stream, Level level) { Scanner scanner = new Scanner(stream); int levelHeight = scanner.nextInt(); int levelWidth = scanner.nextInt(); Tile[][] tiles = new Tile[levelHeight][levelWidth]; for (int y = 0; y < levelHeight; y++) { for (int x = 0; x < levelWidth; x++) { try { int id = scanner.nextInt(); if (tileMap.get(id) == null) continue; Tile tile = tileMap.get(id).newInstance(); tile.setX(x*tileSize); tile.setY(y*tileSize); tiles[y][x] = tile; } catch (InstantiationException | IllegalAccessException e) { e.printStackTrace(); } } } level.setTiles(tiles); return level; } private void loadElementsInLevel(InputStream stream, Level level) { ArrayList<Element> elements = new ArrayList<>(); Scanner scanner = new Scanner(stream); int levelHeight = scanner.nextInt(); int levelWidth = scanner.nextInt(); for (int y = 0; y < levelHeight; y++) { for (int x = 0; x < levelWidth; x++) { try { int id = scanner.nextInt(); if (elementMap.get(id) == null) continue; Element element = elementMap.get(id).newInstance(); element.setX(x*tileSize); element.setY(y*tileSize); elements.add(element); } catch (InstantiationException | IllegalAccessException e) { e.printStackTrace(); } } } level.setElements(elements); } private InputStream getLevelElementsData(int level) { String filePath = levelElementsPaths.get(level); return readFile(filePath); } private InputStream getLevelTilesData(int level) { System.out.println(new File(".").getAbsolutePath()); String filePath = levelTilesPaths.get(level); System.out.println(filePath); return readFile(filePath); } private InputStream readFile(String filePath){ return this.getClass().getResourceAsStream(filePath); } private boolean levelExists(int level) { return levelElementsPaths.get(level) != null && levelTilesPaths.get(level) != null; } }
63169_6
package nl.glassaanhuis.facebooktrial.app; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.GridView; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.facebook.HttpMethod; import com.facebook.NonCachingTokenCachingStrategy; import com.facebook.Request; import com.facebook.Response; import com.facebook.Session; import com.facebook.SessionState; import com.facebook.model.GraphUser; import com.facebook.widget.ProfilePictureView; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.protocol.HTTP; import org.apache.http.util.ByteArrayBuffer; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; public class ProfileActivity extends Activity { private String url; void draw(Session session) { final TextView name = (TextView) findViewById(R.id.userName); final ProfilePictureView pic = (ProfilePictureView) findViewById(R.id.photo); final String str = session.getAccessToken(); Request.newMeRequest(session, new Request.GraphUserCallback() { @Override public void onCompleted(GraphUser user, Response response) { name.setText(user.getName()); pic.setProfileId(user.getId()); ConnectionTask task = new ConnectionTask(); String[] params = new String[2]; params[0] = "http://glas.mycel.nl/facebook?accesstoken=" + str; task.execute(params); } }).executeAsync(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); Session session = Session.getActiveSession(); if (session != null && session.isOpened()) { draw(session); } else { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.profile, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } private class ConnectionTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... urls) { String aString = ""; try { URL aURL = new URL(urls[0]); final HttpURLConnection aHttpURLConnection = (HttpURLConnection) aURL.openConnection(); InputStream aInputStream = aHttpURLConnection.getInputStream(); BufferedInputStream aBufferedInputStream = new BufferedInputStream( aInputStream); ByteArrayBuffer aByteArrayBuffer = new ByteArrayBuffer(50); int current = 0; while ((current = aBufferedInputStream.read()) != -1) { aByteArrayBuffer.append((byte) current); } aString = new String(aByteArrayBuffer.toByteArray()); } catch (IOException e) { e.printStackTrace(); // HAHAA, HOEZO ERROR HANDLING?? } return aString; } @Override protected void onPostExecute(String result) { try { JSONObject jObject = new JSONObject(result); JSONArray plaatjes; JSONArray probeer = jObject.getJSONArray("photos"); plaatjes = jObject.getJSONArray("plaatjes"); // doe iets met data url = probeer.getJSONObject(0).get("source").toString(); GridView gridview = (GridView) findViewById(R.id.gridLayout); gridview.setAdapter(new ImageAdapter(plaatjes, ProfileActivity.this)); RelativeLayout viewtje = (RelativeLayout) findViewById(R.id.background); String[] params = new String[2]; params[0] = url; DownloadImageTask task = new DownloadImageTask(viewtje); task.execute(params); } catch (JSONException e) { e.printStackTrace(); } } } private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { RelativeLayout viewtje; public DownloadImageTask(RelativeLayout bmImage) { this.viewtje = bmImage; } protected Bitmap doInBackground(String... urls) { String urldisplay = urls[0]; Bitmap mIcon11 = null; try { InputStream in = new java.net.URL(urldisplay).openStream(); mIcon11 = BitmapFactory.decodeStream(in); } catch (Exception e) { Log.e("Error", e.getMessage()); e.printStackTrace(); } return mIcon11; } protected void onPostExecute(Bitmap result) { Drawable d = new BitmapDrawable(getResources(),result); viewtje.setBackground(d); viewtje.getBackground().setAlpha(55); } } public void likePage(View v) { //final String urlFb = "fb://page/glasvezelpaleiskwartier"; final String urlFb = "fb://page/1450066045229608"; Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(urlFb)); final PackageManager packageManager = getPackageManager(); List<ResolveInfo> list = packageManager.queryIntentActivities( intent, PackageManager.MATCH_DEFAULT_ONLY); if (list.size() == 0) { //final String urlBrowser = "https://www.facebook.com/glasvezelpaleiskwartier"; final String urlBrowser = "https://www.facebook.com/pages/1450066045229608"; intent.setData(Uri.parse(urlBrowser)); } startActivity(intent); } }
Avans-Everyware-42IN11EWe/FacebookTrial
app/src/main/java/nl/glassaanhuis/facebooktrial/app/ProfileActivity.java
1,810
// doe iets met data
line_comment
nl
package nl.glassaanhuis.facebooktrial.app; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.GridView; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.facebook.HttpMethod; import com.facebook.NonCachingTokenCachingStrategy; import com.facebook.Request; import com.facebook.Response; import com.facebook.Session; import com.facebook.SessionState; import com.facebook.model.GraphUser; import com.facebook.widget.ProfilePictureView; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.protocol.HTTP; import org.apache.http.util.ByteArrayBuffer; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; public class ProfileActivity extends Activity { private String url; void draw(Session session) { final TextView name = (TextView) findViewById(R.id.userName); final ProfilePictureView pic = (ProfilePictureView) findViewById(R.id.photo); final String str = session.getAccessToken(); Request.newMeRequest(session, new Request.GraphUserCallback() { @Override public void onCompleted(GraphUser user, Response response) { name.setText(user.getName()); pic.setProfileId(user.getId()); ConnectionTask task = new ConnectionTask(); String[] params = new String[2]; params[0] = "http://glas.mycel.nl/facebook?accesstoken=" + str; task.execute(params); } }).executeAsync(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); Session session = Session.getActiveSession(); if (session != null && session.isOpened()) { draw(session); } else { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.profile, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } private class ConnectionTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... urls) { String aString = ""; try { URL aURL = new URL(urls[0]); final HttpURLConnection aHttpURLConnection = (HttpURLConnection) aURL.openConnection(); InputStream aInputStream = aHttpURLConnection.getInputStream(); BufferedInputStream aBufferedInputStream = new BufferedInputStream( aInputStream); ByteArrayBuffer aByteArrayBuffer = new ByteArrayBuffer(50); int current = 0; while ((current = aBufferedInputStream.read()) != -1) { aByteArrayBuffer.append((byte) current); } aString = new String(aByteArrayBuffer.toByteArray()); } catch (IOException e) { e.printStackTrace(); // HAHAA, HOEZO ERROR HANDLING?? } return aString; } @Override protected void onPostExecute(String result) { try { JSONObject jObject = new JSONObject(result); JSONArray plaatjes; JSONArray probeer = jObject.getJSONArray("photos"); plaatjes = jObject.getJSONArray("plaatjes"); // doe iets<SUF> url = probeer.getJSONObject(0).get("source").toString(); GridView gridview = (GridView) findViewById(R.id.gridLayout); gridview.setAdapter(new ImageAdapter(plaatjes, ProfileActivity.this)); RelativeLayout viewtje = (RelativeLayout) findViewById(R.id.background); String[] params = new String[2]; params[0] = url; DownloadImageTask task = new DownloadImageTask(viewtje); task.execute(params); } catch (JSONException e) { e.printStackTrace(); } } } private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { RelativeLayout viewtje; public DownloadImageTask(RelativeLayout bmImage) { this.viewtje = bmImage; } protected Bitmap doInBackground(String... urls) { String urldisplay = urls[0]; Bitmap mIcon11 = null; try { InputStream in = new java.net.URL(urldisplay).openStream(); mIcon11 = BitmapFactory.decodeStream(in); } catch (Exception e) { Log.e("Error", e.getMessage()); e.printStackTrace(); } return mIcon11; } protected void onPostExecute(Bitmap result) { Drawable d = new BitmapDrawable(getResources(),result); viewtje.setBackground(d); viewtje.getBackground().setAlpha(55); } } public void likePage(View v) { //final String urlFb = "fb://page/glasvezelpaleiskwartier"; final String urlFb = "fb://page/1450066045229608"; Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(urlFb)); final PackageManager packageManager = getPackageManager(); List<ResolveInfo> list = packageManager.queryIntentActivities( intent, PackageManager.MATCH_DEFAULT_ONLY); if (list.size() == 0) { //final String urlBrowser = "https://www.facebook.com/glasvezelpaleiskwartier"; final String urlBrowser = "https://www.facebook.com/pages/1450066045229608"; intent.setData(Uri.parse(urlBrowser)); } startActivity(intent); } }
15384_31
package protocol; /** * <!-- Versie 1.2 * * ------------- * - CHANGELOG - * ------------- * * Versie 1.2 * + Chat commando updated * + CHAT_playerName_message --peter verzijl * + Defined stone * + elke kleur en vorm hebben nu een char toegewezen gekregen -- peter verzijl * Versie 1.1 * * + consistentie voor de content * + verschillende spelfouten weggewerkt * Versie 0.042 * * + Eerste versie protocol * --> */ /** * <h1 id="protocol-ti-2">Protocol Group-6</h1> * * <p>In dit bestand staat het protocol van werkgroep 4 zoals dat op woensdag.6 januari is afgesproken. </p> *<p> verdere documentatie is in het document overzicht protocollen programeren te vinden </p> * * <h2 id="1-over-standaarden">1. Over Standaarden</h2> * * <p>Bij het afspreken van het protocol zijn de volgende standaarden afgesproken:</p> * * <h3 id="printstream">Printstream</h3> * * <p>Voor communicatie tussen de server en de client is er gekozen voor een Printstream, dit is een voorlopige keuze sinds we dit niet tijdens de sessie hebben besproken</p> * * <ul> * <li> Hoewel er tijdens de protocolsessie geen afspraken zijn gemaakt over wat voor stream er gebruikt gaat worden is er voor deze gekozen.</li> * <li>Een printstream is makkelijk te debuggen</li> * <li>Een printstream is makkelijk door mensen te lezen</li> * </ul> * * <p>Tegen de printstream zijn de volgende argumenten ingebracht:</p> * * <ul> * <li>Een printstream is inefficient in het uitlezen</li> * <li>Een printstream kan gemakkelijk zorgen voor type conflicts</li> * </ul> * * <h2 id="beslissingen">Beslissingen</h2> * * * <h3 id="board">Board</h3> * * <p>Het bord wordt gedefinieerd doormiddel van twee integers</p> * * <p>de eerste steen wordt altijd neergelegd op steen 0,0</p> * <p>De origin van het bordt staat op 0,0 , waar de eerste waarde de colom bijhoudt en de tweede de rij</p> * * <p>De colommen zijn positief aan de rechterhelft van het bord.</p> * * <p>De rijen zijjn positief aan de bovenste helft.</p> * * <p>het is mogelijk om een negatieve positie op het bord te hebben</p> * * * <h3 id="player-names">Player Names</h3> * * <p>Vanwege gebruiksgemak en het vergemakkelijken van het renderen heb ik besloten om de maximale lengte van de naam van een player op 15 karakters te zetten. Dit is in de meeste, zo niet alle, gevallen wel genoeg, en zal door de maximale lengte ook geen problemen meer opleveren door veel te lange usernames in bijvoorbeeld de chat.</p> * * <p>Punt van aandacht bij het programmeren: Players <strong>moeten</strong> een unieke naam hebben: De naam wordt veel gebruikt voor identificatie.</p> * * * <h3 id="leaderboard">Leaderboard</h3> * * <p>Het leaderboard is een extra optie er worden de laatste 10 highscores gemeld</p> * * * <h3 id="STENEN">STENEN</h3> * * <style type="text/css"> .tg {border-collapse:collapse;border-spacing:0;} .tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;} .tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;} .tg .tg-yw4l{vertical-align:top} </style> <table class="tg"> <tr> <th class="tg-031e">char</th> <th class="tg-yw4l">colors</th> <th class="tg-yw4l">Shapes</th> </tr> <tr> <td class="tg-031e">A</td> <td class="tg-yw4l">RED</td> <td class="tg-yw4l">CIRCLE</td> </tr> <tr> <td class="tg-yw4l">B</td> <td class="tg-yw4l">ORANGE</td> <td class="tg-yw4l">CROSS</td> </tr> <tr> <td class="tg-yw4l">C</td> <td class="tg-yw4l">YELLOW</td> <td class="tg-yw4l">DIAMOND</td> </tr> <tr> <td class="tg-yw4l">D</td> <td class="tg-yw4l">GREEN</td> <td class="tg-yw4l">SQUARE</td> </tr> <tr> <td class="tg-yw4l">E</td> <td class="tg-yw4l">BLUE</td> <td class="tg-yw4l">STAR</td> </tr> <tr> <td class="tg-yw4l">F</td> <td class="tg-yw4l">PURPLE</td> <td class="tg-yw4l">PLUS</td> </tr> </table> * <h3 id="errorcodes">Errorcodes</h3> * * <p> er zijn verschillende errorcodes, heb je een goede reden om een extra aan te vragen gooi het over de github </p> * * * <h3 id="over-delimiters">Over Delimiters</h3> * * <p>Ik heb gekozen voor een dubbele carriage return (<code>\n\n</code>) als delimiter <p> * * <p>Als delimiter tussen argumenten gebruiken wij een underscore (<code>_<\code>) omdat dit makkelijk en handig is.</p> * <p>Als delimiter binnen een argument gebruiken wij een sterretje (<code>*<\code>) omdat dit makkelijk en handig is.</p> * * * <h2 id="packets">Packets</h2> * * <p>Hierop volgt een lijst met overeengekomen commando's. Deze zijn gesorteerd op type en waar ze geimplementeerd moeten zijn. </p> * * <p>Per packet wordt ook het datatype erbijgegeven, dit om type conflicts tegen te werken.</p> * * * /** * @author marti * */ public class Protocol { public static class Client { /** * <h3 id="client">Client</h3> */ /** * <p>Connect <br> * Name: <code>HALLO</code> <br> * Descriptie: Commando dat verstuurd wordt om te identificeren bij de server <br> * Content: <code>Player Name_</code> <code>modulesSupported_</code></p> * * <ul> * <li><code>HALLO_playername_features\n\n</code> (15) - De naam van de speler die wil connecten.</li> * Een lijst van ondersteunde <code>modules</code>s, met standaard delimitter van elkaar gescheiden. <br> * <code>Feature</code>: <code>String</code> (15) - Een unieke naam voor een feature. De volgende features zijn afgesproken: * <p>chat_</p> * <p>challenge_</p> * <p> security_</p> * <p>leaderboard_</p> * <p>elk van deze features wordt los toegelicht.</p> * </li> * </ul> */ public static final String HALLO = "HALLO"; /** * <p>Quit <br> * Name: <code>QUIT</code> <br> * Descriptie: commando dat verzonden wordt om de verbinding te verbreken. <br> */ public static final String QUIT = "QUIT"; /** * <p>Invite <br> * Name: <code>INVITE_player\n\n</code> <br> * Descriptie: Packet dat verzonden wordt om een spel te starten met de aangegeven tegenstander. <br> * Content: <code>&lt;Opponent Name&gt;</code> [<code>&lt;BoardX&gt;</code> <code>&lt;BoardY&gt;</code> [<code>&lt;Settings&gt;</code>]]</p> * * <ul> * <li><code>Opponent Name</code>: <code>String</code> (15) - De naam van de speler die de invite moet ontvangen.</li> */ public static final String INVITE = "INVITE"; /** * <p>Accept Invite <br> * Name: <code>ACCEPT\n\n</code> <br> * Descriptie: Packet door de uitgedaagde partij wordt verzonden om op een invite in te gaan. <br> * Content: <code>&lt;Opponent Name&gt;</code></p> * * <ul> * <li><code>Opponent Name</code>: <code>String</code> (15) - De naam van degene die de uitgedaagde partij heeft uitgedaagd.</li> * </ul> */ public static final String ACCEPTINVITE = "ACCEPTINVITE"; /** * <p>Decline Invite <br> * Name: <code>DECLINE\n\n</code> <br> * Descriptie: Packet die door de uitgedaagde partij wordt verzonden om een invite af te slaan. <br> * Content: <code>&lt;Opponent Name&gt;</code></p> * * <ul> * <li><code>Opponent Name</code>: <code>String</code> (15) - De naam van degene die de uitgedaagde partij heeft uitgedaagd.</li> * </ul> */ public static final String DECLINEINVITE = "DECLINEINVITE"; /** * <p>Move <br> * Name: <code>MAKEMOVE</code> <br> * Descriptie: de steen en locatie combinatie waar de steen neergelegd wordt <br> * <p>elke steen wordt bescheven als volgt:</p> * <p>charchar*int*int</p>\ * voorbeeld: * Content: <code>charchar*int*int\n\n</code></p> * <code>MAKEMOVE_AF*11*6_BF*11*7\n\n<code> * */ public static final String MAKEMOVE = "MAKEMOVE"; /** * <p>Chat <br> * Name: <code>CHAT</code> <br> * Descriptie: Bevat een chatmessage <br> * Content: <code>CHAT_playerName_message\n\n;</code></p> * */ public static final String CHAT = "CHAT"; /** * <p>Request Game <br> * Name: <code>REQUESTGAME</code> <br> * Descriptie: Vraagt de server om een game te joinen van een aantal personen<br> * Content: <code>REQUESTGAME_integer\n\n<code> * Valide input voor de integer zijn: * 0: Het maakt je niet uit hoeveel mensen je speelt * 1: match tegen een computerspeler * 2: match met 2 personen * 3: match met 3 personen * 4: match met 4 personen * voorbeeld: * REQUESTGAME_int\n\n * REQUESTGAME_4\n\n */ public static final String REQUESTGAME = "REQUESTGAME"; /** * <p>CHANGESTONE <br> * Name: <code>CHANGESTONE</code> <br> * Descriptie: Vraagt de server om een stenen in te wisselen<br> * Content: <code>CHANGESTONE_steen_steen\n\n <code> */ public static final String CHANGESTONE = "CHANGESTONE"; /** * <p>GETLEADERBOARD<br> * Name: <code>LEADERBOARD</code> <br> * Descriptie: Vraag het leaderboard aan <br> * Content: <code>GETLEADERBOARD\n\n<code> * */ public static final String GETLEADERBOARD = "GETLEADERBOARD"; /** * <p>GETSTONESINBAG<br> * Name: <code>STONESINBAG</code> <br> * Descriptie: een commando waarmee de hoeveelheid stenen in de zak wordt gerequest <br> * Content: <code>GETSTONESINBAG\n\n</code></p> * */ public static final String GETSTONESINBAG = "GETSTONESINBAG"; /** * <p>Error <br> * Name: <code>ERROR</code><br/> * Descriptie: Zend een error naar de server toe.<br/> * Content: <code>ERROR_integer\n\n</code> * er zijn nog geen errors gedefinieerd voor de speler. */ public static final String ERROR = "ERROR"; } public static class Server { /** * <h3 id="server">Server</h3> */ /** * <p>HALLO <br> * Name: <code>HALLO</code> <br> * Descriptie: Signaal dat de connectie is gemaakt en het aangeven van welke functies allemaal zijn toegestaan op deze server. <br> * Content: <code>HALLO_servernaam_features\n\n</code></p> * features worden gescheiden door een underscore */ public static final String HALLO = "HALLO"; /** * <p>Error <br> * Name: <code>ERROR</code> <br> * Descriptie: Een errormessage <br> * Content: <code>ERROR_integer\n\n</code></p> * <ul> * errorcodes die beschikbaar zijn: * 1: notyourturn * 2: notyourstone * 3: notthatmanystonesavailable * 4: nameexists * 5: notchallengable * 6: challengerefused * 7: invalidmove */ public static final String ERROR = "ERROR"; /** * <p>OKWAITFOR <br> * Name: <code>OKWAITFOR</code> <br> * Descriptie: Een lijst met mensen die zich op het moment in de lobby bevinden. Wordt door de server verstuurd bij Connect/Disconnect van een speler, en wanneer aangevraagd. <br> * Content: <code>OKWAITFOR_integer\n\n</code></p> * */ public static final String OKWAITFOR = "OKWAITFOR"; /** * <p>Game Start <br> * Name: <code>START</code> <br> * Descriptie: Een packet dat naar de spelers wordt gestuurd om te laten weten dat het spel gestart is. <br> * Content: <code>START_player_player\n\n</code>]</p> * * <ul> * <li><code>Player 1</code>: <code>String</code> (15) - Naam van de eerste speler</li> * <li><code>Player 2</code>: <code>String</code> (15) - Naam van de tweede speler</li> * </ul> */ public static final String STARTGAME = "STARTGAME"; /** * <p>Game End <br> * Name: <code>END</code> <br> * Descriptie: Een packet dat naar de spelers wordt gestuurd om te laten weten dat het spel is gestopt <br> * Content: <code>END\n\n</code>]</p> * * <ul> * <li><code>Type</code>: <code>String</code> &gt; <code>'WIN'</code> <code>'DISCONNECT'</code> <code>'DRAW'</code> - Type van einde spel</li> * <li><code>Winner Name</code>: <code>String</code> (15) - Naam van de winnaar, of andere info over de reden van het einde.</li> * </ul> */ public static final String GAME_END = "END"; /** * <p>MOVE<br> * Name: <code>REQUEST</code> <br> * Descriptie: een commando om aan te geven welke move gemaakt door wie en welke speler nu aan de beurt is <br> * Content: <p>MOVE_player_playernext_moves\n\n</p> * er kunnen meerdere moves gemaakt worden, deze worden gedelimit door standaarddelimiter * de informatie in de move wordt gedelimit door standaarddelimiter2 */ public static final String MOVE = "MOVE"; /** * <p>Chat <br> * Name: <code>CHAT</code> <br> * Descriptie: Een packet wat een chatbericht bevat <br> * Content: <code>CHAT_bericht\n\n</code></p> */ public static final String CHAT = "CHAT"; /** * <p>ADDTOHAND <br> * Name: <code>ADDTOHAND</code> <br> * Descriptie: een commando waarmee stenen worden toegevoegd aan de hand van de speler <br> * Content: <code>ADDTOHAND_steen_steen_steen\n\n</code></p> * */ public static final String ADDTOHAND = "ADDTOHAND"; /** * <p>STONESINBAG<br> * Name: <code>STONESINBAG</code> <br> * Descriptie: een commando waarmee de hoeveelheid stenen in de zak wordt gegeven <br> * Content: <code>STONESINBAG_integer\n\n</code></p> * */ public static final String STONESINBAG = "STONESINBAG"; /** * <p>Leaderboard <br> * Name: <code>LEADERBOARD</code> <br> * Descriptie: Een packet waarin de statistieken van een aantal spelers worden verstuurd. <br> * Content: <code>LEADERBOARD_playername*integer_playername*integer\n\n</code></p> * * <ul> * <li><code>Player Name</code>: <code>String</code> (15) - Naam van de speler in de betreffende statistiek</li> * <li><code>Ranking</code>: <code>int</code> - Ranking op de server</li> * </ul> * </li> * </ul> */ public static final String LEADERBOARD = "LEADERBOARD"; public static class Features { /** * <p>De verschillende features die optioneel zijn geimplementeerd kunnen worden.</p> * * <p>Let op! Het protocol voor <code>SECURITY</code> is nog niet vastgelegd. */ public static final String CHAT = "CHAT"; public static final String LEADERBOARD = "LEADERBOARD"; public static final String SECURITY = "SECURITY"; public static final String CHALLENGE = "CHALLENGE"; // Deze functie wordt nog niet verwacht wordt dat SSLsocket gebruikt gaat worden } /** * <p>Invite <br> * Name: <code>INVITE</code> <br> * Descriptie: comando dat de server vraagt om iemand te challengen <br> * Content: <code>INVITE_PLAYERNAME\n\n</code></p> * * <ul> * <li><code>Opponent Name</code>: <code>String</code> (15) - De naam van de tegenstander</li> * </ul> * op dit moment is er geen mogelijkheid gedefinieerd om meerdere mensen te challengen */ public static final String INVITE = "INVITE"; /** * <p>Decline invite<br> * Name: <code>DECLINEINVITE</code> <br> * Descriptie: De packet die waarmee een uitnodiging wordt afgewezen<br> * Content: <code>DECLINEINVITE\n\n</code></p> */ public static final String DECLINEINVITE = "DECLINEINVITE"; } public static class Settings { /** * <p>De verschillende settings van het protocol.</p> */ /** * <p>Het protocol heeft characterencoding UTF-16. Dit is de standaard encoding van een string in java, dus daar zouden geen problemen mee moeten zijn.</p> */ public static final String ENCODING = "UTF-16"; /** * <p>Het aantal seconden voordat een client timeout. Dit is in de opdracht vastgesteld, en zal dus niet veranderen.</p> */ public static final int TIMEOUTSECONDS = 15; /** * <p>Default server port nummer. <br> * <b>BELANGRIJK:</b> In de opdracht staat dat je bij het opstarten van de server een poortnummer moet invoeren. De waarde hier is dus niet een waarde die altijd opgaat. </p> */ public static final short DEFAULT_PORT = 4242; /** * <p>Default delimiter tussen header en content, en tussen twee waarden in de content</p> */ public static final char DELIMITER = '_'; /** * <p>tweede delimiter om zaken te scheiden binenin een waarde in de content(bijvoorbeeld bij een steen locatie waarde)</p> * */ public static final char DELIMITER2 = '*'; /** * <p>Teken dat aan het einde van elke packet moet zitten, en dus niet in de rest van de waarden mag zitten.</p> */ public static final String COMMAND_END = "\n\n"; } }
MerijnKleinreesink/SoftwareSystemen
ExtraTest/src/protocol/Protocol.java
5,686
/** * <p>Het protocol heeft characterencoding UTF-16. Dit is de standaard encoding van een string in java, dus daar zouden geen problemen mee moeten zijn.</p> */
block_comment
nl
package protocol; /** * <!-- Versie 1.2 * * ------------- * - CHANGELOG - * ------------- * * Versie 1.2 * + Chat commando updated * + CHAT_playerName_message --peter verzijl * + Defined stone * + elke kleur en vorm hebben nu een char toegewezen gekregen -- peter verzijl * Versie 1.1 * * + consistentie voor de content * + verschillende spelfouten weggewerkt * Versie 0.042 * * + Eerste versie protocol * --> */ /** * <h1 id="protocol-ti-2">Protocol Group-6</h1> * * <p>In dit bestand staat het protocol van werkgroep 4 zoals dat op woensdag.6 januari is afgesproken. </p> *<p> verdere documentatie is in het document overzicht protocollen programeren te vinden </p> * * <h2 id="1-over-standaarden">1. Over Standaarden</h2> * * <p>Bij het afspreken van het protocol zijn de volgende standaarden afgesproken:</p> * * <h3 id="printstream">Printstream</h3> * * <p>Voor communicatie tussen de server en de client is er gekozen voor een Printstream, dit is een voorlopige keuze sinds we dit niet tijdens de sessie hebben besproken</p> * * <ul> * <li> Hoewel er tijdens de protocolsessie geen afspraken zijn gemaakt over wat voor stream er gebruikt gaat worden is er voor deze gekozen.</li> * <li>Een printstream is makkelijk te debuggen</li> * <li>Een printstream is makkelijk door mensen te lezen</li> * </ul> * * <p>Tegen de printstream zijn de volgende argumenten ingebracht:</p> * * <ul> * <li>Een printstream is inefficient in het uitlezen</li> * <li>Een printstream kan gemakkelijk zorgen voor type conflicts</li> * </ul> * * <h2 id="beslissingen">Beslissingen</h2> * * * <h3 id="board">Board</h3> * * <p>Het bord wordt gedefinieerd doormiddel van twee integers</p> * * <p>de eerste steen wordt altijd neergelegd op steen 0,0</p> * <p>De origin van het bordt staat op 0,0 , waar de eerste waarde de colom bijhoudt en de tweede de rij</p> * * <p>De colommen zijn positief aan de rechterhelft van het bord.</p> * * <p>De rijen zijjn positief aan de bovenste helft.</p> * * <p>het is mogelijk om een negatieve positie op het bord te hebben</p> * * * <h3 id="player-names">Player Names</h3> * * <p>Vanwege gebruiksgemak en het vergemakkelijken van het renderen heb ik besloten om de maximale lengte van de naam van een player op 15 karakters te zetten. Dit is in de meeste, zo niet alle, gevallen wel genoeg, en zal door de maximale lengte ook geen problemen meer opleveren door veel te lange usernames in bijvoorbeeld de chat.</p> * * <p>Punt van aandacht bij het programmeren: Players <strong>moeten</strong> een unieke naam hebben: De naam wordt veel gebruikt voor identificatie.</p> * * * <h3 id="leaderboard">Leaderboard</h3> * * <p>Het leaderboard is een extra optie er worden de laatste 10 highscores gemeld</p> * * * <h3 id="STENEN">STENEN</h3> * * <style type="text/css"> .tg {border-collapse:collapse;border-spacing:0;} .tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;} .tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;} .tg .tg-yw4l{vertical-align:top} </style> <table class="tg"> <tr> <th class="tg-031e">char</th> <th class="tg-yw4l">colors</th> <th class="tg-yw4l">Shapes</th> </tr> <tr> <td class="tg-031e">A</td> <td class="tg-yw4l">RED</td> <td class="tg-yw4l">CIRCLE</td> </tr> <tr> <td class="tg-yw4l">B</td> <td class="tg-yw4l">ORANGE</td> <td class="tg-yw4l">CROSS</td> </tr> <tr> <td class="tg-yw4l">C</td> <td class="tg-yw4l">YELLOW</td> <td class="tg-yw4l">DIAMOND</td> </tr> <tr> <td class="tg-yw4l">D</td> <td class="tg-yw4l">GREEN</td> <td class="tg-yw4l">SQUARE</td> </tr> <tr> <td class="tg-yw4l">E</td> <td class="tg-yw4l">BLUE</td> <td class="tg-yw4l">STAR</td> </tr> <tr> <td class="tg-yw4l">F</td> <td class="tg-yw4l">PURPLE</td> <td class="tg-yw4l">PLUS</td> </tr> </table> * <h3 id="errorcodes">Errorcodes</h3> * * <p> er zijn verschillende errorcodes, heb je een goede reden om een extra aan te vragen gooi het over de github </p> * * * <h3 id="over-delimiters">Over Delimiters</h3> * * <p>Ik heb gekozen voor een dubbele carriage return (<code>\n\n</code>) als delimiter <p> * * <p>Als delimiter tussen argumenten gebruiken wij een underscore (<code>_<\code>) omdat dit makkelijk en handig is.</p> * <p>Als delimiter binnen een argument gebruiken wij een sterretje (<code>*<\code>) omdat dit makkelijk en handig is.</p> * * * <h2 id="packets">Packets</h2> * * <p>Hierop volgt een lijst met overeengekomen commando's. Deze zijn gesorteerd op type en waar ze geimplementeerd moeten zijn. </p> * * <p>Per packet wordt ook het datatype erbijgegeven, dit om type conflicts tegen te werken.</p> * * * /** * @author marti * */ public class Protocol { public static class Client { /** * <h3 id="client">Client</h3> */ /** * <p>Connect <br> * Name: <code>HALLO</code> <br> * Descriptie: Commando dat verstuurd wordt om te identificeren bij de server <br> * Content: <code>Player Name_</code> <code>modulesSupported_</code></p> * * <ul> * <li><code>HALLO_playername_features\n\n</code> (15) - De naam van de speler die wil connecten.</li> * Een lijst van ondersteunde <code>modules</code>s, met standaard delimitter van elkaar gescheiden. <br> * <code>Feature</code>: <code>String</code> (15) - Een unieke naam voor een feature. De volgende features zijn afgesproken: * <p>chat_</p> * <p>challenge_</p> * <p> security_</p> * <p>leaderboard_</p> * <p>elk van deze features wordt los toegelicht.</p> * </li> * </ul> */ public static final String HALLO = "HALLO"; /** * <p>Quit <br> * Name: <code>QUIT</code> <br> * Descriptie: commando dat verzonden wordt om de verbinding te verbreken. <br> */ public static final String QUIT = "QUIT"; /** * <p>Invite <br> * Name: <code>INVITE_player\n\n</code> <br> * Descriptie: Packet dat verzonden wordt om een spel te starten met de aangegeven tegenstander. <br> * Content: <code>&lt;Opponent Name&gt;</code> [<code>&lt;BoardX&gt;</code> <code>&lt;BoardY&gt;</code> [<code>&lt;Settings&gt;</code>]]</p> * * <ul> * <li><code>Opponent Name</code>: <code>String</code> (15) - De naam van de speler die de invite moet ontvangen.</li> */ public static final String INVITE = "INVITE"; /** * <p>Accept Invite <br> * Name: <code>ACCEPT\n\n</code> <br> * Descriptie: Packet door de uitgedaagde partij wordt verzonden om op een invite in te gaan. <br> * Content: <code>&lt;Opponent Name&gt;</code></p> * * <ul> * <li><code>Opponent Name</code>: <code>String</code> (15) - De naam van degene die de uitgedaagde partij heeft uitgedaagd.</li> * </ul> */ public static final String ACCEPTINVITE = "ACCEPTINVITE"; /** * <p>Decline Invite <br> * Name: <code>DECLINE\n\n</code> <br> * Descriptie: Packet die door de uitgedaagde partij wordt verzonden om een invite af te slaan. <br> * Content: <code>&lt;Opponent Name&gt;</code></p> * * <ul> * <li><code>Opponent Name</code>: <code>String</code> (15) - De naam van degene die de uitgedaagde partij heeft uitgedaagd.</li> * </ul> */ public static final String DECLINEINVITE = "DECLINEINVITE"; /** * <p>Move <br> * Name: <code>MAKEMOVE</code> <br> * Descriptie: de steen en locatie combinatie waar de steen neergelegd wordt <br> * <p>elke steen wordt bescheven als volgt:</p> * <p>charchar*int*int</p>\ * voorbeeld: * Content: <code>charchar*int*int\n\n</code></p> * <code>MAKEMOVE_AF*11*6_BF*11*7\n\n<code> * */ public static final String MAKEMOVE = "MAKEMOVE"; /** * <p>Chat <br> * Name: <code>CHAT</code> <br> * Descriptie: Bevat een chatmessage <br> * Content: <code>CHAT_playerName_message\n\n;</code></p> * */ public static final String CHAT = "CHAT"; /** * <p>Request Game <br> * Name: <code>REQUESTGAME</code> <br> * Descriptie: Vraagt de server om een game te joinen van een aantal personen<br> * Content: <code>REQUESTGAME_integer\n\n<code> * Valide input voor de integer zijn: * 0: Het maakt je niet uit hoeveel mensen je speelt * 1: match tegen een computerspeler * 2: match met 2 personen * 3: match met 3 personen * 4: match met 4 personen * voorbeeld: * REQUESTGAME_int\n\n * REQUESTGAME_4\n\n */ public static final String REQUESTGAME = "REQUESTGAME"; /** * <p>CHANGESTONE <br> * Name: <code>CHANGESTONE</code> <br> * Descriptie: Vraagt de server om een stenen in te wisselen<br> * Content: <code>CHANGESTONE_steen_steen\n\n <code> */ public static final String CHANGESTONE = "CHANGESTONE"; /** * <p>GETLEADERBOARD<br> * Name: <code>LEADERBOARD</code> <br> * Descriptie: Vraag het leaderboard aan <br> * Content: <code>GETLEADERBOARD\n\n<code> * */ public static final String GETLEADERBOARD = "GETLEADERBOARD"; /** * <p>GETSTONESINBAG<br> * Name: <code>STONESINBAG</code> <br> * Descriptie: een commando waarmee de hoeveelheid stenen in de zak wordt gerequest <br> * Content: <code>GETSTONESINBAG\n\n</code></p> * */ public static final String GETSTONESINBAG = "GETSTONESINBAG"; /** * <p>Error <br> * Name: <code>ERROR</code><br/> * Descriptie: Zend een error naar de server toe.<br/> * Content: <code>ERROR_integer\n\n</code> * er zijn nog geen errors gedefinieerd voor de speler. */ public static final String ERROR = "ERROR"; } public static class Server { /** * <h3 id="server">Server</h3> */ /** * <p>HALLO <br> * Name: <code>HALLO</code> <br> * Descriptie: Signaal dat de connectie is gemaakt en het aangeven van welke functies allemaal zijn toegestaan op deze server. <br> * Content: <code>HALLO_servernaam_features\n\n</code></p> * features worden gescheiden door een underscore */ public static final String HALLO = "HALLO"; /** * <p>Error <br> * Name: <code>ERROR</code> <br> * Descriptie: Een errormessage <br> * Content: <code>ERROR_integer\n\n</code></p> * <ul> * errorcodes die beschikbaar zijn: * 1: notyourturn * 2: notyourstone * 3: notthatmanystonesavailable * 4: nameexists * 5: notchallengable * 6: challengerefused * 7: invalidmove */ public static final String ERROR = "ERROR"; /** * <p>OKWAITFOR <br> * Name: <code>OKWAITFOR</code> <br> * Descriptie: Een lijst met mensen die zich op het moment in de lobby bevinden. Wordt door de server verstuurd bij Connect/Disconnect van een speler, en wanneer aangevraagd. <br> * Content: <code>OKWAITFOR_integer\n\n</code></p> * */ public static final String OKWAITFOR = "OKWAITFOR"; /** * <p>Game Start <br> * Name: <code>START</code> <br> * Descriptie: Een packet dat naar de spelers wordt gestuurd om te laten weten dat het spel gestart is. <br> * Content: <code>START_player_player\n\n</code>]</p> * * <ul> * <li><code>Player 1</code>: <code>String</code> (15) - Naam van de eerste speler</li> * <li><code>Player 2</code>: <code>String</code> (15) - Naam van de tweede speler</li> * </ul> */ public static final String STARTGAME = "STARTGAME"; /** * <p>Game End <br> * Name: <code>END</code> <br> * Descriptie: Een packet dat naar de spelers wordt gestuurd om te laten weten dat het spel is gestopt <br> * Content: <code>END\n\n</code>]</p> * * <ul> * <li><code>Type</code>: <code>String</code> &gt; <code>'WIN'</code> <code>'DISCONNECT'</code> <code>'DRAW'</code> - Type van einde spel</li> * <li><code>Winner Name</code>: <code>String</code> (15) - Naam van de winnaar, of andere info over de reden van het einde.</li> * </ul> */ public static final String GAME_END = "END"; /** * <p>MOVE<br> * Name: <code>REQUEST</code> <br> * Descriptie: een commando om aan te geven welke move gemaakt door wie en welke speler nu aan de beurt is <br> * Content: <p>MOVE_player_playernext_moves\n\n</p> * er kunnen meerdere moves gemaakt worden, deze worden gedelimit door standaarddelimiter * de informatie in de move wordt gedelimit door standaarddelimiter2 */ public static final String MOVE = "MOVE"; /** * <p>Chat <br> * Name: <code>CHAT</code> <br> * Descriptie: Een packet wat een chatbericht bevat <br> * Content: <code>CHAT_bericht\n\n</code></p> */ public static final String CHAT = "CHAT"; /** * <p>ADDTOHAND <br> * Name: <code>ADDTOHAND</code> <br> * Descriptie: een commando waarmee stenen worden toegevoegd aan de hand van de speler <br> * Content: <code>ADDTOHAND_steen_steen_steen\n\n</code></p> * */ public static final String ADDTOHAND = "ADDTOHAND"; /** * <p>STONESINBAG<br> * Name: <code>STONESINBAG</code> <br> * Descriptie: een commando waarmee de hoeveelheid stenen in de zak wordt gegeven <br> * Content: <code>STONESINBAG_integer\n\n</code></p> * */ public static final String STONESINBAG = "STONESINBAG"; /** * <p>Leaderboard <br> * Name: <code>LEADERBOARD</code> <br> * Descriptie: Een packet waarin de statistieken van een aantal spelers worden verstuurd. <br> * Content: <code>LEADERBOARD_playername*integer_playername*integer\n\n</code></p> * * <ul> * <li><code>Player Name</code>: <code>String</code> (15) - Naam van de speler in de betreffende statistiek</li> * <li><code>Ranking</code>: <code>int</code> - Ranking op de server</li> * </ul> * </li> * </ul> */ public static final String LEADERBOARD = "LEADERBOARD"; public static class Features { /** * <p>De verschillende features die optioneel zijn geimplementeerd kunnen worden.</p> * * <p>Let op! Het protocol voor <code>SECURITY</code> is nog niet vastgelegd. */ public static final String CHAT = "CHAT"; public static final String LEADERBOARD = "LEADERBOARD"; public static final String SECURITY = "SECURITY"; public static final String CHALLENGE = "CHALLENGE"; // Deze functie wordt nog niet verwacht wordt dat SSLsocket gebruikt gaat worden } /** * <p>Invite <br> * Name: <code>INVITE</code> <br> * Descriptie: comando dat de server vraagt om iemand te challengen <br> * Content: <code>INVITE_PLAYERNAME\n\n</code></p> * * <ul> * <li><code>Opponent Name</code>: <code>String</code> (15) - De naam van de tegenstander</li> * </ul> * op dit moment is er geen mogelijkheid gedefinieerd om meerdere mensen te challengen */ public static final String INVITE = "INVITE"; /** * <p>Decline invite<br> * Name: <code>DECLINEINVITE</code> <br> * Descriptie: De packet die waarmee een uitnodiging wordt afgewezen<br> * Content: <code>DECLINEINVITE\n\n</code></p> */ public static final String DECLINEINVITE = "DECLINEINVITE"; } public static class Settings { /** * <p>De verschillende settings van het protocol.</p> */ /** * <p>Het protocol heeft<SUF>*/ public static final String ENCODING = "UTF-16"; /** * <p>Het aantal seconden voordat een client timeout. Dit is in de opdracht vastgesteld, en zal dus niet veranderen.</p> */ public static final int TIMEOUTSECONDS = 15; /** * <p>Default server port nummer. <br> * <b>BELANGRIJK:</b> In de opdracht staat dat je bij het opstarten van de server een poortnummer moet invoeren. De waarde hier is dus niet een waarde die altijd opgaat. </p> */ public static final short DEFAULT_PORT = 4242; /** * <p>Default delimiter tussen header en content, en tussen twee waarden in de content</p> */ public static final char DELIMITER = '_'; /** * <p>tweede delimiter om zaken te scheiden binenin een waarde in de content(bijvoorbeeld bij een steen locatie waarde)</p> * */ public static final char DELIMITER2 = '*'; /** * <p>Teken dat aan het einde van elke packet moet zitten, en dus niet in de rest van de waarden mag zitten.</p> */ public static final String COMMAND_END = "\n\n"; } }
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,103
// 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; } }
75992_16
import menus.*; import java.util.ArrayList; import java.util.InputMismatchException; import java.util.Scanner; public class MenuManager { private Scanner scanner = new Scanner(System.in); //Arraylist houd de huidige menu opties bij private Submenu menuOptions; //Arraylist die houd alle vorige menuopties bij voor backtracking private ArrayList<Submenu> previousMenu = new ArrayList<>(); public void start(){ this.menuOptions = getDefaultMenuOptions(); print(); } public void print(){ printMenu(); processUserInput(getUserInput()); } public void reCheckUserInput(){ printMenu(); processUserInput(getUserInput()); } private void processUserInput(int index){ //Als de 0: exit menu is gekozen if(index == 0){ //Kijken of we in de main menu zitten en zowel gwn weg gaan if(previousMenu.size() == 0){ return; } //De huidige menu options terug zetten naar de vorige menu opties menuOptions = previousMenu.get(previousMenu.size() -1); //de vorige menu opties die zijn gecloned verwijderen omdat we ze niet meer nodig hebben previousMenu.remove(previousMenu.size()-1); print(); return; } //Een array begint met 0, maar de menu opties beginnen met 1, dus we willen de index met 1 verminderen index--; //Voer de code uit van de gekozen menu en sla de volgende submenu op in een variable menuOptions.getMenuOptions().get(index).executeMenuOption(); var newMenuOptions = menuOptions.getMenuOptions().get(index).getNextSubMenu(); //Als er geen volgende menu opties zijn checken we voor nieuwe input if(newMenuOptions == null){ reCheckUserInput(); return; } //het huidige menu opslaan voor backtracking previousMenu.add(menuOptions); //het huidige menu updaten met de nieuwe submenu menuOptions = newMenuOptions; print() ; } private int getUserInput(){ boolean noValidAnswer = true; while(noValidAnswer) { try { int answer = scanner.nextInt(); //See if the answer is inbetween the actual posible answers. if (answer > menuOptions.getMenuOptions().size() || answer < 0) { System.out.println("Please enter a valid number."); } else { //Return statement haalt ons uit de while loop return answer; } } catch (InputMismatchException e) { //input mismatch exception means they put text in the input but we're looking for ints so the input mismatches the expected outcome. System.out.println("Please enter a valid number."); } } //Mandatory return statement, actually does nothing return 0; } private void printMenu(){ //Ga langs elke submenu optie en print de naam for(int i = 0; i < menuOptions.getMenuOptions().size(); i++){ System.out.println(i+1 + ": "+menuOptions.getMenuOptions().get(i).getTitle()); } System.out.println("0: Exit"); } private Submenu getDefaultMenuOptions(){ //Dit is het startmenu ArrayList<iMenuOption> menuOptions = new ArrayList<>(); menuOptions.add(new DierenMenuOption()); menuOptions.add(new ExamenMenuOption()); menuOptions.add(new StudentenMenuOption()); Submenu submenu = new Submenu(); submenu.setMenuOptions(menuOptions); return submenu; } }
H-SE-1-8D-2022/voorbeeld-code-menu
src/MenuManager.java
877
//Dit is het startmenu
line_comment
nl
import menus.*; import java.util.ArrayList; import java.util.InputMismatchException; import java.util.Scanner; public class MenuManager { private Scanner scanner = new Scanner(System.in); //Arraylist houd de huidige menu opties bij private Submenu menuOptions; //Arraylist die houd alle vorige menuopties bij voor backtracking private ArrayList<Submenu> previousMenu = new ArrayList<>(); public void start(){ this.menuOptions = getDefaultMenuOptions(); print(); } public void print(){ printMenu(); processUserInput(getUserInput()); } public void reCheckUserInput(){ printMenu(); processUserInput(getUserInput()); } private void processUserInput(int index){ //Als de 0: exit menu is gekozen if(index == 0){ //Kijken of we in de main menu zitten en zowel gwn weg gaan if(previousMenu.size() == 0){ return; } //De huidige menu options terug zetten naar de vorige menu opties menuOptions = previousMenu.get(previousMenu.size() -1); //de vorige menu opties die zijn gecloned verwijderen omdat we ze niet meer nodig hebben previousMenu.remove(previousMenu.size()-1); print(); return; } //Een array begint met 0, maar de menu opties beginnen met 1, dus we willen de index met 1 verminderen index--; //Voer de code uit van de gekozen menu en sla de volgende submenu op in een variable menuOptions.getMenuOptions().get(index).executeMenuOption(); var newMenuOptions = menuOptions.getMenuOptions().get(index).getNextSubMenu(); //Als er geen volgende menu opties zijn checken we voor nieuwe input if(newMenuOptions == null){ reCheckUserInput(); return; } //het huidige menu opslaan voor backtracking previousMenu.add(menuOptions); //het huidige menu updaten met de nieuwe submenu menuOptions = newMenuOptions; print() ; } private int getUserInput(){ boolean noValidAnswer = true; while(noValidAnswer) { try { int answer = scanner.nextInt(); //See if the answer is inbetween the actual posible answers. if (answer > menuOptions.getMenuOptions().size() || answer < 0) { System.out.println("Please enter a valid number."); } else { //Return statement haalt ons uit de while loop return answer; } } catch (InputMismatchException e) { //input mismatch exception means they put text in the input but we're looking for ints so the input mismatches the expected outcome. System.out.println("Please enter a valid number."); } } //Mandatory return statement, actually does nothing return 0; } private void printMenu(){ //Ga langs elke submenu optie en print de naam for(int i = 0; i < menuOptions.getMenuOptions().size(); i++){ System.out.println(i+1 + ": "+menuOptions.getMenuOptions().get(i).getTitle()); } System.out.println("0: Exit"); } private Submenu getDefaultMenuOptions(){ //Dit is<SUF> ArrayList<iMenuOption> menuOptions = new ArrayList<>(); menuOptions.add(new DierenMenuOption()); menuOptions.add(new ExamenMenuOption()); menuOptions.add(new StudentenMenuOption()); Submenu submenu = new Submenu(); submenu.setMenuOptions(menuOptions); return submenu; } }
18325_4
package novi.basics; import static novi.basics.Main.PLAYERINPUT; public class Game { private char [] board; private int maxRounds; private Player player1; private Player player2; private int drawCount; private Player activePlayer; public Game(){ board = new char[]{'1', '2', '3', '4', '5', '6', '7', '8', '9'}; maxRounds = board.length; this.player1 = player1; this.player2 = player2; drawCount = 0; } public void play(Player player1, Player player2) { printBoard(board); activePlayer = player1; for(int round = 0; round < maxRounds; round++) { String activePlayerName = activePlayer.getName(); System.out.println(activePlayerName + ", please choose a field"); int chosenField = PLAYERINPUT.nextInt(); int chosenIndex = chosenField - 1; if (chosenIndex < 9 && chosenIndex >= 0) { if (board[chosenIndex] != player1.getToken() && board[chosenIndex] != player2.getToken()) { board[chosenIndex] = activePlayer.getToken(); printBoard(board); // als het spel gewonnen is // tonen wie er gewonnen heeft (de actieve speler) // de actieve speler krijgt een punt // de scores van de spelers tonen // wanneer we in de laatste beurt zijn en niemand gewonnen heeft // aantal keer gelijk spel ophogen // aantal keer gelijk spel tonen // de beurt doorgeven aan de volgende speler (van speler wisselen) // als de actieve speler, speler 1 is: if (activePlayer == player1) { activePlayer = player2; } else { activePlayer = player1; } } else { maxRounds++; System.out.println("This field is not available, choose another"); } //versie 2: als het veld leeg is, wanneer de waarde gelijk is aan chosenField /*if(board[chosenIndex] != '1' + chosenIndex) { board[chosenIndex] = activePlayerToken; }*/ } else { // het mamimale aantal beurten verhogen maxRounds++; // foutmelding tonen aan de speler System.out.println("The chosen field does not exist, try again"); } // -- terug naar het begin van de volgende beurt } } public static void printBoard(char[] board) { for (int fieldIndex = 0; fieldIndex < board.length; fieldIndex++) { System.out.print(board[fieldIndex] + " "); // als we het tweede veld geprint hebben of het vijfde veld geprint hebben // dan gaan we naar de volgende regel if(fieldIndex == 2 || fieldIndex == 5) { System.out.println(); } } System.out.println(); } }
hogeschoolnovi/tic-tac-toe-warnerverduijn
src/novi/basics/Game.java
746
// wanneer we in de laatste beurt zijn en niemand gewonnen heeft
line_comment
nl
package novi.basics; import static novi.basics.Main.PLAYERINPUT; public class Game { private char [] board; private int maxRounds; private Player player1; private Player player2; private int drawCount; private Player activePlayer; public Game(){ board = new char[]{'1', '2', '3', '4', '5', '6', '7', '8', '9'}; maxRounds = board.length; this.player1 = player1; this.player2 = player2; drawCount = 0; } public void play(Player player1, Player player2) { printBoard(board); activePlayer = player1; for(int round = 0; round < maxRounds; round++) { String activePlayerName = activePlayer.getName(); System.out.println(activePlayerName + ", please choose a field"); int chosenField = PLAYERINPUT.nextInt(); int chosenIndex = chosenField - 1; if (chosenIndex < 9 && chosenIndex >= 0) { if (board[chosenIndex] != player1.getToken() && board[chosenIndex] != player2.getToken()) { board[chosenIndex] = activePlayer.getToken(); printBoard(board); // als het spel gewonnen is // tonen wie er gewonnen heeft (de actieve speler) // de actieve speler krijgt een punt // de scores van de spelers tonen // wanneer we<SUF> // aantal keer gelijk spel ophogen // aantal keer gelijk spel tonen // de beurt doorgeven aan de volgende speler (van speler wisselen) // als de actieve speler, speler 1 is: if (activePlayer == player1) { activePlayer = player2; } else { activePlayer = player1; } } else { maxRounds++; System.out.println("This field is not available, choose another"); } //versie 2: als het veld leeg is, wanneer de waarde gelijk is aan chosenField /*if(board[chosenIndex] != '1' + chosenIndex) { board[chosenIndex] = activePlayerToken; }*/ } else { // het mamimale aantal beurten verhogen maxRounds++; // foutmelding tonen aan de speler System.out.println("The chosen field does not exist, try again"); } // -- terug naar het begin van de volgende beurt } } public static void printBoard(char[] board) { for (int fieldIndex = 0; fieldIndex < board.length; fieldIndex++) { System.out.print(board[fieldIndex] + " "); // als we het tweede veld geprint hebben of het vijfde veld geprint hebben // dan gaan we naar de volgende regel if(fieldIndex == 2 || fieldIndex == 5) { System.out.println(); } } System.out.println(); } }