answer
stringlengths
17
10.2M
package org.usfirst.frc.team3335.robot.subsystems; import org.usfirst.frc.team3335.robot.RobotMap; import edu.wpi.first.wpilibj.AnalogInput; import edu.wpi.first.wpilibj.command.Subsystem; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; public class DoubleUltrasonic extends Subsystem implements LoggableSubsystem { // distance in inches the robot wants to stay from an object //private static final double kHoldDistance = 12.0; // factor to convert sensor values to a distance in inches //private static final double kValueToInches = 0.125; // factor to convert voltage values to a distance in inches // kVoltageToInches = (value V) * (1000mV/V) * (1mm/0.977mV) * (1cm/10mm) * (1in/2.54cm) private static final double kVoltageToInches = 40.2969; private AnalogInput ultrasonicLeft = new AnalogInput(RobotMap.ANALOG_ULTRASONIC_LEFT); private AnalogInput ultrasonicRight = new AnalogInput(RobotMap.ANALOG_ULTRASONIC_RIGHT); public double getDistanceLeft() { return getDistance(ultrasonicLeft); } public double getDistanceRight() { return getDistance(ultrasonicRight); } private double getDistance(AnalogInput ultrasonic) { //return ultrasonic.getValue() * kValueToInches; return ultrasonic.getAverageVoltage()*kVoltageToInches; } @Override protected void initDefaultCommand() { // TODO Auto-generated method stub } @Override public void log() { SmartDashboard.putNumber("Ultrasonic: Left Avg Volt", ultrasonicLeft.getAverageVoltage()); SmartDashboard.putNumber("Ultrasonic: Right Avg Volt", ultrasonicRight.getAverageVoltage()); SmartDashboard.putNumber("Ultrasonic: Left Distance", getDistanceLeft()); SmartDashboard.putNumber("Ultrasonic: Right Distance", getDistanceRight()); } }
package pl.koszela.jan.domain; import java.util.Objects; public class Order { private Product product; private int quantity; public Order(String productName, int quantity) { this.product = Product.builder() .item(productName) .build(); this.quantity = quantity; } public Product getProduct() { return this.product; } public int getQuantity() { return this.quantity; } public void setProduct(Product productName) { this.product = productName; } public void setQuantity(int quantity) { this.quantity = quantity; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Order order = (Order) o; return Objects.equals(product, order.product); } @Override public int hashCode() { return Objects.hash(product, quantity); } @Override public String toString() { return "Order{" + "productName='" + product + '\'' + ", quantity=" + quantity + '}'; } }
package protocolsupport.protocol.core.initial; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.util.concurrent.Future; import net.minecraft.server.v1_8_R3.MinecraftServer; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.EnumMap; import java.util.concurrent.TimeUnit; import protocolsupport.ProtocolSupport; import protocolsupport.api.ProtocolVersion; import protocolsupport.protocol.core.ChannelHandlers; import protocolsupport.protocol.core.IPipeLineBuilder; import protocolsupport.protocol.storage.ProtocolStorage; import protocolsupport.utils.Utils; import protocolsupport.utils.Utils.Converter; import protocolsupport.utils.netty.ChannelUtils; import protocolsupport.utils.netty.ReplayingDecoderBuffer; import protocolsupport.utils.netty.ReplayingDecoderBuffer.EOFSignal; public class InitialPacketDecoder extends SimpleChannelInboundHandler<ByteBuf> { private static final int ping152delay = Utils.getJavaPropertyValue("protocolsupport.ping152delay", 500, Converter.STRING_TO_INT); private static final int pingLegacyDelay = Utils.getJavaPropertyValue("protocolsupport.pinglegacydelay", 1000, Converter.STRING_TO_INT); public static void init() { ProtocolSupport.logInfo("Assume 1.5.2 ping delay: "+ping152delay); ProtocolSupport.logInfo("Assume legacy ping dealy: "+pingLegacyDelay); } private static final EnumMap<ProtocolVersion, IPipeLineBuilder> pipelineBuilders = new EnumMap<ProtocolVersion, IPipeLineBuilder>(ProtocolVersion.class); static { IPipeLineBuilder builder = new protocolsupport.protocol.transformer.v_1_8.PipeLineBuilder(); pipelineBuilders.put(ProtocolVersion.MINECRAFT_FUTURE, builder); pipelineBuilders.put(ProtocolVersion.MINECRAFT_1_8, builder); IPipeLineBuilder builder17 = new protocolsupport.protocol.transformer.v_1_7.PipeLineBuilder(); pipelineBuilders.put(ProtocolVersion.MINECRAFT_1_7_10, builder17); pipelineBuilders.put(ProtocolVersion.MINECRAFT_1_7_5, builder17); IPipeLineBuilder builder16 = new protocolsupport.protocol.transformer.v_1_6.PipeLineBuilder(); pipelineBuilders.put(ProtocolVersion.MINECRAFT_1_6_4, builder16); pipelineBuilders.put(ProtocolVersion.MINECRAFT_1_6_2, builder16); pipelineBuilders.put(ProtocolVersion.MINECRAFT_1_6_1, builder16); IPipeLineBuilder builder15 = new protocolsupport.protocol.transformer.v_1_5.PipeLineBuilder(); pipelineBuilders.put(ProtocolVersion.MINECRAFT_1_5_2, builder15); pipelineBuilders.put(ProtocolVersion.MINECRAFT_1_5_1, builder15); pipelineBuilders.put(ProtocolVersion.MINECRAFT_1_4_7, new protocolsupport.protocol.transformer.v_1_4.PipeLineBuilder()); pipelineBuilders.put(ProtocolVersion.MINECRAFT_LEGACY, new protocolsupport.protocol.transformer.v_legacy.PipeLineBuilder()); } protected final ByteBuf receivedData = Unpooled.buffer(); protected final ReplayingDecoderBuffer replayingBuffer = new ReplayingDecoderBuffer(receivedData); protected volatile Future<?> responseTask; protected void scheduleTask(ChannelHandlerContext ctx, Runnable task, long delay, TimeUnit tu) { cancelTask(); responseTask = ctx.executor().schedule(task, delay, tu); } protected void cancelTask() { if (responseTask != null) { responseTask.cancel(true); responseTask = null; } } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { cancelTask(); super.channelInactive(ctx); } @Override public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { cancelTask(); super.handlerRemoved(ctx); } @Override public void channelRead0(ChannelHandlerContext ctx, ByteBuf buf) throws Exception { if (!buf.isReadable()) { return; } receivedData.writeBytes(buf); receivedData.readerIndex(0); final Channel channel = ctx.channel(); if (MinecraftServer.getServer().isDebugging()) { System.out.println( ChannelUtils.getNetworkManagerSocketAddress(channel) + " data: " + Arrays.toString(Arrays.copyOf(receivedData.array(), receivedData.readableBytes())) ); } ProtocolVersion handshakeversion = null; int firstbyte = replayingBuffer.readUnsignedByte(); switch (firstbyte) { case 0xFE: { //old ping try { if (replayingBuffer.readableBytes() == 0) { //really old protocol probably scheduleTask(ctx, new SetProtocolTask(this, channel, ProtocolVersion.MINECRAFT_LEGACY), pingLegacyDelay, TimeUnit.MILLISECONDS); } else if (replayingBuffer.readUnsignedByte() == 1) { if (replayingBuffer.readableBytes() == 0) { //1.5.2 probably scheduleTask(ctx, new SetProtocolTask(this, channel, ProtocolVersion.MINECRAFT_1_5_2), ping152delay, TimeUnit.MILLISECONDS); } else if ( (replayingBuffer.readUnsignedByte() == 0xFA) && "MC|PingHost".equals(new String(ChannelUtils.toArray(replayingBuffer.readBytes(replayingBuffer.readUnsignedShort() * 2)), StandardCharsets.UTF_16BE)) ) { replayingBuffer.readUnsignedShort(); handshakeversion = ProtocolUtils.get16PingVersion(replayingBuffer.readUnsignedByte()); } } } catch (EOFSignal ex) { } break; } case 0x02: { // <= 1.6.4 handshake try { handshakeversion = ProtocolUtils.readOldHandshake(replayingBuffer); } catch (EOFSignal ex) { } break; } default: { // >= 1.7 handshake replayingBuffer.readerIndex(0); ByteBuf data = getVarIntPrefixedData(replayingBuffer); if (data != null) { handshakeversion = ProtocolUtils.readNettyHandshake(data); } break; } } //if we detected the protocol than we save it and process data if (handshakeversion != null) { setProtocol(channel, receivedData, handshakeversion); } } protected volatile boolean protocolSet = false; protected void setProtocol(final Channel channel, final ByteBuf input, ProtocolVersion version) throws Exception { if (protocolSet) { return; } protocolSet = true; if (MinecraftServer.getServer().isDebugging()) { System.out.println(ChannelUtils.getNetworkManagerSocketAddress(channel)+ " connected with protocol version "+version); } ProtocolStorage.setProtocolVersion(ChannelUtils.getNetworkManagerSocketAddress(channel), version); channel.pipeline().remove(ChannelHandlers.INITIAL_DECODER); pipelineBuilders.get(version).buildPipeLine(channel, version); input.readerIndex(0); channel.pipeline().firstContext().fireChannelRead(input); } //handshake packet has more than 3 bytes for sure, so we can simplify splitting logic private static ByteBuf getVarIntPrefixedData(final ByteBuf byteBuf) { if (byteBuf.readableBytes() < 3) { return null; } int length = ChannelUtils.readVarInt(byteBuf); if (byteBuf.readableBytes() < length) { return null; } return byteBuf.readBytes(length); } }
package system; import org.apache.commons.io.FileUtils; import rss.Feed; import rss.Item; import java.io.File; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; /** * Class DatabaseAccessObject * * @author Axel Nilsson (axnion) */ public class DatabaseAccessObject { private String path; DatabaseAccessObject() { path = "temp.db"; try { load(); } catch(Exception expt) { expt.printStackTrace(); } } DatabaseAccessObject(String path) { this.path = path; try { load(); } catch(Exception expt) { expt.printStackTrace(); } } ArrayList<FeedList> load() throws Exception { Connection connection = loadPrep(); Statement statement = connection.createStatement(); ArrayList<FeedList> feedLists = loadFeedLists(statement); for(FeedList feedList : feedLists) { loadFeeds(statement, feedList); loadItems(statement, feedList); } connection.commit(); statement.close(); connection.close(); return feedLists; } private Connection loadPrep() throws Exception { if(path.equals("temp.db")) { File tempDatabase = new File("temp.db"); tempDatabase.delete(); } Class.forName("org.sqlite.JDBC"); Connection connection = DriverManager.getConnection("jdbc:sqlite:" + path); connection.setAutoCommit(false); Statement statement = connection.createStatement(); String createFeedListSaveDataTable = "CREATE TABLE IF NOT EXISTS save_data_feed_lists(" + "FEEDLISTNAME TEXT PRIMARY KEY UNIQUE NOT NULL, " + "SORTING VARCHAR(16) DEFAULT DATE_DEC NOT NULL);"; String createFeedSaveDataTable = "CREATE TABLE IF NOT EXISTS save_data_feeds" + " (URLTOXML TEXT NOT NULL," + " FEEDLISTNAME TEXT NOT NULL);"; statement.executeUpdate(createFeedListSaveDataTable); statement.executeUpdate(createFeedSaveDataTable); statement.close(); return connection; } private ArrayList<FeedList> loadFeedLists(Statement statement) throws Exception { ArrayList<FeedList> feedLists = new ArrayList<>(); String query = "SELECT * FROM save_data_feed_lists;"; ResultSet results = statement.executeQuery(query); while(results.next()) { feedLists.add(new FeedList(results.getString("feedlistname"), results.getString("sorting"))); } return feedLists; } private void loadFeeds(Statement statement, FeedList feedList) throws Exception { String query = "SELECT * FROM save_data_feeds WHERE FEEDLISTNAME='" + feedList.getName() + "';"; ResultSet results = statement.executeQuery(query); while(results.next()) { feedList.add(results.getString("urltoxml")); } } private void loadItems(Statement statement, FeedList feedList) throws Exception { String query; for(Item item : feedList.getAllItems()) { query = "SELECT * FROM '" + feedList.getName() + "' WHERE ID='" + item.getId() + "';"; ResultSet results = statement.executeQuery(query); results.next(); item.setVisited(results.getBoolean("VISITED")); item.setStarred(results.getBoolean("STARRED")); } } void save(ArrayList<FeedList> feedLists) throws Exception { Connection connection = savePrep(); Statement statement = connection.createStatement(); for(FeedList feedList : feedLists) { saveFeedLists(statement, feedList); saveFeeds(statement, feedList); saveItems(statement, feedList); } connection.commit(); statement.close(); connection.close(); } private Connection savePrep() throws Exception { Class.forName("org.sqlite.JDBC"); Connection connection = DriverManager.getConnection("jdbc:sqlite:" + path); connection.setAutoCommit(false); return connection; } private void saveFeedLists(Statement statement, FeedList feedList) throws Exception { String createFeedListTableQuery = "CREATE TABLE IF NOT EXISTS" + feedList.getName() + " (ID TEXT PRIMARY KEY UNIQUE NOT NULL," + " VISITED BOOLEAN NOT NULL," + " STARRED BOOLEAN NOT NULL);"; String addFeedListToSortTable = "INSERT INTO save_data_feed_lists (FEEDLISTNAME) " + "VALUES ('" + feedList.getName() + "')"; statement.executeUpdate(createFeedListTableQuery); statement.executeUpdate(addFeedListToSortTable); } private void saveFeeds(Statement statement, FeedList feedList) throws Exception { for(Feed feed : feedList.getFeeds()) { String addFeedQuery = "INSERT INTO save_data_feeds (URLTOXML,FEEDLISTNAME) " + "VALUES ('" + feed.getUrlToXML() + "','" + feedList.getName() + "');"; statement.executeUpdate(addFeedQuery); } } private void saveItems(Statement statement, FeedList feedList) throws Exception { for(Item item : feedList.getAllItems()) { String addItemQuery = "INSERT OR IGNORE INTO " + feedList.getName() + " (ID,VISITED,STARRED) VALUES ('" + item.getId() + "','" + item.isVisited() + "','" + item.isStarred() + "');"; statement.executeUpdate(addItemQuery); } } void copy(String destination) throws Exception { FileUtils.copyFile(new File(path), new File(destination)); path = destination; } String getPath() { return path; } void setPath(String newPath) { path = newPath; } }
package tigase.server; import java.lang.management.ManagementFactory; import java.lang.management.MemoryUsage; import java.lang.management.OperatingSystemMXBean; import java.lang.management.ThreadMXBean; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.TreeMap; import java.util.Timer; import java.util.TimerTask; import java.util.LinkedHashSet; import java.util.concurrent.ConcurrentSkipListMap; import java.util.logging.Logger; import java.util.logging.Level; import tigase.xml.Element; import tigase.util.JIDUtils; import tigase.util.UpdatesChecker; import tigase.xmpp.Authorization; import tigase.xmpp.StanzaType; import tigase.xmpp.PacketErrorTypeException; import tigase.disco.XMPPService; import tigase.disco.ServiceEntity; import tigase.disco.ServiceIdentity; import tigase.stats.StatRecord; import static tigase.server.MessageRouterConfig.*; /** * Class MessageRouter * * * Created: Tue Nov 22 07:07:11 2005 * * @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a> * @version $Rev$ */ public class MessageRouter extends AbstractMessageReceiver { // implements XMPPService { public static final String INFO_XMLNS = "http://jabber.org/protocol/disco#info"; public static final String ITEMS_XMLNS = "http://jabber.org/protocol/disco#items"; private static final Logger log = Logger.getLogger("tigase.server.MessageRouter"); //private static final long startupTime = System.currentTimeMillis(); // private Set<String> localAddresses = new CopyOnWriteArraySet<String>(); private String disco_name = DISCO_NAME_PROP_VAL; private boolean disco_show_version = DISCO_SHOW_VERSION_PROP_VAL; private ComponentRegistrator config = null; private ServiceEntity serviceEntity = null; private UpdatesChecker updates_checker = null; private Map<String, XMPPService> xmppServices = new ConcurrentSkipListMap<String, XMPPService>(); private Map<String, ServerComponent> components = new ConcurrentSkipListMap<String, ServerComponent>(); private Map<String, ServerComponent> components_byId = new ConcurrentSkipListMap<String, ServerComponent>(); private Map<String, ComponentRegistrator> registrators = new ConcurrentSkipListMap<String, ComponentRegistrator>(); private Map<String, MessageReceiver> receivers = new ConcurrentSkipListMap<String, MessageReceiver>(); public void processPacketMR(final Packet packet, final Queue<Packet> results) { if (packet.getPermissions() != Permissions.ADMIN) { try { Packet res = Authorization.NOT_AUTHORIZED.getResponseMessage(packet, "You are not authorized for this action.", true); results.offer(res); //processPacket(res); } catch (PacketErrorTypeException e) { log.warning("Packet processing exception: " + e); } return; } log.finest("Command received: " + packet.getStringData()); switch (packet.getCommand()) { case OTHER: if (packet.getStrCommand() != null) { if (packet.getStrCommand().startsWith("controll/")) { String[] spl = packet.getStrCommand().split("/"); String cmd = spl[1]; if (cmd.equals("stop")) { Packet result = packet.commandResult(Command.DataType.result); results.offer(result); //processPacket(result); new Timer("Stopping...", true).schedule(new TimerTask() { public void run() { System.exit(0); } }, 2000); } } } break; default: break; } } @Override protected Integer getMaxQueueSize(int def) { return def*10; } private ServerComponent[] getServerComponentsForRegex(String id) { LinkedHashSet<ServerComponent> comps = new LinkedHashSet<ServerComponent>(); for (MessageReceiver mr: receivers.values()) { if (mr.isInRegexRoutings(id)) { log.finest("Found receiver: " + mr.getName()); comps.add(mr); } } if (comps.size() > 0) { return comps.toArray(new ServerComponent[comps.size()]); } else { return null; } } private ServerComponent getLocalComponent(String jid) { ServerComponent comp = components_byId.get(jid); if (comp != null) { return comp; } String host = JIDUtils.getNodeHost(jid); String nick = JIDUtils.getNodeNick(jid); if (nick != null) { comp = components.get(nick); if (comp != null && (isLocalDomain(host) || host.equals(getDefHostName()))) { return comp; } } int idx = host.indexOf('.'); if (idx > 0) { String cmpName = host.substring(0, idx); String basename = host.substring(idx + 1); comp = components.get(cmpName); if (comp != null && (isLocalDomain(basename) || basename.equals(getDefHostName()))) { return comp; } } return null; } // private String isToLocalComponent(String jid) { // String nick = JIDUtils.getNodeNick(jid); // if (nick == null) { // return null; // String host = JIDUtils.getNodeHost(jid); // if (isLocalDomain(host) && components.get(nick) != null) { // return nick; // return null; // private boolean isLocalDomain(String domain) { // return localAddresses.contains(domain); public void processPacket(Packet packet) { if (packet.getTo() == null) { log.warning("Packet with TO attribute set to NULL: " + packet.getStringData()); return; } // end of if (packet.getTo() == null) // Intentionally comparing to static, final String if (packet.getTo() == NULL_ROUTING) { log.info("NULL routing, it is normal if server doesn't know how to" + " process packet: " + packet.toString()); try { Packet error = Authorization.FEATURE_NOT_IMPLEMENTED.getResponseMessage(packet, "Feature not supported yet.", true); addOutPacketNB(error); } catch (PacketErrorTypeException e) { log.warning("Packet processing exception: " + e); } return; } // if (log.isLoggable(Level.FINER)) { // log.finer("Processing packet: " + packet.getElemName() // + ", type: " + packet.getType()); if (log.isLoggable(Level.FINEST)) { log.finest("Processing packet: " + packet.toString()); } // Detect inifinite loop if from == to // Maybe it is not needed anymore... // There is a need to process packets with the same from and to address // let't try to relax restriction and block all packets with error type // 2008-06-16 if ((packet.getType() == StanzaType.error && packet.getFrom() != null && packet.getFrom().equals(packet.getTo())) || (packet.getFrom() == NULL_ROUTING && packet.getElemFrom() != null && packet.getElemFrom().equals(packet.getTo()))) { log.warning("Possible infinite loop, dropping packet: " + packet.toString()); return; } ServerComponent comp = packet.getElemTo() == null ? null : getLocalComponent(packet.getElemTo()); if (packet.isServiceDisco() && packet.getType() != null && packet.getType() == StanzaType.get && ((comp != null && !(comp instanceof DisableDisco)) || isLocalDomain(packet.getElemTo()))) { log.finest("Processing disco query by: " + getComponentId()); Queue<Packet> results = new LinkedList<Packet>(); processDiscoQuery(packet, results); if (results.size() > 0) { for (Packet res: results) { // No more recurrential calls!! addOutPacketNB(res); } // end of for () } return; } String id = JIDUtils.getNodeID(packet.getTo()); comp = getLocalComponent(id); if (comp != null) { log.finest("Packet is processing by: " + comp.getComponentId()); Queue<Packet> results = new LinkedList<Packet>(); if (comp == this) { processPacketMR(packet, results); } else { comp.processPacket(packet, results); } if (results.size() > 0) { for (Packet res: results) { // No more recurrential calls!! addOutPacketNB(res); // processPacket(res); } // end of for () } return; } // Let's try to find message receiver quick way // In case if packet is handled internally: // String nick = JIDUtils.getNodeNick(packet.getTo()); String host = JIDUtils.getNodeHost(packet.getTo()); // MessageReceiver first = null; // Below code probably never get's executed anyway. // All components included in commented code below should // be picked up by code above. // if (nick != null) { // first = receivers.get(nick); // } // end of if (nick != null) // if (first != null && host.equals(getDefHostName())) { // log.finest("Found receiver: " + first.getName()); // first.addPacketNB(packet); // return; // } // end of if (mr != null) // This packet is not processed localy, so let's find receiver // which will send it to correct destination: ServerComponent[] comps = getComponentsForLocalDomain(host); if (comps == null) { comps = getServerComponentsForRegex(id); } if (comps == null && !isLocalDomain(host)) { comps = getComponentsForNonLocalDomain(host); } if (comps != null) { Queue<Packet> results = new LinkedList<Packet>(); for (ServerComponent serverComponent : comps) { log.finest("Packet processed by: " + serverComponent.getComponentId()); serverComponent.processPacket(packet, results); if (results.size() > 0) { for (Packet res : results) { // No more recurrential calls!! addOutPacketNB(res); // processPacket(res); } // end of for () } } } else { log.finest("There is no component for the packet, sending it back"); try { addOutPacketNB( Authorization.SERVICE_UNAVAILABLE.getResponseMessage(packet, "There is no service found to process your request.", true)); } catch (PacketErrorTypeException e) { // This packet is to local domain, we don't want to send it out // drop packet :-( log.warning("Can't process packet to local domain, dropping..." + packet.toString()); } } // MessageReceiver s2s = null; // for (MessageReceiver mr: receivers.values()) { // Set<String> routings = mr.getRoutings(); // if (routings != null) { // log.finest(mr.getName() + ": Looking for host: " + host + // " in " + routings.toString()); // if (routings.contains(host) || routings.contains(id)) { // log.finest("Found receiver: " + mr.getName()); // mr.addPacketNB(packet); // return; // } // end of if (routings.contains()) // // Resolve wildchars routings.... // if (mr.isInRegexRoutings(id)) { // log.finest("Found receiver: " + mr.getName()); // mr.addPacketNB(packet); // return; // if (routings.contains("*")) { // // I found s2s receiver, remember it for later.... // s2s = mr; // } // end of if (routings.contains()) // } // end of if (routings != null) // else { // log.severe("Routings are null for: " + mr.getName()); // } // end of if (routings != null) else // } // end of for (MessageReceiver mr: receivers.values()) // // It is not for any local host, so maybe it is for some // // remote server, let's try sending it through s2s service: // if (localAddresses.contains(host) || comp != null) { // try { // addOutPacketNB( // Authorization.FEATURE_NOT_IMPLEMENTED.getResponseMessage(packet, // "Your request can not be processed.", true)); // } catch (PacketErrorTypeException e) { // // This packet is to local domain, we don't want to send it out // // drop packet :-( // log.warning("Can't process packet to local domain, dropping..." // + packet.toString()); // return; // if (s2s != null) { // s2s.addPacketNB(packet); // } // end of if (s2s != null) } private ServerComponent[] getComponentsForLocalDomain(String domain) { return vHostManager.getComponentsForLocalDomain(domain); } private ServerComponent[] getComponentsForNonLocalDomain(String domain) { return vHostManager.getComponentsForNonLocalDomain(domain); } public void setConfig(ComponentRegistrator config) { components.put(getName(), this); this.config = config; addRegistrator(config); } public void addRegistrator(ComponentRegistrator registr) { log.info("Adding registrator: " + registr.getClass().getSimpleName()); registrators.put(registr.getName(), registr); addComponent(registr); for (ServerComponent comp : components.values()) { // if (comp != registr) { registr.addComponent(comp); // } // end of if (comp != registr) } // end of for (ServerComponent comp : components) } public void addRouter(MessageReceiver receiver) { log.info("Adding receiver: " + receiver.getClass().getSimpleName()); addComponent(receiver); receivers.put(receiver.getName(), receiver); } public void addComponent(ServerComponent component) { log.info("Adding component: " + component.getClass().getSimpleName()); for (ComponentRegistrator registr : registrators.values()) { if (registr != component) { log.finer("Adding: " + component.getName() + " component to " + registr.getName() + " registrator."); registr.addComponent(component); } // end of if (reg != component) } // end of for () components.put(component.getName(), component); components_byId.put(component.getComponentId(), component); if (component instanceof XMPPService) { xmppServices.put(component.getName(), (XMPPService)component); } } @Override public Map<String, Object> getDefaults(Map<String, Object> params) { Map<String, Object> defs = super.getDefaults(params); MessageRouterConfig.getDefaults(defs, params, getName()); return defs; } private boolean inProperties = false; @Override public void setProperties(Map<String, Object> props) { if (inProperties) { return; } else { inProperties = true; } // end of if (inProperties) else disco_name = (String)props.get(DISCO_NAME_PROP_KEY); disco_show_version = (Boolean)props.get(DISCO_SHOW_VERSION_PROP_KEY); serviceEntity = new ServiceEntity("Tigase", "server", "Session manager"); serviceEntity.addIdentities(new ServiceIdentity[] { new ServiceIdentity("server", "im", disco_name + (disco_show_version ? (" ver. " + tigase.server.XMPPServer.getImplementationVersion()) : ""))}); serviceEntity.addFeatures(XMPPService.DEF_FEATURES); try { super.setProperties(props); // String[] localAddresses = (String[])props.get(LOCAL_ADDRESSES_PROP_KEY); // this.localAddresses.clear(); // if (localAddresses != null && localAddresses.length > 0) { // Collections.addAll(this.localAddresses, localAddresses); // this.localAddresses.add(getDefHostName()); Map<String, ComponentRegistrator> tmp_reg = registrators; Map<String, MessageReceiver> tmp_rec = receivers; components = new TreeMap<String, ServerComponent>(); registrators = new TreeMap<String, ComponentRegistrator>(); receivers = new TreeMap<String, MessageReceiver>(); setConfig(config); MessageRouterConfig conf = new MessageRouterConfig(props); String[] reg_names = conf.getRegistrNames(); for (String name: reg_names) { ComponentRegistrator cr = tmp_reg.remove(name); String cls_name = (String)props.get(REGISTRATOR_PROP_KEY + name + ".class"); try { if (cr == null || !cr.getClass().getName().equals(cls_name)) { if (cr != null) { cr.release(); } cr = conf.getRegistrInstance(name); cr.setName(name); } // end of if (cr == null) addRegistrator(cr); } // end of try catch (Exception e) { e.printStackTrace(); } // end of try-catch } // end of for (String name: reg_names) for (ComponentRegistrator cr: tmp_reg.values()) { cr.release(); } // end of for () tmp_reg.clear(); String[] msgrcv_names = conf.getMsgRcvNames(); for (String name: msgrcv_names) { log.finer("Loading and registering message receiver: " + name); ServerComponent mr = tmp_rec.remove(name); String cls_name = (String)props.get(MSG_RECEIVERS_PROP_KEY + name + ".class"); try { if (mr == null || !mr.getClass().getName().equals(cls_name)) { if (mr != null) { mr.release(); } mr = conf.getMsgRcvInstance(name); mr.setName(name); if (mr instanceof MessageReceiver) { ((MessageReceiver)mr).setParent(this); ((MessageReceiver)mr).start(); } } // end of if (cr == null) if (mr instanceof MessageReceiver) { addRouter((MessageReceiver)mr); } else { addComponent(mr); } } // end of try catch (Exception e) { e.printStackTrace(); } // end of try-catch } // end of for (String name: reg_names) for (MessageReceiver mr: tmp_rec.values()) { mr.release(); } // end of for () tmp_rec.clear(); if ((Boolean)props.get(UPDATES_CHECKING_PROP_KEY)) { installUpdatesChecker((Long)props.get(UPDATES_CHECKING_INTERVAL_PROP_KEY)); } else { stopUpdatesChecker(); } } finally { inProperties = false; } // end of try-finally for (ServerComponent comp : components.values()) { log.info("Initialization completed notification to: " + comp.getName()); comp.initializationCompleted(); } // log.info("Initialization completed notification to: " + config.getName()); // config.initializationCompleted(); } private void stopUpdatesChecker() { if (updates_checker != null) { updates_checker.interrupt(); updates_checker = null; } } private void installUpdatesChecker(long interval) { stopUpdatesChecker(); updates_checker = new UpdatesChecker(interval, this, "This is automated message generated by updates checking module.\n" + " You can disable this function changing configuration option: " + "'/" + getName() + "/" + UPDATES_CHECKING_PROP_KEY + "' or adjust" + " updates checking interval time changing option: " + "'/" + getName() + "/" + UPDATES_CHECKING_INTERVAL_PROP_KEY + "' which" + " now set to " + interval + " days."); updates_checker.start(); } private void processDiscoQuery(final Packet packet, final Queue<Packet> results) { String jid = packet.getElemTo(); String nick = JIDUtils.getNodeNick(jid); String node = packet.getAttribute("/iq/query", "node"); Element query = packet.getElement().getChild("query").clone(); if (packet.isXMLNS("/iq/query", INFO_XMLNS)) { if (isLocalDomain(jid) && node == null) { query = getDiscoInfo(node, jid); for (XMPPService comp: xmppServices.values()) { List<Element> features = comp.getDiscoFeatures(); if (features != null) { query.addChildren(features); } } // end of for () } else { for (XMPPService comp: xmppServices.values()) { // if (jid.startsWith(comp.getName() + ".")) { Element resp = comp.getDiscoInfo(node, jid); if (resp != null) { query = resp; break; } } // end of for () } } if (packet.isXMLNS("/iq/query", ITEMS_XMLNS)) { boolean localDomain = isLocalDomain(jid); if (localDomain) { for (XMPPService comp: xmppServices.values()) { // if (localDomain || (nick != null && comp.getName().equals(nick))) { List<Element> items = comp.getDiscoItems(node, jid); log.finest("DiscoItems processed by: " + comp.getComponentId() + ", items: " + (items == null ? null : items.toString())); if (items != null && items.size() > 0) { query.addChildren(items); } } // end of for () } else { ServerComponent comp = getLocalComponent(packet.getElemTo()); if (comp != null && comp instanceof XMPPService) { List<Element> items = ((XMPPService)comp).getDiscoItems(node, jid); log.finest("DiscoItems processed by: " + comp.getComponentId() + ", items: " + (items == null ? null : items.toString())); if (items != null && items.size() > 0) { query.addChildren(items); } } } } results.offer(packet.okResult(query, 0)); } public Element getDiscoInfo(String node, String jid) { Element query = serviceEntity.getDiscoInfo(null); log.finest("Returing disco-info: " + query.toString()); return query; } public List<Element> getDiscoItems(String node, String jid) { return null; } @Override public List<StatRecord> getStatistics() { List<StatRecord> stats = super.getStatistics(); long uptime = ManagementFactory.getRuntimeMXBean().getUptime(); long days = uptime / (24 * HOUR); long hours = (uptime - (days * 24 * HOUR)) / HOUR; long minutes = (uptime - (days * 24 * HOUR + hours * HOUR)) / MINUTE; long seconds = (uptime - (days * 24 * HOUR + hours * HOUR + minutes * MINUTE)) / SECOND; // StringBuilder sb = new StringBuilder(); stats.add(new StatRecord(getName(), "Uptime", "time", "" + (days > 0 ? days + " day, " : "") + (hours > 0 ? hours + " hour, " : "") + (minutes > 0 ? minutes + " min, " : "") + (seconds > 0 ? seconds + " sec" : "") , Level.INFO)); // Runtime runtime = Runtime.getRuntime(); // Run GC for more accurate memory readings //runtime.gc(); // long maxMem = runtime.maxMemory(); // long totalMem = runtime.totalMemory(); // long freeMem = runtime.freeMemory(); // stats.add(new StatRecord(getName(), "Max JVM mem", "long", maxMem, // Level.FINEST)); // stats.add(new StatRecord(getName(), "Total JVM mem", "long", totalMem, // Level.FINEST)); // stats.add(new StatRecord(getName(), "Free JVM mem", "long", freeMem, // Level.FINEST)); OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); NumberFormat format = NumberFormat.getNumberInstance(); format.setMaximumFractionDigits(4); stats.add(new StatRecord(getName(), "Load average", "double", format.format(osBean.getSystemLoadAverage()), Level.INFO)); stats.add(new StatRecord(getName(), "CPUs no", "int", osBean.getAvailableProcessors(), Level.FINEST)); ThreadMXBean thBean = ManagementFactory.getThreadMXBean(); stats.add(new StatRecord(getName(), "Threads count", "int", thBean.getThreadCount(), Level.FINEST)); long cpuTime = 0; for (long thid : thBean.getAllThreadIds()) { cpuTime += thBean.getThreadCpuTime(thid); } // stats.add(new StatRecord(getName(), "Threads CPU time", "long", cpuTime, // Level.FINEST)); double cpuUsage = (new Long(cpuTime).doubleValue() / 1000000) / new Long( uptime).doubleValue(); format = NumberFormat.getPercentInstance(); format.setMaximumFractionDigits(2); stats.add(new StatRecord(getName(), "CPU usage", "double", format.format(cpuUsage), Level.INFO)); MemoryUsage heap = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage(); MemoryUsage nonHeap = ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage(); format = NumberFormat.getIntegerInstance(); if (format instanceof DecimalFormat) { DecimalFormat decf = (DecimalFormat)format; decf.applyPattern(decf.toPattern()+" KB"); } stats.add(new StatRecord(getName(), "Max Heap mem", "long", format.format(heap.getMax()/1024), Level.INFO)); stats.add(new StatRecord(getName(), "Used Heap", "long", format.format(heap.getUsed()/1024), Level.INFO)); stats.add(new StatRecord(getName(), "Free Heap", "long", format.format((heap.getMax() - heap.getUsed())/1024), Level.INFO)); stats.add(new StatRecord(getName(), "Max NonHeap mem", "long", format.format(nonHeap.getMax()/1024), Level.INFO)); stats.add(new StatRecord(getName(), "Used NonHeap", "long", format.format(nonHeap.getUsed()/1024), Level.INFO)); stats.add(new StatRecord(getName(), "Free NonHeap", "long", format.format((nonHeap.getMax() - nonHeap.getUsed())/1024), Level.INFO)); return stats; } }
package uk.bl.wa.blindex; import java.io.IOException; import java.net.URI; import java.net.URL; import java.util.Arrays; import java.util.Iterator; import java.util.List; import org.apache.hadoop.filecache.DistributedCache; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.FileInputFormat; import org.apache.hadoop.mapred.FileOutputFormat; import org.apache.hadoop.mapred.JobClient; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.MapReduceBase; import org.apache.hadoop.mapred.Mapper; import org.apache.hadoop.mapred.OutputCollector; import org.apache.hadoop.mapred.Reducer; import org.apache.hadoop.mapred.Reporter; import org.apache.hadoop.mapred.TextInputFormat; import org.apache.hadoop.mapred.TextOutputFormat; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.hadoop.Solate; import org.apache.solr.hadoop.SolrInputDocumentWritable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import au.com.bytecode.opencsv.CSVParser; /** * * @author Andrew Jackson <Andrew.Jackson@bl.uk> * */ public class IndexerJob { private static final Logger LOG = LoggerFactory.getLogger(IndexerJob.class); protected static String solrHomeZipName = "solr_home.zip"; /** * * This mapper parses the input table, downloads the relevant XML, parses * the content into Solr documents, computes the target SolrCloud slice and * passes them down to the reducer. * * @author Andrew Jackson <Andrew.Jackson@bl.uk> * */ public static class Map extends MapReduceBase implements Mapper<LongWritable, Text, IntWritable, SolrInputDocumentWritable> { private CSVParser p = new CSVParser(); private Solate sp; private String domidUrlPrefix; /* * (non-Javadoc) * * @see * org.apache.hadoop.mapred.MapReduceBase#configure(org.apache.hadoop * .mapred.JobConf) */ @Override public void configure(JobConf job) { super.configure(job); String zkHost = "openstack2.ad.bl.uk:2181,openstack4.ad.bl.uk:2181,openstack5.ad.bl.uk:2181/solr"; String collection = "jisc2"; int numShards = 4; sp = new Solate(zkHost, collection, numShards); domidUrlPrefix = "http://194.66.239.142/did/"; } public void map(LongWritable key, Text value, OutputCollector<IntWritable, SolrInputDocumentWritable> output, Reporter reporter) throws IOException { // String[] parts = value.toString().split("\\x01"); String[] parts = p.parseLine(value.toString()); // If this is the header line, return now: if ("entityid".equals(parts[0])) return; // Otherwise, grab the content info: // "entityid","entityuid","parentid","simpletitle","contentstreamid","originalname","sizebytes","recordcreated_dt","domid" String entityuid = parts[1]; String simpletitle = parts[3]; String originalname = parts[5]; String recordcreated_dt = parts[7].replaceFirst(" ", "T") + "Z"; String domid = parts[8]; // Split up originalname to get parts String[] on_parts = originalname.replace(".xml", "").split("-"); String npid = on_parts[0]; String year = on_parts[1]; String month = on_parts[2]; String day = on_parts[3]; String pubdate = year + "-" + month + "-" + day + "T00:00:00Z"; // Construct URL: URL xmlUrl = new URL(domidUrlPrefix + domid); // Pass to the SAX-based parser to collect the outputs: List<String> docs = null; try { docs = JISC2TextExtractor.extract(xmlUrl.openStream()); } catch (Exception e) { e.printStackTrace(); return; } for (int i = 0; i < docs.size(); i++) { // Skip empty records: if (docs.get(i).length() == 0) continue; // Page number: int page = i + 1; // Build up a Solr document: String doc_id = entityuid + "/p" + page; SolrInputDocument doc = new SolrInputDocument(); doc.setField("id", doc_id); doc.setField("simpletitle_s", simpletitle); doc.setField("npid_s", npid); doc.setField("originalname_s", originalname); doc.setField("domid_l", domid); doc.setField("page_i", page); doc.setField("pubdate_dt", pubdate); doc.setField("digidate_dt", recordcreated_dt); doc.setField("year_s", year); doc.setField("content", docs.get(i)); output.collect(new IntWritable(sp.getPartition(doc_id, doc)), new SolrInputDocumentWritable(doc)); } } } /** * * This reducer collects the documents for each slice together and commits * them to an embedded instance of the Solr server stored on HDFS * * @author Andrew Jackson <Andrew.Jackson@bl.uk> * */ public static class Reduce extends MapReduceBase implements Reducer<IntWritable, SolrInputDocumentWritable, Text, IntWritable> { private FileSystem fs; private Path solrHomeDir = null; private Path outputDir; private String shardPrefix = "shard"; /* * (non-Javadoc) * * @see * org.apache.hadoop.mapred.MapReduceBase#configure(org.apache.hadoop * .mapred.JobConf) */ @Override public void configure(JobConf job) { LOG.info("Calling configure()..."); super.configure(job); try { // Filesystem: fs = FileSystem.get(job); // Input: solrHomeDir = findSolrConfig(job, solrHomeZipName); LOG.info("Found solrHomeDir " + solrHomeDir); } catch (IOException e) { e.printStackTrace(); LOG.error("FAILED in reducer configuration: " + e); } // Output: outputDir = new Path("/user/admin/jisc2/solr/"); } public void reduce(IntWritable key, Iterator<SolrInputDocumentWritable> values, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException { int slice = key.get(); Path outputShardDir = new Path(outputDir, this.shardPrefix + slice); LOG.info("Running reducer for " + slice + " > " + outputShardDir); EmbeddedSolrServer solrServer = JISC2TextExtractor .createEmbeddedSolrServer(solrHomeDir, fs, outputDir, outputShardDir); while (values.hasNext()) { SolrInputDocument doc = values.next().getSolrInputDocument(); try { solrServer.add(doc); output.collect(new Text("" + key), new IntWritable(1)); } catch (Exception e) { LOG.error("ERROR " + e + " when adding document " + doc.getFieldValue("id")); output.collect(new Text("ERROR " + key), new IntWritable(1)); } } try { solrServer.commit(); solrServer.shutdown(); } catch (SolrServerException e) { LOG.error("ERROR on commit: " + e); } } } public static Path findSolrConfig(JobConf conf, String zipName) throws IOException { Path solrHome = null; Path[] localArchives = DistributedCache.getLocalCacheArchives(conf); if (localArchives.length == 0) { LOG.error("No local cache archives."); throw new IOException(String.format("No local cache archives.")); } for (Path unpackedDir : localArchives) { LOG.info("Looking at: " + unpackedDir + " for " + zipName); if (unpackedDir.getName().equals(zipName)) { LOG.info("Using this unpacked directory as solr home: {}", unpackedDir); solrHome = unpackedDir; break; } } return solrHome; } /** * c.f. SolrRecordWriter, SolrOutputFormat * * Cloudera Search defaults to: /solr/jisc2/core_node1 ...but note no * replicas, which is why the shard-to-core mapping looks easy. * * Take /user/admin/jisc2-xmls/000000_0 Read line-by-line Split on 0x01. * * * @param args * @throws Exception */ public static void main(String[] args) throws Exception { JobConf conf = new JobConf(IndexerJob.Map.class); conf.setJobName("JISC2_Indexer"); conf.setMapOutputKeyClass(IntWritable.class); conf.setMapOutputValueClass(SolrInputDocumentWritable.class); conf.setMapperClass(Map.class); conf.setNumMapTasks(4); conf.setReducerClass(Reduce.class); conf.setNumReduceTasks(4); conf.setInputFormat(TextInputFormat.class); conf.setOutputFormat(TextOutputFormat.class); // Get input and output folder from CLARGS: FileInputFormat.setInputPaths(conf, new Path(args[1])); FileOutputFormat.setOutputPath(conf, new Path(args[2])); conf.setSpeculativeExecution(false); // File solrHomeZip = new // File("src/main/resources/jisc2/solr_home.zip"); Path zipPath = new Path("/user/admin/jisc2-xmls/solr_home.zip"); FileSystem fs = FileSystem.get(conf); // fs.copyFromLocalFile(new Path(solrHomeZip.toString()), zipPath); final URI baseZipUrl = fs.getUri().resolve( zipPath.toString() + '#' + solrHomeZipName); DistributedCache.addCacheArchive(baseZipUrl, conf); LOG.debug("Set Solr distributed cache: {}", Arrays.asList(DistributedCache.getCacheArchives(conf))); LOG.debug("Set zipPath: {}", zipPath); JobClient.runJob(conf); } }
package soot.jimple.toolkits.annotation.nullcheck; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import soot.Local; import soot.RefLikeType; import soot.Unit; import soot.Value; import soot.jimple.ArrayRef; import soot.jimple.ClassConstant; import soot.jimple.DefinitionStmt; import soot.jimple.FieldRef; import soot.jimple.InstanceFieldRef; import soot.jimple.InstanceInvokeExpr; import soot.jimple.InvokeExpr; import soot.jimple.MonitorStmt; import soot.jimple.NewArrayExpr; import soot.jimple.NewExpr; import soot.jimple.NewMultiArrayExpr; import soot.jimple.NullConstant; import soot.jimple.ParameterRef; import soot.jimple.Stmt; import soot.jimple.StringConstant; import soot.jimple.ThisRef; import soot.jimple.internal.AbstractBinopExpr; import soot.jimple.internal.JCastExpr; import soot.jimple.internal.JEqExpr; import soot.jimple.internal.JIfStmt; import soot.jimple.internal.JInstanceOfExpr; import soot.jimple.internal.JNeExpr; import soot.toolkits.graph.UnitGraph; import soot.toolkits.scalar.ForwardBranchedFlowAnalysis; /** * An intraprocedural nullness analysis that computes for each location and each value * in a method if the value is (before or after that location) definetely null, * definetely non-null or neither. * This class replaces {@link BranchedRefVarsAnalysis} which is known to have bugs. * * @author Eric Bodden */ public class NullnessAnalysis extends ForwardBranchedFlowAnalysis { protected final static Object BOTTOM = new Object() { public String toString() {return "bottom";} }; protected final static Object NULL = new Object() { public String toString() {return "null";} }; protected final static Object NON_NULL = new Object() { public String toString() {return "non-null";} }; protected final static Object TOP = new Object() { public String toString() {return "top";} }; /** * Creates a new analysis for the given graph/ * @param graph any unit graph */ public NullnessAnalysis(UnitGraph graph) { super(graph); doAnalysis(); } /** * {@inheritDoc} */ protected void flowThrough(Object flowin, Unit u, List fallOut, List branchOuts) { AnalysisInfo in = (AnalysisInfo) flowin; AnalysisInfo out = new AnalysisInfo(in); AnalysisInfo outBranch = new AnalysisInfo(in); Stmt s = (Stmt)u; //in case of an if statement, we neet to compute the branch-flow; //e.g. for a statement "if(x!=null) goto s" we have x==null for the fallOut and //x!=null for the branchOut //or for an instanceof expression if(s instanceof JIfStmt) { JIfStmt ifStmt = (JIfStmt) s; handleIfStmt(ifStmt, in, out, outBranch); } //in case of a monitor statement, we know that if it succeeds, we have a non-null value else if(s instanceof MonitorStmt) { MonitorStmt monitorStmt = (MonitorStmt) s; out.put(monitorStmt.getOp(), NON_NULL); } //if we have an array ref, set the info for this ref to TOP, //cause we need to be conservative here if(s.containsArrayRef()) { ArrayRef arrayRef = s.getArrayRef(); handleArrayRef(arrayRef,out); } //same for field refs, but also set the receiver object to non-null, if there is one if(s.containsFieldRef()) { FieldRef fieldRef = s.getFieldRef(); handleFieldRef(fieldRef, out); } //same for invoke expr., also set the receiver object to non-null, if there is one if(s.containsInvokeExpr()) { InvokeExpr invokeExpr = s.getInvokeExpr(); handleInvokeExpr(invokeExpr, out); } //allow sublasses to define certain values as always-non-null for (Iterator outIter = out.entrySet().iterator(); outIter.hasNext();) { Entry entry = (Entry) outIter.next(); Value v = (Value) entry.getKey(); if(isAlwaysNonNull(v)) { entry.setValue(NON_NULL); } } //if we have a definition (assignment) statement to a ref-like type, handle it, //i.e. assign it the info of the rhs, except the following special cases: // x=null, assign NULL // x=@this or x= new... assign NON_NULL // x=@param_i, assign TOP if(s instanceof DefinitionStmt) { //need to copy the current out set because we need to assign under this assumption; //so this copy becomes the in-set to handleRefTypeAssignment AnalysisInfo temp = new AnalysisInfo(out); DefinitionStmt defStmt = (DefinitionStmt) s; if(defStmt.getLeftOp().getType() instanceof RefLikeType) { handleRefTypeAssignment(defStmt, temp, out); } } //safe memory by only retaining information about locals for (Iterator outIter = out.keySet().iterator(); outIter.hasNext();) { Value v = (Value) outIter.next(); if(!(v instanceof Local)) { outIter.remove(); } } for (Iterator outBranchIter = outBranch.keySet().iterator(); outBranchIter.hasNext();) { Value v = (Value) outBranchIter.next(); if(!(v instanceof Local)) { outBranchIter.remove(); } } // now copy the computed info to all successors for( Iterator it = fallOut.iterator(); it.hasNext(); ) { copy( out, it.next() ); } for( Iterator it = branchOuts.iterator(); it.hasNext(); ) { copy( outBranch, it.next() ); } } /** * This can be overwritten by sublasses to mark a certain value * as constantly non-null. * @param v any value * @return true if it is known that this value (e.g. a method * return value) is never null */ protected boolean isAlwaysNonNull(Value v) { return false; } private void handleIfStmt(JIfStmt ifStmt, AnalysisInfo in, AnalysisInfo out, AnalysisInfo outBranch) { Value condition = ifStmt.getCondition(); if(condition instanceof JInstanceOfExpr) { //a instanceof X ; if this succeeds, a is not null JInstanceOfExpr expr = (JInstanceOfExpr) condition; handleInstanceOfExpression(expr, in, out, outBranch); } else if(condition instanceof JEqExpr || condition instanceof JNeExpr) { //a==b or a!=b AbstractBinopExpr eqExpr = (AbstractBinopExpr) condition; handleEqualityOrNonEqualityCheck(eqExpr, in, out, outBranch); } } private void handleEqualityOrNonEqualityCheck(AbstractBinopExpr eqExpr, AnalysisInfo in, AnalysisInfo out, AnalysisInfo outBranch) { Value left = eqExpr.getOp1(); Value right = eqExpr.getOp2(); Value val=null; if(left==NullConstant.v()) { if(right!=NullConstant.v()) { val = right; } } else if(right==NullConstant.v()) { if(left!=NullConstant.v()) { val = left; } } //if we compare a local with null then process further... if(val!=null && val instanceof Local) { if(eqExpr instanceof JEqExpr) //a==null handleEquality(val, out, outBranch); else if(eqExpr instanceof JNeExpr) //a!=null handleNonEquality(val, out, outBranch); else throw new IllegalStateException("unexpected condition: "+eqExpr.getClass()); } } private void handleNonEquality(Value val, AnalysisInfo out, AnalysisInfo outBranch) { out.put(val, NULL); outBranch.put(val, NON_NULL); } private void handleEquality(Value val, AnalysisInfo out, AnalysisInfo outBranch) { out.put(val, NON_NULL); outBranch.put(val, NULL); } private void handleInstanceOfExpression(JInstanceOfExpr expr, AnalysisInfo in, AnalysisInfo out, AnalysisInfo outBranch) { Value op = expr.getOp(); //if instanceof succeeds, we have a non-null value outBranch.put(op,NON_NULL); } private void handleArrayRef(ArrayRef arrayRef, AnalysisInfo out) { Value array = arrayRef.getBase(); //here we know that the array must point to an object, but the array value might be anything out.put(array, NON_NULL); out.put(arrayRef, TOP); } private void handleFieldRef(FieldRef fieldRef, AnalysisInfo out) { if(fieldRef instanceof InstanceFieldRef) { InstanceFieldRef instanceFieldRef = (InstanceFieldRef) fieldRef; //here we know that the receiver must point to an object Value base = instanceFieldRef.getBase(); out.put(base,NON_NULL); } //but the referenced object might point to everything out.put(fieldRef, TOP); } private void handleInvokeExpr(InvokeExpr invokeExpr,AnalysisInfo out) { if(invokeExpr instanceof InstanceInvokeExpr) { InstanceInvokeExpr instanceInvokeExpr = (InstanceInvokeExpr) invokeExpr; //here we know that the receiver must point to an object Value base = instanceInvokeExpr.getBase(); out.put(base,NON_NULL); } //but the returned object might point to everything out.put(invokeExpr, TOP); } private void handleRefTypeAssignment(DefinitionStmt assignStmt, AnalysisInfo rhsInfo, AnalysisInfo out) { Value left = assignStmt.getLeftOp(); Value right = assignStmt.getRightOp(); //unbox casted value if(right instanceof JCastExpr) { JCastExpr castExpr = (JCastExpr) right; right = castExpr.getOp(); } if(right instanceof NewExpr || right instanceof NewArrayExpr || right instanceof NewMultiArrayExpr || right instanceof ThisRef || right instanceof StringConstant || right instanceof ClassConstant) { //if we assign new... or @this, the result is non-null rhsInfo.put(right,NON_NULL); } else if(right instanceof ParameterRef) { //if we assign a parameter, we don't know anything rhsInfo.put(right,TOP); } else if(right==NullConstant.v()) { //if we assign null, well, it's null rhsInfo.put(right, NULL); } //assign from rhs to lhs out.put(left,rhsInfo.get(right)); } /** * {@inheritDoc} */ protected void copy(Object source, Object dest) { Map s = (Map) source; Map d = (Map) dest; d.clear(); d.putAll(s); } /** * {@inheritDoc} */ protected Object entryInitialFlow() { return new AnalysisInfo(); } /** * {@inheritDoc} */ protected void merge(Object in1, Object in2, Object out) { AnalysisInfo left = (AnalysisInfo) in1; AnalysisInfo right = (AnalysisInfo) in2; AnalysisInfo res = (AnalysisInfo) out; Set values = new HashSet(); values.addAll(left.keySet()); values.addAll(right.keySet()); res.clear(); for (Iterator keyIter = values.iterator(); keyIter.hasNext();) { Value v = (Value) keyIter.next(); Set leftAndRight = new HashSet(); leftAndRight.add(left.get(v)); leftAndRight.add(right.get(v)); Object result; //TOP stays TOP if(leftAndRight.contains(TOP)) { result = TOP; } else if(leftAndRight.contains(NON_NULL)) { if(leftAndRight.contains(NULL)) { //NULL and NON_NULL merges to TOP result = TOP; } else { //NON_NULL and NON_NULL stays NON_NULL result = NON_NULL; } } else if(leftAndRight.contains(NULL)) { //NULL and NULL stays NULL result = NULL; } else { //only BOTTOM remains result = BOTTOM; } res.put(v, result); } } /** * {@inheritDoc} */ protected Object newInitialFlow() { return new AnalysisInfo(); } public boolean isAlwaysNullBefore(Unit s, Value v) { AnalysisInfo ai = (AnalysisInfo) getFlowBefore(s); return ai.get(v)==NULL; } public boolean isAlwaysNonNullBefore(Unit s, Value v) { AnalysisInfo ai = (AnalysisInfo) getFlowBefore(s); return ai.get(v)==NON_NULL; } /** * The analysis info is a simple mapping of type {@link Value} to * any of the constants BOTTOM, NON_NULL, NULL or TOP. * This class returns BOTTOM by default. * * @author Eric Bodden */ protected static class AnalysisInfo extends HashMap { public AnalysisInfo() { super(); } public AnalysisInfo(Map m) { super(m); } public Object get(Object key) { Object object = super.get(key); if(object==null) { return BOTTOM; } return object; } } }
package com.coxautodev.graphql.tools; import graphql.GraphQL; import graphql.execution.AsyncExecutionStrategy; import graphql.relay.Connection; import graphql.relay.SimpleListConnection; import graphql.schema.*; import graphql.schema.idl.SchemaDirectiveWiring; import graphql.schema.idl.SchemaDirectiveWiringEnvironment; import groovy.lang.Closure; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; public class RelayConnectionTest { private static final Logger log = LoggerFactory.getLogger(RelayConnectionTest.class); @Test public void compiles() { GraphQLSchema schema = SchemaParser.newParser().file("RelayConnection.graphqls") .resolvers(new QueryResolver()) .dictionary(User.class) .directive("connection", new ConnectionDirective()) .build() .makeExecutableSchema(); GraphQL gql = GraphQL.newGraphQL(schema) .queryExecutionStrategy(new AsyncExecutionStrategy()) .build(); Map<String,Object> variables = new HashMap<>(); variables.put("limit", 10); Utils.assertNoGraphQlErrors(gql, variables, new Closure<String>(null) { @Override public String call() { return "query {\n" + " users {\n" + " edges {\n" + " node {\n" + " id\n" + " name\n" + " }\n" + " }\n" + " }\n" + "}"; } }); } static class QueryResolver implements GraphQLQueryResolver { // fixme #114: desired return type to use: Connection<User> public Connection<User> users(int first, String after, DataFetchingEnvironment env) { return new SimpleListConnection<>(Collections.singletonList(new User(1L, "Luke"))).get(env); } } static class User { Long id; String name; public User(Long id, String name) { this.id = id; this.name = name; } } static class ConnectionDirective implements SchemaDirectiveWiring { @Override public GraphQLFieldDefinition onField(SchemaDirectiveWiringEnvironment<GraphQLFieldDefinition> environment) { GraphQLFieldDefinition field = environment.getElement(); log.info("Transforming field"); return field; } } }
package com.facebook.litho; import android.content.Context; import android.graphics.Color; import android.graphics.Rect; import android.os.Build; import android.util.SparseArray; import android.view.accessibility.AccessibilityManager; import com.facebook.litho.testing.testrunner.ComponentsTestRunner; import com.facebook.litho.widget.Text; import com.facebook.litho.testing.TestComponent; import com.facebook.litho.testing.TestDrawableComponent; import com.facebook.litho.testing.TestLayoutComponent; import com.facebook.litho.testing.TestNullLayoutComponent; import com.facebook.litho.testing.TestSizeDependentComponent; import com.facebook.litho.testing.TestViewComponent; import com.facebook.yoga.YogaAlign; import com.facebook.yoga.YogaEdge; import com.facebook.yoga.YogaFlexDirection; import com.facebook.yoga.YogaJustify; import com.facebook.yoga.YogaPositionType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import org.powermock.reflect.Whitebox; import org.robolectric.RuntimeEnvironment; import org.robolectric.Shadows; import org.robolectric.shadows.ShadowAccessibilityManager; import static android.content.Context.ACCESSIBILITY_SERVICE; import static android.support.v4.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO; import static android.support.v4.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO; import static android.support.v4.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS; import static android.support.v4.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES; import static com.facebook.litho.NodeInfo.FOCUS_SET_TRUE; import static com.facebook.yoga.YogaEdge.BOTTOM; import static com.facebook.yoga.YogaEdge.LEFT; import static com.facebook.yoga.YogaEdge.RIGHT; import static com.facebook.yoga.YogaEdge.TOP; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @PrepareForTest(Component.class) @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "android.*"}) @RunWith(ComponentsTestRunner.class) public class LayoutStateCalculateTest { @Rule public PowerMockRule mPowerMockRule = new PowerMockRule(); @Before public void setup() throws Exception { } @Test public void testNoUnnecessaryLayoutOutputsForLayoutSpecs() { final Component component = new InlineLayoutSpec() { @Override protected ComponentLayout onCreateLayout(ComponentContext c) { return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c))) .build(); } }; LayoutState layoutState = calculateLayoutState( RuntimeEnvironment.application, component, -1, SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY), SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY)); assertEquals(2, layoutState.getMountableOutputCount()); } @Test public void testLayoutOutputsForRootInteractiveLayoutSpecs() { final Component component = new InlineLayoutSpec() { @Override protected ComponentLayout onCreateLayout(ComponentContext c) { return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .wrapInView() .build(); } }; LayoutState layoutState = calculateLayoutState( RuntimeEnvironment.application, component, -1, SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY), SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY)); assertEquals(2, layoutState.getMountableOutputCount()); } @Test public void testLayoutOutputsForSpecsWithClickHandling() { final Component component = new InlineLayoutSpec() { @Override protected ComponentLayout onCreateLayout(ComponentContext c) { return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .clickHandler(c.newEventHandler(1))) .build(); } }; LayoutState layoutState = calculateLayoutState( RuntimeEnvironment.application, component, -1, SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY), SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY)); assertEquals(3, layoutState.getMountableOutputCount()); final NodeInfo nodeInfo = layoutState.getMountableOutputAt(1).getNodeInfo(); assertNotNull(nodeInfo); assertNotNull(nodeInfo.getClickHandler()); assertNull(nodeInfo.getLongClickHandler()); assertNull(nodeInfo.getTouchHandler()); } @Test public void testLayoutOutputsForSpecsWithLongClickHandling() { final Component component = new InlineLayoutSpec() { @Override protected ComponentLayout onCreateLayout(ComponentContext c) { return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .longClickHandler(c.newEventHandler(1))) .build(); } }; LayoutState layoutState = calculateLayoutState( RuntimeEnvironment.application, component, -1, SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY), SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY)); assertEquals(3, layoutState.getMountableOutputCount()); final NodeInfo nodeInfo = layoutState.getMountableOutputAt(1).getNodeInfo(); assertNotNull(nodeInfo); assertNull(nodeInfo.getClickHandler()); assertNotNull(nodeInfo.getLongClickHandler()); assertNull(nodeInfo.getTouchHandler()); } @Test public void testLayoutOutputsForSpecsWithTouchHandling() { final Component component = new InlineLayoutSpec() { @Override protected ComponentLayout onCreateLayout(ComponentContext c) { return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .touchHandler(c.newEventHandler(1))) .build(); } }; LayoutState layoutState = calculateLayoutState( RuntimeEnvironment.application, component, -1, SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY), SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY)); assertEquals(3, layoutState.getMountableOutputCount()); final NodeInfo nodeInfo = layoutState.getMountableOutputAt(1).getNodeInfo(); assertNotNull(nodeInfo); assertNotNull(nodeInfo.getTouchHandler()); assertNull(nodeInfo.getClickHandler()); assertNull(nodeInfo.getLongClickHandler()); } @Test public void testLayoutOutputsForDeepLayoutSpecs() { final int paddingSize = 5; final Component component = new InlineLayoutSpec() { @Override protected ComponentLayout onCreateLayout(ComponentContext c) { return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .backgroundColor(0xFFFF0000) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .flexDirection(YogaFlexDirection.ROW) .justifyContent(YogaJustify.SPACE_AROUND) .alignItems(YogaAlign.CENTER) .positionType(YogaPositionType.ABSOLUTE) .positionPx(LEFT, 50) .positionPx(TOP, 50) .positionPx(RIGHT, 200) .positionPx(BOTTOM, 50) .child( Text.create(c) .text("textLeft1")) .child( Text.create(c) .text("textRight1")) .paddingPx(YogaEdge.ALL, paddingSize) .wrapInView()) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .flexDirection(YogaFlexDirection.ROW) .justifyContent(YogaJustify.SPACE_AROUND) .alignItems(YogaAlign.CENTER) .positionType(YogaPositionType.ABSOLUTE) .positionPx(LEFT, 200) .positionPx(TOP, 50) .positionPx(RIGHT, 50) .positionPx(BOTTOM, 50) .child( Text.create(c) .text("textLeft2") .withLayout().flexShrink(0) .wrapInView() .paddingPx(YogaEdge.ALL, paddingSize)) .child( TestViewComponent.create(c) .withLayout().flexShrink(0) .wrapInView())) .build(); } }; LayoutState layoutState = calculateLayoutState( RuntimeEnvironment.application, component, -1, SizeSpec.makeSizeSpec(350, SizeSpec.EXACTLY), SizeSpec.makeSizeSpec(200, SizeSpec.EXACTLY)); // Check total layout outputs. assertEquals(8, layoutState.getMountableOutputCount()); // Check quantity of HostComponents. int totalHosts = 0; for (int i = 0; i < layoutState.getMountableOutputCount(); i++) { ComponentLifecycle lifecycle = getComponentAt(layoutState, i); if (isHostComponent(lifecycle)) { totalHosts++; } } assertEquals(3, totalHosts); //Check all the Layouts are in the correct position. assertTrue(isHostComponent(getComponentAt(layoutState, 0))); assertTrue(getComponentAt(layoutState, 1) instanceof DrawableComponent); assertTrue(isHostComponent(getComponentAt(layoutState, 2))); assertTrue(getComponentAt(layoutState, 3) instanceof Text); assertTrue(getComponentAt(layoutState, 4) instanceof Text); assertTrue(isHostComponent(getComponentAt(layoutState, 5))); assertTrue(getComponentAt(layoutState, 6) instanceof Text); assertTrue(getComponentAt(layoutState, 7) instanceof TestViewComponent); // Check the text within the TextComponents. assertEquals("textLeft1", getTextFromTextComponent(layoutState, 3)); assertEquals("textRight1", getTextFromTextComponent(layoutState, 4)); assertEquals("textLeft2", getTextFromTextComponent(layoutState, 6)); Rect textLayoutBounds = layoutState.getMountableOutputAt(6).getBounds(); Rect textBackgroundBounds = layoutState.getMountableOutputAt(5).getBounds(); assertEquals(textBackgroundBounds.left , textLayoutBounds.left - paddingSize); assertEquals(textBackgroundBounds.top , textLayoutBounds.top - paddingSize); assertEquals(textBackgroundBounds.right , textLayoutBounds.right + paddingSize); assertEquals(textBackgroundBounds.bottom , textLayoutBounds.bottom + paddingSize); } @Test public void testLayoutOutputMountBounds() { final Component component = new InlineLayoutSpec() { @Override protected ComponentLayout onCreateLayout(ComponentContext c) { return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .widthPx(30) .heightPx(30) .wrapInView() .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .widthPx(10) .heightPx(10) .marginPx(YogaEdge.ALL, 10) .wrapInView() .child( TestDrawableComponent.create(c) .withLayout().flexShrink(0) .widthPx(10) .heightPx(10))) .build(); } }; LayoutState layoutState = calculateLayoutState( RuntimeEnvironment.application, component, -1, SizeSpec.makeSizeSpec(350, SizeSpec.EXACTLY), SizeSpec.makeSizeSpec(200, SizeSpec.EXACTLY)); Rect mountBounds = new Rect(); layoutState.getMountableOutputAt(0).getMountBounds(mountBounds); assertEquals(new Rect(0, 0, 30, 30), mountBounds); layoutState.getMountableOutputAt(1).getMountBounds(mountBounds); assertEquals(new Rect(10, 10, 20, 20), mountBounds); layoutState.getMountableOutputAt(2).getMountBounds(mountBounds); assertEquals(new Rect(0, 0, 10, 10), mountBounds); } @Test public void testLayoutOutputsForDeepLayoutSpecsWithBackground() { final int paddingSize = 5; final Component component = new InlineLayoutSpec() { @Override protected ComponentLayout onCreateLayout(ComponentContext c) { return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .backgroundColor(0xFFFF0000) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .flexDirection(YogaFlexDirection.ROW) .justifyContent(YogaJustify.SPACE_AROUND) .alignItems(YogaAlign.CENTER) .positionType(YogaPositionType.ABSOLUTE) .positionPx(LEFT, 50) .positionPx(TOP, 50) .positionPx(RIGHT, 200) .positionPx(BOTTOM, 50) .child( Text.create(c) .text("textLeft1")) .child( Text.create(c) .text("textRight1")) .backgroundColor(0xFFFF0000) .foregroundColor(0xFFFF0000) .paddingPx(YogaEdge.ALL, paddingSize) .wrapInView()) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .flexDirection(YogaFlexDirection.ROW) .justifyContent(YogaJustify.SPACE_AROUND) .alignItems(YogaAlign.CENTER) .positionType(YogaPositionType.ABSOLUTE) .positionPx(LEFT, 200) .positionPx(TOP, 50) .positionPx(RIGHT, 50) .positionPx(BOTTOM, 50) .child( Text.create(c) .text("textLeft2") .withLayout().flexShrink(0) .wrapInView() .backgroundColor(0xFFFF0000) .paddingPx(YogaEdge.ALL, paddingSize)) .child( TestViewComponent.create(c) .withLayout().flexShrink(0) .backgroundColor(0xFFFF0000) .foregroundColor(0x0000FFFF) .paddingPx(YogaEdge.ALL, paddingSize))) .build(); } }; LayoutState layoutState = calculateLayoutState( RuntimeEnvironment.application, component, -1, SizeSpec.makeSizeSpec(350, SizeSpec.EXACTLY), SizeSpec.makeSizeSpec(200, SizeSpec.EXACTLY)); // Account for Android version in the foreground. If >= M the foreground is part of the // ViewLayoutOutput otherwise it has its own LayoutOutput. boolean foregroundHasOwnOutput = Build.VERSION.SDK_INT < Build.VERSION_CODES.M; // Check total layout outputs. assertEquals( foregroundHasOwnOutput ? 12 : 11, layoutState.getMountableOutputCount()); // Check quantity of HostComponents. int totalHosts = 0; for (int i = 0; i < layoutState.getMountableOutputCount(); i++) { ComponentLifecycle lifecycle = getComponentAt(layoutState, i); if (isHostComponent(lifecycle)) { totalHosts++; } } assertEquals(3, totalHosts); //Check all the Layouts are in the correct position. assertTrue(isHostComponent(getComponentAt(layoutState, 0))); assertTrue(getComponentAt(layoutState, 1) instanceof DrawableComponent); assertTrue(isHostComponent(getComponentAt(layoutState, 2))); assertTrue(getComponentAt(layoutState, 3) instanceof DrawableComponent); assertTrue(getComponentAt(layoutState, 4) instanceof Text); assertTrue(getComponentAt(layoutState, 5) instanceof Text); assertTrue(getComponentAt(layoutState, 6) instanceof DrawableComponent); assertTrue(isHostComponent(getComponentAt(layoutState, 7))); assertTrue(getComponentAt(layoutState, 8) instanceof DrawableComponent); assertTrue(getComponentAt(layoutState, 9) instanceof Text); assertTrue(getComponentAt(layoutState, 10) instanceof TestViewComponent); if (foregroundHasOwnOutput) { assertTrue(getComponentAt(layoutState, 11) instanceof DrawableComponent); } // Check the text within the TextComponents. assertEquals("textLeft1", getTextFromTextComponent(layoutState, 4)); assertEquals("textRight1", getTextFromTextComponent(layoutState, 5)); assertEquals("textLeft2", getTextFromTextComponent(layoutState, 9)); //Check that the backgrounds have the same size of the components to which they are associated assertEquals( layoutState.getMountableOutputAt(2).getBounds(), layoutState.getMountableOutputAt(3).getBounds()); assertEquals( layoutState.getMountableOutputAt(2).getBounds(), layoutState.getMountableOutputAt(6).getBounds()); Rect textLayoutBounds = layoutState.getMountableOutputAt(9).getBounds(); Rect textBackgroundBounds = layoutState.getMountableOutputAt(8).getBounds(); assertEquals(textBackgroundBounds.left , textLayoutBounds.left - paddingSize); assertEquals(textBackgroundBounds.top , textLayoutBounds.top - paddingSize); assertEquals(textBackgroundBounds.right , textLayoutBounds.right + paddingSize); assertEquals(textBackgroundBounds.bottom , textLayoutBounds.bottom + paddingSize); assertEquals(layoutState.getMountableOutputAt(7).getBounds(),layoutState.getMountableOutputAt(8).getBounds()); ViewNodeInfo viewNodeInfo = layoutState.getMountableOutputAt(10).getViewNodeInfo(); assertNotNull(viewNodeInfo); assertTrue(viewNodeInfo.getBackground() != null); if (foregroundHasOwnOutput) { assertTrue(viewNodeInfo.getForeground() == null); } else { assertTrue(viewNodeInfo.getForeground() != null); } assertTrue(viewNodeInfo.getPaddingLeft() == paddingSize); assertTrue(viewNodeInfo.getPaddingTop() == paddingSize); assertTrue(viewNodeInfo.getPaddingRight() == paddingSize); assertTrue(viewNodeInfo.getPaddingBottom() == paddingSize); } @Test public void testLayoutOutputsForMegaDeepLayoutSpecs() { final Component component = new InlineLayoutSpec() { @Override protected ComponentLayout onCreateLayout(ComponentContext c) { return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .child(TestDrawableComponent.create(c)) .wrapInView()) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child( TestDrawableComponent.create(c) .withLayout().flexShrink(0) .wrapInView()) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .child(TestDrawableComponent.create(c)) .wrapInView()) .wrapInView()) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .child(TestDrawableComponent.create(c))) .wrapInView()) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .child(TestViewComponent.create(c))) .wrapInView()) .build(); } }; LayoutState layoutState = calculateLayoutState( RuntimeEnvironment.application, component, -1, SizeSpec.makeSizeSpec(350, SizeSpec.EXACTLY), SizeSpec.makeSizeSpec(200, SizeSpec.EXACTLY)); // Check total layout outputs. assertEquals(18, layoutState.getMountableOutputCount()); // Check quantity of HostComponents. int totalHosts = 0; for (int i = 0; i < layoutState.getMountableOutputCount(); i++) { ComponentLifecycle lifecycle = getComponentAt(layoutState, i); if (isHostComponent(lifecycle)) { totalHosts++; } } assertEquals(7, totalHosts); // Check all the Components match the right LayoutOutput positions. // Tree One. assertTrue(isHostComponent(getComponentAt(layoutState, 0))); assertTrue(isHostComponent(getComponentAt(layoutState, 1))); assertTrue(getComponentAt(layoutState, 2) instanceof TestDrawableComponent); assertTrue(getComponentAt(layoutState, 3) instanceof TestDrawableComponent); // Tree Two. assertTrue(isHostComponent(getComponentAt(layoutState, 4))); assertTrue(isHostComponent(getComponentAt(layoutState, 5))); assertTrue(getComponentAt(layoutState, 6) instanceof TestDrawableComponent); assertTrue(isHostComponent(getComponentAt(layoutState, 7))); assertTrue(getComponentAt(layoutState, 8) instanceof TestDrawableComponent); assertTrue(getComponentAt(layoutState, 9) instanceof TestDrawableComponent); // Tree Three. assertTrue(isHostComponent(getComponentAt(layoutState, 10))); assertTrue(getComponentAt(layoutState, 11) instanceof TestDrawableComponent); assertTrue(getComponentAt(layoutState, 12) instanceof TestDrawableComponent); assertTrue(getComponentAt(layoutState, 13) instanceof TestDrawableComponent); // Tree Four. assertTrue(isHostComponent(getComponentAt(layoutState, 14))); assertTrue(getComponentAt(layoutState, 15) instanceof TestDrawableComponent); assertTrue(getComponentAt(layoutState, 16) instanceof TestDrawableComponent); assertTrue(getComponentAt(layoutState, 17) instanceof TestViewComponent); } @Test public void testLayoutOutputStableIds() { final Component component1 = new InlineLayoutSpec() { @Override protected ComponentLayout onCreateLayout(ComponentContext c) { return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .contentDescription("cd0")) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .child(TestDrawableComponent.create(c)) .contentDescription("cd1")) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .child(TestViewComponent.create(c)) .contentDescription("cd2")) .build(); } }; final Component component2 = new InlineLayoutSpec() { @Override protected ComponentLayout onCreateLayout(ComponentContext c) { return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .contentDescription("cd0")) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .child(TestDrawableComponent.create(c)) .contentDescription("cd1")) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .child(TestViewComponent.create(c)) .contentDescription("cd2")) .build(); } }; LayoutState layoutState = calculateLayoutState( RuntimeEnvironment.application, component1, -1, SizeSpec.makeSizeSpec(350, SizeSpec.EXACTLY), SizeSpec.makeSizeSpec(20, SizeSpec.EXACTLY)); LayoutState sameComponentLayoutState = calculateLayoutState( RuntimeEnvironment.application, component2, -1, SizeSpec.makeSizeSpec(350, SizeSpec.EXACTLY), SizeSpec.makeSizeSpec(20, SizeSpec.EXACTLY)); assertEquals( layoutState.getMountableOutputCount(), sameComponentLayoutState.getMountableOutputCount()); for (int i = 0; i < layoutState.getMountableOutputCount(); i++) { assertEquals( layoutState.getMountableOutputAt(i).getId(), sameComponentLayoutState.getMountableOutputAt(i).getId()); } } @Test public void testLayoutOutputStableIdsForMegaDeepComponent() { final Component component1 = new InlineLayoutSpec() { @Override protected ComponentLayout onCreateLayout(ComponentContext c) { return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .child(TestDrawableComponent.create(c)) .wrapInView()) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child( TestDrawableComponent.create(c) .withLayout().flexShrink(0) .wrapInView()) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .child(TestDrawableComponent.create(c)) .wrapInView()) .wrapInView()) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .child(TestDrawableComponent.create(c))) .wrapInView()) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .child(TestViewComponent.create(c))) .wrapInView()) .build(); } }; final Component component2 = new InlineLayoutSpec() { @Override protected ComponentLayout onCreateLayout(ComponentContext c) { return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .child(TestDrawableComponent.create(c)) .wrapInView()) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child( TestDrawableComponent.create(c) .withLayout().flexShrink(0) .wrapInView()) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .child(TestDrawableComponent.create(c)) .wrapInView()) .wrapInView()) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .child(TestDrawableComponent.create(c))) .wrapInView()) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .child(TestViewComponent.create(c))) .wrapInView()) .build(); } }; LayoutState layoutState = calculateLayoutState( RuntimeEnvironment.application, component1, -1, SizeSpec.makeSizeSpec(350, SizeSpec.EXACTLY), SizeSpec.makeSizeSpec(20, SizeSpec.EXACTLY)); LayoutState sameComponentLayoutState = calculateLayoutState( RuntimeEnvironment.application, component2, -1, SizeSpec.makeSizeSpec(350, SizeSpec.EXACTLY), SizeSpec.makeSizeSpec(20, SizeSpec.EXACTLY)); assertEquals( layoutState.getMountableOutputCount(), sameComponentLayoutState.getMountableOutputCount()); for (int i = 0; i < layoutState.getMountableOutputCount(); i++) { assertEquals( layoutState.getMountableOutputAt(i).getId(), sameComponentLayoutState.getMountableOutputAt(i).getId()); } } @Test public void testPartiallyStableIds() { final Component component1 = new InlineLayoutSpec() { @Override protected ComponentLayout onCreateLayout(ComponentContext c) { return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .child(TestDrawableComponent.create(c)) .build(); } }; final Component component2 = new InlineLayoutSpec() { @Override protected ComponentLayout onCreateLayout(ComponentContext c) { return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .child(TestDrawableComponent.create(c))) .build(); } }; LayoutState layoutState1 = calculateLayoutState( RuntimeEnvironment.application, component1, -1, SizeSpec.makeSizeSpec(350, SizeSpec.EXACTLY), SizeSpec.makeSizeSpec(20, SizeSpec.EXACTLY)); LayoutState layoutState2 = calculateLayoutState( RuntimeEnvironment.application, component2, -1, SizeSpec.makeSizeSpec(350, SizeSpec.EXACTLY), SizeSpec.makeSizeSpec(20, SizeSpec.EXACTLY)); assertEquals( layoutState1.getMountableOutputAt(0).getId(), layoutState2.getMountableOutputAt(0).getId()); assertEquals( layoutState1.getMountableOutputAt(1).getId(), layoutState2.getMountableOutputAt(1).getId()); assertEquals(3, layoutState1.getMountableOutputCount()); assertEquals(4, layoutState2.getMountableOutputCount()); } @Test public void testDifferentIds() { final Component component1 = new InlineLayoutSpec() { @Override protected ComponentLayout onCreateLayout(ComponentContext c) { return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .child(TestDrawableComponent.create(c)) .build(); } }; final Component component2 = new InlineLayoutSpec() { @Override protected ComponentLayout onCreateLayout(ComponentContext c) { return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child( TestDrawableComponent.create(c) .withLayout().flexShrink(0) .wrapInView()) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .child(TestDrawableComponent.create(c)) .wrapInView()) .build(); } }; LayoutState layoutState1 = calculateLayoutState( RuntimeEnvironment.application, component1, -1, SizeSpec.makeSizeSpec(350, SizeSpec.EXACTLY), SizeSpec.makeSizeSpec(20, SizeSpec.EXACTLY)); LayoutState layoutState2 = calculateLayoutState( RuntimeEnvironment.application, component2, -1, SizeSpec.makeSizeSpec(350, SizeSpec.EXACTLY), SizeSpec.makeSizeSpec(20, SizeSpec.EXACTLY)); assertNotEquals( layoutState1.getMountableOutputAt(1).getId(), layoutState2.getMountableOutputAt(1).getId()); } @Test public void testLayoutOutputsWithInteractiveLayoutSpecAsLeafs() { final Component component = new InlineLayoutSpec() { @Override protected ComponentLayout onCreateLayout(ComponentContext c) { return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestLayoutComponent.create(c)) .wrapInView()) .build(); } }; LayoutState layoutState = calculateLayoutState( RuntimeEnvironment.application, component, -1, SizeSpec.makeSizeSpec(350, SizeSpec.EXACTLY), SizeSpec.makeSizeSpec(200, SizeSpec.EXACTLY)); // Check total layout outputs. assertEquals(3, layoutState.getMountableOutputCount()); assertTrue(isHostComponent(getComponentAt(layoutState, 0))); assertTrue(getComponentAt(layoutState, 1) instanceof TestDrawableComponent); assertTrue(isHostComponent(getComponentAt(layoutState, 2))); } private static ComponentLifecycle getComponentAt(LayoutState layoutState, int index) { return layoutState.getMountableOutputAt(index).getComponent().getLifecycle(); } private static CharSequence getTextFromTextComponent(LayoutState layoutState, int index) { return Whitebox.getInternalState(layoutState.getMountableOutputAt(index).getComponent(), "text"); } private static boolean isHostComponent(ComponentLifecycle component) { return component instanceof HostComponent; } @Test public void testNoMeasureOnNestedComponentWithSameSpecs() { final ComponentContext c = new ComponentContext(RuntimeEnvironment.application); final Size size = new Size(); final TestComponent innerComponent = TestDrawableComponent.create(c, 0, 0, false, true, true, false, false).build(); final int widthSpec = SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY); final int heightSpec = SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY); innerComponent.measure( c, widthSpec, heightSpec, size); InternalNode internalNode = ((Component) innerComponent).getCachedLayout(); internalNode.setLastWidthSpec(widthSpec); internalNode.setLastHeightSpec(heightSpec); internalNode.setLastMeasuredWidth(internalNode.getWidth()); internalNode.setLastMeasuredHeight(internalNode.getHeight()); innerComponent.resetInteractions(); final Component component = new InlineLayoutSpec() { @Override protected ComponentLayout onCreateLayout(ComponentContext c) { return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child( Layout.create(c, innerComponent).flexShrink(0) .widthPx(100) .heightPx(100)) .build(); } }; calculateLayoutState( RuntimeEnvironment.application, component, -1, SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY), SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY)); assertFalse(innerComponent.wasMeasureCalled()); } @Test public void testNoMeasureOnNestedComponentWithNewMeasureSpecExact() { final ComponentContext c = new ComponentContext(RuntimeEnvironment.application); final Size size = new Size(); final TestComponent innerComponent = TestDrawableComponent.create(c, 0, 0, false, true, true, false, false).build(); final int widthSpec = SizeSpec.makeSizeSpec(100, SizeSpec.AT_MOST); final int heightSpec = SizeSpec.makeSizeSpec(100, SizeSpec.AT_MOST); innerComponent.measure( c, widthSpec, heightSpec, size); InternalNode internalNode = ((Component) innerComponent).getCachedLayout(); internalNode.setLastWidthSpec(widthSpec); internalNode.setLastHeightSpec(heightSpec); internalNode.setLastMeasuredWidth(100); internalNode.setLastMeasuredHeight(100); innerComponent.resetInteractions(); final Component component = new InlineLayoutSpec() { @Override protected ComponentLayout onCreateLayout(ComponentContext c) { return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child( Layout.create(c, innerComponent).flexShrink(0) .widthPx(100) .heightPx(100)) .build(); } }; calculateLayoutState( RuntimeEnvironment.application, component, -1, SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY), SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY)); assertFalse(innerComponent.wasMeasureCalled()); } @Test public void testNoMeasureOnNestedComponentWithNewMeasureSpecOldUnspecified() { final ComponentContext c = new ComponentContext(RuntimeEnvironment.application); final Size size = new Size(); final TestComponent innerComponent = TestDrawableComponent.create(c, 0, 0, false, true, true, false, false).build(); final int widthSpec = SizeSpec.makeSizeSpec(0, SizeSpec.UNSPECIFIED); final int heightSpec = SizeSpec.makeSizeSpec(0, SizeSpec.UNSPECIFIED); innerComponent.measure( c, widthSpec, heightSpec, size); InternalNode internalNode = ((Component) innerComponent).getCachedLayout(); internalNode.setLastWidthSpec(widthSpec); internalNode.setLastHeightSpec(heightSpec); internalNode.setLastMeasuredWidth(99); internalNode.setLastMeasuredHeight(99); innerComponent.resetInteractions(); final Component component = new InlineLayoutSpec() { @Override protected ComponentLayout onCreateLayout(ComponentContext c) { return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(innerComponent) .build(); } }; calculateLayoutState( RuntimeEnvironment.application, component, -1, SizeSpec.makeSizeSpec(100, SizeSpec.AT_MOST), SizeSpec.makeSizeSpec(100, SizeSpec.AT_MOST)); assertFalse(innerComponent.wasMeasureCalled()); } @Test public void testNoMeasureOnNestedComponentWithOldAndNewAtMost() { final ComponentContext c = new ComponentContext(RuntimeEnvironment.application); final Size size = new Size(); final TestComponent innerComponent = TestDrawableComponent.create(c, 0, 0, false, true, true, false, false).build(); final int widthSpec = SizeSpec.makeSizeSpec(100, SizeSpec.AT_MOST); final int heightSpec = SizeSpec.makeSizeSpec(100, SizeSpec.AT_MOST); innerComponent.measure( c, widthSpec, heightSpec, size); InternalNode internalNode = ((Component) innerComponent).getCachedLayout(); internalNode.setLastWidthSpec(widthSpec); internalNode.setLastHeightSpec(heightSpec); internalNode.setLastMeasuredWidth(50); internalNode.setLastMeasuredHeight(50); innerComponent.resetInteractions(); final Component component = new InlineLayoutSpec() { @Override protected ComponentLayout onCreateLayout(ComponentContext c) { return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(innerComponent) .build(); } }; calculateLayoutState( RuntimeEnvironment.application, component, -1, SizeSpec.makeSizeSpec(50, SizeSpec.AT_MOST), SizeSpec.makeSizeSpec(50, SizeSpec.AT_MOST)); assertFalse(innerComponent.wasMeasureCalled()); } @Test public void testLayoutOutputsForTwiceNestedComponent() { final Component component = new InlineLayoutSpec() { @Override protected ComponentLayout onCreateLayout(ComponentContext c) { return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c))) .wrapInView()) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c))) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)))) .build(); } }; LayoutState layoutState = calculateLayoutState( RuntimeEnvironment.application, component, -1, SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY), SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY)); assertEquals(5, layoutState.getMountableOutputCount()); long hostMarkerRoot = layoutState.getMountableOutputAt(0).getId(); long hostMarkerOne = layoutState.getMountableOutputAt(1).getId(); // First output is the inner host for the click handler assertEquals(hostMarkerRoot, layoutState.getMountableOutputAt(1).getHostMarker()); // Second output is the child of the inner host assertEquals(hostMarkerOne, layoutState.getMountableOutputAt(2).getHostMarker()); // Third and fourth outputs are children of the root view. assertEquals(hostMarkerRoot, layoutState.getMountableOutputAt(3).getHostMarker()); assertEquals(hostMarkerRoot, layoutState.getMountableOutputAt(4).getHostMarker()); } @Test public void testLayoutOutputsForComponentWithBackgrounds() { final Component component = new InlineLayoutSpec() { @Override protected ComponentLayout onCreateLayout(ComponentContext c) { return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .backgroundColor(0xFFFF0000) .foregroundColor(0xFFFF0000) .child(TestDrawableComponent.create(c)) .build(); } }; LayoutState layoutState = calculateLayoutState( RuntimeEnvironment.application, component, -1, SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY), SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY)); assertEquals(4, layoutState.getMountableOutputCount()); // First and third output are the background and the foreground assertTrue(getComponentAt(layoutState, 1) instanceof DrawableComponent); assertTrue(getComponentAt(layoutState, 3) instanceof DrawableComponent); } @Test public void testLayoutOutputsForNonComponentClickableNode() { final Component component = new InlineLayoutSpec() { @Override protected ComponentLayout onCreateLayout(ComponentContext c) { return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .wrapInView()) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .child(TestDrawableComponent.create(c)) .wrapInView()) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .child(TestViewComponent.create(c)) .wrapInView()) .build(); } }; LayoutState layoutState = calculateLayoutState( RuntimeEnvironment.application, component, -1, SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY), SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY)); assertEquals(9, layoutState.getMountableOutputCount()); long hostMarkerRoot = layoutState.getMountableOutputAt(0).getHostMarker(); long hostMarkerZero = layoutState.getMountableOutputAt(1).getHostMarker(); long hostMarkerTwo = layoutState.getMountableOutputAt(4).getHostMarker(); long hostMarkerThree = layoutState.getMountableOutputAt(7).getHostMarker(); assertEquals(hostMarkerRoot, layoutState.getMountableOutputAt(1).getHostMarker()); assertEquals(hostMarkerZero, layoutState.getMountableOutputAt(3).getHostMarker()); assertEquals(hostMarkerTwo, layoutState.getMountableOutputAt(5).getHostMarker()); assertEquals(hostMarkerZero, layoutState.getMountableOutputAt(6).getHostMarker()); assertEquals(hostMarkerThree, layoutState.getMountableOutputAt(8).getHostMarker()); assertTrue(isHostComponent(getComponentAt(layoutState, 0))); assertTrue(isHostComponent(getComponentAt(layoutState, 1))); assertTrue(getComponentAt(layoutState, 2) instanceof TestDrawableComponent); assertTrue(isHostComponent(getComponentAt(layoutState, 3))); assertTrue(getComponentAt(layoutState, 4) instanceof TestDrawableComponent); assertTrue(getComponentAt(layoutState, 5) instanceof TestDrawableComponent); assertTrue(isHostComponent(getComponentAt(layoutState, 6))); assertTrue(getComponentAt(layoutState, 7) instanceof TestDrawableComponent); assertTrue(getComponentAt(layoutState, 8) instanceof TestViewComponent); } @Test public void testLayoutOutputsForNonComponentContentDescriptionNode() { enableAccessibility(); final Component component = new InlineLayoutSpec() { @Override protected ComponentLayout onCreateLayout(ComponentContext c) { return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .contentDescription("cd0")) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .child(TestDrawableComponent.create(c)) .contentDescription("cd1")) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .child(TestViewComponent.create(c)) .contentDescription("cd2")) .build(); } }; LayoutState layoutState = calculateLayoutState( RuntimeEnvironment.application, component, -1, SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY), SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY)); assertEquals(9, layoutState.getMountableOutputCount()); long hostMarkerRoot = layoutState.getMountableOutputAt(0).getHostMarker(); long hostMarkerZero = layoutState.getMountableOutputAt(1).getHostMarker(); long hostMarkerTwo = layoutState.getMountableOutputAt(4).getHostMarker(); long hostMarkerThree = layoutState.getMountableOutputAt(7).getHostMarker(); assertEquals(hostMarkerRoot, layoutState.getMountableOutputAt(1).getHostMarker()); assertEquals(hostMarkerZero, layoutState.getMountableOutputAt(3).getHostMarker()); assertEquals(hostMarkerTwo, layoutState.getMountableOutputAt(5).getHostMarker()); assertEquals(hostMarkerZero, layoutState.getMountableOutputAt(6).getHostMarker()); assertEquals(hostMarkerThree, layoutState.getMountableOutputAt(8).getHostMarker()); assertTrue(isHostComponent(getComponentAt(layoutState, 0))); assertTrue(isHostComponent(getComponentAt(layoutState, 1))); assertTrue(getComponentAt(layoutState, 2) instanceof TestDrawableComponent); assertTrue(isHostComponent(getComponentAt(layoutState, 3))); assertTrue(getComponentAt(layoutState, 4) instanceof TestDrawableComponent); assertTrue(getComponentAt(layoutState, 5) instanceof TestDrawableComponent); assertTrue(isHostComponent(getComponentAt(layoutState, 6))); assertTrue(getComponentAt(layoutState, 7) instanceof TestDrawableComponent); assertTrue(getComponentAt(layoutState, 8) instanceof TestViewComponent); } @Test public void testLayoutOutputsForFocusableOnRoot() { final Component component = new InlineLayoutSpec() { @Override protected ComponentLayout onCreateLayout(ComponentContext c) { return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .focusable(true) .build(); } }; LayoutState layoutState = calculateLayoutState( RuntimeEnvironment.application, component, -1, SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY), SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY)); assertEquals(2, layoutState.getMountableOutputCount()); long hostMarkerZero = layoutState.getMountableOutputAt(0).getHostMarker(); assertEquals(hostMarkerZero, layoutState.getMountableOutputAt(1).getHostMarker()); assertTrue(isHostComponent(getComponentAt(layoutState, 0))); assertTrue(getComponentAt(layoutState, 1) instanceof TestDrawableComponent); assertEquals(FOCUS_SET_TRUE, layoutState.getMountableOutputAt(0).getNodeInfo().getFocusState()); } @Test public void testLayoutOutputsForFocusable() { final Component component = new InlineLayoutSpec() { @Override protected ComponentLayout onCreateLayout(ComponentContext c) { return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .focusable(true)) .build(); } }; LayoutState layoutState = calculateLayoutState( RuntimeEnvironment.application, component, -1, SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY), SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY)); assertEquals(3, layoutState.getMountableOutputCount()); assertNull(layoutState.getMountableOutputAt(0).getNodeInfo()); assertEquals(FOCUS_SET_TRUE, layoutState.getMountableOutputAt(1).getNodeInfo().getFocusState()); } @Test public void testLayoutOutputsForAccessibilityEnabled() { enableAccessibility(); final Component component = new InlineLayoutSpec() { @Override protected ComponentLayout onCreateLayout(ComponentContext c) { return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .flexDirection(YogaFlexDirection.ROW) .alignItems(YogaAlign.CENTER) .paddingDip(YogaEdge.ALL, 10) .contentDescription("This is root view") .child( TestDrawableComponent.create(c) .withLayout().flexShrink(0) .widthDip(30) .heightDip(30)) .child( TestDrawableComponent.create(c, true, true, true, true, false) .withLayout().flexShrink(0) .flex(1).flexBasisDip(0) .backgroundColor(Color.RED) .marginDip(YogaEdge.HORIZONTAL, 10)) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .flexDirection(YogaFlexDirection.ROW) .alignItems(YogaAlign.CENTER) .paddingDip(YogaEdge.ALL, 10) .contentDescription("This is a container") .child( TestDrawableComponent.create(c) .withLayout().flexShrink(0) .widthDip(30) .heightDip(30) .contentDescription("This is an image")) .child( TestDrawableComponent.create(c, true, true, true, true, false) .withLayout().flexShrink(0) .flex(1).flexBasisDip(0) .marginDip(YogaEdge.HORIZONTAL, 10))) .build(); } }; LayoutState layoutState = calculateLayoutState( RuntimeEnvironment.application, component, -1, SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY), SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY)); assertEquals(10, layoutState.getMountableOutputCount()); long hostMarkerRoot = layoutState.getMountableOutputAt(1).getHostMarker(); long hostMarkerOne = layoutState.getMountableOutputAt(3).getHostMarker(); long hostMarkerTwo = layoutState.getMountableOutputAt(6).getHostMarker(); long hostMarkerThree = layoutState.getMountableOutputAt(7).getHostMarker(); long hostMarkerFour = layoutState.getMountableOutputAt(9).getHostMarker(); assertEquals(hostMarkerRoot, layoutState.getMountableOutputAt(1).getHostMarker()); assertEquals(hostMarkerOne, layoutState.getMountableOutputAt(3).getHostMarker()); assertEquals(hostMarkerOne, layoutState.getMountableOutputAt(4).getHostMarker()); assertEquals(hostMarkerTwo, layoutState.getMountableOutputAt(6).getHostMarker()); assertEquals(hostMarkerThree, layoutState.getMountableOutputAt(7).getHostMarker()); assertEquals(hostMarkerFour, layoutState.getMountableOutputAt(9).getHostMarker()); assertTrue(isHostComponent(getComponentAt(layoutState, 0))); assertTrue(getComponentAt(layoutState, 1) instanceof TestDrawableComponent); assertTrue(isHostComponent(getComponentAt(layoutState, 2))); assertTrue(getComponentAt(layoutState, 3) instanceof DrawableComponent); assertTrue(getComponentAt(layoutState, 4) instanceof TestDrawableComponent); assertTrue(isHostComponent(getComponentAt(layoutState, 5))); assertTrue(isHostComponent(getComponentAt(layoutState, 6))); assertTrue(getComponentAt(layoutState, 7) instanceof TestDrawableComponent); assertTrue(isHostComponent(getComponentAt(layoutState, 8))); assertTrue(getComponentAt(layoutState, 9) instanceof TestDrawableComponent); } @Test public void testLayoutOutputsWithImportantForAccessibility() { enableAccessibility(); final Component component = new InlineLayoutSpec() { @Override protected ComponentLayout onCreateLayout(ComponentContext c) { return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .contentDescription("This is root view") .child( TestDrawableComponent.create(c) .withLayout().flexShrink(0) .widthDip(30) .heightDip(30)) .child( TestDrawableComponent.create(c, true, true, true, true, false) .withLayout().flexShrink(0) .flex(1).flexBasisDip(0) .backgroundColor(Color.RED) .marginDip(YogaEdge.HORIZONTAL, 10) .importantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO)) .child( Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .flexDirection(YogaFlexDirection.ROW) .alignItems(YogaAlign.CENTER) .paddingDip(YogaEdge.ALL, 10) .importantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) .child( TestDrawableComponent.create(c) .withLayout().flexShrink(0) .widthDip(30) .heightDip(30) .importantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES) .contentDescription("This is an image"))) .build(); } }; LayoutState layoutState = calculateLayoutState( RuntimeEnvironment.application, component, -1, SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY), SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY)); assertEquals(7, layoutState.getMountableOutputCount()); long hostMarkerRoot = layoutState.getMountableOutputAt(1).getHostMarker(); long hostMarkerOne = layoutState.getMountableOutputAt(5).getHostMarker(); long hostMarkerTwo = layoutState.getMountableOutputAt(6).getHostMarker(); assertEquals(hostMarkerRoot, layoutState.getMountableOutputAt(1).getHostMarker()); assertEquals(hostMarkerRoot, layoutState.getMountableOutputAt(2).getHostMarker()); assertEquals(hostMarkerRoot, layoutState.getMountableOutputAt(3).getHostMarker()); assertEquals(hostMarkerRoot, layoutState.getMountableOutputAt(4).getHostMarker()); assertEquals(hostMarkerOne, layoutState.getMountableOutputAt(5).getHostMarker()); assertEquals(hostMarkerTwo, layoutState.getMountableOutputAt(6).getHostMarker()); assertTrue(isHostComponent(getComponentAt(layoutState, 0))); assertTrue(getComponentAt(layoutState, 1) instanceof TestDrawableComponent); assertTrue(getComponentAt(layoutState, 2) instanceof DrawableComponent); assertTrue(getComponentAt(layoutState, 3) instanceof TestDrawableComponent); assertTrue(isHostComponent(getComponentAt(layoutState, 4))); assertTrue(isHostComponent(getComponentAt(layoutState, 5))); assertTrue(getComponentAt(layoutState, 6) instanceof TestDrawableComponent); assertEquals( layoutState.getMountableOutputAt(0).getImportantForAccessibility(), IMPORTANT_FOR_ACCESSIBILITY_AUTO); assertEquals( layoutState.getMountableOutputAt(1).getImportantForAccessibility(), IMPORTANT_FOR_ACCESSIBILITY_AUTO); assertEquals( layoutState.getMountableOutputAt(2).getImportantForAccessibility(), IMPORTANT_FOR_ACCESSIBILITY_NO); assertEquals( layoutState.getMountableOutputAt(3).getImportantForAccessibility(), IMPORTANT_FOR_ACCESSIBILITY_NO); assertEquals( layoutState.getMountableOutputAt(4).getImportantForAccessibility(), IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); assertEquals( layoutState.getMountableOutputAt(5).getImportantForAccessibility(), IMPORTANT_FOR_ACCESSIBILITY_YES); assertEquals( layoutState.getMountableOutputAt(6).getImportantForAccessibility(), IMPORTANT_FOR_ACCESSIBILITY_YES); } @Test public void testLayoutOutputsForClickHandlerAndViewTagsOnRoot() { final Component component = new InlineLayoutSpec() { @Override protected ComponentLayout onCreateLayout(ComponentContext c) { return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .clickHandler(c.newEventHandler(1)) .viewTags(new SparseArray<>()) .build(); } }; LayoutState layoutState = calculateLayoutState( RuntimeEnvironment.application, component, -1, SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY), SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY)); assertEquals(2, layoutState.getMountableOutputCount()); long hostMarkerZero = layoutState.getMountableOutputAt(0).getHostMarker(); assertEquals(hostMarkerZero, layoutState.getMountableOutputAt(1).getHostMarker()); assertTrue(isHostComponent(getComponentAt(layoutState, 0))); assertTrue(getComponentAt(layoutState, 1) instanceof TestDrawableComponent); final NodeInfo nodeInfo = layoutState.getMountableOutputAt(0).getNodeInfo(); assertNotNull(nodeInfo); assertNotNull(nodeInfo.getClickHandler()); assertNotNull(nodeInfo.getViewTags()); } @Test public void testLayoutOutputsForLongClickHandlerAndViewTagsOnRoot() { final Component component = new InlineLayoutSpec() { @Override protected ComponentLayout onCreateLayout(ComponentContext c) { return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child(TestDrawableComponent.create(c)) .longClickHandler(c.newEventHandler(1)) .viewTags(new SparseArray<>()) .build(); } }; LayoutState layoutState = calculateLayoutState( RuntimeEnvironment.application, component, -1, SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY), SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY)); assertEquals(2, layoutState.getMountableOutputCount()); long hostMarkerZero = layoutState.getMountableOutputAt(0).getHostMarker(); assertEquals(hostMarkerZero, layoutState.getMountableOutputAt(1).getHostMarker()); assertTrue(isHostComponent(getComponentAt(layoutState, 0))); assertTrue(getComponentAt(layoutState, 1) instanceof TestDrawableComponent); final NodeInfo nodeInfo = layoutState.getMountableOutputAt(0).getNodeInfo(); assertNotNull(nodeInfo); assertNotNull(nodeInfo.getLongClickHandler()); assertNotNull(nodeInfo.getViewTags()); } @Test public void testLayoutOutputsForForceWrappedComponent() { final Component component = new InlineLayoutSpec() { @Override protected ComponentLayout onCreateLayout(ComponentContext c) { return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .child( TestDrawableComponent.create(c) .withLayout().flexShrink(0) .wrapInView()) .build(); } }; final LayoutState layoutState = calculateLayoutState( RuntimeEnvironment.application, component, -1, SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY), SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY)); assertEquals(3, layoutState.getMountableOutputCount()); assertTrue(getComponentAt(layoutState, 0) instanceof HostComponent); assertTrue(getComponentAt(layoutState, 1) instanceof HostComponent); assertTrue(getComponentAt(layoutState, 2) instanceof TestDrawableComponent); } @Test public void testLayoutOutputForRootNestedTreeComponent() { LayoutState layoutState = calculateLayoutState( RuntimeEnvironment.application, TestSizeDependentComponent.create(new ComponentContext(RuntimeEnvironment.application)) .setFixSizes(true) .setDelegate(false) .build(), -1, SizeSpec.makeSizeSpec(350, SizeSpec.EXACTLY), SizeSpec.makeSizeSpec(200, SizeSpec.EXACTLY)); // Check total layout outputs. assertEquals(4, layoutState.getMountableOutputCount()); Rect mountBounds = new Rect(); // Check host. assertTrue(isHostComponent(getComponentAt(layoutState, 0))); layoutState.getMountableOutputAt(0).getMountBounds(mountBounds); assertEquals(new Rect(0, 0, 350, 200), mountBounds); assertEquals(0, layoutState.getMountableOutputAt(0).getHostMarker()); // Check NestedTree assertTrue(getComponentAt(layoutState, 1) instanceof DrawableComponent); layoutState.getMountableOutputAt(1).getMountBounds(mountBounds); assertEquals(new Rect(5, 5, 55, 55), mountBounds); assertTrue(getComponentAt(layoutState, 2) instanceof TestDrawableComponent); layoutState.getMountableOutputAt(2).getMountBounds(mountBounds); assertEquals(new Rect(5, 5, 55, 55), mountBounds); assertTrue(getComponentAt(layoutState, 3) instanceof TestViewComponent); layoutState.getMountableOutputAt(3).getMountBounds(mountBounds); assertEquals(new Rect(8, 58, 342, 78), mountBounds); } @Test public void testLayoutOutputForDelegateNestedTreeComponentDelegate() { final Component component = new InlineLayoutSpec() { @Override protected ComponentLayout onCreateLayout(ComponentContext c) { return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .paddingPx(YogaEdge.ALL, 2) .child( TestSizeDependentComponent.create(c) .setFixSizes(true) .setDelegate(true) .withLayout().flexShrink(0) .marginPx(YogaEdge.ALL, 11)) .build(); } }; LayoutState layoutState = calculateLayoutState( RuntimeEnvironment.application, component, -1, SizeSpec.makeSizeSpec(350, SizeSpec.EXACTLY), SizeSpec.makeSizeSpec(200, SizeSpec.EXACTLY)); // Check total layout outputs. assertEquals(3, layoutState.getMountableOutputCount()); Rect mountBounds = new Rect(); // Check host. assertTrue(isHostComponent(getComponentAt(layoutState, 0))); layoutState.getMountableOutputAt(0).getMountBounds(mountBounds); assertEquals(new Rect(0, 0, 350, 200), mountBounds); // Check NestedTree assertTrue(getComponentAt(layoutState, 1) instanceof DrawableComponent); layoutState.getMountableOutputAt(1).getMountBounds(mountBounds); assertEquals(new Rect(13, 13, 63, 63), mountBounds); assertTrue(getComponentAt(layoutState, 2) instanceof TestDrawableComponent); layoutState.getMountableOutputAt(2).getMountBounds(mountBounds); assertEquals(new Rect(13, 13, 63, 63), mountBounds); } @Test public void testLayoutOutputForDelegateNestedTreeComponent() { final Component component = new InlineLayoutSpec() { @Override protected ComponentLayout onCreateLayout(ComponentContext c) { return Container.create(c).flexDirection(YogaFlexDirection.COLUMN).flexShrink(0).alignContent(YogaAlign.FLEX_START) .paddingPx(YogaEdge.ALL, 2) .child( TestSizeDependentComponent.create(c) .setFixSizes(true) .setDelegate(false) .withLayout().flexShrink(0) .marginPx(YogaEdge.ALL, 11)) .build(); } }; LayoutState layoutState = calculateLayoutState( RuntimeEnvironment.application, component, -1, SizeSpec.makeSizeSpec(350, SizeSpec.EXACTLY), SizeSpec.makeSizeSpec(200, SizeSpec.EXACTLY)); // Check total layout outputs. assertEquals(4, layoutState.getMountableOutputCount()); Rect mountBounds = new Rect(); // Check host. assertTrue(isHostComponent(getComponentAt(layoutState, 0))); layoutState.getMountableOutputAt(0).getMountBounds(mountBounds); assertEquals(new Rect(0, 0, 350, 200), mountBounds); assertEquals(0, layoutState.getMountableOutputAt(0).getHostMarker()); // Check NestedTree assertTrue(getComponentAt(layoutState, 1) instanceof DrawableComponent); layoutState.getMountableOutputAt(1).getMountBounds(mountBounds); assertEquals(new Rect(18, 18, 68, 68), mountBounds); assertTrue(getComponentAt(layoutState, 2) instanceof TestDrawableComponent); layoutState.getMountableOutputAt(2).getMountBounds(mountBounds); assertEquals(new Rect(18, 18, 68, 68), mountBounds); assertTrue(getComponentAt(layoutState, 3) instanceof TestViewComponent); layoutState.getMountableOutputAt(3).getMountBounds(mountBounds); assertEquals(new Rect(21, 71, 329, 91), mountBounds); } @Test public void testLayoutOutputForRootWithDelegateNestedTreeComponent() { final Component component = new InlineLayoutSpec() { @Override protected ComponentLayout onCreateLayout(ComponentContext c) { return TestSizeDependentComponent.create(c) .setFixSizes(true) .setDelegate(false) .buildWithLayout(); } }; LayoutState layoutState = calculateLayoutState( RuntimeEnvironment.application, component, -1, SizeSpec.makeSizeSpec(350, SizeSpec.EXACTLY), SizeSpec.makeSizeSpec(200, SizeSpec.EXACTLY)); // Check total layout outputs. assertEquals(4, layoutState.getMountableOutputCount()); Rect mountBounds = new Rect(); // Check host. assertTrue(isHostComponent(getComponentAt(layoutState, 0))); layoutState.getMountableOutputAt(0).getMountBounds(mountBounds); assertEquals(new Rect(0, 0, 350, 200), mountBounds); assertEquals(0, layoutState.getMountableOutputAt(0).getHostMarker()); // Check NestedTree assertTrue(getComponentAt(layoutState, 1) instanceof DrawableComponent); layoutState.getMountableOutputAt(1).getMountBounds(mountBounds); assertEquals(new Rect(5, 5, 55, 55), mountBounds); assertTrue(getComponentAt(layoutState, 2) instanceof TestDrawableComponent); layoutState.getMountableOutputAt(2).getMountBounds(mountBounds); assertEquals(new Rect(5, 5, 55, 55), mountBounds); assertTrue(getComponentAt(layoutState, 3) instanceof TestViewComponent); layoutState.getMountableOutputAt(3).getMountBounds(mountBounds); assertEquals(new Rect(8, 58, 342, 78), mountBounds); } @Test public void testLayoutOutputRootWithPaddingOverridingDelegateNestedTreeComponent() { final Component component = new InlineLayoutSpec() { @Override protected ComponentLayout onCreateLayout(ComponentContext c) { final Component<TestSizeDependentComponent> nestedTreeRootComponent = TestSizeDependentComponent.create(c) .setFixSizes(true) .setDelegate(false) .build(); return Layout.create(c, nestedTreeRootComponent).flexShrink(0) .paddingPx(YogaEdge.ALL, 10) .build(); } }; LayoutState layoutState = calculateLayoutState( RuntimeEnvironment.application, component, -1, SizeSpec.makeSizeSpec(350, SizeSpec.EXACTLY), SizeSpec.makeSizeSpec(200, SizeSpec.EXACTLY)); // Check total layout outputs. assertEquals(4, layoutState.getMountableOutputCount()); Rect mountBounds = new Rect(); // Check host. assertTrue(isHostComponent(getComponentAt(layoutState, 0))); layoutState.getMountableOutputAt(0).getMountBounds(mountBounds); assertEquals(new Rect(0, 0, 350, 200), mountBounds); assertEquals(0, layoutState.getMountableOutputAt(0).getHostMarker()); // Check NestedTree assertTrue(getComponentAt(layoutState, 1) instanceof DrawableComponent); layoutState.getMountableOutputAt(1).getMountBounds(mountBounds); assertEquals(new Rect(10, 10, 60, 60), mountBounds); assertTrue(getComponentAt(layoutState, 2) instanceof TestDrawableComponent); layoutState.getMountableOutputAt(2).getMountBounds(mountBounds); assertEquals(new Rect(10, 10, 60, 60), mountBounds); assertTrue(getComponentAt(layoutState, 3) instanceof TestViewComponent); layoutState.getMountableOutputAt(3).getMountBounds(mountBounds); assertEquals(new Rect(13, 63, 337, 83), mountBounds); } @Test
package com.github.therapi.apidoc; import static net.javacrumbs.jsonunit.JsonAssert.assertJsonEquals; import static org.junit.Assert.assertFalse; import java.util.List; import java.util.Optional; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; public class JsonSchemaProviderTest { private interface Zoo { String getName(); List<Animal> getAnimals(); } private interface Animal { String getSpecies(); } private static class NoPublicFields { private int x; } @Test public void testGetSchema() throws Exception { Optional<String> schema = new JsonSchemaProvider().getSchema(new ObjectMapper(), Zoo.class); String expected = "{\n" + " \"type\" : \"object\",\n" + " \"id\" : \"urn:jsonschema:com:github:therapi:apidoc:JsonSchemaProviderTest:Zoo\",\n" + " \"properties\" : {\n" + " \"name\" : {\n" + " \"type\" : \"string\"\n" + " },\n" + " \"animals\" : {\n" + " \"type\" : \"array\",\n" + " \"items\" : {\n" + " \"type\" : \"object\",\n" + " \"$ref\" : \"urn:jsonschema:com:github:therapi:apidoc:JsonSchemaProviderTest:Animal\"\n" + " }\n" + " }\n" + " }\n" + "}"; assertJsonEquals(expected, schema.get()); } @Test public void noSchema() throws Exception { assertFalse(new JsonSchemaProvider().getSchema(new ObjectMapper(), NoPublicFields.class).isPresent()); } }
package com.github.therapi.apidoc; import static com.github.therapi.apidoc.JsonSchemaProvider.classNameToHyperlink; import static com.github.therapi.jackson.ObjectMappers.newLenientObjectMapper; import static net.javacrumbs.jsonunit.JsonAssert.assertJsonEquals; import static org.apache.commons.lang3.StringUtils.deleteWhitespace; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import java.util.Optional; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.therapi.core.MethodDefinition; import com.github.therapi.core.ParameterDefinition; import com.github.therapi.core.StandardParameterIntrospector; import org.junit.Test; public class JsonSchemaProviderTest { private enum Color { RED, GREEN, BLUE } private interface Zoo { String getName(); List<Animal> getAnimals(); } private interface Animal { String getSpecies(); Color getColor(); } private static class NoPublicFields { private int x; } @SuppressWarnings("unused") public void exampleMethod(String string, boolean primitiveBoolean, Boolean boxedBoolean, int primitiveInt, Integer boxedInt, long primitiveLong, Long boxedLong, float primitiveFloat, Float boxedFloat, double primitiveDouble, Double boxedDouble, String[] stringArray, List<String> stringList, Zoo zoo) { } @Test public void testGetMethodSchema() throws Exception { ObjectMapper objectMapper = newLenientObjectMapper(); Method method = Arrays.stream(getClass().getMethods()) .filter(m -> m.getName().equals("exampleMethod")) .findAny().get(); List<ParameterDefinition> paramDefs = new StandardParameterIntrospector(objectMapper).findParameters(method, this); MethodDefinition methodDef = new MethodDefinition("test", "exampleMethod", method, this, paramDefs); String result = new JsonSchemaProvider().getSchema(objectMapper, methodDef); String expected = "{\n" + " \"type\" : \"object\",\n" + " \"id\" : \"urn:jsonschema:com:github:therapi:method:test.exampleMethod\",\n" + " \"properties\" : {\n" + " \"string\" : {\n" + " \"type\" : \"string\"\n" + " },\n" + " \"primitiveBoolean\" : {\n" + " \"type\" : \"boolean\"\n" + " },\n" + " \"boxedBoolean\" : {\n" + " \"type\" : \"boolean\"\n" + " },\n" + " \"primitiveInt\" : {\n" + " \"type\" : \"integer\"\n" + " },\n" + " \"boxedInt\" : {\n" + " \"type\" : \"integer\"\n" + " },\n" + " \"primitiveLong\" : {\n" + " \"type\" : \"integer\"\n" + " },\n" + " \"boxedLong\" : {\n" + " \"type\" : \"integer\"\n" + " },\n" + " \"primitiveFloat\" : {\n" + " \"type\" : \"number\"\n" + " },\n" + " \"boxedFloat\" : {\n" + " \"type\" : \"number\"\n" + " },\n" + " \"primitiveDouble\" : {\n" + " \"type\" : \"number\"\n" + " },\n" + " \"boxedDouble\" : {\n" + " \"type\" : \"number\"\n" + " },\n" + " \"stringArray\" : {\n" + " \"type\" : \"array\",\n" + " \"items\" : {\n" + " \"type\" : \"string\"\n" + " }\n" + " },\n" + " \"stringList\" : {\n" + " \"type\" : \"array\",\n" + " \"items\" : {\n" + " \"type\" : \"string\"\n" + " }\n" + " },\n" + " \"zoo\" : {\n" + " \"type\" : \"object\",\n" + " \"id\" : \"urn:jsonschema:com:github:therapi:apidoc:JsonSchemaProviderTest:Zoo\",\n" + " \"properties\" : {\n" + " \"name\" : {\n" + " \"type\" : \"string\"\n" + " },\n" + " \"animals\" : {\n" + " \"type\" : \"array\",\n" + " \"items\" : {\n" + " \"type\" : \"object\",\n" + " \"id\" : \"urn:jsonschema:com:github:therapi:apidoc:JsonSchemaProviderTest:Animal\",\n" + " \"properties\" : {\n" + " \"color\" : {\n" + " \"type\" : \"string\",\n" + " \"enum\" : [ \"RED\", \"GREEN\", \"BLUE\" ]\n" + " },\n" + " \"species\" : {\n" + " \"type\" : \"string\"\n" + " }\n" + " }\n" + " }\n" + " }\n" + " }\n" + " }\n" + " }\n" + "}\n"; assertJsonEquals(expected, result); } @Test public void testGetSchema() throws Exception { Optional<String> schema = new JsonSchemaProvider().getSchemaForHtml(new ObjectMapper(), Zoo.class, classNameToHyperlink()); String expected = "{\n" + " &quot;type&quot; : &quot;object&quot;,\n" + " &quot;id&quot; : &quot;com.github.therapi.apidoc.JsonSchemaProviderTest$Zoo&quot;,\n" + " &quot;properties&quot; : {\n" + " &quot;name&quot; : {\n" + " &quot;type&quot; : &quot;string&quot;\n" + " },\n" + " &quot;animals&quot; : {\n" + " &quot;type&quot; : &quot;array&quot;,\n" + " &quot;items&quot; : {\n" + " &quot;type&quot; : &quot;object&quot;,\n" + " &quot;$ref&quot; : &quot;<a href=\"com.github.therapi.apidoc.JsonSchemaProviderTest$Animal\">com.github.therapi.apidoc.JsonSchemaProviderTest$Animal</a>&quot;\n" + " }\n" + " }\n" + " }\n" + "}"; assertEquals(deleteWhitespace(expected), deleteWhitespace(schema.get())); } @Test public void noSchema() throws Exception { assertFalse(new JsonSchemaProvider() .getSchemaForHtml(new ObjectMapper(), NoPublicFields.class, classNameToHyperlink()) .isPresent()); } }
package com.imcode.imcms.service; import com.imcode.imcms.config.TestConfig; import com.imcode.imcms.util.datainitializer.CategoryDataInitializer; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.junit.Assert.assertEquals; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = TestConfig.class) public class CategoryTypeServiceTest { @Autowired private CategoryTypeService categoryTypeService; @Autowired private CategoryDataInitializer categoryDataInitilizer; @Before public void setUpCategoryDataInitilizer() { categoryDataInitilizer.cleanRepositories(); categoryDataInitilizer.init(4); } @Test public void getAllExpectedEqualsCategoryTypesAsDtoTest() { assertEquals(categoryDataInitilizer.getCategoryTypesAsDTO(), categoryTypeService.getAll()); } @After public void clearData() { categoryDataInitilizer.cleanRepositories(); } }
package com.nickww.finitefield; import static org.junit.Assert.*; import org.junit.Test; import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; public class FiniteByteFieldMatrixTest { private static final FiniteByteFieldMatrix matrix = new FiniteByteFieldMatrix(new byte[][] {{1, 2}, {3, 4}, {-10, -11}, {124, -123}}); private static final FiniteByteFieldMatrix square = new FiniteByteFieldMatrix(new byte[][] {{1, 2, 3}, {4, -10, -11}, {124, -123, 5}}); @Test(expected=NullPointerException.class) public void testConstructorNullArray() { new FiniteByteFieldMatrix(null); } @Test(expected=IllegalArgumentException.class) public void testConstructorEmptyArray() { new FiniteByteFieldMatrix(new byte[][] {}); } @Test(expected=IllegalArgumentException.class) public void testConstructorEmptyColumns() { new FiniteByteFieldMatrix(new byte[][] {{}, {}, {}}); } @Test(expected=IllegalArgumentException.class) public void testConstructorRowsDifferentSizes() { new FiniteByteFieldMatrix(new byte[][] {{1, 2}, {1}}); } @Test public void testNumRows() { assertEquals(4, matrix.numRows()); assertEquals(3, square.numRows()); } @Test public void testNumCols() { assertEquals(2, matrix.numCols()); assertEquals(3, square.numCols()); } @Test public void testIsSquare() { assertFalse(matrix.isSquare()); assertTrue(square.isSquare()); } @Test(expected=IllegalStateException.class) public void testDeterminantOfRectangularMatrix() { matrix.determinant(); } @Test public void testDeterminantOfSquareMatrix() { assertEquals(-99, square.determinant()); } @Test public void testTranspose() { byte[][] transposedData = {{1, 3, -10, 124}, {2, 4, -11, -123}}; FiniteByteFieldMatrix transposedMatrix = new FiniteByteFieldMatrix(transposedData); assertEquals(transposedMatrix, matrix.transpose()); } @Test public void testCofactorSquareMatrix() { FiniteByteFieldMatrix expectedCofactor = new FiniteByteFieldMatrix(new byte[][]{{29, 77, -1}, {-98, -127, 125}, {-16, -7, -2}}); assertEquals(expectedCofactor, square.cofactor()); } @Test(expected=IllegalStateException.class) public void testCofactorRectangularMatrix() { matrix.cofactor(); } @Test public void testTimes() { byte c = 20; byte[][] times = new byte[][] {{20, 40}, {60, 80}, {12, 48}, {106, -86}}; FiniteByteFieldMatrix expectedResult = new FiniteByteFieldMatrix(times); assertEquals(expectedResult, matrix.times(c)); } @Test(expected=IllegalArgumentException.class) public void testTimesImproperDimensions() { matrix.times(square); } @Test public void testMinor() { byte[][] minorData = new byte[][] {{4, -10}, {124, -123}}; FiniteByteFieldMatrix expectedResult = new FiniteByteFieldMatrix(minorData); assertEquals(expectedResult, square.minor(0, 2)); } @Test(expected=IndexOutOfBoundsException.class) public void testMinorOutOfBoundsRow() { square.minor(3, 2); } @Test(expected=IndexOutOfBoundsException.class) public void testMinorOutOfBoundsCol() { square.minor(0, 3); } @Test(expected=IndexOutOfBoundsException.class) public void testMinorNegativeRow() { square.minor(-1, 2); } @Test(expected=IndexOutOfBoundsException.class) public void testMinorNegativeCol() { square.minor(0, -1); } @Test public void testTimesMatrix() { FiniteByteFieldMatrix m = new FiniteByteFieldMatrix(new byte[][] {{1, 2}, {3, 4}}); FiniteByteFieldMatrix expectedResult = new FiniteByteFieldMatrix(new byte[][] {{7, 10}, {15, 22}, {-14, 14}, {-24, -38}}); assertEquals(expectedResult, matrix.times(m)); } @Test public void testSolve() { FiniteByteFieldMatrix m = new FiniteByteFieldMatrix(new byte[][] {{1, 2}, {3, 4}, {5, 6}}); FiniteByteFieldMatrix result = new FiniteByteFieldMatrix(new byte[][] {{8, 0}, {9, -11}, {-7, -60}}); assertEquals(m, square.solve(result)); assertEquals(result, square.times(m)); } @Test public void testInverse() { assertEquals(FiniteByteFieldMatrix.identity(3), square.times(square.inverse())); assertEquals(FiniteByteFieldMatrix.identity(3), square.inverse().times(square)); } @Test(expected=IllegalStateException.class) public void testInverseRectangularMatrix() { matrix.inverse(); } @Test public void testHashCodeEquals() { EqualsVerifier .forClass(FiniteByteFieldMatrix.class) .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED) .withPrefabValues(FiniteByteFieldMatrix.class, FiniteByteFieldMatrix.identity(1), FiniteByteFieldMatrix.identity(2)) .verify(); } @Test(expected=IllegalArgumentException.class) public void testBuildWithNegativeRowCount() { FiniteByteFieldMatrix.build(-1, 10, (i, j) -> (byte)1); } @Test(expected=IllegalArgumentException.class) public void testBuildWithNegativeColCount() { FiniteByteFieldMatrix.build(10, -1, (i, j) -> (byte)1); } @Test(expected=NullPointerException.class) public void testBuildWithNullFunction() { FiniteByteFieldMatrix.build(10, 10, null); } @Test public void testBuild() { FiniteByteFieldMatrix builtMatrix = FiniteByteFieldMatrix.build(3, 3, (i, j) -> (byte)(i * j)); FiniteByteFieldMatrix expectedMatrix = new FiniteByteFieldMatrix(new byte[][] {{0, 0, 0}, {0, 1, 2}, {0, 2, 4}}); assertEquals(builtMatrix, expectedMatrix); } @Test(expected=NullPointerException.class) public void testColumnVectorNullArray() { FiniteByteFieldMatrix.columnVector(null); } @Test(expected=IllegalArgumentException.class) public void testColumnVectorEmptyArray() { FiniteByteFieldMatrix matrix = FiniteByteFieldMatrix.columnVector(new byte[0]); assertEquals(0, matrix.numRows()); assertEquals(0, matrix.numCols()); } @Test public void testColumnVector() { FiniteByteFieldMatrix matrix = FiniteByteFieldMatrix.columnVector(new byte[] {10, 20, 30, -10}); assertEquals(4, matrix.numRows()); assertEquals(1, matrix.numCols()); } @Test(expected=NullPointerException.class) public void testRowVectorNullArray() { FiniteByteFieldMatrix.rowVector(null); } @Test(expected=IllegalArgumentException.class) public void testRowVectorEmptyArray() { FiniteByteFieldMatrix matrix = FiniteByteFieldMatrix.rowVector(new byte[0]); assertEquals(0, matrix.numRows()); assertEquals(0, matrix.numCols()); } @Test public void testRowVector() { FiniteByteFieldMatrix matrix = FiniteByteFieldMatrix.rowVector(new byte[] {10, 20, 30, -10}); assertEquals(1, matrix.numRows()); assertEquals(4, matrix.numCols()); } @Test public void testGetData() { byte[][] originalData = new byte[][] {{10, 20}, {30, 40}}; byte[][] data = new byte[][] {{10, 20}, {30, 40}}; FiniteByteFieldMatrix matrix = new FiniteByteFieldMatrix(data); // check immutability: matrix.getData()[0][0] = 2; assertArrayEquals(originalData, data); assertArrayEquals(data, matrix.getData()); } @Test public void testGetRow() { byte[][] originalData = new byte[][] {{10, 20}, {30, 40}}; byte[][] data = new byte[][] {{10, 20}, {30, 40}}; FiniteByteFieldMatrix matrix = new FiniteByteFieldMatrix(data); // check immutability: matrix.getRow(0)[0] = 2; assertArrayEquals(originalData[0], data[0]); assertArrayEquals(data[0], matrix.getRow(0)); } @Test public void testGetCol() { byte[][] originalData = new byte[][] {{10, 20}, {30, 40}}; byte[][] data = new byte[][] {{10, 20}, {30, 40}}; FiniteByteFieldMatrix matrix = new FiniteByteFieldMatrix(data); // check immutability: matrix.getCol(0)[0] = 2; assertEquals(originalData[0][0], data[0][0]); assertEquals(originalData[1][0], data[1][0]); assertEquals(data[0][0], matrix.getCol(0)[0]); assertEquals(data[1][0], matrix.getCol(0)[1]); } }
// of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // copies or substantial portions of the Software. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // 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 io.github.jonestimd.swing.window; import java.awt.Component; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.image.ImageProducer; import java.lang.reflect.Field; import java.net.URL; import java.util.ResourceBundle; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import io.github.jonestimd.AsyncTest; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import static java.lang.System.*; import static org.assertj.core.api.Assertions.*; public class StatusFrameTest { private static final String RESOURCE_PREFIX = "StatusFrameTest"; private static final String HEIGHT_RESOURCE = RESOURCE_PREFIX + ".height"; private static final String WIDTH_RESOURCE = RESOURCE_PREFIX + ".width"; private static final String STATE_RESOURCE = RESOURCE_PREFIX + ".state"; private static final Integer RESTORE_WIDTH = 300; private static final Integer RESTORE_HEIGHT = 250; private static final long SWING_TIMEOUT = 500L; private final ResourceBundle bundle = ResourceBundle.getBundle("test-resources"); private StatusFrame frame; @Before public void clearProperties() throws Exception { System.getProperties().remove(STATE_RESOURCE); System.getProperties().remove(WIDTH_RESOURCE); System.getProperties().remove(HEIGHT_RESOURCE); } @After public void disposeFrame() { frame.setVisible(false); frame.dispose(); } private void checkSize(int actual, int expected) { assertThat(actual).isBetween(expected - 10, expected); } @Test public void savesSizeToSystemProperties() throws Exception { createStatusFrame(RESOURCE_PREFIX); SwingUtilities.invokeAndWait(() -> frame.setVisible(true)); Dimension size = frame.getSize(); int state = frame.getExtendedState(); SwingUtilities.invokeAndWait(() -> { frame.setVisible(false); frame.dispose(); }); assertThat(System.getProperty(STATE_RESOURCE)).isEqualTo(Integer.toString(state)); checkSize(Integer.getInteger(WIDTH_RESOURCE), size.width); checkSize(Integer.getInteger(HEIGHT_RESOURCE), size.height); } @Test public void usesDefaultSize() throws Exception { createStatusFrame(RESOURCE_PREFIX + ".defaultSize"); SwingUtilities.invokeAndWait(() -> frame.setVisible(true)); assertThat(frame.getExtendedState()).isEqualTo(0); checkSize(frame.getWidth(), StatusFrame.DEFAULT_WIDTH); checkSize(frame.getHeight(), StatusFrame.DEFAULT_HEIGHT); } @Test public void restoresSizeFromResourceBundle() throws Exception { createStatusFrame(RESOURCE_PREFIX); SwingUtilities.invokeAndWait(() -> frame.setVisible(true)); assertThat(frame.getExtendedState()).isEqualTo(0); checkSize(frame.getWidth(), getInt(WIDTH_RESOURCE)); checkSize(frame.getHeight(), getInt(HEIGHT_RESOURCE)); } private int getInt(String key) { return Integer.parseInt(bundle.getString(key)); } @Test public void restoresSizeFromSystemProperties() throws Exception { System.setProperty(STATE_RESOURCE, "0"); System.setProperty(WIDTH_RESOURCE, RESTORE_WIDTH.toString()); System.setProperty(HEIGHT_RESOURCE, RESTORE_HEIGHT.toString()); createStatusFrame(RESOURCE_PREFIX); SwingUtilities.invokeAndWait(() -> frame.setVisible(true)); assertThat(frame.getExtendedState()).isEqualTo(0); checkSize(frame.getWidth(), RESTORE_WIDTH); checkSize(frame.getHeight(), RESTORE_HEIGHT); } @Test public void ignoresInvalidWidthFromSystemProperties() throws Exception { System.setProperty(STATE_RESOURCE, "0"); System.setProperty(WIDTH_RESOURCE, "-300"); System.setProperty(HEIGHT_RESOURCE, RESTORE_HEIGHT.toString()); createStatusFrame(RESOURCE_PREFIX); SwingUtilities.invokeAndWait(() -> frame.setVisible(true)); assertThat(frame.getExtendedState()).isEqualTo(0); int expectedWidth = getInt(WIDTH_RESOURCE); checkSize(frame.getWidth(), expectedWidth); checkSize(frame.getHeight(), RESTORE_HEIGHT); } @Test public void ignoresInvalidHeightFromSystemProperties() throws Exception { System.setProperty(STATE_RESOURCE, "0"); System.setProperty(WIDTH_RESOURCE, RESTORE_WIDTH.toString()); System.setProperty(HEIGHT_RESOURCE, "-250"); createStatusFrame(RESOURCE_PREFIX); SwingUtilities.invokeAndWait(() -> frame.setVisible(true)); assertThat(frame.getExtendedState()).isEqualTo(0); checkSize(frame.getWidth(), RESTORE_WIDTH); checkSize(frame.getHeight(), getInt(HEIGHT_RESOURCE)); } @Test public void savesMaximizedStateToSystemProperties() throws Exception { createStatusFrame(RESOURCE_PREFIX); SwingUtilities.invokeAndWait(() -> frame.setVisible(true)); Dimension size = frame.getSize(); SwingUtilities.invokeAndWait(() -> frame.setExtendedState(frame.getExtendedState() | JFrame.MAXIMIZED_BOTH)); int state = frame.getExtendedState(); SwingUtilities.invokeAndWait(() -> { frame.setVisible(false); frame.dispose(); }); assertThat(System.getProperty(STATE_RESOURCE)).isEqualTo(Integer.toString(state)); checkSize(Integer.getInteger(WIDTH_RESOURCE), size.width); checkSize(Integer.getInteger(HEIGHT_RESOURCE), size.height); } @Test @Ignore public void restoresMaximizedStateFromSystemProperties() throws Exception { System.setProperty(STATE_RESOURCE, Integer.toString(JFrame.MAXIMIZED_BOTH)); System.setProperty(WIDTH_RESOURCE, RESTORE_WIDTH.toString()); System.setProperty(HEIGHT_RESOURCE, RESTORE_HEIGHT.toString()); createStatusFrame(RESOURCE_PREFIX); SwingUtilities.invokeAndWait(() -> frame.setVisible(true)); AsyncTest.timeout(SWING_TIMEOUT, () -> (frame.getExtendedState() & JFrame.MAXIMIZED_BOTH) == JFrame.MAXIMIZED_BOTH); SwingUtilities.invokeAndWait(() -> frame.setExtendedState(frame.getExtendedState() & ~JFrame.MAXIMIZED_BOTH)); AsyncTest.timeout(SWING_TIMEOUT, () -> Math.abs(frame.getWidth() - RESTORE_WIDTH) < 50 && Math.abs(frame.getHeight() - RESTORE_HEIGHT) < 50); } @Test public void noFocusAfterDisableUI() throws Exception { createStatusFrame(RESOURCE_PREFIX); SwingUtilities.invokeAndWait(() -> frame.setVisible(true)); SwingUtilities.invokeAndWait(() -> frame.disableUI("wait...")); AsyncTest.timeout(SWING_TIMEOUT, frame.getGlassPane()::isFocusOwner); SwingUtilities.invokeAndWait(frame::enableUI); AsyncTest.timeout(SWING_TIMEOUT, () -> !frame.getGlassPane().isFocusOwner()); } @Test public void setsWaitCursorOnGlassPane() throws Exception { createStatusFrame(RESOURCE_PREFIX); assertThat(frame.getGlassPane().getCursor()).isEqualTo(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); } @Test public void noApplicationIcons() throws Exception { frame = new StatusFrame(ResourceBundle.getBundle("test-resources2"), RESOURCE_PREFIX); assertThat(frame.getIconImages()).hasSize(0); } @Test public void setsApplicationIcons() throws Exception { createStatusFrame(RESOURCE_PREFIX); assertThat(frame.getIconImages()).hasSize(2); assertThat(getUrl(frame.getIconImages().get(0).getSource()).getFile()).endsWith("/app-small-icon.png"); assertThat(getUrl(frame.getIconImages().get(1).getSource()).getFile()).endsWith("/app-large-icon.png"); } @Test public void setsFrameIcons() throws Exception { createStatusFrame(RESOURCE_PREFIX + ".icons"); assertThat(frame.getIconImages()).hasSize(2); assertThat(getUrl(frame.getIconImages().get(0).getSource()).getFile()).endsWith("/small-icon.png"); assertThat(getUrl(frame.getIconImages().get(1).getSource()).getFile()).endsWith("/large-icon.png"); } private URL getUrl(ImageProducer source) throws Exception { Field field = source.getClass().getDeclaredField("url"); field.setAccessible(true); return (URL) field.get(source); } @Test public void disableUIBlocksKeyboardInput() throws Exception { TestAction action = createFrameWithMenuBar(); SwingUtilities.invokeAndWait(() -> frame.setVisible(true)); SwingUtilities.invokeAndWait(() -> frame.disableUI("wait...")); // AsyncTest.timeout(SWING_TIMEOUT, frame.getGlassPane()::isFocusOwner); SwingUtilities.invokeAndWait(() -> { KeyEvent event = new KeyEvent(frame.getGlassPane(), KeyEvent.KEY_PRESSED, currentTimeMillis(), KeyEvent.CTRL_DOWN_MASK, KeyEvent.VK_A, KeyEvent.CHAR_UNDEFINED); SwingUtilities.processKeyBindings(event); }); assertThat(action.actionPerformed).isFalse(); } @Test public void disableUIWithNullMessageBlocksKeyboardInput() throws Exception { TestAction action = createFrameWithMenuBar(); SwingUtilities.invokeAndWait(() -> frame.setVisible(true)); SwingUtilities.invokeAndWait(() -> frame.disableUI(null)); // AsyncTest.timeout(SWING_TIMEOUT, frame.getGlassPane()::isFocusOwner); SwingUtilities.invokeAndWait(() -> { KeyEvent event = new KeyEvent(frame.getGlassPane(), KeyEvent.KEY_PRESSED, currentTimeMillis(), KeyEvent.CTRL_DOWN_MASK, KeyEvent.VK_A, KeyEvent.CHAR_UNDEFINED); SwingUtilities.processKeyBindings(event); }); assertThat(action.actionPerformed).isFalse(); } @Test public void disableUIBlocksMouseInput() throws Exception { createFrameWithMenuBar(); SwingUtilities.invokeAndWait(() -> frame.setVisible(true)); SwingUtilities.invokeAndWait(() -> frame.disableUI("wait...")); // AsyncTest.timeout(SWING_TIMEOUT, frame.getGlassPane()::isFocusOwner); SwingUtilities.invokeAndWait(() -> { Point frameLoc = frame.getLocationOnScreen(); Point menuLoc = frame.getJMenuBar().getLocationOnScreen(); Point location = new Point(menuLoc.x - frameLoc.x, menuLoc.y - frameLoc.y); MouseEvent event = new MouseEvent(frame, MouseEvent.MOUSE_PRESSED, currentTimeMillis(), MouseEvent.BUTTON1_DOWN_MASK, location.x, location.y, 1, false, MouseEvent.BUTTON1); frame.dispatchEvent(event); }); assertThat(frame.getJMenuBar().getMenu(0).isPopupMenuVisible()).isFalse(); } private TestAction createFrameWithMenuBar() { createStatusFrame(RESOURCE_PREFIX); TestAction action = new TestAction(); JMenuBar menuBar = new JMenuBar(); JMenu menu = new JMenu("Menu"); menu.add(action); menuBar.add(menu); frame.setJMenuBar(menuBar); return action; } @Test public void enableUIRestoresFocusOwner() throws Exception { JTextField field = new JTextField(); createStatusFrame(RESOURCE_PREFIX, new JTextField(), field); SwingUtilities.invokeLater(() -> { frame.setVisible(true); field.requestFocus(); }); AsyncTest.timeout(SWING_TIMEOUT, field::isFocusOwner); SwingUtilities.invokeAndWait(() -> frame.disableUI("wait...")); AsyncTest.timeout(SWING_TIMEOUT, frame.getGlassPane()::isFocusOwner); SwingUtilities.invokeAndWait(frame::enableUI); AsyncTest.timeout(SWING_TIMEOUT, field::isFocusOwner); } @Test public void setUnsavedChangesAddsIndicatorToTitle() throws Exception { createStatusFrame(RESOURCE_PREFIX); frame.setTitle("Frame title"); frame.setUnsavedChanges(true); assertThat(frame.getTitle()).matches(".* \\*$"); frame.setUnsavedChanges(false); assertThat(frame.getTitle()).doesNotMatch(".* \\*$"); } private void createStatusFrame(String resourcePrefix, Component... fields) { JPanel panel = new JPanel(); for (Component field : fields) { panel.add(field); } frame = new StatusFrame(bundle, resourcePrefix); frame.getContentPane().add(panel); } private static class TestAction extends AbstractAction { private boolean actionPerformed = false; public TestAction() { super("Action"); putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke('A', KeyEvent.CTRL_MASK)); } @Override public void actionPerformed(ActionEvent e) { actionPerformed = true; } } }
package jdbm.recman; import java.io.IOException; import java.io.OutputStream; /** * This class manages physical row ids, and their data. */ final class PhysicalRowIdManager { // The file we're talking to and the associated page manager. final private RecordFile file; final private PageManager pageman; final private FreePhysicalRowIdPageManager freeman; final private int BLOCK_SIZE; final short DATA_PER_PAGE ; /** * Creates a new rowid manager using the indicated record file. and page manager. */ PhysicalRowIdManager(RecordFile file, PageManager pageManager, FreePhysicalRowIdPageManager freeman) throws IOException { this.file = file; this.pageman = pageManager; this.freeman = freeman; this.BLOCK_SIZE = file.BLOCK_SIZE; DATA_PER_PAGE = (short) (BLOCK_SIZE - DataPage.O_DATA); } /** * Inserts a new record. Returns the new physical rowid. */ long insert(byte[] data, int start, int length) throws IOException { if (length < 1) throw new IllegalArgumentException("Lenght is <1"); if (start < 0) throw new IllegalArgumentException("negative start"); long retval = alloc(length); write(retval, data, start, length); return retval; } /** * Updates an existing record. Returns the possibly changed physical rowid. */ long update(long rowid, byte[] data, int start, int length) throws IOException { // fetch the record header BlockIo block = file.get(Location.getBlock(rowid)); short head = Location.getOffset(rowid); int availSize = RecordHeader.getAvailableSize(block, head); if (length > availSize || //difference between free and available space can be only 64KB. //if bigger, need to realocate and free block availSize - length > RecordHeader.MAX_SIZE_SPACE ) { // not enough space - we need to copy to a new rowid. file.release(block); free(rowid); rowid = alloc(length); } else { file.release(block); } // 'nuff space, write it in and return the rowid. write(rowid, data, start, length); return rowid; } /** * Deletes a record. */ void delete(long rowid) throws IOException { free(rowid); } /** * Retrieves a record. */ // byte[] fetch( Location rowid ) // throws IOException // // fetch the record header // PageCursor curs = new PageCursor( pageman, rowid.getBlock() ); // BlockIo block = file.get( curs.getCurrent() ); // RecordHeader head = new RecordHeader( block, rowid.getOffset() ); // // allocate a return buffer // byte[] retval = new byte[ head.getCurrentSize() ]; // if ( retval.length == 0 ) { // file.release( curs.getCurrent(), false ); // return retval; // // copy bytes in // int offsetInBuffer = 0; // int leftToRead = retval.length; // short dataOffset = (short) (rowid.getOffset() + RecordHeader.SIZE); // while ( leftToRead > 0 ) { // // copy current page's data to return buffer // int toCopy = RecordFile.BLOCK_SIZE - dataOffset; // if ( leftToRead < toCopy ) { // toCopy = leftToRead; // System.arraycopy( block.getData(), dataOffset, // retval, offsetInBuffer, // toCopy ); // // Go to the next block // leftToRead -= toCopy; // offsetInBuffer += toCopy; // file.release( block ); // if ( leftToRead > 0 ) { // block = file.get( curs.next() ); // dataOffset = DataPage.O_DATA; // return retval; void fetch(OutputStream out, long rowid) throws IOException { // fetch the record header PageCursor curs = new PageCursor(pageman, Location.getBlock(rowid)); BlockIo block = file.get(curs.getCurrent()); short head = Location.getOffset(rowid); // allocate a return buffer // byte[] retval = new byte[ head.getCurrentSize() ]; final int size = RecordHeader.getCurrentSize(block,head); if (size == 0) { file.release(curs.getCurrent(), false); return; } // copy bytes in int offsetInBuffer = 0; int leftToRead = size; short dataOffset = (short) (Location.getOffset(rowid) + RecordHeader.SIZE); while (leftToRead > 0) { // copy current page's data to return buffer int toCopy = BLOCK_SIZE - dataOffset; if (leftToRead < toCopy) { toCopy = leftToRead; } byte[] blockData = block.getData(); int finish = dataOffset + toCopy; out.write(blockData, dataOffset, finish - dataOffset); // Go to the next block leftToRead -= toCopy; offsetInBuffer += toCopy; // out.flush(); file.release(block); if (leftToRead > 0) { block = file.get(curs.next()); dataOffset = DataPage.O_DATA; } } // return retval; } /** * Allocate a new rowid with the indicated size. */ private long alloc(int size) throws IOException { size = RecordHeader.roundAvailableSize(size); long retval = freeman.get(size); if (retval == 0) { retval = allocNew(size, pageman.getLast(Magic.USED_PAGE)); } return retval; } /** * Allocates a new rowid. The second parameter is there to allow for a recursive call - it indicates where the * search should start. */ private long allocNew(int size, long start) throws IOException { BlockIo curBlock; DataPage curPage; if (start == 0) { // we need to create a new page. start = pageman.allocate(Magic.USED_PAGE); curBlock = file.get(start); curPage = DataPage.getDataPageView(curBlock,BLOCK_SIZE); curPage.setFirst(DataPage.O_DATA); RecordHeader.setAvailableSize(curBlock, DataPage.O_DATA, 0); RecordHeader.setCurrentSize(curBlock, DataPage.O_DATA, 0); } else { curBlock = file.get(start); curPage = DataPage.getDataPageView(curBlock,BLOCK_SIZE); } // follow the rowids on this page to get to the last one. We don't // fall off, because this is the last page, remember? short pos = curPage.getFirst(); if (pos == 0) { // page is exactly filled by the last block of a record file.release(curBlock); return allocNew(size, 0); } short hdr = pos; int availSize = RecordHeader.getAvailableSize(curBlock, hdr); while (availSize != 0 && pos < BLOCK_SIZE) { pos += availSize + RecordHeader.SIZE; if (pos == BLOCK_SIZE) { // Again, a filled page. file.release(curBlock); return allocNew(size, 0); } hdr = pos; availSize = RecordHeader.getAvailableSize(curBlock, hdr); } if (pos == RecordHeader.SIZE) { // the last record exactly filled the page. Restart forcing // a new page. file.release(curBlock); } // we have the position, now tack on extra pages until we've got // enough space. long retval = Location.toLong(start, pos); int freeHere = BLOCK_SIZE - pos - RecordHeader.SIZE; if (freeHere < size) { // check whether the last page would have only a small bit left. // if yes, increase the allocation. A small bit is a record // header plus 16 bytes. int lastSize = (size - freeHere) % DATA_PER_PAGE; if ((DATA_PER_PAGE - lastSize) < (RecordHeader.SIZE + 16)) { size += (DATA_PER_PAGE - lastSize); size = RecordHeader.roundAvailableSize(size); } // write out the header now so we don't have to come back. RecordHeader.setAvailableSize(curBlock, hdr, size); file.release(start, true); int neededLeft = size - freeHere; // Refactor these two blocks! while (neededLeft >= DATA_PER_PAGE) { start = pageman.allocate(Magic.USED_PAGE); curBlock = file.get(start); curPage = DataPage.getDataPageView(curBlock, BLOCK_SIZE); curPage.setFirst((short) 0); // no rowids, just data file.release(start, true); neededLeft -= DATA_PER_PAGE; } if (neededLeft > 0) { // done with whole chunks, allocate last fragment. start = pageman.allocate(Magic.USED_PAGE); curBlock = file.get(start); curPage = DataPage.getDataPageView(curBlock, BLOCK_SIZE); curPage.setFirst((short) (DataPage.O_DATA + neededLeft)); file.release(start, true); } } else { // just update the current page. If there's less than 16 bytes // left, we increase the allocation (16 bytes is an arbitrary // number). if (freeHere - size <= (16 + RecordHeader.SIZE)) { size = freeHere; } RecordHeader.setAvailableSize(curBlock, hdr, size); file.release(start, true); } return retval; } private void free(long id) throws IOException { // get the rowid, and write a zero current size into it. BlockIo curBlock = file.get(Location.getBlock(id)); DataPage curPage = DataPage.getDataPageView(curBlock,BLOCK_SIZE); RecordHeader.setCurrentSize(curBlock, Location.getOffset(id), 0); file.release(Location.getBlock(id), true); // write the rowid to the free list freeman.put(id, RecordHeader.getAvailableSize(curBlock, Location.getOffset(id))); } /** * Writes out data to a rowid. Assumes that any resizing has been done. */ private void write(long rowid, byte[] data, int start, int length) throws IOException { PageCursor curs = new PageCursor(pageman, Location.getBlock(rowid)); BlockIo block = file.get(curs.getCurrent()); short hdr = Location.getOffset(rowid); RecordHeader.setCurrentSize(block, hdr, length); if (length == 0) { file.release(curs.getCurrent(), true); return; } // copy bytes in int offsetInBuffer = start; int leftToWrite = length; short dataOffset = (short) (Location.getOffset(rowid) + RecordHeader.SIZE); while (leftToWrite > 0) { // copy current page's data to return buffer int toCopy = BLOCK_SIZE - dataOffset; if (leftToWrite < toCopy) { toCopy = leftToWrite; } System.arraycopy(data, offsetInBuffer, block.getData(), dataOffset, toCopy); // Go to the next block leftToWrite -= toCopy; offsetInBuffer += toCopy; file.release(curs.getCurrent(), true); if (leftToWrite > 0) { block = file.get(curs.next()); dataOffset = DataPage.O_DATA; } } } void commit() throws IOException { freeman.commit(); } }
package test; import java.util.List; import main.java.riotapi.RiotAPI; import dto.*; import org.junit.*; public class TeamRequestTest { private RiotAPI api; @Before public void setup() { System.out.println("\nTest starting..."); api = new RiotAPI("YOUR-API-KEY"); } @After public void teardown() { System.out.println("\nTest finished."); } @Test public void testGetTeamsValidRegionValidID() { List<Team> teams = api.getTeams("na", 20714655); Assert.assertNotNull(teams); } @Test public void testGetTeamsValidRegionInvalidID() { List<Team> teams = api.getTeams("na", 9999999); Assert.assertNull(teams); } @Test public void testGetTeamsInvalidRegionValidID() { List<Team> teams = api.getTeams("oc", 20714655); Assert.assertNull(teams); } @Test public void testGetTeamValidSetRegionValidID() { api.setRegion("na"); List<Team> teams = api.getTeams(20714655); Assert.assertNotNull(teams); } @Test public void testGetTeamInvalidSetRegionValidID() { api.setRegion("oc"); List<Team> teams = api.getTeams(20714655); Assert.assertNull(teams); } @Test public void testGetTeamValidSetRegionInvalidID() { api.setRegion("na"); List<Team> teams = api.getTeams(99999999); Assert.assertNull(teams); } }
package StevenDimDoors.mod_pocketDim.helpers; import java.io.File; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Random; import java.util.regex.Pattern; import net.minecraft.block.Block; import net.minecraft.block.BlockContainer; import net.minecraft.util.WeightedRandom; import net.minecraft.world.World; import StevenDimDoors.mod_pocketDim.DDProperties; import StevenDimDoors.mod_pocketDim.DungeonGenerator; import StevenDimDoors.mod_pocketDim.LinkData; import StevenDimDoors.mod_pocketDim.mod_pocketDim; import StevenDimDoors.mod_pocketDim.helpers.jnbt.ByteArrayTag; import StevenDimDoors.mod_pocketDim.helpers.jnbt.CompoundTag; import StevenDimDoors.mod_pocketDim.helpers.jnbt.ListTag; import StevenDimDoors.mod_pocketDim.helpers.jnbt.NBTOutputStream; import StevenDimDoors.mod_pocketDim.helpers.jnbt.ShortTag; import StevenDimDoors.mod_pocketDim.helpers.jnbt.Tag; import StevenDimDoors.mod_pocketDim.items.itemDimDoor; import StevenDimDoors.mod_pocketDim.util.WeightedContainer; public class DungeonHelper { private static DungeonHelper instance = null; private static DDProperties properties = null; public static final Pattern NamePattern = Pattern.compile("[A-Za-z0-9_]+"); private static final String SCHEMATIC_FILE_EXTENSION = ".schematic"; private static final int DEFAULT_DUNGEON_WEIGHT = 100; private static final int MAX_DUNGEON_WEIGHT = 10000; //Used to prevent overflows and math breaking down private static final String HUB_DUNGEON_TYPE = "Hub"; private static final String TRAP_DUNGEON_TYPE = "Trap"; private static final String SIMPLE_HALL_DUNGEON_TYPE = "SimpleHall"; private static final String COMPLEX_HALL_DUNGEON_TYPE = "ComplexHall"; private static final String EXIT_DUNGEON_TYPE = "Exit"; private static final String DEAD_END_DUNGEON_TYPE = "DeadEnd"; private static final String MAZE_DUNGEON_TYPE = "Maze"; //The list of dungeon types will be kept as an array for now. If we allow new //dungeon types in the future, then this can be changed to an ArrayList. private static final String[] DUNGEON_TYPES = new String[] { HUB_DUNGEON_TYPE, TRAP_DUNGEON_TYPE, SIMPLE_HALL_DUNGEON_TYPE, COMPLEX_HALL_DUNGEON_TYPE, EXIT_DUNGEON_TYPE, DEAD_END_DUNGEON_TYPE, MAZE_DUNGEON_TYPE }; private Random rand = new Random(); private HashMap<Integer, LinkData> customDungeonStatus = new HashMap<Integer, LinkData>(); public ArrayList<DungeonGenerator> customDungeons = new ArrayList<DungeonGenerator>(); public ArrayList<DungeonGenerator> registeredDungeons = new ArrayList<DungeonGenerator>(); private ArrayList<DungeonGenerator> simpleHalls = new ArrayList<DungeonGenerator>(); private ArrayList<DungeonGenerator> complexHalls = new ArrayList<DungeonGenerator>(); private ArrayList<DungeonGenerator> deadEnds = new ArrayList<DungeonGenerator>(); private ArrayList<DungeonGenerator> hubs = new ArrayList<DungeonGenerator>(); private ArrayList<DungeonGenerator> mazes = new ArrayList<DungeonGenerator>(); private ArrayList<DungeonGenerator> pistonTraps = new ArrayList<DungeonGenerator>(); private ArrayList<DungeonGenerator> exits = new ArrayList<DungeonGenerator>(); public ArrayList<Integer> metadataFlipList = new ArrayList<Integer>(); public ArrayList<Integer> metadataNextList = new ArrayList<Integer>(); public DungeonGenerator defaultBreak = new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/somethingBroke.schematic", true); public DungeonGenerator defaultUp = new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/simpleStairsUp.schematic", true); private HashSet<String> dungeonTypeChecker; private HashMap<String, ArrayList<DungeonGenerator>> dungeonTypeMapping; private DungeonHelper() { //Load the dungeon type checker with the list of all types in lowercase. //Capitalization matters for matching in a hash set. dungeonTypeChecker = new HashSet<String>(); for (String dungeonType : DUNGEON_TYPES) { dungeonTypeChecker.add(dungeonType.toLowerCase()); } //Add all the basic dungeon types to dungeonTypeMapping //Dungeon type names must be passed in lowercase to make matching easier. dungeonTypeMapping = new HashMap<String, ArrayList<DungeonGenerator>>(); dungeonTypeMapping.put(SIMPLE_HALL_DUNGEON_TYPE.toLowerCase(), simpleHalls); dungeonTypeMapping.put(COMPLEX_HALL_DUNGEON_TYPE.toLowerCase(), complexHalls); dungeonTypeMapping.put(HUB_DUNGEON_TYPE.toLowerCase(), hubs); dungeonTypeMapping.put(EXIT_DUNGEON_TYPE.toLowerCase(), exits); dungeonTypeMapping.put(DEAD_END_DUNGEON_TYPE.toLowerCase(), deadEnds); dungeonTypeMapping.put(MAZE_DUNGEON_TYPE.toLowerCase(), mazes); dungeonTypeMapping.put(TRAP_DUNGEON_TYPE.toLowerCase(), pistonTraps); //Load our reference to the DDProperties singleton if (properties == null) properties = DDProperties.instance(); registerCustomDungeons(); } private void registerCustomDungeons() { File file = new File(properties.CustomSchematicDirectory); if (file.exists() || file.mkdir()) { copyfile.copyFile("/mods/DimDoors/text/How_to_add_dungeons.txt", file.getAbsolutePath() + "/How_to_add_dungeons.txt"); } registerFlipBlocks(); importCustomDungeons(properties.CustomSchematicDirectory); registerBaseDungeons(); } public static DungeonHelper initialize() { if (instance == null) { instance = new DungeonHelper(); } else { throw new IllegalStateException("Cannot initialize DungeonHelper twice"); } return instance; } public static DungeonHelper instance() { if (instance == null) { //This is to prevent some frustrating bugs that could arise when classes //are loaded in the wrong order. Trust me, I had to squash a few... throw new IllegalStateException("Instance of DungeonHelper requested before initialization"); } return instance; } public LinkData createCustomDungeonDoor(World world, int x, int y, int z) { //Create a link above the specified position. Link to a new pocket dimension. LinkData link = new LinkData(world.provider.dimensionId, 0, x, y + 1, z, x, y + 1, z, true, 3); link = dimHelper.instance.createPocket(link, true, false); //Place a Warp Door linked to that pocket itemDimDoor.placeDoorBlock(world, x, y, z, 3, mod_pocketDim.ExitDoor); //Register the pocket as a custom dungeon customDungeonStatus.put(link.destDimID, dimHelper.instance.getLinkDataFromCoords(link.destXCoord, link.destYCoord, link.destZCoord, link.destDimID)); return link; } public boolean isCustomDungeon(int dimensionID) { return customDungeonStatus.containsKey(dimensionID); } public boolean validateSchematicName(String name) { String[] dungeonData; if (!name.endsWith(SCHEMATIC_FILE_EXTENSION)) return false; dungeonData = name.substring(0, name.length() - SCHEMATIC_FILE_EXTENSION.length()).split("_"); //Check for a valid number of parts if (dungeonData.length < 3 || dungeonData.length > 4) return false; //Check if the dungeon type is valid if (!dungeonTypeChecker.contains(dungeonData[0].toLowerCase())) return false; //Check if the name is valid if (!NamePattern.matcher(dungeonData[1]).matches()) return false; //Check if the open/closed flag is present if (!dungeonData[2].equalsIgnoreCase("open") && !dungeonData[2].equalsIgnoreCase("closed")) return false; //If the weight is present, check that it is valid if (dungeonData.length == 4) { try { int weight = Integer.parseInt(dungeonData[3]); if (weight < 0 || weight > MAX_DUNGEON_WEIGHT) return false; } catch (NumberFormatException e) { //Not a number return false; } } return true; } public void registerCustomDungeon(File schematicFile) { String name = schematicFile.getName(); String path = schematicFile.getAbsolutePath(); try { if (validateSchematicName(name)) { //Strip off the file extension while splitting the file name String[] dungeonData = name.substring(0, name.length() - SCHEMATIC_FILE_EXTENSION.length()).split("_"); String dungeonType = dungeonData[0].toLowerCase(); boolean isOpen = dungeonData[2].equalsIgnoreCase("open"); int weight = (dungeonData.length == 4) ? Integer.parseInt(dungeonData[3]) : DEFAULT_DUNGEON_WEIGHT; //Add this custom dungeon to the list corresponding to its type DungeonGenerator generator = new DungeonGenerator(weight, path, isOpen); dungeonTypeMapping.get(dungeonType).add(generator); registeredDungeons.add(generator); customDungeons.add(generator); System.out.println("Imported " + name); } else { System.out.println("Could not parse dungeon filename, not adding dungeon to generation lists"); customDungeons.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, path, true)); System.out.println("Imported " + name); } } catch(Exception e) { e.printStackTrace(); System.out.println("Failed to import " + name); } } public void importCustomDungeons(String path) { File directory = new File(path); File[] schematicNames = directory.listFiles(); if (schematicNames != null) { for (File schematicFile: schematicNames) { if (schematicFile.getName().endsWith(SCHEMATIC_FILE_EXTENSION)) { registerCustomDungeon(schematicFile); } } } } public void registerFlipBlocks() { metadataFlipList.add(Block.dispenser.blockID); metadataFlipList.add(Block.stairsStoneBrick.blockID); metadataFlipList.add(Block.lever.blockID); metadataFlipList.add(Block.stoneButton.blockID); metadataFlipList.add(Block.redstoneRepeaterIdle.blockID); metadataFlipList.add(Block.redstoneRepeaterActive.blockID); metadataFlipList.add(Block.tripWireSource.blockID); metadataFlipList.add(Block.torchWood.blockID); metadataFlipList.add(Block.torchRedstoneIdle.blockID); metadataFlipList.add(Block.torchRedstoneActive.blockID); metadataFlipList.add(Block.doorIron.blockID); metadataFlipList.add(Block.doorWood.blockID); metadataFlipList.add(Block.pistonBase.blockID); metadataFlipList.add(Block.pistonStickyBase.blockID); metadataFlipList.add(Block.pistonExtension.blockID); metadataFlipList.add(Block.redstoneComparatorIdle.blockID); metadataFlipList.add(Block.redstoneComparatorActive.blockID); metadataFlipList.add(Block.signPost.blockID); metadataFlipList.add(Block.signWall.blockID); metadataFlipList.add(Block.skull.blockID); metadataFlipList.add(Block.ladder.blockID); metadataFlipList.add(Block.vine.blockID); metadataFlipList.add(Block.anvil.blockID); metadataFlipList.add(Block.chest.blockID); metadataFlipList.add(Block.chestTrapped.blockID); metadataFlipList.add(Block.hopperBlock.blockID); metadataFlipList.add(Block.stairsNetherBrick.blockID); metadataFlipList.add(Block.stairsCobblestone.blockID); metadataFlipList.add(Block.stairsNetherBrick.blockID); metadataFlipList.add(Block.stairsNetherQuartz.blockID); metadataFlipList.add(Block.stairsSandStone.blockID); metadataNextList.add(Block.redstoneRepeaterIdle.blockID); metadataNextList.add(Block.redstoneRepeaterActive.blockID); } public void registerBaseDungeons() { hubs.add(new DungeonGenerator(2 * DEFAULT_DUNGEON_WEIGHT, "/schematics/4WayBasicHall.schematic", false)); hubs.add(new DungeonGenerator(2 * DEFAULT_DUNGEON_WEIGHT, "/schematics/4WayHallExit.schematic", false)); hubs.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/doorTotemRuins.schematic", true)); hubs.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/hallwayTrapRooms1.schematic", false)); hubs.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/longDoorHallway.schematic", false)); hubs.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/smallRotundaWithExit.schematic", false)); hubs.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/fortRuins.schematic", true)); simpleHalls.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/collapsedSingleTunnel1.schematic", false)); simpleHalls.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/singleStraightHall1.schematic", false)); simpleHalls.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/smallBranchWithExit.schematic", false)); simpleHalls.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/smallSimpleLeft.schematic", false)); simpleHalls.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/smallSimpleRight.schematic", false)); simpleHalls.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/simpleStairsUp.schematic", false)); simpleHalls.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/simpleStairsDown.schematic", false)); simpleHalls.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/simpleSmallT1.schematic", false)); complexHalls.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/tntPuzzleTrap.schematic", false)); complexHalls.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/brokenPillarsO.schematic", true)); complexHalls.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/buggyTopEntry1.schematic", true)); complexHalls.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/exitRuinsWithHiddenDoor.schematic", true)); complexHalls.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/hallwayHiddenTreasure.schematic", false)); complexHalls.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/mediumPillarStairs.schematic", true)); complexHalls.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/ruinsO.schematic", true)); complexHalls.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/pitStairs.schematic", true)); deadEnds.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/azersDungeonO.schematic", false)); deadEnds.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/diamondTowerTemple1.schematic", true)); deadEnds.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/fallingTrapO.schematic", false)); deadEnds.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/hiddenStaircaseO.schematic", true)); deadEnds.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/lavaTrapO.schematic", true)); deadEnds.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/randomTree.schematic", true)); deadEnds.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/smallHiddenTowerO.schematic", true)); deadEnds.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/smallSilverfishRoom.schematic", false)); deadEnds.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/tntTrapO.schematic", true)); deadEnds.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/smallDesert.schematic", true)); deadEnds.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/smallPond.schematic", true)); pistonTraps.add(new DungeonGenerator(2 * DEFAULT_DUNGEON_WEIGHT, "/schematics/hallwayPitFallTrap.schematic", false)); pistonTraps.add(new DungeonGenerator(2 * DEFAULT_DUNGEON_WEIGHT, "/schematics/pistonFloorHall.schematic", false)); pistonTraps.add(new DungeonGenerator(2 * DEFAULT_DUNGEON_WEIGHT, "/schematics/wallFallcomboPistonHall.schematic", false)); pistonTraps.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/fakeTNTTrap.schematic", false)); pistonTraps.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/pistonFallRuins.schematic", false)); pistonTraps.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/pistonSmasherHall.schematic", false)); pistonTraps.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/simpleDropHall.schematic", false)); pistonTraps.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/fallingTNThall.schematic", false)); pistonTraps.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/lavaPyramid.schematic", true)); mazes.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/smallMaze1.schematic", false)); mazes.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/smallMultilevelMaze.schematic", false)); exits.add(new DungeonGenerator(2 * DEFAULT_DUNGEON_WEIGHT, "/schematics/lockingExitHall.schematic", false)); exits.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/exitCube.schematic", true)); exits.add(new DungeonGenerator(DEFAULT_DUNGEON_WEIGHT, "/schematics/smallExitPrison.schematic", true)); registeredDungeons.addAll(simpleHalls); registeredDungeons.addAll(exits); registeredDungeons.addAll(pistonTraps); registeredDungeons.addAll(mazes); registeredDungeons.addAll(deadEnds); registeredDungeons.addAll(complexHalls); registeredDungeons.addAll(hubs); } public boolean exportDungeon(World world, int xI, int yI, int zI, String exportPath) { int xMin; int yMin; int zMin; int xMax; int yMax; int zMax; xMin=xMax=xI; yMin=yMax=yI; zMin=zMax=zI; for (int count = 0; count < 50; count++) { if(world.getBlockId(xMin, yI, zI)!=properties.PermaFabricBlockID) { xMin } if(world.getBlockId(xI, yMin, zI)!=properties.PermaFabricBlockID) { yMin } if(world.getBlockId(xI, yI, zMin)!=properties.PermaFabricBlockID) { zMin } if(world.getBlockId(xMax, yI, zI)!=properties.PermaFabricBlockID) { xMax++; } if(world.getBlockId(xI, yMax, zI)!=properties.PermaFabricBlockID) { yMax++; } if(world.getBlockId(xI, yI, zMax)!=properties.PermaFabricBlockID) { zMax++; } } short width =(short) (xMax-xMin); short height= (short) (yMax-yMin); short length= (short) (zMax-zMin); //ArrayList<NBTTagCompound> tileEntities = new ArrayList<NBTTagCompound>(); ArrayList<Tag> tileEntites = new ArrayList<Tag>(); byte[] blocks = new byte[width * height * length]; byte[] addBlocks = null; byte[] blockData = new byte[width * height * length]; for (int x = 0; x < width; ++x) { for (int y = 0; y < height; ++y) { for (int z = 0; z < length; ++z) { int index = y * width * length + z * width + x; int blockID = world.getBlockId(x+xMin, y+yMin, z+zMin); int meta= world.getBlockMetadata(x+xMin, y+yMin, z+zMin); if(blockID==properties.DimensionalDoorID) { blockID=Block.doorIron.blockID; } if(blockID==properties.WarpDoorID) { blockID=Block.doorWood.blockID; } // Save 4096 IDs in an AddBlocks section if (blockID > 255) { if (addBlocks == null) { // Lazily create section addBlocks = new byte[(blocks.length >> 1) + 1]; } addBlocks[index >> 1] = (byte) (((index & 1) == 0) ? addBlocks[index >> 1] & 0xF0 | (blockID >> 8) & 0xF : addBlocks[index >> 1] & 0xF | ((blockID >> 8) & 0xF) << 4); } blocks[index] = (byte) blockID; blockData[index] = (byte) meta; if (Block.blocksList[blockID] instanceof BlockContainer) { //TODO fix this /** TileEntity tileEntityBlock = world.getBlockTileEntity(x+xMin, y+yMin, z+zMin); NBTTagCompound tag = new NBTTagCompound(); tileEntityBlock.writeToNBT(tag); CompoundTag tagC = new CompoundTag("TileEntity",Map.class.cast(tag.getTags())); // Get the list of key/values from the block if (tagC != null) { tileEntites.add(tagC); } **/ } } } } /** * * nbtdata.setShort("Width", width); nbtdata.setShort("Height", height); nbtdata.setShort("Length", length); nbtdata.setByteArray("Blocks", blocks); nbtdata.setByteArray("Data", blockData); */ HashMap<String, Tag> schematic = new HashMap<String, Tag>(); schematic.put("Blocks", new ByteArrayTag("Blocks", blocks)); schematic.put("Data", new ByteArrayTag("Data", blockData)); schematic.put("Width", new ShortTag("Width", (short) width)); schematic.put("Length", new ShortTag("Length", (short) length)); schematic.put("Height", new ShortTag("Height", (short) height)); schematic.put("TileEntites", new ListTag("TileEntities", CompoundTag.class,tileEntites)); if (addBlocks != null) { schematic.put("AddBlocks", new ByteArrayTag("AddBlocks", addBlocks)); } CompoundTag schematicTag = new CompoundTag("Schematic", schematic); try { NBTOutputStream stream = new NBTOutputStream(new FileOutputStream(exportPath)); stream.writeTag(schematicTag); stream.close(); return true; } catch(Exception e) { e.printStackTrace(); return false; } } public void generateDungeonLink(LinkData incoming) { DungeonGenerator dungeon; int depth = dimHelper.instance.getDimDepth(incoming.locDimID); int depthWeight = rand.nextInt(depth + 2) + rand.nextInt(depth + 2) - 2; int count = 10; boolean flag = true; try { if (incoming.destYCoord > 15) { do { count flag = true; //Select a dungeon at random, taking into account its weight dungeon = getRandomDungeon(rand, registeredDungeons); if (depth <= 1) { if(rand.nextBoolean()) { dungeon = complexHalls.get(rand.nextInt(complexHalls.size())); } else if(rand.nextBoolean()) { dungeon = hubs.get(rand.nextInt(hubs.size())); } else if(rand.nextBoolean()) { dungeon = hubs.get(rand.nextInt(hubs.size())); } else if(deadEnds.contains(dungeon)||exits.contains(dungeon)) { flag=false; } } else if (depth <= 3 && (deadEnds.contains(dungeon) || exits.contains(dungeon) || rand.nextBoolean())) { if(rand.nextBoolean()) { dungeon = hubs.get(rand.nextInt(hubs.size())); } else if(rand.nextBoolean()) { dungeon = mazes.get(rand.nextInt(mazes.size())); } else if(rand.nextBoolean()) { dungeon = pistonTraps.get(rand.nextInt(pistonTraps.size())); } else { flag = false; } } else if (rand.nextInt(3) == 0 && !complexHalls.contains(dungeon)) { if (rand.nextInt(3) == 0) { dungeon = simpleHalls.get(rand.nextInt(simpleHalls.size())); } else if(rand.nextBoolean()) { dungeon = pistonTraps.get(rand.nextInt(pistonTraps.size())); } else if (depth < 4) { dungeon = hubs.get(rand.nextInt(hubs.size())); } } else if (depthWeight - depthWeight / 2 > depth -4 && (deadEnds.contains(dungeon) || exits.contains(dungeon))) { if(rand.nextBoolean()) { dungeon = simpleHalls.get(rand.nextInt(simpleHalls.size())); } else if(rand.nextBoolean()) { dungeon = complexHalls.get(rand.nextInt(complexHalls.size())); } else if(rand.nextBoolean()) { dungeon = pistonTraps.get(rand.nextInt(pistonTraps.size())); } else { flag = false; } } else if (depthWeight > 7 && hubs.contains(dungeon)) { if(rand.nextInt(12)+5<depthWeight) { if(rand.nextBoolean()) { dungeon = exits.get(rand.nextInt(exits.size())); } else if(rand.nextBoolean()) { dungeon = deadEnds.get(rand.nextInt(deadEnds.size())); } else { dungeon = pistonTraps.get(rand.nextInt(pistonTraps.size())); } } else { flag = false; } } else if (depth > 10 && hubs.contains(dungeon)) { flag = false; } } while (!flag && count > 0); } else { dungeon = defaultUp; } } catch (Exception e) { e.printStackTrace(); if (registeredDungeons.size() > 0) { //Select a random dungeon dungeon = getRandomDungeon(rand, registeredDungeons); } else { return; } } dimHelper.dimList.get(incoming.destDimID).dungeonGenerator = dungeon; } public Collection<String> getDungeonNames() { //Use a HashSet to guarantee that all dungeon names will be distinct. //This shouldn't be necessary if we keep proper lists without repetitions, //but it's a fool-proof workaround. HashSet<String> dungeonNames = new HashSet<String>(); dungeonNames.addAll( parseDungeonNames(registeredDungeons) ); dungeonNames.addAll( parseDungeonNames(customDungeons) ); //Sort dungeon names alphabetically ArrayList<String> sortedNames = new ArrayList<String>(dungeonNames); Collections.sort(sortedNames); return sortedNames; } private static ArrayList<String> parseDungeonNames(ArrayList<DungeonGenerator> dungeons) { String name; File schematic; ArrayList<String> names = new ArrayList<String>(dungeons.size()); for (DungeonGenerator dungeon : dungeons) { //Retrieve the file name and strip off the file extension schematic = new File(dungeon.schematicPath); name = schematic.getName(); name = name.substring(0, name.length() - SCHEMATIC_FILE_EXTENSION.length()); names.add(name); } return names; } private static DungeonGenerator getRandomDungeon(Random random, Collection<DungeonGenerator> dungeons) { //Use Minecraft's WeightedRandom to select our dungeon. =D ArrayList<WeightedContainer<DungeonGenerator>> weights = new ArrayList<WeightedContainer<DungeonGenerator>>(dungeons.size()); for (DungeonGenerator dungeon : dungeons) { weights.add(new WeightedContainer<DungeonGenerator>(dungeon, dungeon.weight)); } @SuppressWarnings("unchecked") WeightedContainer<DungeonGenerator> resultContainer = (WeightedContainer<DungeonGenerator>) WeightedRandom.getRandomItem(random, weights); return (resultContainer != null) ? resultContainer.getData() : null; } }
package ca.uwaterloo.joos; import java.util.*; import java.io.*; public class Scanner { private DFA dfa = null; @SuppressWarnings("serial") public class ScanException extends Exception { public ScanException(String string) { super(string); } } public Scanner(DFA dfa) { this.dfa = dfa; } /** * Turn a string into a list of tokens * @param inStr The input string * @return A list of Token * @throws ScanException */ public List<Token> stringToTokens(final String inStr) throws ScanException { List<Token> tokens = new ArrayList<Token>(); char[] inChars = inStr.toCharArray(); for(int i = 0, n = inStr.length(); i < n; i = extractToken(inChars, i, n, tokens)); return tokens; } /** * Turn an input file into a list of tokens * @param inputFile The input file * @return A list of Token * @throws ScanException * @throws IOException The input file is unreadable */ public List<Token> fileToTokens(File inputFile) throws ScanException, IOException { FileInputStream inputStream = new FileInputStream(inputFile); int inLen = inputStream.available(); byte inBytes[] = new byte[inLen + 1]; inputStream.read(inBytes); inputStream.close(); inBytes[inLen] = '\n'; String inStr = new String(inBytes); return this.stringToTokens(inStr); } /** * Extract a token from the string into the tokens list * Note: it will skip all leading whitespace * @param inChars Raw input char array * @param begin The beginning index * @param end The ending index * @param tokens Where new token will be export to * @return The ending index for the extracted token * @throws ScanException */ private int extractToken(final char[] inChars, int begin, int end, List<Token> tokens) throws ScanException { String state = this.dfa.getStartingState(); String lexeme = ""; // Go through each char, from begin for(; begin < end; begin++) { String inChar = String.valueOf(inChars[begin]); // Skip white spaces if(lexeme.length() == 0 && this.isWhitespace(inChar)) { continue; } // Find next state String next = this.dfa.nextStateFor(state, inChar); // If don't have next state, and if(next == null){ // is on an accepting state, export token and break if(this.dfa.isAcceptingState(state)){ String transformedKind = this.dfa.getTokenKindTransformation(lexeme); Token token = new Token(transformedKind == null ? state : transformedKind, lexeme); tokens.add(token); Main.getLogger().info("Token added: " + token); break; } // not on an accepting state, throw exception (using simplified max munch) else { Main.getLogger().severe("Token ended at non-accepting state: " + lexeme); throw new ScanException("Token ended at non-accepting state"); } } // Shift state and append new char state = next; lexeme = lexeme + inChar; } return begin; } private boolean isWhitespace(String string) { return string.matches("\\s"); } }
package cafe.image.meta.iptc; import java.io.IOException; import java.io.InputStream; import cafe.image.meta.Metadata; import cafe.image.meta.MetadataReader; import cafe.image.meta.MetadataType; import cafe.io.IOUtils; public class IPTC extends Metadata { private MetadataReader reader; public static void showIPTC(byte[] iptc) { if(iptc != null && iptc.length > 0) { IPTCReader reader = new IPTCReader(iptc); try { reader.read(); reader.showMetadata(); } catch (IOException e) { e.printStackTrace(); } } } public static void showIPTC(InputStream is) { try { showIPTC(IOUtils.inputStreamToByteArray(is)); } catch (IOException e) { e.printStackTrace(); } } public IPTC(byte[] data) { super(MetadataType.IPTC, data); reader = new IPTCReader(data); } public MetadataReader getReader() { return reader; } }
package edu.wustl.catissuecore.domain; import java.io.Serializable; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import edu.wustl.catissuecore.actionForm.AliquotForm; import edu.wustl.catissuecore.actionForm.CollectionEventParametersForm; import edu.wustl.catissuecore.actionForm.CreateSpecimenForm; import edu.wustl.catissuecore.actionForm.NewSpecimenForm; import edu.wustl.catissuecore.actionForm.ReceivedEventParametersForm; import edu.wustl.catissuecore.actionForm.SpecimenForm; import edu.wustl.catissuecore.bean.ConsentBean; import edu.wustl.catissuecore.bizlogic.BizLogicFactory; import edu.wustl.catissuecore.util.EventsUtil; import edu.wustl.catissuecore.util.SearchUtil; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.catissuecore.util.global.Utility; import edu.wustl.common.actionForm.AbstractActionForm; import edu.wustl.common.actionForm.IValueObject; import edu.wustl.common.bizlogic.IBizLogic; import edu.wustl.common.domain.AbstractDomainObject; import edu.wustl.common.exception.AssignDataException; import edu.wustl.common.util.MapDataParser; import edu.wustl.common.util.global.Validator; import edu.wustl.common.util.logger.Logger; /** * A single unit of tissue, body fluid, or derivative biological macromolecule * that is collected or created from a Participant * @hibernate.class table="CATISSUE_SPECIMEN" * @hibernate.discriminator column="SPECIMEN_CLASS" */ public class Specimen extends AbstractDomainObject implements Serializable { private static final long serialVersionUID = -905954650055370532L; /** * System generated unique id. */ protected Long id; /** * Type of specimen. e.g. Serum, Plasma, Blood, Fresh Tissue etc. */ protected String type; /** * Is this specimen still physically available in the tissue bank? */ protected Boolean available; /** * Reference to dimensional position one of the specimen in Storage Container. */ protected Integer positionDimensionOne; /** * Reference to dimensional position two of the specimen in Storage Container. */ protected Integer positionDimensionTwo; /** * Barcode assigned to the specimen. */ protected String barcode; /** * Comment on specimen. */ protected String comment; /** * Defines whether this Specimen record can be queried (Active) * or not queried (Inactive) by any actor. */ protected String activityStatus; /** * Parent specimen from which this specimen is derived. */ protected Specimen parentSpecimen; /** * Collection of attributes of a Specimen that renders it potentially harmful to a User. */ protected Collection biohazardCollection = new HashSet(); /** * A physically discreet container that is used to store a specimen e.g. Box, Freezer etc. */ protected StorageContainer storageContainer; /** * Collection of Specimen Event Parameters associated with this specimen. */ protected Collection specimenEventCollection = new HashSet(); /** * Collection of children specimens derived from this specimen. */ protected Collection childrenSpecimen = new HashSet(); /** * Collection of a pre-existing, externally defined id associated with a specimen. */ protected Collection externalIdentifierCollection = new HashSet(); /** * An event that results in the collection of one or more specimen from a participant. */ protected AbstractSpecimenCollectionGroup specimenCollectionGroup; /** * The combined anatomic state and pathological diseaseclassification of a specimen. */ protected SpecimenCharacteristics specimenCharacteristics; /** * A boolean variable which contains a true value if this specimen object is an aliquot * else it contains false value. */ // protected Boolean isAliquot = Boolean.FALSE; /** * Histoathological character of specimen. * e.g. Non-Malignant, Malignant, Non-Malignant Diseased, Pre-Malignant. */ protected String pathologicalStatus; /** * A historical information about the specimen i.e. whether the specimen is a new specimen * or a derived specimen or an aliquot. */ protected String lineage; /** * A label name of this specimen. */ protected String label; /** * The quantity of a specimen. */ protected Quantity initialQuantity; /** * The available quantity of a specimen. */ protected Quantity availableQuantity; protected transient boolean isParentChanged = false; private transient int noOfAliquots; private transient Map aliqoutMap = new HashMap(); protected transient boolean disposeParentSpecimen = false; /** * The consent tier status for multiple participants for a particular specimen. */ protected Collection consentTierStatusCollection; //Mandar 15-jan-07 /* * To perform operation based on withdraw button clicked. * Default No Action to allow normal behaviour. */ protected String consentWithdrawalOption=Constants.WITHDRAW_RESPONSE_NOACTION; //Mandar 23-jan-07 /* * To apply changes to child specimen based on consent status changes. * Default Apply none to allow normal behaviour. */ protected String applyChangesTo=Constants.APPLY_NONE; protected String collectionStatus; protected Boolean isCollectionProtocolRequirement; public Boolean getIsCollectionProtocolRequirement() { return isCollectionProtocolRequirement; } public void setIsCollectionProtocolRequirement( Boolean collectionProtocolRequirement) { this.isCollectionProtocolRequirement = collectionProtocolRequirement; } /** * @return the consentTierStatusCollection * @hibernate.collection-one-to-many class="edu.wustl.catissuecore.domain.ConsentTierStatus" lazy="true" cascade="save-update" * @hibernate.set name="consentTierStatusCollection" table="CATISSUE_CONSENT_TIER_STATUS" * @hibernate.collection-key column="SPECIMEN_ID" */ public Collection getConsentTierStatusCollection() { return consentTierStatusCollection; } /** * @param consentTierStatusCollection the consentTierStatusCollection to set */ public void setConsentTierStatusCollection(Collection consentTierStatusCollection) { this.consentTierStatusCollection = consentTierStatusCollection; } /** * Name: Sachin Lale * Bug ID: 3835 * Patch ID: 3835_1 * See also: 1-4 * Description : Addeed createdOn field for derived and aliqut Specimen. */ protected Date createdOn; public Specimen() { isCollectionProtocolRequirement = false; } //Constructor public Specimen(AbstractActionForm form) throws AssignDataException { this(); setAllValues(form); } /** * Returns the system generated unique id. * @hibernate.id name="id" column="IDENTIFIER" type="long" length="30" * unsaved-value="null" generator-class="native" * @hibernate.generator-param name="sequence" value="CATISSUE_SPECIMEN_SEQ" * @return the system generated unique id. * @see #setId(Long) */ public Long getId() { return id; } /** * Sets the system generated unique id. * @param id the system generated unique id. * @see #getId() * */ public void setId(Long id) { this.id = id; } /** * Returns the type of specimen. e.g. Serum, Plasma, Blood, Fresh Tissue etc. * @hibernate.property name="type" type="string" column="TYPE" length="50" * @return The type of specimen. e.g. Serum, Plasma, Blood, Fresh Tissue etc. * @see #setType(String) */ public String getType() { return type; } /** * Sets the type of specimen. e.g. Serum, Plasma, Blood, Fresh Tissue etc. * @param type The type of specimen. e.g. Serum, Plasma, Blood, Fresh Tissue etc. * @see #getType() */ public void setType(String type) { this.type = type; } /** * Returns true if this specimen still physically available * in the tissue bank else returns false. * @hibernate.property name="available" type="boolean" column="AVAILABLE" * @return true if this specimen still physically available * in the tissue bank else returns false. * @see #setAvailable(Boolean) */ public Boolean getAvailable() { return available; } /** * Sets true if this specimen still physically available * in the tissue bank else returns false. * @param available true if this specimen still physically available else false. * @see #getAvailable() */ public void setAvailable(Boolean available) { this.available = available; } /** * Returns the reference to dimensional position one of the specimen in Storage Container. * @hibernate.property name="positionDimensionOne" type="int" column="POSITION_DIMENSION_ONE" length="30" * @return the reference to dimensional position one of the specimen in Storage Container. * @see #setPositionDimensionOne(Integer) */ public Integer getPositionDimensionOne() { return positionDimensionOne; } /** * Sets the reference to dimensional position one of the specimen in Storage Container. * @param positionDimensionOne the reference to dimensional position one of the specimen * in Storage Container. * @see #getPositionDimensionOne() */ public void setPositionDimensionOne(Integer positionDimensionOne) { this.positionDimensionOne = positionDimensionOne; } /** * Returns the reference to dimensional position two of the specimen in Storage Container. * @hibernate.property name="positionDimensionTwo" type="int" column="POSITION_DIMENSION_TWO" length="50" * @return the reference to dimensional position two of the specimen in Storage Container. * @see #setPositionDimensionOne(Integer) */ public Integer getPositionDimensionTwo() { return positionDimensionTwo; } /** * Sets the reference to dimensional position two of the specimen in Storage Container. * @param positionDimensionTwo the reference to dimensional position two of the specimen * in Storage Container. * @see #getPositionDimensionTwo() */ public void setPositionDimensionTwo(Integer positionDimensionTwo) { this.positionDimensionTwo = positionDimensionTwo; } /** * Returns the barcode assigned to the specimen. * @hibernate.property name="barcode" type="string" column="BARCODE" length="255" unique="true" * @return the barcode assigned to the specimen. * @see #setBarcode(String) */ public String getBarcode() { return barcode; } /** * Sets the barcode assigned to the specimen. * @param barCode the barcode assigned to the specimen. * @see #getBarcode() */ public void setBarcode(String barcode) { this.barcode = barcode; } /** * Returns the comments on the specimen. * @hibernate.property name="comment" type="string" column="COMMENTS" length="2000" * @return the comments on the specimen. * @see #setComment(String) */ public String getComment() { return comment; } /** * Sets the comment on the specimen. * @param comments The comments to set. * @see #getComment() */ public void setComment(String comment) { this.comment = comment; } /** * Returns whether this Specimen record can be queried (Active) or not queried (Inactive) by any actor. * @hibernate.property name="activityStatus" type="string" column="ACTIVITY_STATUS" length="50" * @return "Active" if this Specimen record can be queried or "Inactive" if cannot be queried. * @see #setActivityStatus(String) */ public String getActivityStatus() { return activityStatus; } /** * Sets whether this Specimen record can be queried (Active) or not queried (Inactive) by any actor. * @param activityStatus "Active" if this Specimen record can be queried else "Inactive". * @see #getActivityStatus() */ public void setActivityStatus(String activityStatus) { this.activityStatus = activityStatus; } /** * Returns the parent specimen from which this specimen is derived. * @hibernate.many-to-one column="PARENT_SPECIMEN_ID" * class="edu.wustl.catissuecore.domain.Specimen" constrained="true" * @return the parent specimen from which this specimen is derived. * @see #setParentSpecimen(SpecimenNew) */ public Specimen getParentSpecimen() { return parentSpecimen; } /** * Sets the parent specimen from which this specimen is derived. * @param parentSpecimen the parent specimen from which this specimen is derived. * @see #getParentSpecimen() */ public void setParentSpecimen(Specimen parentSpecimen) { this.parentSpecimen = parentSpecimen; } /** * Returns the collection of attributes of a Specimen * that renders it potentially harmful to a User. * @hibernate.set name="biohazardCollection" table="CATISSUE_SPECIMEN_BIOHZ_REL" * cascade="none" inverse="false" lazy="false" * @hibernate.collection-key column="SPECIMEN_ID" * @hibernate.collection-many-to-many class="edu.wustl.catissuecore.domain.Biohazard" column="BIOHAZARD_ID" * @return the collection of attributes of a Specimen * that renders it potentially harmful to a User. * @see #setBiohazardCollection(Set) */ public Collection getBiohazardCollection() { return biohazardCollection; } /** * Sets the collection of attributes of a Specimen * that renders it potentially harmful to a User. * @param biohazardCollection the collection of attributes of a Specimen * that renders it potentially harmful to a User. * @see #getBiohazardCollection() */ public void setBiohazardCollection(Collection biohazardCollection) { this.biohazardCollection = biohazardCollection; } /** * Returns the collection of Specimen Event Parameters associated with this specimen. * @hibernate.set name="specimenEventCollection" table="CATISSUE_SPECIMEN_EVENT" * cascade="save-update" inverse="true" lazy="false" * @hibernate.collection-key column="SPECIMEN_ID" * @hibernate.collection-one-to-many class="edu.wustl.catissuecore.domain.SpecimenEventParameters" * @return the collection of Specimen Event Parameters associated with this specimen. * @see #setSpecimenEventCollection(Set) */ public Collection getSpecimenEventCollection() { return specimenEventCollection; } /** * Sets the collection of Specimen Event Parameters associated with this specimen. * @param specimenEventCollection the collection of Specimen Event Parameters * associated with this specimen. * @see #getSpecimenEventCollection() */ public void setSpecimenEventCollection(Collection specimenEventCollection) { this.specimenEventCollection = specimenEventCollection; } /** * Returns the collection of children specimens derived from this specimen. * @hibernate.set name="childrenSpecimen" table="CATISSUE_SPECIMEN" * cascade="save-update" inverse="true" lazy="false" * @hibernate.collection-key column="PARENT_SPECIMEN_ID" * @hibernate.collection-one-to-many class="edu.wustl.catissuecore.domain.Specimen" * @return the collection of children specimens derived from this specimen. * @see #setChildrenSpecimen(Set) */ public Collection getChildrenSpecimen() { return childrenSpecimen; } /** * Sets the collection of children specimens derived from this specimen. * @param childrenSpecimen the collection of children specimens * derived from this specimen. * @see #getChildrenSpecimen() */ public void setChildrenSpecimen(Collection childrenSpecimen) { this.childrenSpecimen = childrenSpecimen; } /** * Returns the physically discreet container that is used to store a specimen e.g. Box, Freezer etc. * @hibernate.many-to-one column="STORAGE_CONTAINER_IDENTIFIER" * class="edu.wustl.catissuecore.domain.StorageContainer" constrained="true" * @return the physically discreet container that is used to store a specimen e.g. Box, Freezer etc. * @see #setStorageContainer(StorageContainer) */ public StorageContainer getStorageContainer() { return storageContainer; } /** * Sets the physically discreet container that is used to store a specimen e.g. Box, Freezer etc. * @param storageContainer the physically discreet container that is used to store a specimen * e.g. Box, Freezer etc. * @see #getStorageContainer() */ public void setStorageContainer(StorageContainer storageContainer) { this.storageContainer = storageContainer; } /** * Returns the collection of a pre-existing, externally defined id associated with a specimen. * @hibernate.set name="externalIdentifierCollection" table="CATISSUE_EXTERNAL_IDENTIFIER" * cascade="save-update" inverse="true" lazy="false" * @hibernate.collection-key column="SPECIMEN_ID" * @hibernate.collection-one-to-many class="edu.wustl.catissuecore.domain.ExternalIdentifier" * @return the collection of a pre-existing, externally defined id associated with a specimen. * @see #setExternalIdentifierCollection(Set) */ public Collection getExternalIdentifierCollection() { return externalIdentifierCollection; } /** * Sets the collection of a pre-existing, externally defined id * associated with a specimen. * @param externalIdentifierCollection the collection of a pre-existing, * externally defined id associated with a specimen. * @see #getExternalIdentifierCollection() */ public void setExternalIdentifierCollection(Collection externalIdentifierCollection) { this.externalIdentifierCollection = externalIdentifierCollection; } /** * Returns the event that results in the collection of one or more specimen from a participant. * @hibernate.many-to-one column="SPECIMEN_COLLECTION_GROUP_ID" * class="edu.wustl.catissuecore.domain.SpecimenCollectionGroup" constrained="true" * @return the event that results in the collection of one or more specimen from a participant. * @see #setSpecimenCollectionGroup(SpecimenCollectionGroup) */ public AbstractSpecimenCollectionGroup getSpecimenCollectionGroup() { return specimenCollectionGroup; } /** * Sets the event that results in the collection of one or more specimen from a participant. * @param specimenCollectionGroup the event that results in the collection of one or more * specimen from a participant. * @see #getSpecimenCollectionGroup() */ public void setSpecimenCollectionGroup(AbstractSpecimenCollectionGroup specimenCollectionGroup) { this.specimenCollectionGroup = specimenCollectionGroup; } /** * Returns the combined anatomic state and pathological diseaseclassification of a specimen. * @hibernate.many-to-one column="SPECIMEN_CHARACTERISTICS_ID" * class="edu.wustl.catissuecore.domain.SpecimenCharacteristics" constrained="true" * @return the combined anatomic state and pathological diseaseclassification of a specimen. * @see #setSpecimenCharacteristics(SpecimenCharacteristics) */ public SpecimenCharacteristics getSpecimenCharacteristics() { return specimenCharacteristics; } /** * Sets the combined anatomic state and pathological diseaseclassification of a specimen. * @param specimenCharacteristics the combined anatomic state and pathological disease * classification of a specimen. * @see #getSpecimenCharacteristics() */ public void setSpecimenCharacteristics(SpecimenCharacteristics specimenCharacteristics) { this.specimenCharacteristics = specimenCharacteristics; } public boolean isParentChanged() { return isParentChanged; } public void setParentChanged(boolean isParentChanged) { this.isParentChanged = isParentChanged; } /** * This function Copies the data from an NewSpecimenForm object to a Specimen object. * @param specimenForm A formbean object containing the information about the Specimen. * */ public void setAllValues(IValueObject valueObject) throws AssignDataException { AbstractActionForm abstractForm = (AbstractActionForm)valueObject; if (SearchUtil.isNullobject(storageContainer)) { storageContainer = null; } if (SearchUtil.isNullobject(specimenCollectionGroup)) { specimenCollectionGroup = new SpecimenCollectionGroup(); } if (SearchUtil.isNullobject(specimenCharacteristics)) { specimenCharacteristics = new SpecimenCharacteristics(); } if (SearchUtil.isNullobject(initialQuantity)) { initialQuantity = new Quantity(); } if (SearchUtil.isNullobject(availableQuantity)) { availableQuantity = new Quantity(); } try{ if (abstractForm.isAddOperation()) { this.isCollectionProtocolRequirement = new Boolean(false); } if (abstractForm instanceof AliquotForm) { AliquotForm form = (AliquotForm) abstractForm; // Dispose parent specimen Bug 3773 this.setDisposeParentSpecimen(form.getDisposeParentSpecimen()); Validator validator = new Validator(); this.aliqoutMap = form.getAliquotMap(); this.noOfAliquots = Integer.parseInt(form.getNoOfAliquots()); this.parentSpecimen = new Specimen(); this.collectionStatus = Constants.COLLECTION_STATUS_COLLECTED; /** * Patch ID: 3835_1_2 * See also: 1_1 to 1_5 * Description : Set createdOn date for aliquot. */ this.createdOn = Utility.parseDate(form.getCreatedDate(), Constants.DATE_PATTERN_MM_DD_YYYY); if (!validator.isEmpty(form.getSpecimenLabel())) // TODO { parentSpecimen.setLabel(form.getSpecimenLabel()); parentSpecimen.setId(new Long(form.getSpecimenID())); } else if (!validator.isEmpty(form.getBarcode())) { parentSpecimen.setId(new Long(form.getSpecimenID())); parentSpecimen.setBarcode(form.getBarcode()); } } else { String qty = ((SpecimenForm) abstractForm).getQuantity(); if(qty != null && qty.trim().length() > 0 ) this.initialQuantity = new Quantity(((SpecimenForm) abstractForm).getQuantity()); else this.initialQuantity = new Quantity("0"); this.label = ((SpecimenForm) abstractForm).getLabel(); if (abstractForm.isAddOperation()) { this.availableQuantity = new Quantity(this.initialQuantity); } else { this.availableQuantity = new Quantity(((SpecimenForm) abstractForm).getAvailableQuantity()); } Validator validator = new Validator(); if (abstractForm instanceof NewSpecimenForm) { NewSpecimenForm form = (NewSpecimenForm) abstractForm; /**For Migration Start**/ // This case is handled in Biz logic. // if(form.getSpecimenCollectionGroupName()!=null&&!form.getSpecimenCollectionGroupName().trim().equals("")) // form.setSpecimenCollectionGroupId(Utility.getSCGId(form.getSpecimenCollectionGroupName().trim())); /**For Migration End**/ this.activityStatus = form.getActivityStatus(); if (form.isAddOperation()) { this.collectionStatus = Constants.COLLECTION_STATUS_COLLECTED; } else { this.collectionStatus = form.getCollectionStatus(); } if (!validator.isEmpty(form.getBarcode())) this.barcode = form.getBarcode(); else this.barcode = null; this.comment = form.getComments(); this.type = form.getType(); if (form.isAddOperation()) { this.available = new Boolean(true); } else { this.available = new Boolean(form.isAvailable()); } //in case of edit if (!form.isAddOperation()) { //specimen is a new specimen if (parentSpecimen == null) { String parentSpecimenId = form.getParentSpecimenId(); // specimen created from another specimen if (parentSpecimenId != null && !parentSpecimenId.trim().equals("") && Long.parseLong(parentSpecimenId) > 0) { isParentChanged = true; } } else //specimen created from another specimen { if (!parentSpecimen.getLabel().equalsIgnoreCase(form.getParentSpecimenName())) { isParentChanged = true; } } /** * Patch ID: 3835_1_3 * See also: 1_1 to 1_5 * Description : Set createdOn date in edit mode for new specimen */ this.createdOn = Utility.parseDate(form.getCreatedDate(), Constants.DATE_PATTERN_MM_DD_YYYY); } Logger.out.debug("isParentChanged " + isParentChanged); //Setting the SpecimenCharacteristics this.pathologicalStatus = form.getPathologicalStatus(); specimenCharacteristics.tissueSide = form.getTissueSide(); specimenCharacteristics.tissueSite = form.getTissueSite(); //Getting the Map of External Identifiers Map extMap = form.getExternalIdentifier(); MapDataParser parser = new MapDataParser("edu.wustl.catissuecore.domain"); Collection extCollection = parser.generateData(extMap); this.externalIdentifierCollection = extCollection; Map bioMap = form.getBiohazard(); Logger.out.debug("PRE FIX MAP " + bioMap); bioMap = fixMap(bioMap); Logger.out.debug("POST FIX MAP " + bioMap); //Getting the Map of Biohazards parser = new MapDataParser("edu.wustl.catissuecore.domain"); Collection bioCollection = parser.generateData(bioMap); Logger.out.debug("BIO-COL : " + bioCollection); this.biohazardCollection = bioCollection; //Mandar : autoevents 14-july-06 start if (form.isAddOperation()) { Logger.out.debug("Setting Collection event in specimen domain object"); //seting collection event values CollectionEventParametersForm collectionEvent = new CollectionEventParametersForm(); collectionEvent.setCollectionProcedure(form.getCollectionEventCollectionProcedure()); collectionEvent.setComments(form.getCollectionEventComments()); collectionEvent.setContainer(form.getCollectionEventContainer()); collectionEvent.setTimeInHours(form.getCollectionEventTimeInHours()); collectionEvent.setTimeInMinutes(form.getCollectionEventTimeInMinutes()); collectionEvent.setDateOfEvent(form.getCollectionEventdateOfEvent()); collectionEvent.setUserId(form.getCollectionEventUserId()); collectionEvent.setOperation(form.getOperation()); CollectionEventParameters collectionEventParameters = new CollectionEventParameters(); collectionEventParameters.setAllValues(collectionEvent); collectionEventParameters.setSpecimen(this); Logger.out.debug("Before specimenEventCollection.size(): " + specimenEventCollection.size()); specimenEventCollection.add(collectionEventParameters); Logger.out.debug("After specimenEventCollection.size(): " + specimenEventCollection.size()); Logger.out.debug("...14-July-06... : CollectionEvent set"); Logger.out.debug("Setting Received event in specimen domain object"); //setting received event values ReceivedEventParametersForm receivedEvent = new ReceivedEventParametersForm(); receivedEvent.setComments(form.getReceivedEventComments()); receivedEvent.setDateOfEvent(form.getReceivedEventDateOfEvent()); receivedEvent.setReceivedQuality(form.getReceivedEventReceivedQuality()); receivedEvent.setUserId(form.getReceivedEventUserId()); receivedEvent.setTimeInMinutes(form.getReceivedEventTimeInMinutes()); receivedEvent.setTimeInHours(form.getReceivedEventTimeInHours()); receivedEvent.setOperation(form.getOperation()); ReceivedEventParameters receivedEventParameters = new ReceivedEventParameters(); receivedEventParameters.setAllValues(receivedEvent); receivedEventParameters.setSpecimen(this); /** * Patch ID: 3835_1_4 * See also: 1_1 to 1_5 * Description :createdOn should be collection event date for new specimen. */ this.createdOn = Utility.parseDate(form.getCollectionEventdateOfEvent(), Constants.DATE_PATTERN_MM_DD_YYYY); Logger.out.debug("Before specimenEventCollection.size(): " + specimenEventCollection.size()); specimenEventCollection.add(receivedEventParameters); Logger.out.debug("After specimenEventCollection.size(): " + specimenEventCollection.size()); Logger.out.debug("...14-July-06... : ReceivedEvent set"); } //Mandar : autoevents 14-july-06 end if (form.isAddOperation()) { if(form.getStContSelection()==1) { this.storageContainer = null; this.positionDimensionOne = null; this.positionDimensionTwo = null; } if(form.getStContSelection()==2) { long stContainerId = Long.parseLong(form.getStorageContainer()); if(this.storageContainer == null) { this.storageContainer = new StorageContainer(); } this.storageContainer.setId(stContainerId); this.positionDimensionOne = new Integer(form.getPositionDimensionOne()); this.positionDimensionTwo = new Integer(form.getPositionDimensionTwo()); } else if(form.getStContSelection()==3) { this.storageContainer.setName(form.getSelectedContainerName()); if (form.getPos1() != null && !form.getPos1().trim().equals("") && form.getPos2() != null && !form.getPos2().trim().equals("")) { this.positionDimensionOne = new Integer(form.getPos1()); this.positionDimensionTwo = new Integer(form.getPos2()); } } } else { if(!validator.isEmpty(form.getSelectedContainerName())) { //this.storageContainer = new StorageContainer(); this.storageContainer.setName(form.getSelectedContainerName()); this.positionDimensionOne = new Integer(form.getPositionDimensionOne()); this.positionDimensionTwo = new Integer(form.getPositionDimensionTwo()); } else { this.storageContainer = null; this.positionDimensionOne = null; this.positionDimensionTwo = null; } } if (form.isParentPresent()) { parentSpecimen = new CellSpecimen(); //parentSpecimen.setId(new Long(form.getParentSpecimenId())); parentSpecimen.setLabel(form.getParentSpecimenName()); } else { parentSpecimen = null; //specimenCollectionGroup = null; this.specimenCollectionGroup.setId(new Long(form.getSpecimenCollectionGroupId())); // this.specimenCollectionGroup.setGroupName(form.getSpecimenCollectionGroupName()); IBizLogic iBizLogic = BizLogicFactory.getInstance().getBizLogic(Constants.DEFAULT_BIZ_LOGIC); List scgList = iBizLogic.retrieve(SpecimenCollectionGroup.class.getName(), "name",form.getSpecimenCollectionGroupName()); if(!scgList.isEmpty()) { this.specimenCollectionGroup =(SpecimenCollectionGroup) scgList.get(0); } } } else if (abstractForm instanceof CreateSpecimenForm) { CreateSpecimenForm form = (CreateSpecimenForm) abstractForm; this.activityStatus = form.getActivityStatus(); this.collectionStatus = Constants.COLLECTION_STATUS_COLLECTED; if (!validator.isEmpty(form.getBarcode())) this.barcode = form.getBarcode(); else this.barcode = null; this.comment = form.getComments(); //this.positionDimensionOne = new Integer(form.getPositionDimensionOne()); //this.positionDimensionTwo = new Integer(form.getPositionDimensionTwo()); this.type = form.getType(); /** * Patch ID: 3835_1_5 * See also: 1_1 to 1_5 * Description : Set createdOn date for derived specimen . */ this.createdOn = Utility.parseDate(form.getCreatedDate(), Constants.DATE_PATTERN_MM_DD_YYYY); if (form.isAddOperation()) { this.available = new Boolean(true); } else { this.available = new Boolean(form.isAvailable()); } //this.storageContainer.setId(new Long(form.getStorageContainer())); this.parentSpecimen = new CellSpecimen(); //this.parentSpecimen.setId(new Long(form.getParentSpecimenId())); this.parentSpecimen.setLabel(form.getParentSpecimenLabel()); //Getting the Map of External Identifiers Map extMap = form.getExternalIdentifier(); MapDataParser parser = new MapDataParser("edu.wustl.catissuecore.domain"); Collection extCollection = parser.generateData(extMap); this.externalIdentifierCollection = extCollection; // if (form.isVirtuallyLocated()) // this.storageContainer = null; // this.positionDimensionOne = null; // this.positionDimensionTwo = null; // else // this.storageContainer.setId(new Long(form.getStorageContainer())); // this.positionDimensionOne = new Integer(form.getPositionDimensionOne()); // this.positionDimensionTwo = new Integer(form.getPositionDimensionTwo()); //setting the value of storage container if (form.isAddOperation()) { if(form.getStContSelection()==1) { this.storageContainer = null; this.positionDimensionOne = null; this.positionDimensionTwo = null; } if(form.getStContSelection()==2) { this.storageContainer.setId(new Long(form.getStorageContainer())); this.positionDimensionOne = new Integer(form.getPositionDimensionOne()); this.positionDimensionTwo = new Integer(form.getPositionDimensionTwo()); } else if(form.getStContSelection()==3) { this.storageContainer.setName(form.getSelectedContainerName()); this.positionDimensionOne = new Integer(form.getPos1()); this.positionDimensionTwo = new Integer(form.getPos2()); } } } } } catch (Exception excp) { Logger.out.error(excp.getMessage(), excp); throw new AssignDataException(); } //Setting the consentTier responses. (Virender Mehta) if (abstractForm instanceof NewSpecimenForm) { NewSpecimenForm form = (NewSpecimenForm) abstractForm; this.consentTierStatusCollection = prepareParticipantResponseCollection(form); this.consentWithdrawalOption = form.getWithdrawlButtonStatus(); this.applyChangesTo = form.getApplyChangesTo(); } } /** * For Consent Tracking * Setting the Domain Object * @param form CollectionProtocolRegistrationForm * @return consentResponseColl */ private Collection prepareParticipantResponseCollection(NewSpecimenForm form) { MapDataParser mapdataParser = new MapDataParser("edu.wustl.catissuecore.bean"); Collection beanObjColl=null; try { beanObjColl = mapdataParser.generateData(form.getConsentResponseForSpecimenValues()); } catch (Exception e) { e.printStackTrace(); } Iterator iter = beanObjColl.iterator(); Collection consentResponseColl = new HashSet(); while(iter.hasNext()) { ConsentBean consentBean = (ConsentBean)iter.next(); ConsentTierStatus consentTierstatus = new ConsentTierStatus(); //Setting response consentTierstatus.setStatus(consentBean.getSpecimenLevelResponse()); if(consentBean.getSpecimenLevelResponseID()!=null&&consentBean.getSpecimenLevelResponseID().trim().length()>0) { consentTierstatus.setId(Long.parseLong(consentBean.getSpecimenLevelResponseID())); } //Setting consent tier ConsentTier consentTier = new ConsentTier(); consentTier.setId(new Long(consentBean.getConsentTierID())); consentTierstatus.setConsentTier(consentTier); consentResponseColl.add(consentTierstatus); } return consentResponseColl; } protected Map fixMap(Map orgMap) { Map newMap = new HashMap(); Iterator it = orgMap.keySet().iterator(); while (it.hasNext()) { String key = (String) it.next(); //Logger.out.debug("key "+key); if (key.indexOf("persisted") == -1) { String value = String.valueOf(orgMap.get(key)); newMap.put(key, value); } } return newMap; } /** * This function returns the actual type of the specimen i.e Cell / Fluid / Molecular / Tissue. */ public final String getClassName() { String className = null; if (this instanceof CellSpecimen) { className = Constants.CELL; } else if (this instanceof MolecularSpecimen) { className = Constants.MOLECULAR; } else if (this instanceof FluidSpecimen) { className = Constants.FLUID; } else if (this instanceof TissueSpecimen) { className = Constants.TISSUE; } return className; } public String getObjectId() { Logger.out.debug(this.getClass().getName() + " is an instance of Specimen class"); return Specimen.class.getName() + "_" + this.getId(); } /** * Returns the available quantity of a specimen. * @return The available quantity of a specimen. * @hibernate.component class="edu.wustl.catissuecore.domain.Quantity" * @see #setAvailableQuantity(Quantity) */ public Quantity getAvailableQuantity() { return availableQuantity; } /** * Sets the available quantity of a specimen. * @param availableQuantity the available quantity of a specimen. * @see #getAvailableQuantity() */ public void setAvailableQuantity(Quantity availableQuantity) { this.availableQuantity = availableQuantity; } /** * Returns the quantity of a specimen. * @return The quantity of a specimen. * @hibernate.component class="edu.wustl.catissuecore.domain.Quantity" * @see #setinitialQuantity(Quantity) */ public Quantity getInitialQuantity() { return initialQuantity; } /** * Sets the quantity of a specimen. * @param quantity The quantity of a specimen. * @see #getInitialQuantity() */ public void setInitialQuantity(Quantity initialQuantity) { this.initialQuantity = initialQuantity; } /** * Returns the Histoathological character of specimen. * e.g. Non-Malignant, Malignant, Non-Malignant Diseased, Pre-Malignant. * @hibernate.property name="pathologicalStatus" type="string" * column="PATHOLOGICAL_STATUS" length="50" * @return the Histoathological character of specimen. * @see #setPathologicalStatus(String) */ public String getPathologicalStatus() { return pathologicalStatus; } /** * Sets the Histoathological character of specimen. * e.g. Non-Malignant, Malignant, Non-Malignant Diseased, Pre-Malignant. * @param pathologicalStatus the Histoathological character of specimen. * @see #getPathologicalStatus() */ public void setPathologicalStatus(String pathologicalStatus) { this.pathologicalStatus = pathologicalStatus; } /* * Returns true if this specimen object is an aliquot else false. * @hibernate.property name="isAliquot" type="boolean" column="IS_ALIQUOT" * @return the Histoathological character of specimen. * @see #setIsAliquot(Boolean) public Boolean getIsAliquot() { return isAliquot; }*/ /* * Sets true if this specimen object is an aliquot else false. * @param isAliquot true if this specimen object is an aliquot else false. * @see #getIsAliquot() public void setIsAliquot(Boolean isAliquot) { this.isAliquot = isAliquot; }*/ /** * Returns the map that contains distinguished fields per aliquots. * @return The map that contains distinguished fields per aliquots. * @see #setAliquotMap(Map) */ public Map getAliqoutMap() { return aliqoutMap; } /** * Sets the map of distinguished fields of aliquots. * @param aliquotMap A map of distinguished fields of aliquots. * @see #getAliquotMap() */ public void setAliqoutMap(Map aliqoutMap) { this.aliqoutMap = aliqoutMap; } /** * Returns the no. of aliquots to be created. * @return The no. of aliquots to be created. * @see #setNoOfAliquots(int) */ public int getNoOfAliquots() { return noOfAliquots; } /** * Sets the no. of aliquots to be created. * @param noOfAliquots The no. of aliquots to be created. * @see #getNoOfAliquots() */ public void setNoOfAliquots(int noOfAliquots) { this.noOfAliquots = noOfAliquots; } /** * Returns the label name of specimen. * @hibernate.property name="label" type="string" * column="LABEL" length="255" * @return the label name of specimen. * @see #setLabel(String) */ public String getLabel() { return label; } /** * Sets the label name of specimen. * @param label The label name of specimen. * @see #getLabel() */ public void setLabel(String label) { this.label = label; } /** * Returns the historical information about the specimen. * @hibernate.property name="lineage" type="string" * column="LINEAGE" length="50" * @return The historical information about the specimen. * @see #setLineage(String) */ public String getLineage() { return lineage; } /** * Sets the historical information about the specimen. * @param label The historical information about the specimen. * @see #getLineage() */ public void setLineage(String lineage) { this.lineage = lineage; } /** * Returns message label to display on success add or edit * @return String */ public String getMessageLabel() { return this.label; } public String getConsentWithdrawalOption() { return consentWithdrawalOption; } public void setConsentWithdrawalOption(String consentWithdrawalOption) { this.consentWithdrawalOption = consentWithdrawalOption; } public String getApplyChangesTo() { return applyChangesTo; } public void setApplyChangesTo(String applyChangesTo) { this.applyChangesTo = applyChangesTo; } /** * @return Returns the disposeParentSpecimen. */ public boolean getDisposeParentSpecimen() { return disposeParentSpecimen; } /** * @param disposeParentSpecimen The disposeParentSpecimen to set. */ public void setDisposeParentSpecimen(boolean disposeParentSpecimen) { this.disposeParentSpecimen = disposeParentSpecimen; } /** * Name: Sachin Lale * Bug ID: 3835 * Patch ID: 3835_2 * See also: 1-4 * Description : Addeed createdOn field for derived and aliqut Specimen. * Returns the date on which the Participant is * registered to the Collection Protocol. * @hibernate.property name="createdOn" column="CREATED_ON_DATE" type="date" * @return the date on which the Dervive/aliqut Specimen is created * @see #setCreatedOn(Date) */ public Date getCreatedOn() { return createdOn; } /** * Sets the date on which the Participant is * registered to the Collection Protocol. * @param registrationDate the date on which the Participant is * registered to the Collection Protocol. * @see #getRegistrationDate() */ public void setCreatedOn(Date createdOn) { this.createdOn = createdOn; } public String getCollectionStatus() { return collectionStatus; } public void setCollectionStatus(String collectionStatus) { this.collectionStatus = collectionStatus; } public Specimen(Specimen specimen) { this.activityStatus = specimen.getActivityStatus(); this.applyChangesTo = specimen.getApplyChangesTo(); this.available = specimen.getAvailable(); if(specimen.getInitialQuantity() != null) { this.availableQuantity = new Quantity(specimen.getInitialQuantity()); this.initialQuantity = new Quantity(specimen.getInitialQuantity()); } this.biohazardCollection = setBiohazardCollection(specimen); this.createdOn = specimen.getCreatedOn(); this.comment = specimen.getComment(); this.lineage = specimen.getLineage(); this.pathologicalStatus = specimen.getPathologicalStatus(); this.collectionStatus = Constants.COLLECTION_STATUS_PENDING; if(specimen.getSpecimenCharacteristics() != null) { this.specimenCharacteristics = new SpecimenCharacteristics(specimen.getSpecimenCharacteristics()); } this.type = specimen.getType(); this.isCollectionProtocolRequirement = new Boolean(false); } private Collection setBiohazardCollection(Specimen specimen) { Collection biohazardCollectionN = new HashSet(); Collection biohazardCollection = specimen.getBiohazardCollection(); if(biohazardCollection != null && !biohazardCollection.isEmpty()) { Iterator it = biohazardCollection.iterator(); while(it.hasNext()) { Biohazard bio = (Biohazard)it.next(); Biohazard bioN = new Biohazard(bio); biohazardCollectionN.add(bioN); } } return biohazardCollectionN; } public Specimen createClone() { Specimen cloneSpecimen = new Specimen(this); return cloneSpecimen; } public void setDefaultSpecimenEventCollection(Long userID) { Collection specimenEventCollection = new HashSet(); User user = new User(); user.setId(userID); CollectionEventParameters collectionEventParameters = EventsUtil.populateCollectionEventParameters(user); collectionEventParameters.setSpecimen(this); specimenEventCollection.add(collectionEventParameters); ReceivedEventParameters receivedEventParameters = EventsUtil.populateReceivedEventParameters(user); receivedEventParameters.setSpecimen(this); specimenEventCollection.add(receivedEventParameters); setSpecimenEventCollection(specimenEventCollection); } public void setConsentTierStatusCollectionFromSCG(SpecimenCollectionGroup specimenCollectionGroup) { Collection consentTierStatusCollectionN = new HashSet(); Collection consentTierStatusCollection = specimenCollectionGroup.getConsentTierStatusCollection(); if(consentTierStatusCollection != null && !consentTierStatusCollection.isEmpty()) { Iterator it = consentTierStatusCollection.iterator(); while(it.hasNext()) { ConsentTierStatus consentTierStatus = (ConsentTierStatus)it.next(); ConsentTierStatus consentTierstatusN = new ConsentTierStatus(consentTierStatus); consentTierStatusCollectionN.add(consentTierstatusN); } } setConsentTierStatusCollection(consentTierStatusCollectionN); } }
package org.jpos.iso; import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.Matchers.hasItemInArray; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.math.BigDecimal; import java.math.MathContext; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.BitSet; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.TimeZone; import org.jpos.util.LogUtil; import org.junit.Test; public class ISOUtilTest { final String lineSep = System.getProperty("line.separator"); @Test public void testAsciiToEbcdic() throws Throwable { byte[] a = new byte[0]; byte[] result = ISOUtil.asciiToEbcdic(a); assertEquals("result.length", 0, result.length); } @Test public void testAsciiToEbcdic1() throws Throwable { byte[] a = new byte[1]; byte[] result = ISOUtil.asciiToEbcdic(a); assertEquals("result.length", 1, result.length); assertEquals("result[0]", (byte) 0, result[0]); } @Test public void testAsciiToEbcdic2() throws Throwable { byte[] e = new byte[13]; ISOUtil.asciiToEbcdic("testISOUtils", e, 0); assertEquals("e[0]", (byte) -93, e[0]); } @Test(expected=ArrayIndexOutOfBoundsException.class) public void testAsciiToEbcdic3() throws Throwable { ISOUtil.asciiToEbcdic("", new byte[3], 100); } @Test public void testAsciiToEbcdic4() throws Throwable { byte[] result = ISOUtil.asciiToEbcdic(""); assertEquals("result.length", 0, result.length); } @Test public void testAsciiToEbcdic5() throws Throwable { byte[] result = ISOUtil.asciiToEbcdic("testISOUtils"); assertEquals("result.length", 12, result.length); assertEquals("result[0]", (byte) -93, result[0]); } @Test public void testAsciiToEbcdic6() throws Throwable { byte[] result = ISOUtil.asciiToEbcdic("testISOUtils"); byte[] expected = new byte[]{(byte)0xA3, (byte)0x85, (byte)0xA2, (byte)0xA3, (byte)0xC9, (byte)0xE2, (byte)0xD6, (byte)0xE4, (byte)0xA3, (byte) 0x89, (byte)0x93, (byte)0xA2 }; assertArrayEquals("full result", expected, result); } @Test public void testAsciiToEbcdic7() throws Throwable { String testString = "testISOUtils1047`¬!\"£$%^&*()-=_+;:[]{}'@ byte[] result = ISOUtil.asciiToEbcdic(testString); byte[] expected = testString.getBytes("Cp1047"); assertArrayEquals("full result", expected, result); } @Test public void testAsciiToEbcdicThrowsArrayIndexOutOfBoundsException() throws Throwable { byte[] e = new byte[0]; try { ISOUtil.asciiToEbcdic("testISOUtils", e, 100); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { } } @Test(expected = NullPointerException.class) public void testAsciiToEbcdicThrowsNullPointerException() throws Throwable { ISOUtil.asciiToEbcdic((byte[]) null); } @Test public void testAsciiToEbcdicThrowsNullPointerException1() throws Throwable { byte[] e = new byte[3]; try { ISOUtil.asciiToEbcdic((String) null, e, 100); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { assertNull("ex.getMessage()", ex.getMessage()); assertEquals("e.length", 3, e.length); } } @Test(expected = NullPointerException.class) public void testAsciiToEbcdicThrowsNullPointerException2() throws Throwable { ISOUtil.asciiToEbcdic((String) null); } @Test public void testBcd2str() throws Throwable { byte[] b = new byte[0]; String result = ISOUtil.bcd2str(b, 100, 0, true); assertEquals("result", "", result); } @Test public void testBcd2str1() throws Throwable { byte[] b = new byte[2]; String result = ISOUtil.bcd2str(b, 0, 2, true); assertEquals("result", "00", result); } @Test public void testBcd2str2() throws Throwable { byte[] b = new byte[2]; b[0] = (byte) -61; String result = ISOUtil.bcd2str(b, 0, 1, false); assertEquals("result", "C", result); } @Test public void testBcd2str3() throws Throwable { byte[] b = new byte[1]; b[0] = (byte) -3; String result = ISOUtil.bcd2str(b, 0, 1, true); assertEquals("result", "=", result); } @Test public void testBcd2str4() throws Throwable { byte[] b = new byte[2]; b[0] = (byte) -31; String result = ISOUtil.bcd2str(b, 0, 1, false); assertEquals("result", "E", result); } @Test public void testBcd2str5() throws Throwable { byte[] b = new byte[3]; String result = ISOUtil.bcd2str(b, 0, 1, true); assertEquals("result", "0", result); } @Test public void testBcd2str6() throws Throwable { byte[] b = new byte[3]; b[1] = (byte) 14; String result = ISOUtil.bcd2str(b, 0, 3, true); assertEquals("result", "00E", result); } @Test(expected = ArrayIndexOutOfBoundsException.class) public void testBcd2strThrowsArrayIndexOutOfBoundsException() throws Throwable { byte[] b = new byte[41]; b[25] = (byte) -100; b[30] = (byte) 13; b[35] = (byte) -29; ISOUtil.bcd2str(b, 16, 61, true); } @Test(expected = ArrayIndexOutOfBoundsException.class) public void testBcd2strThrowsArrayIndexOutOfBoundsException1() throws Throwable { byte[] b = new byte[41]; b[25] = (byte) -100; b[30] = (byte) 13; b[35] = (byte) -29; ISOUtil.bcd2str(b, 16, 61, false); } @Test(expected = ArrayIndexOutOfBoundsException.class) public void testBcd2strThrowsArrayIndexOutOfBoundsException2() throws Throwable { byte[] b = new byte[25]; b[2] = (byte) -63; b[3] = (byte) 62; b[23] = (byte) 29; ISOUtil.bcd2str(b, 0, 100, true); } @Test(expected = ArrayIndexOutOfBoundsException.class) public void testBcd2strThrowsArrayIndexOutOfBoundsException3() throws Throwable { byte[] b = new byte[41]; b[25] = (byte) -100; b[35] = (byte) -29; ISOUtil.bcd2str(b, 16, 61, false); } @Test(expected = ArrayIndexOutOfBoundsException.class) public void testBcd2strThrowsArrayIndexOutOfBoundsException4() throws Throwable { byte[] b = new byte[2]; b[1] = (byte) 28; ISOUtil.bcd2str(b, 0, 27, true); } @Test(expected = ArrayIndexOutOfBoundsException.class) public void testBcd2strThrowsArrayIndexOutOfBoundsException5() throws Throwable { byte[] b = new byte[25]; b[2] = (byte) -63; b[3] = (byte) 62; ISOUtil.bcd2str(b, 0, 100, true); } @Test(expected = NegativeArraySizeException.class) public void testBcd2strThrowsNegativeArraySizeException() throws Throwable { byte[] b = new byte[3]; ISOUtil.bcd2str(b, 100, -1, true); } @Test(expected = NullPointerException.class) public void testBcd2strThrowsNullPointerException() throws Throwable { ISOUtil.bcd2str(null, 100, 1, false); } @Test(expected = NullPointerException.class) public void testBcd2strThrowsNullPointerException1() throws Throwable { ISOUtil.bcd2str(null, 100, 1, true); } @Test(expected = NullPointerException.class) public void testBcd2strThrowsNullPointerException2() throws Throwable { ISOUtil.bcd2str(null, 100, 1000, true); } @Test public void testBitSet2byte() throws Throwable { byte[] b = new byte[1]; BitSet bmap = new BitSet(); ISOUtil.hex2BitSet(bmap, b, 0); byte[] b2 = new byte[0]; ISOUtil.hex2BitSet(bmap, b2, -1); BitSet b3 = new BitSet(100); b3.or(bmap); byte[] result = ISOUtil.bitSet2byte(b3); assertEquals("result.length", 8, result.length); assertEquals("result[0]", (byte) -16, result[0]); } @Test public void testBitSet2byte3() throws Throwable { byte[] result = ISOUtil.bitSet2byte(new BitSet(100)); assertEquals("result.length", 0, result.length); } @Test public void testBitSetByteHexInteroperability() throws Throwable { BitSet bs = new BitSet(); bs.set(1); bs.set(63); bs.set(127); bs.set(191); byte[] b = ISOUtil.bitSet2byte(bs); BitSet bs1 = ISOUtil.byte2BitSet(b, 0, 192); BitSet bs2 = ISOUtil.hex2BitSet(ISOUtil.hexString(b).getBytes(), 0, 192); assertEquals("BitSets should be equal", bs1, bs2); } @Test public void testBitSetByteHexInteroperability2() throws Throwable { byte[] b = ISOUtil.hex2byte("F23C04800EE0000080000000000000000000380000000000"); BitSet bs1 = ISOUtil.byte2BitSet(b, 0, 192); BitSet bs2 = ISOUtil.hex2BitSet (ISOUtil.hexString(b).getBytes(), 0, 192); assertEquals("BitSets should be equal", bs1, bs2); assertEquals("Image matches", ISOUtil.hexString(b), ISOUtil.hexString(ISOUtil.bitSet2byte(bs1))); } @Test public void testBitSetByteHexInteroperability3() throws Throwable { byte[] b = ISOUtil.hex2byte("F23C04800AE00000800000000000010863BC780000000010"); BitSet bs1 = ISOUtil.byte2BitSet(b, 0, 192); BitSet bs2 = ISOUtil.hex2BitSet (ISOUtil.hexString(b).getBytes(), 0, 192); assertEquals("BitSets should be equal", bs1, bs2); assertEquals("Image matches", ISOUtil.hexString(b), ISOUtil.hexString(ISOUtil.bitSet2byte(bs1))); } @Test(expected = NullPointerException.class) public void testBitSet2byteThrowsNullPointerException() throws Throwable { ISOUtil.bitSet2byte(null); } @Test public void testBitSet2extendedByte() throws Throwable { byte[] result = ISOUtil.bitSet2extendedByte(new BitSet(100)); assertEquals("result.length", 16, result.length); assertEquals("result[0]", (byte) -128, result[0]); } @Test public void testShortBitset2Byte() { byte[] expected = ISOUtil.hex2byte("C00000"); BitSet b = new BitSet(); b.set(1); b.set(2); int configuredLength = 3; int len = configuredLength >= 8 ? b.length()+62 >>6 <<3 : configuredLength; byte[] sb = ISOUtil.bitSet2byte(b, len); BitSet b1 = ISOUtil.byte2BitSet(sb, 0, len << 3); assertEquals(3, len); assertArrayEquals(expected, sb); assertEquals(b, b1); } @Test(expected = NullPointerException.class) public void testBitSet2extendedByteThrowsNullPointerException() throws Throwable { ISOUtil.bitSet2extendedByte(null); } @Test public void testBitSet2String() throws Throwable { BitSet bmap = new BitSet(100); byte[] b = new byte[1]; ISOUtil.byte2BitSet(bmap, b, 100); bmap.set(100); bmap.flip(0, 100); String result = ISOUtil.bitSet2String(bmap); assertEquals( "result", "11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111000000000000000000000000000", result); } @Test public void testBitSet2String1() throws Throwable { String result = ISOUtil.bitSet2String(new BitSet(100)); assertEquals( "result", "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", result); } @Test public void testBitSet2String2() throws Throwable { String result = ISOUtil.bitSet2String(new BitSet(0)); assertEquals("result", "", result); } @Test(expected = NullPointerException.class) public void testBitSet2StringThrowsNullPointerException() throws Throwable { ISOUtil.bitSet2String(null); } @Test public void testBlankUnPad() throws Throwable { String result = ISOUtil.blankUnPad(""); assertEquals("result", "", result); } @Test public void testBlankUnPad1() throws Throwable { String result = ISOUtil.blankUnPad("1"); assertEquals("result", "1", result); } @Test(expected = NullPointerException.class) public void testBlankUnPadThrowsNullPointerException() throws Throwable { ISOUtil.blankUnPad(null); } @Test public void testByte2BitSet() throws Throwable { byte[] b = new byte[9]; BitSet result = ISOUtil.byte2BitSet(b, 0, true); assertEquals("result.size()", 64, result.size()); } @Test public void testByte2BitSet1() throws Throwable { byte[] b = new byte[9]; b[4] = (byte) 1; BitSet result = ISOUtil.byte2BitSet(b, 0, true); assertEquals("result.size()", 64, result.size()); } @Test public void testByte2BitSet11() throws Throwable { byte[] b = new byte[9]; b[1] = (byte) -3; BitSet result = ISOUtil.byte2BitSet(b, 0, 63); assertEquals("result.size()", 64, result.size()); } @Test public void testByte2BitSet2() throws Throwable { byte[] b = new byte[10]; BitSet result = ISOUtil.byte2BitSet(b, 0, 1000); assertEquals("result.size()", 64, result.size()); } @Test public void testByte2BitSet3() throws Throwable { byte[] b = new byte[9]; b[1] = (byte) -3; BitSet result = ISOUtil.byte2BitSet(b, 0, 127); assertEquals("result.size()", 64, result.size()); } @Test public void testByte2BitSet5() throws Throwable { byte[] b = new byte[1]; BitSet result = ISOUtil.byte2BitSet(null, b, 100); assertNull("result", result); } @Test public void testByte2BitSet6() throws Throwable { byte[] b = new byte[0]; BitSet result = ISOUtil.byte2BitSet(null, b, 100); assertNull("result", result); } @Test public void testByte2BitSet7() throws Throwable { byte[] b = new byte[9]; b[1] = (byte) -3; BitSet result = ISOUtil.byte2BitSet(b, 0, 128); assertEquals("result.size()", 64, result.size()); } @Test public void testByte2BitSet8() throws Throwable { byte[] b = new byte[9]; b[1] = (byte) -3; BitSet result = ISOUtil.byte2BitSet(b, 0, 1000); assertEquals("result.size()", 64, result.size()); } @Test public void testByte2BitSet9() throws Throwable { byte[] b = new byte[10]; BitSet result = ISOUtil.byte2BitSet(b, 0, 100); assertEquals("result.size()", 64, result.size()); } @Test public void testByte2BitSetThrowsArrayIndexOutOfBoundsException() throws Throwable { byte[] b = new byte[71]; b[62] = (byte) -128; b[63] = (byte) 1; try { ISOUtil.byte2BitSet(b, 62, true); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "71", ex.getMessage()); } } @Test public void testByte2BitSetThrowsArrayIndexOutOfBoundsException1() throws Throwable { byte[] b = new byte[3]; b[0] = (byte) 3; try { ISOUtil.byte2BitSet(b, 0, true); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "3", ex.getMessage()); } } @Test public void testByte2BitSetThrowsArrayIndexOutOfBoundsException10() throws Throwable { byte[] b = new byte[3]; try { ISOUtil.byte2BitSet(b, 100, 64); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "100", ex.getMessage()); } } @Test public void testByte2BitSetThrowsArrayIndexOutOfBoundsException12() throws Throwable { byte[] b = new byte[1]; b[0] = (byte) -29; try { ISOUtil.byte2BitSet(b, 0, false); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "1", ex.getMessage()); } } @Test public void testByte2BitSetThrowsArrayIndexOutOfBoundsException13() throws Throwable { byte[] b = new byte[1]; try { ISOUtil.byte2BitSet(b, 0, false); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "1", ex.getMessage()); } } @Test public void testByte2BitSetThrowsArrayIndexOutOfBoundsException14() throws Throwable { byte[] b = new byte[1]; try { ISOUtil.byte2BitSet(b, 0, true); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "1", ex.getMessage()); } } @Test public void testByte2BitSetThrowsArrayIndexOutOfBoundsException15() throws Throwable { byte[] b = new byte[0]; try { ISOUtil.byte2BitSet(b, 100, false); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "100", ex.getMessage()); } } @Test public void testByte2BitSetThrowsArrayIndexOutOfBoundsException16() throws Throwable { byte[] b = new byte[0]; try { ISOUtil.byte2BitSet(b, 100, true); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "100", ex.getMessage()); } } // This test SHOULD NOT throw an ArrayIndexOutOfBoundsException // because the first bit of the first byte (byte[1] since we're calling with offset 1) is 0. // Therefore, only 8 bytes should be decoded, which is enough for the 11 available bytes in the array // The test used to be successful (i.e. failed) because of a bad implementation of ISOUtil.byte2BitSet // when asked for more than 128 bits, and bit 1 of the bitmap was 0 and bit 65 was one (in which case it // wrongly attempted to unpack 24 bytes instead of just 8) // @Test // public void testByte2BitSetThrowsArrayIndexOutOfBoundsException17() throws Throwable { // byte[] b = new byte[12]; // b[1] = (byte) 1; // b[9] = (byte) -128; // try { // ISOUtil.byte2BitSet(b, 1, 129); // fail("Expected ArrayIndexOutOfBoundsException to be thrown"); // } catch (ArrayIndexOutOfBoundsException ex) { // assertEquals("ex.getMessage()", "12", ex.getMessage()); @Test public void testByte2BitSetThrowsArrayIndexOutOfBoundsException18() throws Throwable { byte[] b = new byte[12]; b[1] = (byte) -63; b[9] = (byte) -128; try { ISOUtil.byte2BitSet(b, 1, 1000); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "12", ex.getMessage()); } } @Test public void testByte2BitSetThrowsArrayIndexOutOfBoundsException19() throws Throwable { byte[] b = new byte[2]; b[1] = (byte) 59; try { ISOUtil.byte2BitSet(b, 0, 128); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "2", ex.getMessage()); } } @Test public void testByte2BitSetThrowsArrayIndexOutOfBoundsException2() throws Throwable { byte[] b = new byte[2]; b[1] = (byte) -1; try { ISOUtil.byte2BitSet(b, 1, 129); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "2", ex.getMessage()); } } @Test public void testByte2BitSetThrowsArrayIndexOutOfBoundsException3() throws Throwable { byte[] b = new byte[2]; b[1] = (byte) -1; try { ISOUtil.byte2BitSet(b, 1, 127); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "2", ex.getMessage()); } } @Test public void testByte2BitSetThrowsArrayIndexOutOfBoundsException4() throws Throwable { byte[] b = new byte[1]; b[0] = (byte) 9; try { ISOUtil.byte2BitSet(b, 0, 63); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "1", ex.getMessage()); } } @Test public void testByte2BitSetThrowsArrayIndexOutOfBoundsException5() throws Throwable { byte[] b = new byte[1]; b[0] = (byte) 3; try { ISOUtil.byte2BitSet(b, 0, 129); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "1", ex.getMessage()); } } @Test public void testByte2BitSetThrowsArrayIndexOutOfBoundsException6() throws Throwable { byte[] b = new byte[1]; b[0] = (byte) -61; try { ISOUtil.byte2BitSet(b, 0, 64); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "1", ex.getMessage()); } } @Test public void testByte2BitSetThrowsArrayIndexOutOfBoundsException7() throws Throwable { byte[] b = new byte[2]; try { ISOUtil.byte2BitSet(b, 0, 128); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "2", ex.getMessage()); } } @Test public void testByte2BitSetThrowsArrayIndexOutOfBoundsException8() throws Throwable { byte[] b = new byte[1]; try { ISOUtil.byte2BitSet(b, 0, 63); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "1", ex.getMessage()); } } @Test public void testByte2BitSetThrowsArrayIndexOutOfBoundsException9() throws Throwable { byte[] b = new byte[1]; try { ISOUtil.byte2BitSet(b, 0, 129); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "1", ex.getMessage()); } } @Test public void testByte2BitSetThrowsIndexOutOfBoundsException() throws Throwable { BitSet bmap = new BitSet(100); byte[] b = new byte[0]; ISOUtil.byte2BitSet(bmap, b, 100); byte[] b2 = new byte[4]; b2[0] = (byte) 1; try { ISOUtil.byte2BitSet(bmap, b2, -30); fail("Expected IndexOutOfBoundsException to be thrown"); } catch (IndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "bitIndex < 0: -22", ex.getMessage()); assertEquals("bmap.size()", 128, bmap.size()); } } @Test(expected = NullPointerException.class) public void testByte2BitSetThrowsNullPointerException() throws Throwable { ISOUtil.byte2BitSet(null, 100, true); } @Test(expected = NullPointerException.class) public void testByte2BitSetThrowsNullPointerException1() throws Throwable { byte[] b = new byte[4]; b[2] = (byte) 127; ISOUtil.byte2BitSet(null, b, 100); } @Test public void testByte2BitSetThrowsNullPointerException2() throws Throwable { BitSet bmap = new BitSet(100); try { ISOUtil.byte2BitSet(bmap, null, 100); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { assertNull("ex.getMessage()", ex.getMessage()); assertEquals("bmap.size()", 128, bmap.size()); } } @Test(expected = NullPointerException.class) public void testByte2BitSetThrowsNullPointerException3() throws Throwable { ISOUtil.byte2BitSet(null, 100, 65); } @Test public void testConcat() throws Throwable { byte[] array1 = new byte[3]; byte[] result = ISOUtil.concat(array1, 0, 1, ISOUtil.asciiToEbcdic("testISOUtils"), 10, 0); assertEquals("result.length", 1, result.length); assertEquals("result[0]", (byte) 0, result[0]); } @Test public void testConcat1() throws Throwable { byte[] array2 = new byte[3]; byte[] array1 = new byte[3]; byte[] result = ISOUtil.concat(array1, 0, 0, array2, 1, 0); assertEquals("result.length", 0, result.length); } @Test public void testConcat2() throws Throwable { byte[] array1 = new byte[1]; byte[] array2 = new byte[3]; byte[] result = ISOUtil.concat(array1, array2); assertEquals("result.length", 4, result.length); assertEquals("result[0]", (byte) 0, result[0]); } @Test public void testConcat3() throws Throwable { byte[] array2 = new byte[0]; byte[] array1 = new byte[0]; byte[] result = ISOUtil.concat(array1, array2); assertEquals("result.length", 0, result.length); } @Test(expected = NegativeArraySizeException.class) public void testConcatThrowsNegativeArraySizeException() throws Throwable { byte[] array1 = new byte[0]; byte[] array2 = new byte[1]; ISOUtil.concat(array1, 100, 0, array2, 1000, -1); } @Test(expected = NullPointerException.class) public void testConcatThrowsNullPointerException() throws Throwable { ISOUtil.concat(null, 100, 1000, ISOUtil.asciiToEbcdic("testISOUtils"), 0, -1); } @Test(expected = NullPointerException.class) public void testConcatThrowsNullPointerException1() throws Throwable { byte[] array2 = new byte[3]; ISOUtil.concat(null, array2); } @Test public void testDumpString() throws Throwable { byte[] b = new byte[5]; b[1] = (byte) 22; b[2] = (byte) 7; b[3] = (byte) 29; b[4] = (byte) -17; String result = ISOUtil.dumpString(b); assertEquals("result", "{NULL}{SYN}{BEL}[1D]\uFFEF", result); } @Test public void testDumpString1() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 6; b[1] = (byte) 32; b[3] = (byte) 16; String result = ISOUtil.dumpString(b); assertEquals("result", "{ACK} {NULL}{DLE}{NULL}", result); } @Test public void testDumpString10() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 6; b[1] = (byte) 5; b[2] = (byte) -29; b[3] = (byte) -6; b[4] = (byte) 27; String result = ISOUtil.dumpString(b); assertEquals("result", "{ACK}{ENQ}\uFFE3\uFFFA[1B]", result); } @Test public void testDumpString100() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 21; b[1] = (byte) 15; b[2] = (byte) -128; b[3] = (byte) -2; b[4] = (byte) 16; String result = ISOUtil.dumpString(b); assertEquals("result", "{NAK}[0F]\uFF80\uFFFE{DLE}", result); } @Test public void testDumpString101() throws Throwable { byte[] b = new byte[3]; b[0] = (byte) 13; b[1] = (byte) 93; b[2] = (byte) 17; String result = ISOUtil.dumpString(b); assertEquals("result", "{CR}][11]", result); } @Test public void testDumpString102() throws Throwable { byte[] b = new byte[4]; b[0] = (byte) 1; b[2] = (byte) 29; String result = ISOUtil.dumpString(b); assertEquals("result", "{SOH}{NULL}[1D]{NULL}", result); } @Test public void testDumpString103() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 2; b[2] = (byte) -16; b[3] = (byte) 28; String result = ISOUtil.dumpString(b); assertEquals("result", "{STX}{NULL}\uFFF0{FS}{NULL}", result); } @Test public void testDumpString104() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 5; b[1] = (byte) 32; b[2] = (byte) 127; b[3] = (byte) 21; String result = ISOUtil.dumpString(b); assertEquals("result", "{ENQ} [7F]{NAK}{NULL}", result); } @Test public void testDumpString105() throws Throwable { byte[] b = new byte[3]; b[0] = (byte) 11; b[1] = (byte) -10; b[2] = (byte) 21; String result = ISOUtil.dumpString(b); assertEquals("result", "[0B]\uFFF6{NAK}", result); } @Test public void testDumpString106() throws Throwable { byte[] b = new byte[3]; b[0] = (byte) 28; b[1] = (byte) -17; b[2] = (byte) 20; String result = ISOUtil.dumpString(b); assertEquals("result", "{FS}\uFFEF[14]", result); } @Test public void testDumpString107() throws Throwable { byte[] b = new byte[4]; b[1] = (byte) 6; b[2] = (byte) 25; b[3] = (byte) -23; String result = ISOUtil.dumpString(b); assertEquals("result", "{NULL}{ACK}[19]\uFFE9", result); } @Test public void testDumpString108() throws Throwable { byte[] b = new byte[2]; b[1] = (byte) 10; String result = ISOUtil.dumpString(b); assertEquals("result", "{NULL}{LF}", result); } @Test public void testDumpString109() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 1; b[1] = (byte) -15; b[2] = (byte) -19; b[3] = (byte) -108; b[4] = (byte) -16; String result = ISOUtil.dumpString(b); assertEquals("result", "{SOH}\uFFF1\uFFED\uFF94\uFFF0", result); } @Test public void testDumpString11() throws Throwable { byte[] b = new byte[4]; b[0] = (byte) 24; b[1] = (byte) 6; b[3] = (byte) 22; String result = ISOUtil.dumpString(b); assertEquals("result", "[18]{ACK}{NULL}{SYN}", result); } @Test public void testDumpString110() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 16; b[1] = (byte) 9; b[2] = (byte) 93; b[3] = (byte) -3; b[4] = (byte) -1; String result = ISOUtil.dumpString(b); assertEquals("result", "{DLE}[09]]\uFFFD\uFFFF", result); } @Test public void testDumpString111() throws Throwable { byte[] b = new byte[3]; b[0] = (byte) 7; b[1] = (byte) -13; b[2] = (byte) 26; String result = ISOUtil.dumpString(b); assertEquals("result", "{BEL}\uFFF3[1A]", result); } @Test public void testDumpString112() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 6; b[1] = (byte) 14; b[2] = (byte) 94; b[3] = (byte) -5; b[4] = (byte) -28; String result = ISOUtil.dumpString(b); assertEquals("result", "{ACK}[0E]^\uFFFB\uFFE4", result); } @Test public void testDumpString113() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 3; b[1] = (byte) 30; b[2] = (byte) -91; String result = ISOUtil.dumpString(b); assertEquals("result", "{ETX}{RS}\uFFA5{NULL}{NULL}", result); } @Test public void testDumpString114() throws Throwable { byte[] b = new byte[3]; b[0] = (byte) 28; String result = ISOUtil.dumpString(b); assertEquals("result", "{FS}{NULL}{NULL}", result); } @Test public void testDumpString115() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 2; b[1] = (byte) 15; b[2] = (byte) -93; b[4] = (byte) 28; String result = ISOUtil.dumpString(b); assertEquals("result", "{STX}[0F]\uFFA3{NULL}{FS}", result); } @Test public void testDumpString116() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 30; b[1] = (byte) -26; b[2] = (byte) -7; b[3] = (byte) -27; b[4] = (byte) 27; String result = ISOUtil.dumpString(b); assertEquals("result", "{RS}\uFFE6\uFFF9\uFFE5[1B]", result); } @Test public void testDumpString117() throws Throwable { byte[] b = new byte[4]; b[0] = (byte) 1; b[1] = (byte) 96; b[2] = (byte) 29; b[3] = (byte) 12; String result = ISOUtil.dumpString(b); assertEquals("result", "{SOH}`[1D][0C]", result); } @Test public void testDumpString118() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 5; b[1] = (byte) 32; b[3] = (byte) 21; String result = ISOUtil.dumpString(b); assertEquals("result", "{ENQ} {NULL}{NAK}{NULL}", result); } @Test public void testDumpString119() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 16; b[1] = (byte) 9; b[2] = (byte) 93; String result = ISOUtil.dumpString(b); assertEquals("result", "{DLE}[09]]{NULL}{NULL}", result); } @Test public void testDumpString12() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 4; b[1] = (byte) 1; b[2] = (byte) 13; b[3] = (byte) -23; b[4] = (byte) 23; String result = ISOUtil.dumpString(b); assertEquals("result", "{EOT}{SOH}{CR}\uFFE9[17]", result); } @Test public void testDumpString120() throws Throwable { byte[] b = new byte[4]; b[0] = (byte) 24; b[1] = (byte) 6; b[2] = (byte) 23; b[3] = (byte) 22; String result = ISOUtil.dumpString(b); assertEquals("result", "[18]{ACK}[17]{SYN}", result); } @Test public void testDumpString121() throws Throwable { byte[] b = new byte[2]; b[0] = (byte) 1; b[1] = (byte) 15; String result = ISOUtil.dumpString(b); assertEquals("result", "{SOH}[0F]", result); } @Test public void testDumpString122() throws Throwable { byte[] b = new byte[4]; b[0] = (byte) 22; b[1] = (byte) 30; b[2] = (byte) 2; b[3] = (byte) -3; String result = ISOUtil.dumpString(b); assertEquals("result", "{SYN}{RS}{STX}\uFFFD", result); } @Test public void testDumpString123() throws Throwable { byte[] b = new byte[2]; b[1] = (byte) 7; String result = ISOUtil.dumpString(b); assertEquals("result", "{NULL}{BEL}", result); } @Test public void testDumpString124() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 4; b[1] = (byte) 1; b[2] = (byte) 13; b[3] = (byte) -23; String result = ISOUtil.dumpString(b); assertEquals("result", "{EOT}{SOH}{CR}\uFFE9{NULL}", result); } @Test public void testDumpString125() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 21; b[1] = (byte) 22; b[2] = (byte) 7; b[4] = (byte) -17; String result = ISOUtil.dumpString(b); assertEquals("result", "{NAK}{SYN}{BEL}{NULL}\uFFEF", result); } @Test public void testDumpString126() throws Throwable { byte[] b = new byte[4]; b[0] = (byte) 5; b[1] = (byte) 8; b[2] = (byte) -8; b[3] = (byte) 16; String result = ISOUtil.dumpString(b); assertEquals("result", "{ENQ}[08]\uFFF8{DLE}", result); } @Test public void testDumpString127() throws Throwable { byte[] b = new byte[4]; b[0] = (byte) 22; b[1] = (byte) 1; b[3] = (byte) -9; String result = ISOUtil.dumpString(b); assertEquals("result", "{SYN}{SOH}{NULL}\uFFF7", result); } @Test public void testDumpString128() throws Throwable { byte[] b = new byte[3]; b[0] = (byte) 21; b[1] = (byte) -18; b[2] = (byte) 91; String result = ISOUtil.dumpString(b); assertEquals("result", "{NAK}\uFFEE[", result); } @Test public void testDumpString129() throws Throwable { byte[] b = new byte[3]; b[0] = (byte) 7; b[1] = (byte) -24; String result = ISOUtil.dumpString(b); assertEquals("result", "{BEL}\uFFE8{NULL}", result); } @Test public void testDumpString13() throws Throwable { byte[] b = new byte[4]; b[0] = (byte) 28; b[1] = (byte) -8; b[3] = (byte) 31; String result = ISOUtil.dumpString(b); assertEquals("result", "{FS}\uFFF8{NULL}[1F]", result); } @Test public void testDumpString130() throws Throwable { byte[] b = new byte[4]; b[0] = (byte) 5; b[2] = (byte) 119; String result = ISOUtil.dumpString(b); assertEquals("result", "{ENQ}{NULL}w{NULL}", result); } @Test public void testDumpString131() throws Throwable { byte[] b = new byte[2]; b[1] = (byte) 5; String result = ISOUtil.dumpString(b); assertEquals("result", "{NULL}{ENQ}", result); } @Test public void testDumpString132() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 10; b[1] = (byte) -6; b[4] = (byte) 22; String result = ISOUtil.dumpString(b); assertEquals("result", "{LF}\uFFFA{NULL}{NULL}{SYN}", result); } @Test public void testDumpString133() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 10; b[1] = (byte) -6; b[2] = (byte) -29; b[3] = (byte) 11; b[4] = (byte) 22; String result = ISOUtil.dumpString(b); assertEquals("result", "{LF}\uFFFA\uFFE3[0B]{SYN}", result); } @Test public void testDumpString134() throws Throwable { byte[] b = new byte[4]; b[1] = (byte) 30; b[2] = (byte) 2; b[3] = (byte) -3; String result = ISOUtil.dumpString(b); assertEquals("result", "{NULL}{RS}{STX}\uFFFD", result); } @Test public void testDumpString135() throws Throwable { byte[] b = new byte[3]; b[0] = (byte) 11; b[2] = (byte) 21; String result = ISOUtil.dumpString(b); assertEquals("result", "[0B]{NULL}{NAK}", result); } @Test public void testDumpString136() throws Throwable { byte[] b = new byte[4]; b[0] = (byte) 5; b[1] = (byte) 8; b[3] = (byte) 16; String result = ISOUtil.dumpString(b); assertEquals("result", "{ENQ}[08]{NULL}{DLE}", result); } @Test public void testDumpString137() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 2; b[1] = (byte) 21; b[2] = (byte) -16; String result = ISOUtil.dumpString(b); assertEquals("result", "{STX}{NAK}\uFFF0{NULL}{NULL}", result); } @Test public void testDumpString138() throws Throwable { byte[] b = new byte[3]; b[0] = (byte) 28; b[1] = (byte) -4; String result = ISOUtil.dumpString(b); assertEquals("result", "{FS}\uFFFC{NULL}", result); } @Test public void testDumpString139() throws Throwable { byte[] b = new byte[4]; b[0] = (byte) 5; b[1] = (byte) 23; b[2] = (byte) 119; b[3] = (byte) -105; String result = ISOUtil.dumpString(b); assertEquals("result", "{ENQ}[17]w\uFF97", result); } @Test public void testDumpString14() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 10; b[1] = (byte) -12; b[2] = (byte) 31; b[3] = (byte) 15; b[4] = (byte) 26; String result = ISOUtil.dumpString(b); assertEquals("result", "{LF}\uFFF4[1F][0F][1A]", result); } @Test public void testDumpString140() throws Throwable { byte[] b = new byte[4]; b[0] = (byte) 1; b[1] = (byte) 96; b[2] = (byte) 29; String result = ISOUtil.dumpString(b); assertEquals("result", "{SOH}`[1D]{NULL}", result); } @Test public void testDumpString141() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 21; b[1] = (byte) 15; b[2] = (byte) -128; b[4] = (byte) 16; String result = ISOUtil.dumpString(b); assertEquals("result", "{NAK}[0F]\uFF80{NULL}{DLE}", result); } @Test public void testDumpString142() throws Throwable { byte[] b = new byte[2]; b[0] = (byte) 4; String result = ISOUtil.dumpString(b); assertEquals("result", "{EOT}{NULL}", result); } @Test public void testDumpString143() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 21; b[1] = (byte) 22; b[3] = (byte) 29; b[4] = (byte) -17; String result = ISOUtil.dumpString(b); assertEquals("result", "{NAK}{SYN}{NULL}[1D]\uFFEF", result); } @Test public void testDumpString144() throws Throwable { byte[] b = new byte[3]; b[0] = (byte) 13; b[2] = (byte) 17; String result = ISOUtil.dumpString(b); assertEquals("result", "{CR}{NULL}[11]", result); } @Test public void testDumpString145() throws Throwable { byte[] b = new byte[5]; b[1] = (byte) 32; b[2] = (byte) 127; b[3] = (byte) 21; String result = ISOUtil.dumpString(b); assertEquals("result", "{NULL} [7F]{NAK}{NULL}", result); } @Test public void testDumpString146() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 4; b[1] = (byte) 1; b[2] = (byte) 13; b[4] = (byte) 23; String result = ISOUtil.dumpString(b); assertEquals("result", "{EOT}{SOH}{CR}{NULL}[17]", result); } @Test public void testDumpString147() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 22; b[2] = (byte) -26; String result = ISOUtil.dumpString(b); assertEquals("result", "{SYN}{NULL}\uFFE6{NULL}{NULL}", result); } @Test public void testDumpString148() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 30; b[1] = (byte) -29; b[4] = (byte) 9; String result = ISOUtil.dumpString(b); assertEquals("result", "{RS}\uFFE3{NULL}{NULL}[09]", result); } @Test public void testDumpString149() throws Throwable { byte[] b = new byte[2]; b[0] = (byte) 22; String result = ISOUtil.dumpString(b); assertEquals("result", "{SYN}{NULL}", result); } @Test public void testDumpString15() throws Throwable { byte[] b = new byte[4]; b[1] = (byte) 23; b[2] = (byte) 5; String result = ISOUtil.dumpString(b); assertEquals("result", "{NULL}[17]{ENQ}{NULL}", result); } @Test public void testDumpString150() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 3; b[2] = (byte) -91; String result = ISOUtil.dumpString(b); assertEquals("result", "{ETX}{NULL}\uFFA5{NULL}{NULL}", result); } @Test public void testDumpString151() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 3; b[1] = (byte) -20; b[4] = (byte) 4; String result = ISOUtil.dumpString(b); assertEquals("result", "{ETX}\uFFEC{NULL}{NULL}{EOT}", result); } @Test public void testDumpString16() throws Throwable { byte[] b = new byte[2]; b[0] = (byte) 1; String result = ISOUtil.dumpString(b); assertEquals("result", "{SOH}{NULL}", result); } @Test public void testDumpString17() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 6; b[1] = (byte) 5; b[2] = (byte) -29; b[4] = (byte) 27; String result = ISOUtil.dumpString(b); assertEquals("result", "{ACK}{ENQ}\uFFE3{NULL}[1B]", result); } @Test public void testDumpString18() throws Throwable { byte[] b = new byte[4]; b[0] = (byte) 4; b[1] = (byte) 23; String result = ISOUtil.dumpString(b); assertEquals("result", "{EOT}[17]{NULL}{NULL}", result); } @Test public void testDumpString19() throws Throwable { byte[] b = new byte[4]; b[0] = (byte) 5; b[2] = (byte) -8; b[3] = (byte) 16; String result = ISOUtil.dumpString(b); assertEquals("result", "{ENQ}{NULL}\uFFF8{DLE}", result); } @Test public void testDumpString2() throws Throwable { byte[] b = new byte[2]; b[0] = (byte) 4; b[1] = (byte) 5; String result = ISOUtil.dumpString(b); assertEquals("result", "{EOT}{ENQ}", result); } @Test public void testDumpString20() throws Throwable { byte[] b = new byte[4]; b[0] = (byte) 22; b[1] = (byte) 1; b[2] = (byte) 9; b[3] = (byte) -9; String result = ISOUtil.dumpString(b); assertEquals("result", "{SYN}{SOH}[09]\uFFF7", result); } @Test public void testDumpString21() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 30; b[1] = (byte) -26; String result = ISOUtil.dumpString(b); assertEquals("result", "{RS}\uFFE6{NULL}{NULL}{NULL}", result); } @Test public void testDumpString22() throws Throwable { byte[] b = new byte[4]; b[1] = (byte) 8; b[2] = (byte) -31; String result = ISOUtil.dumpString(b); assertEquals("result", "{NULL}[08]\uFFE1{NULL}", result); } @Test public void testDumpString23() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 2; b[1] = (byte) -21; b[2] = (byte) -6; b[3] = (byte) 7; b[4] = (byte) 31; String result = ISOUtil.dumpString(b); assertEquals("result", "{STX}\uFFEB\uFFFA{BEL}[1F]", result); } @Test public void testDumpString24() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 2; b[1] = (byte) 21; b[2] = (byte) -16; b[3] = (byte) 28; b[4] = (byte) 2; String result = ISOUtil.dumpString(b); assertEquals("result", "{STX}{NAK}\uFFF0{FS}{STX}", result); } @Test public void testDumpString25() throws Throwable { byte[] b = new byte[3]; b[0] = (byte) 2; b[2] = (byte) -23; String result = ISOUtil.dumpString(b); assertEquals("result", "{STX}{NULL}\uFFE9", result); } @Test public void testDumpString26() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 10; b[1] = (byte) -12; b[2] = (byte) 31; String result = ISOUtil.dumpString(b); assertEquals("result", "{LF}\uFFF4[1F]{NULL}{NULL}", result); } @Test public void testDumpString27() throws Throwable { byte[] b = new byte[4]; b[0] = (byte) 22; b[2] = (byte) 2; b[3] = (byte) -3; String result = ISOUtil.dumpString(b); assertEquals("result", "{SYN}{NULL}{STX}\uFFFD", result); } @Test public void testDumpString28() throws Throwable { byte[] b = new byte[4]; b[0] = (byte) 22; b[1] = (byte) 18; b[2] = (byte) -26; b[3] = (byte) 11; String result = ISOUtil.dumpString(b); assertEquals("result", "{SYN}[12]\uFFE6[0B]", result); } @Test public void testDumpString29() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 2; b[2] = (byte) -93; b[3] = (byte) 4; b[4] = (byte) 28; String result = ISOUtil.dumpString(b); assertEquals("result", "{STX}{NULL}\uFFA3{EOT}{FS}", result); } @Test public void testDumpString3() throws Throwable { byte[] b = new byte[2]; b[1] = (byte) 30; String result = ISOUtil.dumpString(b); assertEquals("result", "{NULL}{RS}", result); } @Test public void testDumpString30() throws Throwable { byte[] b = new byte[4]; b[0] = (byte) 28; b[1] = (byte) -8; b[2] = (byte) 16; String result = ISOUtil.dumpString(b); assertEquals("result", "{FS}\uFFF8{DLE}{NULL}", result); } @Test public void testDumpString31() throws Throwable { byte[] b = new byte[5]; b[2] = (byte) 13; String result = ISOUtil.dumpString(b); assertEquals("result", "{NULL}{NULL}{CR}{NULL}{NULL}", result); } @Test public void testDumpString32() throws Throwable { byte[] b = new byte[1]; b[0] = (byte) 49; String result = ISOUtil.dumpString(b); assertEquals("result", "1", result); } @Test public void testDumpString33() throws Throwable { byte[] b = new byte[2]; b[0] = (byte) 16; b[1] = (byte) -7; String result = ISOUtil.dumpString(b); assertEquals("result", "{DLE}\uFFF9", result); } @Test public void testDumpString34() throws Throwable { byte[] b = new byte[4]; b[0] = (byte) 28; b[1] = (byte) -8; b[2] = (byte) 16; b[3] = (byte) 31; String result = ISOUtil.dumpString(b); assertEquals("result", "{FS}\uFFF8{DLE}[1F]", result); } @Test public void testDumpString35() throws Throwable { byte[] b = new byte[3]; b[0] = (byte) 26; b[1] = (byte) 8; b[2] = (byte) -24; String result = ISOUtil.dumpString(b); assertEquals("result", "[1A][08]\uFFE8", result); } @Test public void testDumpString36() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 16; b[2] = (byte) 93; String result = ISOUtil.dumpString(b); assertEquals("result", "{DLE}{NULL}]{NULL}{NULL}", result); } @Test public void testDumpString37() throws Throwable { byte[] b = new byte[3]; b[0] = (byte) 21; b[1] = (byte) -18; String result = ISOUtil.dumpString(b); assertEquals("result", "{NAK}\uFFEE{NULL}", result); } @Test public void testDumpString38() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 2; b[1] = (byte) 21; b[2] = (byte) -16; b[3] = (byte) 28; String result = ISOUtil.dumpString(b); assertEquals("result", "{STX}{NAK}\uFFF0{FS}{NULL}", result); } @Test public void testDumpString39() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 2; b[1] = (byte) 15; b[2] = (byte) -93; b[3] = (byte) 4; b[4] = (byte) 28; String result = ISOUtil.dumpString(b); assertEquals("result", "{STX}[0F]\uFFA3{EOT}{FS}", result); } @Test public void testDumpString4() throws Throwable { byte[] b = new byte[4]; b[0] = (byte) 4; b[1] = (byte) -12; b[2] = (byte) 27; String result = ISOUtil.dumpString(b); assertEquals("result", "{EOT}\uFFF4[1B]{NULL}", result); } @Test public void testDumpString40() throws Throwable { byte[] b = new byte[3]; b[0] = (byte) 28; b[2] = (byte) 20; String result = ISOUtil.dumpString(b); assertEquals("result", "{FS}{NULL}[14]", result); } @Test public void testDumpString41() throws Throwable { byte[] b = new byte[2]; b[0] = (byte) 6; b[1] = (byte) 7; String result = ISOUtil.dumpString(b); assertEquals("result", "{ACK}{BEL}", result); } @Test public void testDumpString42() throws Throwable { byte[] b = new byte[4]; b[0] = (byte) 24; b[3] = (byte) 22; String result = ISOUtil.dumpString(b); assertEquals("result", "[18]{NULL}{NULL}{SYN}", result); } @Test public void testDumpString43() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 6; b[1] = (byte) 5; b[2] = (byte) -29; String result = ISOUtil.dumpString(b); assertEquals("result", "{ACK}{ENQ}\uFFE3{NULL}{NULL}", result); } @Test public void testDumpString44() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) -1; b[2] = (byte) 13; String result = ISOUtil.dumpString(b); assertEquals("result", "\uFFFF{NULL}{CR}{NULL}{NULL}", result); } @Test public void testDumpString45() throws Throwable { byte[] b = new byte[2]; b[0] = (byte) 4; b[1] = (byte) -22; String result = ISOUtil.dumpString(b); assertEquals("result", "{EOT}\uFFEA", result); } @Test public void testDumpString46() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 4; b[1] = (byte) 1; b[3] = (byte) -23; b[4] = (byte) 23; String result = ISOUtil.dumpString(b); assertEquals("result", "{EOT}{SOH}{NULL}\uFFE9[17]", result); } @Test public void testDumpString47() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 2; b[1] = (byte) 15; b[2] = (byte) -93; b[3] = (byte) 4; String result = ISOUtil.dumpString(b); assertEquals("result", "{STX}[0F]\uFFA3{EOT}{NULL}", result); } @Test public void testDumpString48() throws Throwable { byte[] b = new byte[2]; b[0] = (byte) 6; b[1] = (byte) 8; String result = ISOUtil.dumpString(b); assertEquals("result", "{ACK}[08]", result); } @Test public void testDumpString49() throws Throwable { byte[] b = new byte[3]; b[0] = (byte) 2; b[1] = (byte) 16; b[2] = (byte) -23; String result = ISOUtil.dumpString(b); assertEquals("result", "{STX}{DLE}\uFFE9", result); } @Test public void testDumpString5() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 10; b[1] = (byte) -6; b[3] = (byte) 11; b[4] = (byte) 22; String result = ISOUtil.dumpString(b); assertEquals("result", "{LF}\uFFFA{NULL}[0B]{SYN}", result); } @Test public void testDumpString50() throws Throwable { byte[] b = new byte[2]; b[0] = (byte) 24; b[1] = (byte) 18; String result = ISOUtil.dumpString(b); assertEquals("result", "[18][12]", result); } @Test public void testDumpString51() throws Throwable { byte[] b = new byte[0]; String result = ISOUtil.dumpString(b); assertEquals("result", "", result); } @Test public void testDumpString52() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 2; b[1] = (byte) -21; b[3] = (byte) 7; b[4] = (byte) 31; String result = ISOUtil.dumpString(b); assertEquals("result", "{STX}\uFFEB{NULL}{BEL}[1F]", result); } @Test public void testDumpString53() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 10; b[2] = (byte) 31; String result = ISOUtil.dumpString(b); assertEquals("result", "{LF}{NULL}[1F]{NULL}{NULL}", result); } @Test public void testDumpString54() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 5; b[1] = (byte) 32; b[2] = (byte) 127; String result = ISOUtil.dumpString(b); assertEquals("result", "{ENQ} [7F]{NULL}{NULL}", result); } @Test public void testDumpString55() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 6; b[1] = (byte) 32; b[2] = (byte) -93; b[3] = (byte) 16; b[4] = (byte) -28; String result = ISOUtil.dumpString(b); assertEquals("result", "{ACK} \uFFA3{DLE}\uFFE4", result); } @Test public void testDumpString56() throws Throwable { byte[] b = new byte[5]; b[1] = (byte) 1; b[2] = (byte) 13; b[3] = (byte) -23; b[4] = (byte) 23; String result = ISOUtil.dumpString(b); assertEquals("result", "{NULL}{SOH}{CR}\uFFE9[17]", result); } @Test public void testDumpString57() throws Throwable { byte[] b = new byte[3]; b[0] = (byte) 7; b[2] = (byte) 26; String result = ISOUtil.dumpString(b); assertEquals("result", "{BEL}{NULL}[1A]", result); } @Test public void testDumpString58() throws Throwable { byte[] b = new byte[4]; b[0] = (byte) 22; b[1] = (byte) 1; b[2] = (byte) 9; String result = ISOUtil.dumpString(b); assertEquals("result", "{SYN}{SOH}[09]{NULL}", result); } @Test public void testDumpString59() throws Throwable { byte[] b = new byte[4]; b[0] = (byte) 4; b[1] = (byte) -12; b[2] = (byte) 27; b[3] = (byte) 12; String result = ISOUtil.dumpString(b); assertEquals("result", "{EOT}\uFFF4[1B][0C]", result); } @Test public void testDumpString6() throws Throwable { byte[] b = new byte[4]; b[0] = (byte) 4; b[1] = (byte) 23; b[2] = (byte) 5; String result = ISOUtil.dumpString(b); assertEquals("result", "{EOT}[17]{ENQ}{NULL}", result); } @Test public void testDumpString60() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 5; b[1] = (byte) 32; b[2] = (byte) 127; b[3] = (byte) 21; b[4] = (byte) -9; String result = ISOUtil.dumpString(b); assertEquals("result", "{ENQ} [7F]{NAK}\uFFF7", result); } @Test public void testDumpString61() throws Throwable { byte[] b = new byte[5]; b[1] = (byte) -20; b[2] = (byte) 13; b[4] = (byte) 4; String result = ISOUtil.dumpString(b); assertEquals("result", "{NULL}\uFFEC{CR}{NULL}{EOT}", result); } @Test public void testDumpString62() throws Throwable { byte[] b = new byte[4]; b[0] = (byte) 4; b[1] = (byte) 23; b[2] = (byte) 5; b[3] = (byte) 29; String result = ISOUtil.dumpString(b); assertEquals("result", "{EOT}[17]{ENQ}[1D]", result); } @Test public void testDumpString63() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 1; b[1] = (byte) -15; String result = ISOUtil.dumpString(b); assertEquals("result", "{SOH}\uFFF1{NULL}{NULL}{NULL}", result); } @Test public void testDumpString64() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 3; b[1] = (byte) -20; b[2] = (byte) 13; b[3] = (byte) -24; b[4] = (byte) 4; String result = ISOUtil.dumpString(b); assertEquals("result", "{ETX}\uFFEC{CR}\uFFE8{EOT}", result); } @Test public void testDumpString65() throws Throwable { byte[] b = new byte[4]; b[0] = (byte) 22; b[1] = (byte) -18; b[2] = (byte) 30; b[3] = (byte) -27; String result = ISOUtil.dumpString(b); assertEquals("result", "{SYN}\uFFEE{RS}\uFFE5", result); } @Test public void testDumpString66() throws Throwable { byte[] b = new byte[3]; b[2] = (byte) 6; String result = ISOUtil.dumpString(b); assertEquals("result", "{NULL}{NULL}{ACK}", result); } @Test public void testDumpString67() throws Throwable { byte[] b = new byte[3]; b[0] = (byte) 2; b[1] = (byte) 16; String result = ISOUtil.dumpString(b); assertEquals("result", "{STX}{DLE}{NULL}", result); } @Test public void testDumpString68() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 2; b[1] = (byte) -21; b[4] = (byte) 31; String result = ISOUtil.dumpString(b); assertEquals("result", "{STX}\uFFEB{NULL}{NULL}[1F]", result); } @Test public void testDumpString69() throws Throwable { byte[] b = new byte[2]; b[1] = (byte) -15; String result = ISOUtil.dumpString(b); assertEquals("result", "{NULL}\uFFF1", result); } @Test public void testDumpString7() throws Throwable { byte[] b = new byte[5]; b[1] = (byte) -21; b[3] = (byte) 7; b[4] = (byte) 31; String result = ISOUtil.dumpString(b); assertEquals("result", "{NULL}\uFFEB{NULL}{BEL}[1F]", result); } @Test public void testDumpString70() throws Throwable { byte[] b = new byte[2]; b[0] = (byte) 22; b[1] = (byte) 29; String result = ISOUtil.dumpString(b); assertEquals("result", "{SYN}[1D]", result); } @Test public void testDumpString71() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 2; b[1] = (byte) 15; b[3] = (byte) 4; b[4] = (byte) 28; String result = ISOUtil.dumpString(b); assertEquals("result", "{STX}[0F]{NULL}{EOT}{FS}", result); } @Test public void testDumpString72() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 30; b[1] = (byte) -29; b[2] = (byte) -8; b[3] = (byte) 7; b[4] = (byte) 9; String result = ISOUtil.dumpString(b); assertEquals("result", "{RS}\uFFE3\uFFF8{BEL}[09]", result); } @Test public void testDumpString73() throws Throwable { byte[] b = new byte[2]; b[0] = (byte) 3; b[1] = (byte) 92; String result = ISOUtil.dumpString(b); assertEquals("result", "{ETX}\\", result); } @Test public void testDumpString74() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 21; b[2] = (byte) -128; b[4] = (byte) 16; String result = ISOUtil.dumpString(b); assertEquals("result", "{NAK}{NULL}\uFF80{NULL}{DLE}", result); } @Test public void testDumpString75() throws Throwable { byte[] b = new byte[2]; b[0] = (byte) -19; b[1] = (byte) 30; String result = ISOUtil.dumpString(b); assertEquals("result", "\uFFED{RS}", result); } @Test public void testDumpString76() throws Throwable { byte[] b = new byte[2]; b[0] = (byte) 6; b[1] = (byte) -27; String result = ISOUtil.dumpString(b); assertEquals("result", "{ACK}\uFFE5", result); } @Test public void testDumpString77() throws Throwable { byte[] b = new byte[3]; b[1] = (byte) 28; b[2] = (byte) 3; String result = ISOUtil.dumpString(b); assertEquals("result", "{NULL}{FS}{ETX}", result); } @Test public void testDumpString78() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 3; b[1] = (byte) -20; b[2] = (byte) 13; String result = ISOUtil.dumpString(b); assertEquals("result", "{ETX}\uFFEC{CR}{NULL}{NULL}", result); } @Test public void testDumpString79() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 4; b[2] = (byte) 13; b[3] = (byte) -23; b[4] = (byte) 23; String result = ISOUtil.dumpString(b); assertEquals("result", "{EOT}{NULL}{CR}\uFFE9[17]", result); } @Test public void testDumpString8() throws Throwable { byte[] b = new byte[5]; b[1] = (byte) 15; b[2] = (byte) -93; b[3] = (byte) 4; b[4] = (byte) 28; String result = ISOUtil.dumpString(b); assertEquals("result", "{NULL}[0F]\uFFA3{EOT}{FS}", result); } @Test public void testDumpString80() throws Throwable { byte[] b = new byte[4]; b[0] = (byte) 22; b[1] = (byte) 30; b[3] = (byte) -3; String result = ISOUtil.dumpString(b); assertEquals("result", "{SYN}{RS}{NULL}\uFFFD", result); } @Test public void testDumpString81() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 2; b[1] = (byte) 21; b[3] = (byte) 28; String result = ISOUtil.dumpString(b); assertEquals("result", "{STX}{NAK}{NULL}{FS}{NULL}", result); } @Test public void testDumpString82() throws Throwable { byte[] b = new byte[2]; b[1] = (byte) 15; String result = ISOUtil.dumpString(b); assertEquals("result", "{NULL}[0F]", result); } @Test public void testDumpString83() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 3; b[1] = (byte) -20; b[2] = (byte) 13; b[4] = (byte) 4; String result = ISOUtil.dumpString(b); assertEquals("result", "{ETX}\uFFEC{CR}{NULL}{EOT}", result); } @Test public void testDumpString84() throws Throwable { byte[] b = new byte[3]; b[0] = (byte) 3; b[2] = (byte) 6; String result = ISOUtil.dumpString(b); assertEquals("result", "{ETX}{NULL}{ACK}", result); } @Test public void testDumpString85() throws Throwable { byte[] b = new byte[4]; b[0] = (byte) 22; b[2] = (byte) 9; b[3] = (byte) -9; String result = ISOUtil.dumpString(b); assertEquals("result", "{SYN}{NULL}[09]\uFFF7", result); } @Test public void testDumpString86() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 3; b[1] = (byte) 30; b[2] = (byte) -91; b[3] = (byte) 94; b[4] = (byte) -30; String result = ISOUtil.dumpString(b); assertEquals("result", "{ETX}{RS}\uFFA5^\uFFE2", result); } @Test public void testDumpString87() throws Throwable { byte[] b = new byte[3]; b[0] = (byte) 7; b[1] = (byte) -24; b[2] = (byte) 90; String result = ISOUtil.dumpString(b); assertEquals("result", "{BEL}\uFFE8Z", result); } @Test public void testDumpString88() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 2; b[1] = (byte) -21; b[3] = (byte) 7; String result = ISOUtil.dumpString(b); assertEquals("result", "{STX}\uFFEB{NULL}{BEL}{NULL}", result); } @Test public void testDumpString89() throws Throwable { byte[] b = new byte[1]; String result = ISOUtil.dumpString(b); assertEquals("result", "{NULL}", result); } @Test public void testDumpString9() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 6; b[2] = (byte) 94; String result = ISOUtil.dumpString(b); assertEquals("result", "{ACK}{NULL}^{NULL}{NULL}", result); } @Test public void testDumpString90() throws Throwable { byte[] b = new byte[2]; b[0] = (byte) 1; b[1] = (byte) 10; String result = ISOUtil.dumpString(b); assertEquals("result", "{SOH}{LF}", result); } @Test public void testDumpString91() throws Throwable { byte[] b = new byte[4]; b[0] = (byte) 22; b[1] = (byte) 30; b[2] = (byte) 2; String result = ISOUtil.dumpString(b); assertEquals("result", "{SYN}{RS}{STX}{NULL}", result); } @Test public void testDumpString92() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 21; b[1] = (byte) 22; b[2] = (byte) 7; b[3] = (byte) 29; String result = ISOUtil.dumpString(b); assertEquals("result", "{NAK}{SYN}{BEL}[1D]{NULL}", result); } @Test public void testDumpString93() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 21; b[1] = (byte) 22; b[2] = (byte) 7; b[3] = (byte) 29; b[4] = (byte) -17; String result = ISOUtil.dumpString(b); assertEquals("result", "{NAK}{SYN}{BEL}[1D]\uFFEF", result); } @Test public void testDumpString94() throws Throwable { byte[] b = new byte[3]; b[0] = (byte) 3; String result = ISOUtil.dumpString(b); assertEquals("result", "{ETX}{NULL}{NULL}", result); } @Test public void testDumpString95() throws Throwable { byte[] b = new byte[4]; b[1] = (byte) 6; b[2] = (byte) 25; String result = ISOUtil.dumpString(b); assertEquals("result", "{NULL}{ACK}[19]{NULL}", result); } @Test public void testDumpString96() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 21; b[2] = (byte) 7; b[3] = (byte) 29; b[4] = (byte) -17; String result = ISOUtil.dumpString(b); assertEquals("result", "{NAK}{NULL}{BEL}[1D]\uFFEF", result); } @Test public void testDumpString97() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 30; b[1] = (byte) -29; b[3] = (byte) 7; String result = ISOUtil.dumpString(b); assertEquals("result", "{RS}\uFFE3{NULL}{BEL}{NULL}", result); } @Test public void testDumpString98() throws Throwable { byte[] b = new byte[4]; b[0] = (byte) 28; b[2] = (byte) 16; b[3] = (byte) 31; String result = ISOUtil.dumpString(b); assertEquals("result", "{FS}{NULL}{DLE}[1F]", result); } @Test public void testDumpString99() throws Throwable { byte[] b = new byte[5]; b[0] = (byte) 30; b[1] = (byte) -29; b[3] = (byte) 7; b[4] = (byte) 9; String result = ISOUtil.dumpString(b); assertEquals("result", "{RS}\uFFE3{NULL}{BEL}[09]", result); } @Test(expected = NullPointerException.class) public void testDumpStringThrowsNullPointerException() throws Throwable { ISOUtil.dumpString(null); } @Test public void testEbcdicToAscii() throws Throwable { byte[] e = new byte[2]; String result = ISOUtil.ebcdicToAscii(e); assertEquals("result", "\u0000\u0000", result); } @Test public void testEbcdicToAscii1() throws Throwable { byte[] e = new byte[3]; String result = ISOUtil.ebcdicToAscii(e, 0, 1); assertEquals("result", "\u0000", result); } @Test public void testEbcdicToAsciiBytes() throws Throwable { byte[] e = new byte[2]; byte[] result = ISOUtil.ebcdicToAsciiBytes(e, 0, 1); assertEquals("result.length", 1, result.length); assertEquals("result[0]", (byte) 0, result[0]); } @Test public void testEbcdicToAsciiBytes2() throws Throwable { byte[] e = new byte[0]; byte[] result = ISOUtil.ebcdicToAsciiBytes(e); assertEquals("result.length", 0, result.length); } @Test public void testEbcdicToAsciiBytes3() throws Throwable { byte[] e = new byte[2]; byte[] result = ISOUtil.ebcdicToAsciiBytes(e); assertEquals("result.length", 2, result.length); assertEquals("result[0]", (byte) 0, result[0]); } @Test(expected=IndexOutOfBoundsException.class) public void testEbcdicToAsciiBytesThrowsArrayIndexOutOfBoundsException() throws Throwable { ISOUtil.ebcdicToAsciiBytes(new byte[1], 0, 100); } @Test(expected=IndexOutOfBoundsException.class) public void testEbcdicToAsciiBytesThrowsArrayIndexOutOfBoundsException1() throws Throwable { ISOUtil.ebcdicToAsciiBytes(new byte[1], 100, 1000); } @Test(expected = IndexOutOfBoundsException.class) public void testEbcdicToAsciiBytesThrowsNegativeArraySizeException() throws Throwable { byte[] e = new byte[1]; ISOUtil.ebcdicToAsciiBytes(e, 100, -1); } @Test(expected = NullPointerException.class) public void testEbcdicToAsciiBytesThrowsNullPointerException() throws Throwable { ISOUtil.ebcdicToAsciiBytes(null, 100, 1000); } @Test(expected = NullPointerException.class) public void testEbcdicToAsciiBytesThrowsNullPointerException1() throws Throwable { ISOUtil.ebcdicToAsciiBytes(null); } @Test(expected=IndexOutOfBoundsException.class) public void testEbcdicToAsciiThrowsArrayIndexOutOfBoundsException() throws Throwable { ISOUtil.ebcdicToAscii(new byte[1], 100, 1000); } @Test(expected = IndexOutOfBoundsException.class) public void testEbcdicToAsciiThrowsNegativeArraySizeException() throws Throwable { ISOUtil.ebcdicToAscii(new byte[1], 100, -1); } @Test(expected = NullPointerException.class) public void testEbcdicToAsciiThrowsNullPointerException() throws Throwable { ISOUtil.ebcdicToAscii(null); } @Test public void testFormatAmount() throws Throwable { String result = ISOUtil.formatAmount(100000L, 7); assertEquals("result", "1000.00", result); } @Test public void testFormatAmount1() throws Throwable { String result = ISOUtil.formatAmount(1000L, 100); assertEquals("result", " 10.00", result); } @Test public void testFormatAmount2() throws Throwable { String result = ISOUtil.formatAmount(100L, 100); assertEquals("result", " 1.00", result); } @Test public void testFormatAmount3() throws Throwable { String result = ISOUtil.formatAmount(99L, 100); assertEquals("result", " 0.99", result); } @Test public void testFormatAmount4() throws Throwable { String result = ISOUtil.formatAmount(101L, 4); assertEquals("result", "1.01", result); } @Test public void testFormatAmountThrowsISOException() throws Throwable { try { ISOUtil.formatAmount(99L, 0); fail("Expected ISOException to be thrown"); } catch (ISOException ex) { assertEquals("ex.getMessage()", "invalid len 3/-1", ex.getMessage()); assertNull("ex.nested", ex.nested); } } @Test public void testFormatAmountThrowsISOException1() throws Throwable { try { ISOUtil.formatAmount(100L, 0); fail("Expected ISOException to be thrown"); } catch (ISOException ex) { assertEquals("ex.getMessage()", "invalid len 3/-1", ex.getMessage()); assertNull("ex.nested", ex.nested); } } @Test public void testFormatAmountThrowsISOException2() throws Throwable { try { ISOUtil.formatAmount(Long.MIN_VALUE, 100); fail("Expected ISOException to be thrown"); } catch (ISOException ex) { assertEquals("ex.getMessage()", "invalid len 20/3", ex.getMessage()); assertNull("ex.nested", ex.nested); } } @Test public void testFormatDouble() throws Throwable { String result = ISOUtil.formatDouble(100.0, 100); assertEquals("result", " 100.00", result); } @Test public void testFormatDouble1() throws Throwable { String result = ISOUtil.formatDouble(100.0, 0); assertEquals("result", "100.00", result); } @Test public void testHex2BitSet() throws Throwable { byte[] b = new byte[82]; BitSet result = ISOUtil.hex2BitSet(b, 0, false); assertEquals("result.size()", 128, result.size()); } @Test public void testHex2BitSet1() throws Throwable { byte[] b = new byte[82]; BitSet result = ISOUtil.hex2BitSet(b, 0, true); assertEquals("result.size()", 256, result.size()); } @Test public void testHex2BitSet10() throws Throwable { byte[] b = new byte[80]; BitSet result = ISOUtil.hex2BitSet(b, 0, 1000); assertEquals("result.size()", 384, result.size()); } @Test public void testHex2BitSet3() throws Throwable { byte[] b = new byte[0]; BitSet result = ISOUtil.hex2BitSet(null, b, 100); assertNull("result", result); } @Test public void testHex2BitSet4() throws Throwable { byte[] b = new byte[20]; b[11] = (byte) 65; BitSet result = ISOUtil.hex2BitSet(b, 0, false); assertEquals("result.size()", 128, result.size()); } @Test public void testHex2BitSet7() throws Throwable { byte[] b = new byte[46]; BitSet result = ISOUtil.hex2BitSet(b, 0, 64); assertEquals("result.size()", 128, result.size()); } @Test public void testHex2BitSet9() throws Throwable { byte[] b = new byte[80]; BitSet result = ISOUtil.hex2BitSet(b, 0, 100); assertEquals("result.size()", 256, result.size()); } @Test public void testHex2BitSetThrowsArrayIndexOutOfBoundsException() throws Throwable { byte[] b = new byte[19]; b[14] = (byte) 65; try { ISOUtil.hex2BitSet(b, 0, true); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "19", ex.getMessage()); } } @Test public void testHex2BitSetThrowsArrayIndexOutOfBoundsException1() throws Throwable { byte[] b = new byte[2]; b[1] = (byte) 48; try { ISOUtil.hex2BitSet(b, 0, false); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "2", ex.getMessage()); } } @Test public void testHex2BitSetThrowsArrayIndexOutOfBoundsException10() throws Throwable { byte[] b = new byte[19]; b[4] = (byte) 65; try { ISOUtil.hex2BitSet(b, 0, 65); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "19", ex.getMessage()); } } @Test public void testHex2BitSetThrowsArrayIndexOutOfBoundsException11() throws Throwable { byte[] b = new byte[83]; b[68] = (byte) 65; try { ISOUtil.hex2BitSet(b, 66, 127); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "83", ex.getMessage()); } } @Test public void testHex2BitSetThrowsArrayIndexOutOfBoundsException12() throws Throwable { byte[] b = new byte[19]; try { ISOUtil.hex2BitSet(b, 0, 65); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "19", ex.getMessage()); } } @Test public void testHex2BitSetThrowsArrayIndexOutOfBoundsException13() throws Throwable { byte[] b = new byte[20]; b[16] = (byte) 66; try { ISOUtil.hex2BitSet(b, 0, 100); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "20", ex.getMessage()); } } @Test public void testHex2BitSetThrowsArrayIndexOutOfBoundsException2() throws Throwable { byte[] b = new byte[18]; try { ISOUtil.hex2BitSet(b, 0, 1000); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "18", ex.getMessage()); } } @Test public void testHex2BitSetThrowsArrayIndexOutOfBoundsException3() throws Throwable { byte[] b = new byte[3]; b[0] = (byte) 66; try { ISOUtil.hex2BitSet(b, 0, 64); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "3", ex.getMessage()); } } @Test public void testHex2BitSetThrowsArrayIndexOutOfBoundsException4() throws Throwable { byte[] b = new byte[3]; try { ISOUtil.hex2BitSet(b, 0, 65); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "3", ex.getMessage()); } } @Test public void testHex2BitSetThrowsArrayIndexOutOfBoundsException5() throws Throwable { byte[] b = new byte[3]; try { ISOUtil.hex2BitSet(b, 0, 63); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "3", ex.getMessage()); } } @Test public void testHex2BitSetThrowsArrayIndexOutOfBoundsException6() throws Throwable { byte[] b = new byte[3]; try { ISOUtil.hex2BitSet(b, 0, true); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "3", ex.getMessage()); } } @Test public void testHex2BitSetThrowsArrayIndexOutOfBoundsException7() throws Throwable { byte[] b = new byte[1]; try { ISOUtil.hex2BitSet(b, 0, false); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "1", ex.getMessage()); } } @Test public void testHex2BitSetThrowsArrayIndexOutOfBoundsException8() throws Throwable { byte[] b = new byte[2]; try { ISOUtil.hex2BitSet(b, 100, false); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "100", ex.getMessage()); } } @Test public void testHex2BitSetThrowsArrayIndexOutOfBoundsException9() throws Throwable { byte[] b = new byte[0]; try { ISOUtil.hex2BitSet(b, 100, true); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "100", ex.getMessage()); } } @Test public void testHex2BitSetThrowsIndexOutOfBoundsException() throws Throwable { BitSet bmap = new BitSet(100); byte[] b = new byte[2]; ISOUtil.byte2BitSet(bmap, b, 100); byte[] b2 = new byte[4]; try { ISOUtil.hex2BitSet(bmap, b2, -29); fail("Expected IndexOutOfBoundsException to be thrown"); } catch (IndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "bitIndex < 0: -28", ex.getMessage()); assertEquals("bmap.size()", 128, bmap.size()); } } @Test(expected = NullPointerException.class) public void testHex2BitSetThrowsNullPointerException() throws Throwable { ISOUtil.hex2BitSet(null, 100, true); } @Test(expected = NullPointerException.class) public void testHex2BitSetThrowsNullPointerException1() throws Throwable { ISOUtil.hex2BitSet(null, 100, 63); } @Test(expected = NullPointerException.class) public void testHex2BitSetThrowsNullPointerException2() throws Throwable { ISOUtil.hex2BitSet(null, 100, 65); } @Test(expected = NullPointerException.class) public void testHex2BitSetThrowsNullPointerException3() throws Throwable { byte[] b = new byte[2]; ISOUtil.hex2BitSet(null, b, 100); } @Test public void testHex2BitSetThrowsNullPointerException4() throws Throwable { BitSet bmap = new BitSet(); try { ISOUtil.hex2BitSet(bmap, null, 100); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { assertNull("ex.getMessage()", ex.getMessage()); assertEquals("bmap.size()", 64, bmap.size()); } } @Test public void testHex2byte() throws Throwable { byte[] b = new byte[3]; byte[] result = ISOUtil.hex2byte(b, 0, 1); assertEquals("result.length", 1, result.length); assertEquals("result[0]", (byte) -1, result[0]); } @Test public void testHex2byte1() throws Throwable { byte[] b = new byte[3]; byte[] result = ISOUtil.hex2byte(b, 100, 0); assertEquals("result.length", 0, result.length); } @Test public void testHex2byte2() throws Throwable { byte[] result = ISOUtil.hex2byte(""); assertEquals("result.length", 0, result.length); } @Test public void testHex2byte3() throws Throwable { byte[] result = ISOUtil.hex2byte("testISOUtils"); assertEquals("result.length", 6, result.length); assertEquals("result[0]", (byte) -2, result[0]); } @Test public void testHex2byteThrowsArrayIndexOutOfBoundsException() throws Throwable { byte[] b = new byte[3]; try { ISOUtil.hex2byte(b, 0, 100); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "3", ex.getMessage()); } } @Test(expected = NegativeArraySizeException.class) public void testHex2byteThrowsNegativeArraySizeException() throws Throwable { byte[] b = new byte[1]; ISOUtil.hex2byte(b, 100, -1); } @Test(expected = NullPointerException.class) public void testHex2byteThrowsNullPointerException() throws Throwable { ISOUtil.hex2byte(null, 100, 1000); } @Test(expected = NullPointerException.class) public void testHex2byteThrowsNullPointerException1() throws Throwable { ISOUtil.hex2byte(null); } @Test public void testHex2byteThrowsRuntimeException() throws Throwable { byte[] result = ISOUtil.hex2byte("testISOUtils1"); assertNotNull(result); } @Test public void testHexdump() throws Throwable { byte[] b = new byte[34]; b[16] = (byte) 127; String result = ISOUtil.hexdump(b, 0, 17); assertEquals("result", "0000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................" + lineSep + "0010 7F ." + lineSep, result); } @Test public void testHexdump1() throws Throwable { byte[] b = new byte[34]; b[17] = (byte) 31; String result = ISOUtil.hexdump(b, 0, 32); assertEquals("result", "0000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................" + lineSep + "0010 00 1F 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................" + lineSep, result); } @Test public void testHexdump10() throws Throwable { byte[] b = new byte[2]; b[1] = (byte) 32; String result = ISOUtil.hexdump(b); assertEquals("result", "0000 00 20 . " + lineSep, result); } @Test public void testHexdump11() throws Throwable { byte[] b = new byte[3]; b[1] = (byte) 127; String result = ISOUtil.hexdump(b); assertEquals("result", "0000 00 7F 00 ..." + lineSep, result); } @Test public void testHexdump12() throws Throwable { byte[] b = new byte[12]; b[8] = (byte) 32; String result = ISOUtil.hexdump(b, 0, 10); assertEquals("result", "0000 00 00 00 00 00 00 00 00 20 00 ........ ." + lineSep, result); } @Test public void testHexdump13() throws Throwable { byte[] b = new byte[0]; String result = ISOUtil.hexdump(b); assertEquals("result", "", result); } @Test public void testHexdump14() throws Throwable { byte[] b = new byte[2]; b[0] = (byte) 126; String result = ISOUtil.hexdump(b); assertEquals("result", "0000 7E 00 ~." + lineSep, result); } @Test public void testHexdump15() throws Throwable { byte[] b = new byte[1]; b[0] = (byte) 33; String result = ISOUtil.hexdump(b); assertEquals("result", "0000 21 !" + lineSep, result); } @Test public void testHexdump16() throws Throwable { byte[] b = new byte[2]; b[0] = (byte) 31; String result = ISOUtil.hexdump(b); assertEquals("result", "0000 1F 00 .." + lineSep, result); } @Test public void testHexdump17() throws Throwable { byte[] b = new byte[3]; b[1] = (byte) 31; String result = ISOUtil.hexdump(b, 0, 3); assertEquals("result", "0000 00 1F 00 ..." + lineSep, result); } @Test public void testHexdump18() throws Throwable { byte[] b = new byte[19]; b[0] = (byte) 127; b[1] = (byte) 32; b[5] = (byte) 31; String result = ISOUtil.hexdump(b, 0, 17); assertEquals("result", "0000 7F 20 00 00 00 1F 00 00 00 00 00 00 00 00 00 00 . .............." + lineSep + "0010 00 ." + lineSep, result); } @Test public void testHexdump19() throws Throwable { byte[] b = new byte[19]; b[0] = (byte) 127; b[1] = (byte) 32; String result = ISOUtil.hexdump(b, 0, 2); assertEquals("result", "0000 7F 20 . " + lineSep, result); } @Test public void testHexdump2() throws Throwable { byte[] b = new byte[19]; b[1] = (byte) 32; b[5] = (byte) 31; String result = ISOUtil.hexdump(b, 0, 17); assertEquals("result", "0000 00 20 00 00 00 1F 00 00 00 00 00 00 00 00 00 00 . .............." + lineSep + "0010 00 ." + lineSep, result); } @Test public void testHexdump20() throws Throwable { byte[] b = new byte[1]; b[0] = (byte) 32; String result = ISOUtil.hexdump(b, 0, 1); assertEquals("result", "0000 20 " + lineSep, result); } @Test public void testHexdump21() throws Throwable { byte[] b = new byte[19]; b[0] = (byte) 127; b[1] = (byte) 32; String result = ISOUtil.hexdump(b, 0, 3); assertEquals("result", "0000 7F 20 00 . ." + lineSep, result); } @Test public void testHexdump22() throws Throwable { byte[] b = new byte[18]; b[14] = (byte) 46; String result = ISOUtil.hexdump(b, 10,5); assertEquals("result", "0000 00 00 00 00 2E ....." + lineSep, result); } @Test public void testHexdump23() throws Throwable { byte[] b = new byte[12]; b[6] = (byte) -48; String result = ISOUtil.hexdump(b, 0, 10); assertEquals("result", "0000 00 00 00 00 00 00 D0 00 00 00 .........." + lineSep, result); } @Test public void testHexdump3() throws Throwable { byte[] b = new byte[2]; String result = ISOUtil.hexdump(b, 100, 0); assertEquals("result", "", result); } @Test public void testHexdump4() throws Throwable { byte[] b = new byte[3]; b[1] = (byte) -4; String result = ISOUtil.hexdump(b, 1, 1); assertEquals("result", "0000 FC ." + lineSep, result); } @Test public void testHexdump5() throws Throwable { byte[] b = new byte[19]; b[0] = (byte) 127; b[1] = (byte) 32; b[5] = (byte) 31; String result = ISOUtil.hexdump(b, 0, 10); assertEquals("result", "0000 7F 20 00 00 00 1F 00 00 00 00 . ........" + lineSep, result); } @Test public void testHexdump6() throws Throwable { byte[] b = new byte[34]; String result = ISOUtil.hexdump(b, 0, 10); assertEquals("result", "0000 00 00 00 00 00 00 00 00 00 00 .........." + lineSep, result); } @Test public void testHexdump7() throws Throwable { byte[] b = new byte[10]; b[7] = (byte) -2; String result = ISOUtil.hexdump(b, 7, 1); assertEquals("result", "0000 FE ." + lineSep, result); } @Test public void testHexdump8() throws Throwable { byte[] b = new byte[3]; b[1] = (byte) 31; b[2] = (byte) -48; String result = ISOUtil.hexdump(b, 0, 3); assertEquals("result", "0000 00 1F D0 ..." + lineSep, result); } @Test public void testHexdump9() throws Throwable { byte[] b = new byte[34]; b[16] = (byte) 127; String result = ISOUtil.hexdump(b, 0, 32); assertEquals("result", "0000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................" + lineSep + "0010 7F 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................" + lineSep, result); } @Test public void testHexdumpThrowsArrayIndexOutOfBoundsException() throws Throwable { byte[] b = new byte[19]; b[0] = (byte) 127; b[1] = (byte) 32; b[5] = (byte) 31; try { ISOUtil.hexdump(b, 0, 100); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "19", ex.getMessage()); } } @Test public void testHexdumpThrowsArrayIndexOutOfBoundsException1() throws Throwable { byte[] b = new byte[34]; b[16] = (byte) 127; b[17] = (byte) 31; try { ISOUtil.hexdump(b, 0, 100); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "34", ex.getMessage()); } } @Test public void testHexdumpThrowsArrayIndexOutOfBoundsException10() throws Throwable { byte[] b = new byte[2]; try { ISOUtil.hexdump(b, 0, 100); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "2", ex.getMessage()); } } @Test public void testHexdumpThrowsArrayIndexOutOfBoundsException11() throws Throwable { byte[] b = new byte[1]; b[0] = (byte) -49; try { ISOUtil.hexdump(b, 0, 100); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "1", ex.getMessage()); } } @Test public void testHexdumpThrowsArrayIndexOutOfBoundsException12() throws Throwable { byte[] b = new byte[10]; b[7] = (byte) -2; try { ISOUtil.hexdump(b, 0, 100); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "10", ex.getMessage()); } } @Test public void testHexdumpThrowsArrayIndexOutOfBoundsException2() throws Throwable { byte[] b = new byte[3]; b[1] = (byte) 49; b[2] = (byte) -2; try { ISOUtil.hexdump(b, 0, 100); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "3", ex.getMessage()); } } @Test public void testHexdumpThrowsArrayIndexOutOfBoundsException3() throws Throwable { byte[] b = new byte[9]; b[7] = (byte) 46; try { ISOUtil.hexdump(b, 0, 100); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "9", ex.getMessage()); } } @Test public void testHexdumpThrowsArrayIndexOutOfBoundsException4() throws Throwable { byte[] b = new byte[3]; b[1] = (byte) 49; try { ISOUtil.hexdump(b, 0, 100); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "3", ex.getMessage()); } } @Test public void testHexdumpThrowsArrayIndexOutOfBoundsException5() throws Throwable { byte[] b = new byte[18]; b[14] = (byte) 46; try { ISOUtil.hexdump(b, 10, 100); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "18", ex.getMessage()); } } @Test public void testHexdumpThrowsArrayIndexOutOfBoundsException6() throws Throwable { byte[] b = new byte[12]; b[6] = (byte) -48; b[8] = (byte) 32; try { ISOUtil.hexdump(b, 0, 100); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "12", ex.getMessage()); } } @Test public void testHexdumpThrowsArrayIndexOutOfBoundsException7() throws Throwable { byte[] b = new byte[3]; b[1] = (byte) 31; b[2] = (byte) -48; try { ISOUtil.hexdump(b, 0, 100); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "3", ex.getMessage()); } } @Test public void testHexdumpThrowsArrayIndexOutOfBoundsException8() throws Throwable { byte[] b = new byte[1]; b[0] = (byte) 32; try { ISOUtil.hexdump(b, 0, 100); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "1", ex.getMessage()); } } @Test public void testHexdumpThrowsArrayIndexOutOfBoundsException9() throws Throwable { byte[] b = new byte[9]; b[7] = (byte) 46; b[8] = (byte) -3; try { ISOUtil.hexdump(b, 7, 100); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "9", ex.getMessage()); } } @Test(expected = NullPointerException.class) public void testHexdumpThrowsNullPointerException() throws Throwable { ISOUtil.hexdump(null, 100, 1000); } @Test(expected = NullPointerException.class) public void testHexdumpThrowsNullPointerException1() throws Throwable { ISOUtil.hexdump(null); } @Test public void testHexor() throws Throwable { String result = ISOUtil.hexor("", ""); assertEquals("result", "", result); } @Test public void testHexor1() throws Throwable { String result = ISOUtil.hexor("testISOUtilOp1", "testISOUtilOp2"); assertEquals("result", "00000000000003", result); } @Test public void testHexString() throws Throwable { byte[] b = new byte[2]; String result = ISOUtil.hexString(b, 0, 1); assertEquals("result", "00", result); } @Test public void testHexString1() throws Throwable { byte[] b = new byte[3]; String result = ISOUtil.hexString(b, 100, 0); assertEquals("result", "", result); } @Test public void testHexString2() throws Throwable { byte[] b = new byte[1]; String result = ISOUtil.hexString(b); assertEquals("result", "00", result); } @Test public void testHexString3() throws Throwable { byte[] b = new byte[0]; String result = ISOUtil.hexString(b); assertEquals("result", "", result); } @Test public void testHexStringThrowsArrayIndexOutOfBoundsException() throws Throwable { byte[] b = new byte[3]; try { ISOUtil.hexString(b, 100, 1000); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "100", ex.getMessage()); } } @Test public void testHexStringThrowsArrayIndexOutOfBoundsException1() throws Throwable { byte[] b = new byte[1]; try { ISOUtil.hexString(b, 0, 100); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "1", ex.getMessage()); } } @Test(expected = NegativeArraySizeException.class) public void testHexStringThrowsNegativeArraySizeException() throws Throwable { byte[] b = new byte[1]; ISOUtil.hexString(b, 100, -1); } @Test(expected = NullPointerException.class) public void testHexStringThrowsNullPointerException() throws Throwable { ISOUtil.hexString(null, 100, 1000); } @Test(expected = NullPointerException.class) public void testHexStringThrowsNullPointerException1() throws Throwable { ISOUtil.hexString(null); } @Test public void testIsAlphaNumeric() throws Throwable { boolean result = ISOUtil.isAlphaNumeric("testISOUtil\rs"); assertFalse("result", result); } @Test public void testIsAlphaNumeric1() throws Throwable { boolean result = ISOUtil.isAlphaNumeric(")\r3\u001F,\u0011-\u0005\u000FU\u000E5M2)\u0017h\u0011&ln" + lineSep + "G4@\u0015\u000272A\u001D9&qW\u001An|YP"); assertFalse("result", result); } @Test(expected = NullPointerException.class) public void testIsAlphaNumericThrowsNullPointerException() throws Throwable { ISOUtil.isAlphaNumeric(null); } @Test public void testIsAlphaNumericThrowsStringIndexOutOfBoundsException() throws Throwable { try { ISOUtil.isAlphaNumeric(" "); fail("Expected StringIndexOutOfBoundsException to be thrown"); } catch (StringIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "String index out of range: 1", ex.getMessage()); } } @Test public void testIsAlphaNumericThrowsStringIndexOutOfBoundsException1() throws Throwable { try { ISOUtil.isAlphaNumeric(""); fail("Expected StringIndexOutOfBoundsException to be thrown"); } catch (StringIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "String index out of range: 0", ex.getMessage()); } } @Test public void testIsAlphaNumericThrowsStringIndexOutOfBoundsException2() throws Throwable { try { ISOUtil.isAlphaNumeric("testISOUtils"); fail("Expected StringIndexOutOfBoundsException to be thrown"); } catch (StringIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "String index out of range: 12", ex.getMessage()); } } @Test public void testIsBlank() throws Throwable { boolean result = ISOUtil.isBlank(""); assertTrue("result", result); } @Test public void testIsBlank1() throws Throwable { boolean result = ISOUtil.isBlank("1"); assertFalse("result", result); } @Test(expected = NullPointerException.class) public void testIsBlankThrowsNullPointerException() throws Throwable { ISOUtil.isBlank(null); } @Test public void testIsNumeric() throws Throwable { boolean result = ISOUtil.isNumeric("10Characte", 32); assertTrue("result", result); } @Test public void testIsNumeric1() throws Throwable { boolean result = ISOUtil.isNumeric("testISOUtils", 100); assertFalse("result", result); } @Test public void testIsNumeric2() throws Throwable { boolean result = ISOUtil.isNumeric("testISOUtil\rs", 32); assertFalse("result", result); } @Test public void testIsNumeric3() throws Throwable { boolean result = ISOUtil.isNumeric("", 100); assertFalse("result", result); } @Test(expected = NullPointerException.class) public void testIsNumericThrowsNullPointerException() throws Throwable { ISOUtil.isNumeric(null, 100); } @Test public void testIsZero() throws Throwable { boolean result = ISOUtil.isZero("0 q"); assertFalse("result", result); } @Test public void testIsZero1() throws Throwable { boolean result = ISOUtil.isZero("000"); assertTrue("result", result); } @Test public void testIsZero2() throws Throwable { boolean result = ISOUtil.isZero("testISOUtils"); assertFalse("result", result); } @Test public void testIsZero3() throws Throwable { boolean result = ISOUtil.isZero(""); assertTrue("result", result); } @Test(expected = NullPointerException.class) public void testIsZeroThrowsNullPointerException() throws Throwable { ISOUtil.isZero(null); } @Test public void testNormalize() throws Throwable { String result = ISOUtil .normalize( "S\u0002\"m\u0011Ap}q\\!\u0005\u0010$:\"X\u0008FM\u00028\u000E&CZ#\"\"]'\u0008k\"\u000B$jT>L\u0017-<3z\u0000%E<\u0011\"j\u001F\u0014\u001C\fR\u00138\r\">\u0016<T7l\u0002]oM|w\"$4*ks{~Cqqx7fW^^zi}gV;cY<A=ylA%DR-9", true); assertEquals( "result", "S\\u0002&quot;m\\u0011Ap}q\\!\\u0005\\u0010$:&quot;X\\u0008FM\\u00028\\u000e&amp;CZ#&quot;&quot;]&apos;\\u0008k&quot;\\u000b$jT&gt;L\\u0017-&lt;3z\\u0000%E&lt;\\u0011&quot;j\\u001f\\u0014\\u001c\\u000cR\\u00138\\u000d&quot;&gt;\\u0016&lt;T7l\\u0002]oM|w&quot;$4*ks{~Cqqx7fW^^zi}gV;cY&lt;A=ylA%DR-9", result); } @Test public void testNormalize1() throws Throwable { String result = ISOUtil.normalize("testISOUtil\rs", true); assertEquals("result", "testISOUtil\\u000ds", result); } @Test public void testNormalize10() throws Throwable { String result = ISOUtil.normalize(null, true); assertEquals("result", "", result); } @Test public void testNormalize11() throws Throwable { String result = ISOUtil.normalize("", true); assertEquals("result", "", result); } @Test public void testNormalize12() throws Throwable { String result = ISOUtil.normalize("\u5BC7<t2e76HTO- 63;TwFix", true); assertEquals("result", "\u5BC7&lt;t2e76HTO- 63;TwFix", result); } @Test public void testNormalize13() throws Throwable { String result = ISOUtil.normalize("\u0014", true); assertEquals("result", "\\u0014", result); } @Test public void testNormalize14() throws Throwable { String result = ISOUtil.normalize("\u7D79\u0001#h<Fuo|s)C<D&\\J:'{ul'p\\Nz@^dt`.", true); assertEquals("result", "\u7D79\\u0001#h&lt;Fuo|s)C&lt;D&amp;\\J:&apos;{ul&apos;p\\Nz@^dt`.", result); } @Test public void testNormalize15() throws Throwable { String result = ISOUtil.normalize("&quot;", true); assertEquals("result", "&amp;quot;", result); } @Test public void testNormalize16() throws Throwable { String result = ISOUtil.normalize(" "); assertEquals("result", " ", result); } @Test public void testNormalize17() throws Throwable { String result = ISOUtil.normalize("testISOUtil\rs"); assertEquals("result", "testISOUtil\\u000ds", result); } @Test public void testNormalize18() throws Throwable { String result = ISOUtil.normalize("\rI\u0004\"e", true); assertEquals("result", "\\u000dI\\u0004&quot;e", result); } @Test public void testNormalize19() throws Throwable { String result = ISOUtil .normalize( "\u0014iSa4\r@\u0005/\u001Ai>iK>&%EA]\u001E\u001D:B\u000F-\u0016\u0012K=9\u001D\u0019t:&.2\"F<}Nf\u0011\u0003\u0008,\u0015=\u001D\n?\u0012\u000Eo<E\u001F\u0007\u001AC\u001C3\u0012d7:rf^l,`", false); assertEquals( "result", "\\u0014iSa4&#13;@\\u0005/\\u001ai&gt;iK&gt;&amp;%EA]\\u001e\\u001d:B\\u000f-\\u0016\\u0012K=9\\u001d\\u0019t:&amp;.2&quot;F&lt;}Nf\\u0011\\u0003\\u0008,\\u0015=\\u001d&#10;?\\u0012\\u000eo&lt;E\\u001f\\u0007\\u001aC\\u001c3\\u0012d7:rf^l,`", result); } @Test public void testNormalize2() throws Throwable { String result = ISOUtil.normalize(" ", true); assertEquals("result", " ", result); } @Test public void testNormalize20() throws Throwable { String result = ISOUtil.normalize("\rX XX", false); assertEquals("result", "&#13;X XX", result); } @Test public void testNormalize21() throws Throwable { String result = ISOUtil .normalize( "\u0004r2\u0013&mX&\u0014\u0017hT\u000E}Y!{\u0004&\u0016\u000Fb\"D\u001B\u0014Qz\u001E-&fe<\u0012]<.5\\\u0001\u0000\u001D%v\u001FraS\"mMlc\u0014\u001F\u0008Q\"\u0019&\u000E\\\u0004\u000F\t\u000F&:\u4BF6", true); assertEquals( "result", "\\u0004r2\\u0013&amp;mX&amp;\\u0014\\u0017hT\\u000e}Y!{\\u0004&amp;\\u0016\\u000fb&quot;D\\u001b\\u0014Qz\\u001e-&amp;fe&lt;\\u0012]&lt;.5\\\\u0001\\u0000\\u001d%v\\u001fraS&quot;mMlc\\u0014\\u001f\\u0008Q&quot;\\u0019&amp;\\u000e\\\\u0004\\u000f\\u0009\\u000f&amp;:\u4BF6", result); } @Test public void testNormalize22() throws Throwable { String result = ISOUtil .normalize( "@|k7\u0014[\"7w\u0002'>\u0005\u001D[\u001D\fu0,\"9'K\u0007u\u0017[@\">V><uNo>\u001Eyj8>, pS5V&</sCZ \u0008dBz\"M\"%Wv)lQ)<u7>c]VKWRExFkiXlc1#'>?QU |d45\\eZR", true); assertEquals( "result", "@|k7\\u0014[&quot;7w\\u0002&apos;&gt;\\u0005\\u001d[\\u001d\\u000cu0,&quot;9&apos;K\\u0007u\\u0017[@&quot;&gt;V&gt;&lt;uNo&gt;\\u001eyj8&gt;, pS5V&amp;&lt;/sCZ \\u0008dBz&quot;M&quot;%Wv)lQ)&lt;u7&gt;c]VKWRExFkiXlc1#&apos;&gt;?QU |d45\\eZR", result); } @Test public void testNormalize23() throws Throwable { String result = ISOUtil.normalize(">&Y/G%za1ZHz$O^bPBeB nUlTf{n9,", true); assertEquals("result", "&gt;&amp;Y/G%za1ZHz$O^bPBeB nUlTf{n9,", result); } @Test public void testNormalize24() throws Throwable { String result = ISOUtil .normalize( "iC\u0012Vi<\t< A\\`>|&\rw\u0018l\u0000d\u000F_`>\\ N8\u0016%Up\rf\u0005\u0019G>%>1Wnx;Ul0Rz}%[wn\u000E\u001C*\t>DJ,<\uDB18\uCA4B\u8FF8\u340F\u4F1F", false); assertEquals( "result", "iC\\u0012Vi&lt;\\u0009&lt; A\\`&gt;|&amp;&#13;w\\u0018l\\u0000d\\u000f_`&gt;\\ N8\\u0016%Up&#13;f\\u0005\\u0019G&gt;%&gt;1Wnx;Ul0Rz}%[wn\\u000e\\u001c*\\u0009&gt;DJ,&lt;\uDB18\uCA4B\u8FF8\u340F\u4F1F", result); } @Test public void testNormalize3() throws Throwable { String result = ISOUtil.normalize("#g];unko,nsk 3<yhj>\\-)fw47&3,@p~rh[2cGi[", true); assertEquals("result", "#g];unko,nsk 3&lt;yhj&gt;\\-)fw47&amp;3,@p~rh[2cGi[", result); } @Test public void testNormalize4() throws Throwable { String result = ISOUtil.normalize(" XX XXXX XX XXXX X XXX XX XXXXX XXXXX XX XXXXXXXX XX X X \t XXX", true); assertEquals("result", " XX XXXX XX XXXX X XXX XX XXXXX XXXXX XX XXXXXXXX XX X X \\u0009 XXX", result); } @Test public void testNormalize5() throws Throwable { String result = ISOUtil .normalize( "iC\u0012Vi<\t< A\\`>|&\rw\u0018l\u0000d\u000F_`>\\ N8\u0016%Up\rf\u0005\u0019G>%>1Wnx;Ul0Rz}%[wn\u000E\u001C*\t>DJ,<\uDB18\uCA4B\u8FF8\u340F\u4F1F", true); assertEquals( "result", "iC\\u0012Vi&lt;\\u0009&lt; A\\`&gt;|&amp;\\u000dw\\u0018l\\u0000d\\u000f_`&gt;\\ N8\\u0016%Up\\u000df\\u0005\\u0019G&gt;%&gt;1Wnx;Ul0Rz}%[wn\\u000e\\u001c*\\u0009&gt;DJ,&lt;\uDB18\uCA4B\u8FF8\u340F\u4F1F", result); } @Test public void testNormalize6() throws Throwable { String result = ISOUtil.normalize("\rI\u0004\"e", false); assertEquals("result", "&#13;I\\u0004&quot;e", result); } @Test public void testNormalize7() throws Throwable { String result = ISOUtil.normalize("J\u0006YTuVP>F}R+Js:(aD", true); assertEquals("result", "J\\u0006YTuVP&gt;F}R+Js:(aD", result); } @Test public void testNormalize8() throws Throwable { String result = ISOUtil.normalize(">=\u0011[\u0011_f\u0019<&[", true); assertEquals("result", "&gt;=\\u0011[\\u0011_f\\u0019&lt;&amp;[", result); } @Test public void testNormalize9() throws Throwable { String s = "<\u0010}\"\uCD88\uD16A\u1384\uFE1A\u44B2\u2712\u3BD7\u3AE5\uFCC4\uD19B\u16F2\uD45A\u45F8\u65FF\uA224\u3930\u946E\u8FB0\u3550\u061D\u4741\u8084\u8606\u6B1A\u8F81\uC634\u0190\u2053\uFA5A\u4C3F\uD365\uF7A7\uF8D4"; String result = ISOUtil.normalize(s, true); assertEquals( "result", "&lt;\\u0010}&quot;\uCD88\uD16A\u1384\uFE1A\u44B2\u2712\u3BD7\u3AE5\uFCC4\uD19B\u16F2\uD45A\u45F8\u65FF\uA224\u3930\u946E\u8FB0\u3550\u061D\u4741\u8084\u8606\u6B1A\u8F81\uC634\u0190\u2053\uFA5A\u4C3F\uD365\uF7A7\uF8D4", result); } @Test public void testNormalizeDenormalize() throws Throwable { String s = "\u0010}\uCD88\uD16A\u1384\uFE1A\u44B2\u2712\u3BD7\u3AE5\uFCC4\uD19B\u16F2\uD45A\u45F8\u65FF\uA224\u3930\u946E\u8FB0\u3550\u061D\u4741\u8084\u8606\u6B1A\u8F81\uC634\u0190\u2053\uFA5A\u4C3F\uD365\uF7A7\uF8D4"; String result = ISOUtil.normalize(s, true); assertEquals( "result", "\\u0010}\uCD88\uD16A\u1384\uFE1A\u44B2\u2712\u3BD7\u3AE5\uFCC4\uD19B\u16F2\uD45A\u45F8\u65FF\uA224\u3930\u946E\u8FB0\u3550\u061D\u4741\u8084\u8606\u6B1A\u8F81\uC634\u0190\u2053\uFA5A\u4C3F\uD365\uF7A7\uF8D4", result); assertEquals("original", s, ISOUtil.stripUnicode(result)); } @Test public void testPadleft() throws Throwable { String result = ISOUtil.padleft("testString", 11, '2'); assertEquals("result", "2testString", result); } @Test public void testPadleft1() throws Throwable { String result = ISOUtil.padleft("2C", 2, ' '); assertEquals("result", "2C", result); } @Test public void testPadleftThrowsISOException() throws Throwable { try { ISOUtil.padleft("testString", 0, '\u0002'); fail("Expected ISOException to be thrown"); } catch (ISOException ex) { assertEquals("ex.getMessage()", "invalid len 10/0", ex.getMessage()); assertNull("ex.nested", ex.nested); } } @Test(expected = NullPointerException.class) public void testPadleftThrowsNullPointerException() throws Throwable { ISOUtil.padleft(null, 0, '\u0002'); } @Test public void testParseInt() throws Throwable { char[] cArray = new char[2]; cArray[0] = 'S'; cArray[1] = 'C'; int result = ISOUtil.parseInt(cArray, 35); assertEquals("result", 992, result); } @Test public void testParseInt1() throws Throwable { char[] cArray = new char[1]; cArray[0] = '1'; int result = ISOUtil.parseInt(cArray); assertEquals("result", 1, result); } @Test public void testParseInt2() throws Throwable { int result = ISOUtil.parseInt("1", 10); assertEquals("result", 1, result); } @Test public void testParseInt3() throws Throwable { int result = ISOUtil.parseInt("2C", 31); assertEquals("result", 74, result); } @Test public void testParseInt4() throws Throwable { int result = ISOUtil.parseInt("1"); assertEquals("result", 1, result); } @Test public void testParseInt5() throws Throwable { byte[] bArray = new byte[1]; bArray[0] = (byte) 49; int result = ISOUtil.parseInt(bArray); assertEquals("result", 1, result); } @Test public void testParseIntThrowsArrayIndexOutOfBoundsException() throws Throwable { char[] cArray = new char[0]; try { ISOUtil.parseInt(cArray, 100); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "0", ex.getMessage()); } } @Test public void testParseIntThrowsArrayIndexOutOfBoundsException1() throws Throwable { char[] cArray = new char[0]; try { ISOUtil.parseInt(cArray); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "0", ex.getMessage()); } } @Test public void testParseIntThrowsArrayIndexOutOfBoundsException2() throws Throwable { byte[] bArray = new byte[0]; try { ISOUtil.parseInt(bArray, 100); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "0", ex.getMessage()); } } @Test public void testParseIntThrowsArrayIndexOutOfBoundsException3() throws Throwable { byte[] bArray = new byte[0]; try { ISOUtil.parseInt(bArray); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "0", ex.getMessage()); } } @Test(expected = NullPointerException.class) public void testParseIntThrowsNullPointerException() throws Throwable { ISOUtil.parseInt((char[]) null, 100); } @Test(expected = NullPointerException.class) public void testParseIntThrowsNullPointerException1() throws Throwable { ISOUtil.parseInt((char[]) null); } @Test(expected = NullPointerException.class) public void testParseIntThrowsNullPointerException2() throws Throwable { ISOUtil.parseInt((String) null, 100); } @Test(expected = NullPointerException.class) public void testParseIntThrowsNullPointerException3() throws Throwable { ISOUtil.parseInt((String) null); } @Test(expected = NullPointerException.class) public void testParseIntThrowsNullPointerException4() throws Throwable { ISOUtil.parseInt((byte[]) null, 100); } @Test(expected = NullPointerException.class) public void testParseIntThrowsNullPointerException5() throws Throwable { ISOUtil.parseInt((byte[]) null); } @Test public void testParseIntThrowsNumberFormatException() throws Throwable { char[] cArray = new char[9]; cArray[0] = 'c'; cArray[1] = '1'; try { ISOUtil.parseInt(cArray, 35); fail("Expected NumberFormatException to be thrown"); } catch (NumberFormatException ex) { assertEquals("ex.getMessage()", "Char array contains non-digit", ex.getMessage()); } } @Test public void testParseIntThrowsNumberFormatException1() throws Throwable { char[] cArray = new char[8]; cArray[0] = '1'; try { ISOUtil.parseInt(cArray, 10); fail("Expected NumberFormatException to be thrown"); } catch (NumberFormatException ex) { assertEquals("ex.getMessage()", "Char array contains non-digit", ex.getMessage()); } } @Test public void testParseIntThrowsNumberFormatException10() throws Throwable { try { ISOUtil.parseInt("0\"/", 10); fail("Expected NumberFormatException to be thrown"); } catch (NumberFormatException ex) { assertEquals("ex.getMessage()", "String contains non-digit", ex.getMessage()); } } @Test public void testParseIntThrowsNumberFormatException11() throws Throwable { try { ISOUtil.parseInt("9Characte", 100); fail("Expected NumberFormatException to be thrown"); } catch (NumberFormatException ex) { assertEquals("ex.getMessage()", "String contains non-digit", ex.getMessage()); } } @Test public void testParseIntThrowsNumberFormatException12() throws Throwable { try { ISOUtil.parseInt("8Charact", 100); fail("Expected NumberFormatException to be thrown"); } catch (NumberFormatException ex) { assertEquals("ex.getMessage()", "String contains non-digit", ex.getMessage()); } } @Test public void testParseIntThrowsNumberFormatException13() throws Throwable { try { ISOUtil.parseInt("10Characte", 100); fail("Expected NumberFormatException to be thrown"); } catch (NumberFormatException ex) { assertEquals("ex.getMessage()", "Number can have maximum 9 digits", ex.getMessage()); } } @Test public void testParseIntThrowsNumberFormatException2() throws Throwable { byte[] bArray = new byte[8]; bArray[0] = (byte) 55; try { ISOUtil.parseInt(bArray, 10); fail("Expected NumberFormatException to be thrown"); } catch (NumberFormatException ex) { assertEquals("ex.getMessage()", "Byte array contains non-digit", ex.getMessage()); } } @Test public void testParseIntThrowsNumberFormatException3() throws Throwable { byte[] bArray = new byte[8]; try { ISOUtil.parseInt(bArray, 100); fail("Expected NumberFormatException to be thrown"); } catch (NumberFormatException ex) { assertEquals("ex.getMessage()", "Byte array contains non-digit", ex.getMessage()); } } @Test public void testParseIntThrowsNumberFormatException4() throws Throwable { byte[] bArray = new byte[9]; try { ISOUtil.parseInt(bArray, 100); fail("Expected NumberFormatException to be thrown"); } catch (NumberFormatException ex) { assertEquals("ex.getMessage()", "Byte array contains non-digit", ex.getMessage()); } } @Test public void testParseIntThrowsNumberFormatException5() throws Throwable { byte[] bArray = new byte[10]; try { ISOUtil.parseInt(bArray, 100); fail("Expected NumberFormatException to be thrown"); } catch (NumberFormatException ex) { assertEquals("ex.getMessage()", "Number can have maximum 9 digits", ex.getMessage()); } } @Test public void testParseIntThrowsNumberFormatException6() throws Throwable { char[] cArray = new char[9]; try { ISOUtil.parseInt(cArray, 100); fail("Expected NumberFormatException to be thrown"); } catch (NumberFormatException ex) { assertEquals("ex.getMessage()", "Char array contains non-digit", ex.getMessage()); } } @Test public void testParseIntThrowsNumberFormatException7() throws Throwable { char[] cArray = new char[10]; try { ISOUtil.parseInt(cArray, 100); fail("Expected NumberFormatException to be thrown"); } catch (NumberFormatException ex) { assertEquals("ex.getMessage()", "Number can have maximum 9 digits", ex.getMessage()); } } @Test public void testParseIntThrowsNumberFormatException8() throws Throwable { try { ISOUtil.parseInt("o`2L\\*@@ fail("Expected NumberFormatException to be thrown"); } catch (NumberFormatException ex) { assertEquals("ex.getMessage()", "String contains non-digit", ex.getMessage()); } } @Test public void testParseIntThrowsNumberFormatException9() throws Throwable { try { ISOUtil.parseInt("9Characte", 28); fail("Expected NumberFormatException to be thrown"); } catch (NumberFormatException ex) { assertEquals("ex.getMessage()", "String contains non-digit", ex.getMessage()); } } @Test public void testParseIntThrowsStringIndexOutOfBoundsException() throws Throwable { try { ISOUtil.parseInt("", 100); fail("Expected StringIndexOutOfBoundsException to be thrown"); } catch (StringIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "String index out of range: 0", ex.getMessage()); } } @Test public void testParseIntThrowsStringIndexOutOfBoundsException1() throws Throwable { try { ISOUtil.parseInt(""); fail("Expected StringIndexOutOfBoundsException to be thrown"); } catch (StringIndexOutOfBoundsException ex) { assertEquals("ex.getMessage()", "String index out of range: 0", ex.getMessage()); } } @Test public void testProtect() throws Throwable { String result = ISOUtil.protect("10Characte"); assertEquals("result", "10Characte", result); } @Test public void testProtect1() throws Throwable { String result = ISOUtil.protect("=WaW=4V0"); assertEquals("result", "=___=___", result); } @Test public void testProtect10() throws Throwable { String result = ISOUtil.protect("=====^===========^====^==="); assertEquals("result", "=====^===========^====^===", result); } @Test public void testProtect11() throws Throwable { String result = ISOUtil.protect("testISOUtils"); assertEquals("result", "testIS__tils", result); } @Test public void testProtect12() throws Throwable { String result = ISOUtil.protect("=HNb^D4uZfz0@|\")61b:~dSS`[.2!!qlL4Z0"); assertEquals("result", "=___^D4uZfz0@|\")61b:~dSS`[.2!!qlL4Z0", result); } @Test public void testProtect13() throws Throwable { String result = ISOUtil.protect("^58*(=@"); assertEquals("result", "^58*(=_", result); } @Test public void testProtect14() throws Throwable { String result = ISOUtil.protect("===\u3455w"); assertEquals("result", "===__", result); } @Test public void testProtect15() throws Throwable { String result = ISOUtil.protect("=\u0AC4\uC024\uF29B=~2A)~5aCgl\"lLU*lm_cJ1M/!KFnA"); assertEquals("result", "=___=________________________KFnA", result); } @Test public void testProtect16() throws Throwable { String result = ISOUtil.protect("\u30C5\uE09B\u6028\uB54E\u2094\uFA25\uAD56\u3A1F\uE55C\u31AA\u5FE0=$"); assertEquals("result", "\u30C5\uE09B\u6028\uB54E\u2094\uFA25_\u3A1F\uE55C\u31AA\u5FE0=_", result); } @Test public void testProtect17() throws Throwable { String result = ISOUtil.protect("+6+[=I?"); assertEquals("result", "+6+[=__", result); } @Test public void testProtect18() throws Throwable { String result = ISOUtil.protect("======="); assertEquals("result", "=======", result); } @Test public void testProtect19() throws Throwable { String result = ISOUtil.protect("===^^+^="); assertEquals("result", "===^^+^=", result); } @Test public void testProtect2() throws Throwable { String result = ISOUtil.protect("===^==="); assertEquals("result", "===^===", result); } @Test public void testProtect20() throws Throwable { String result = ISOUtil.protect("\u6D1D^KI"); assertEquals("result", "_^KI", result); } @Test public void testProtect21() throws Throwable { String result = ISOUtil.protect("=7G^=^"); assertEquals("result", "=__^=^", result); } @Test public void testProtect3() throws Throwable { String result = ISOUtil.protect("^D==N^=r=\u0002^g)=="); assertEquals("result", "^D==_^=_=_^g)==", result); } @Test public void testProtect4() throws Throwable { String result = ISOUtil.protect("="); assertEquals("result", "=", result); } @Test public void testProtect5() throws Throwable { String result = ISOUtil.protect(""); assertEquals("result", "", result); } @Test public void testProtect6() throws Throwable { String result = ISOUtil.protect("VqM_'"); assertEquals("result", "_____", result); } @Test public void testProtect7() throws Throwable { String result = ISOUtil.protect("\\7.=^6C3"); assertEquals("result", "\\7.=^6C3", result); } @Test public void testProtect8() throws Throwable { String result = ISOUtil.protect("#<gF=uG!"); assertEquals("result", " } @Test public void testProtect9() throws Throwable { String result = ISOUtil.protect("^9a{=o;G"); assertEquals("result", "^9a{=___", result); } @Test public void testProtectT2D1() throws Throwable { String result = ISOUtil.protect("#<gFDuG!"); assertEquals("result", " } @Test public void testProtectT2D2() throws Throwable { String result = ISOUtil.protect("9a{#<gFuG!53Do;G"); assertEquals("result", "9a{ } @Test public void testProtectT1D1() throws Throwable { String result = ISOUtil.protect("a{#<gFuG!53o;G609^FOO/BAR COM^67890o;G"); assertEquals("result", "a{ } @Test public void testProtectT1D2() throws Throwable { String result = ISOUtil.protect("9a{#<gFuG!^FOO/BAR COM^67890o;G"); assertEquals("result", "9a{ } @Test public void testProtectT1D3() throws Throwable { String result = ISOUtil.protect("9a{D<gFuG!^FOO/BAR COM^67890o;G"); assertEquals("result", "9a{D<gFuG!^FOO/BAR COM^________", result); } @Test(expected = NullPointerException.class) public void testProtectThrowsNullPointerException() throws Throwable { ISOUtil.protect(null); } @Test public void testSleep() throws Throwable { ISOUtil.sleep(100L); assertTrue("Test completed without Exception", true); } @Test public void testSleepThrowsIllegalArgumentException() throws Throwable { try { ISOUtil.sleep(-30L); fail("Expected IllegalArgumentException to be thrown"); } catch (IllegalArgumentException ex) { assertEquals("ex.getMessage()", "timeout value is negative", ex.getMessage()); } } @Test public void testStr2bcd() throws Throwable { byte[] result = ISOUtil.str2bcd(" ", true); assertEquals("result.length", 1, result.length); assertEquals("result[0]", (byte) -16, result[0]); } @Test public void testStr2bcd1() throws Throwable { byte[] result = ISOUtil.str2bcd("testISOUtils", true); assertEquals("result.length", 6, result.length); assertEquals("result[0]", (byte) 117, result[0]); } @Test public void testStr2bcd10() throws Throwable { byte[] result = ISOUtil.str2bcd("", true); assertEquals("result.length", 0, result.length); } @Test public void testStr2bcd11() throws Throwable { byte[] result = ISOUtil.str2bcd("", true, (byte) 0); assertEquals("result.length", 0, result.length); } @Test public void testStr2bcd12() throws Throwable { byte[] result = ISOUtil.str2bcd("testISOUtils1", true, (byte) 0); assertEquals("result.length", 7, result.length); assertEquals("result[0]", (byte) 68, result[0]); } @Test public void testStr2bcd13() throws Throwable { byte[] result = ISOUtil.str2bcd("testISOUtils", true, (byte) 0); assertEquals("result.length", 6, result.length); assertEquals("result[0]", (byte) 117, result[0]); } @Test public void testStr2bcd14() throws Throwable { byte[] result = ISOUtil.str2bcd(" ", true, (byte) 0); assertEquals("result.length", 1, result.length); assertEquals("result[0]", (byte) -16, result[0]); } @Test public void testStr2bcd15() throws Throwable { byte[] result = ISOUtil.str2bcd(" ", false, (byte) 0); assertEquals("result.length", 1, result.length); assertEquals("result[0]", (byte) 0, result[0]); } @Test public void testStr2bcd16() throws Throwable { byte[] result = ISOUtil.str2bcd("testISOUtils1", false, (byte) 0); assertEquals("result.length", 7, result.length); assertEquals("result[0]", (byte) 117, result[0]); } @Test public void testStr2bcd2() throws Throwable { byte[] d = new byte[0]; byte[] result = ISOUtil.str2bcd("", true, d, 100); assertSame("result", d, result); } @Test public void testStr2bcd3() throws Throwable { byte[] d = new byte[1]; byte[] result = ISOUtil.str2bcd("", true, d, 100); assertSame("result", d, result); assertEquals("d[0]", (byte) 0, d[0]); } @Test public void testStr2bcd4() throws Throwable { byte[] d = new byte[2]; byte[] result = ISOUtil.str2bcd("3Ch", true, d, 0); assertEquals("d[0]", (byte) 3, d[0]); assertSame("result", d, result); } @Test public void testStr2bcd5() throws Throwable { byte[] d = new byte[2]; byte[] result = ISOUtil.str2bcd(" ", false, d, 0); assertSame("result", d, result); assertEquals("d[0]", (byte) 0, d[0]); } @Test public void testStr2bcd6() throws Throwable { byte[] d = new byte[69]; byte[] result = ISOUtil.str2bcd("testISOUtils1", false, d, 0); assertEquals("d[0]", (byte) 117, d[0]); assertSame("result", d, result); } @Test public void testStr2bcd7() throws Throwable { byte[] d = new byte[2]; byte[] result = ISOUtil.str2bcd(" ", true, d, 0); assertEquals("d[0]", (byte) -16, d[0]); assertSame("result", d, result); } @Test public void testStr2bcd8() throws Throwable { byte[] d = new byte[4]; byte[] result = ISOUtil.str2bcd("2C", true, d, 0); assertEquals("d[0]", (byte) 51, d[0]); assertSame("result", d, result); } @Test public void testStr2bcd9() throws Throwable { byte[] result = ISOUtil.str2bcd(" ", false); assertEquals("result.length", 1, result.length); assertEquals("result[0]", (byte) 0, result[0]); } @Test public void testStr2bcdThrowsArrayIndexOutOfBoundsException() throws Throwable { byte[] d = new byte[2]; try { ISOUtil.str2bcd("testISOUtils1", true, d, 0); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("d[0]", (byte) 68, d[0]); // assertEquals("ex.getMessage()", "2", ex.getMessage()); } } @Test public void testStr2bcdThrowsArrayIndexOutOfBoundsException1() throws Throwable { byte[] d = new byte[2]; try { ISOUtil.str2bcd("testISOUtils1", false, d, 0); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("d[0]", (byte) 117, d[0]); // assertEquals("ex.getMessage()", "2", ex.getMessage()); } } @Test public void str2bcdRightPadF() { byte[] d = ISOUtil.str2bcd("123", false, (byte) 0xF); assertEquals("123F", ISOUtil.hexString(d)); } @Test public void str2bcdLeftPadF() { byte[] d = ISOUtil.str2bcd("123", true, (byte) 0xF); assertEquals("F123", ISOUtil.hexString(d)); } @Test public void testStr2bcdThrowsArrayIndexOutOfBoundsException2() throws Throwable { byte[] d = new byte[2]; try { ISOUtil.str2bcd("testISOUtils", true, d, 0); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("d[0]", (byte) 117, d[0]); // assertEquals("ex.getMessage()", "2", ex.getMessage()); } } @Test public void testStr2bcdThrowsArrayIndexOutOfBoundsException3() throws Throwable { byte[] a = new byte[1]; byte[] d = ISOUtil.asciiToEbcdic(a); try { ISOUtil.str2bcd("testISOUtils1", true, d, 0); fail("Expected ArrayIndexOutOfBoundsException to be thrown"); } catch (ArrayIndexOutOfBoundsException ex) { assertEquals("d[0]", (byte) 68, d[0]); } } @Test(expected = ArrayIndexOutOfBoundsException.class) public void testStr2bcdThrowsArrayIndexOutOfBoundsException4() throws Throwable { byte[] d = new byte[2]; ISOUtil.str2bcd("testISOUtils1", false, d, 100); } @Test(expected = NullPointerException.class) public void testStr2bcdThrowsNullPointerException() throws Throwable { ISOUtil.str2bcd(null, true); } @Test(expected = NullPointerException.class) public void testStr2bcdThrowsNullPointerException1() throws Throwable { ISOUtil.str2bcd(null, true, (byte) 0); } @Test(expected = NullPointerException.class) public void testStr2bcdThrowsNullPointerException2() throws Throwable { ISOUtil.str2bcd("testISOUtils1", true, null, 100); } @Test(expected = NullPointerException.class) public void testStr2bcdThrowsNullPointerException3() throws Throwable { ISOUtil.str2bcd("testISOUtils", true, null, 100); } @Test(expected = NullPointerException.class) public void testStr2bcdThrowsNullPointerException4() throws Throwable { byte[] d = new byte[2]; ISOUtil.str2bcd(null, true, d, 100); } @Test public void testStrpad() throws Throwable { String result = ISOUtil.strpad("testISOUtils", 0); assertEquals("result", "testISOUtils", result); } @Test public void testStrpad1() throws Throwable { String result = ISOUtil.strpad("testISOUtils", 100); assertEquals("result", "testISOUtils ", result); } @Test public void testStrpadf() throws Throwable { String result = ISOUtil.strpadf("testISOUtils", 0); assertEquals("result", "testISOUtils", result); } @Test public void testStrpadf1() throws Throwable { String result = ISOUtil.strpadf("", 100); assertEquals("result", "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", result); } @Test(expected = NullPointerException.class) public void testStrpadfThrowsNullPointerException() throws Throwable { ISOUtil.strpadf(null, 100); } @Test(expected = NullPointerException.class) public void testStrpadThrowsNullPointerException() throws Throwable { ISOUtil.strpad(null, 100); } @Test public void testToIntArray() throws Throwable { int[] result = ISOUtil.toIntArray("42"); assertEquals("result.length", 1, result.length); assertEquals("result[0]", 42, result[0]); } @Test public void testToIntArray1() throws Throwable { int[] result = ISOUtil.toIntArray(""); assertEquals("result.length", 0, result.length); } @Test(expected = NullPointerException.class) public void testToIntArrayThrowsNullPointerException() throws Throwable { ISOUtil.toIntArray(null); } @Test public void testToIntArrayThrowsNumberFormatException() throws Throwable { try { ISOUtil.toIntArray("testISOUtils"); fail("Expected NumberFormatException to be thrown"); } catch (NumberFormatException ex) { assertEquals("ex.getMessage()", "For input string: \"testISOUtils\"", ex.getMessage()); } } @Test public void testTrim() throws Throwable { byte[] array = new byte[2]; byte[] result = ISOUtil.trim(array, 1); assertEquals("result.length", 1, result.length); assertEquals("result[0]", (byte) 0, result[0]); } @Test public void testTrim1() throws Throwable { byte[] array = new byte[2]; byte[] result = ISOUtil.trim(array, 0); assertEquals("result.length", 0, result.length); } @Test public void testTrim2() throws Throwable { String result = ISOUtil.trim("testISOUtils"); assertEquals("result", "testISOUtils", result); } @Test public void testTrimNullReturnsNull() throws Throwable { String result = ISOUtil.trim(null); assertNull("result", result); } @Test public void testTrimf() throws Throwable { String result = ISOUtil.trimf(""); assertEquals("result", "", result); } @Test public void testTrimf1() throws Throwable { String result = ISOUtil.trimf("2C"); assertEquals("result", "2C", result); } @Test public void testTrimf2() throws Throwable { String result = ISOUtil.trimf("FF"); assertEquals("result", "", result); } @Test public void testTrimf3() throws Throwable { String result = ISOUtil.trimf("F"); assertEquals("result", "", result); } @Test public void testTrimf4() throws Throwable { String result = ISOUtil.trimf(" "); assertEquals("result", "", result); } @Test public void testTrimf5() throws Throwable { String result = ISOUtil.trimf(null); assertNull("result", result); } @Test(expected = ArrayIndexOutOfBoundsException.class) public void testTrimThrowsArrayIndexOutOfBoundsException() throws Throwable { byte[] array = new byte[2]; ISOUtil.trim(array, 100); } @Test(expected = NegativeArraySizeException.class) public void testTrimThrowsNegativeArraySizeException() throws Throwable { byte[] array = new byte[3]; ISOUtil.trim(array, -1); } @Test(expected = NullPointerException.class) public void testTrimThrowsNullPointerException() throws Throwable { ISOUtil.trim(null, 100); } @Test public void testUnPadLeft() throws Throwable { String result = ISOUtil.unPadLeft("", ' '); assertEquals("result", "", result); } @Test public void testUnPadLeft1() throws Throwable { String result = ISOUtil.unPadLeft("", '\u001F'); assertEquals("result", "", result); } @Test public void testUnPadLeft3() throws Throwable { String result = ISOUtil.unPadLeft("testISOUtils", 't'); assertEquals("result", "estISOUtils", result); } @Test(expected = NullPointerException.class) public void testUnPadLeftThrowsNullPointerException() throws Throwable { ISOUtil.unPadLeft(null, ' '); } @Test public void testUnPadRight() throws Throwable { String result = ISOUtil.unPadRight("f", 'f'); assertEquals("result", "f", result); } @Test public void testUnPadRight1() throws Throwable { String result = ISOUtil.unPadRight("", ' '); assertEquals("result", "", result); } @Test public void testUnPadRight2() throws Throwable { String result = ISOUtil.unPadRight("", 'A'); assertEquals("result", "", result); } @Test public void testUnPadRight3() throws Throwable { String result = ISOUtil.unPadRight("f", ' '); assertEquals("result", "f", result); } @Test public void testUnPadRight4() throws Throwable { String result = ISOUtil.unPadRight(" &ON\\.!Wio=p^'@*xS'*ItLh|_g[,K2H|FkD]RPGQ", 'Q'); assertEquals("result", " &ON\\.!Wio=p^'@*xS'*ItLh|_g[,K2H|FkD]RPG", result); } @Test(expected = NullPointerException.class) public void testUnPadRightThrowsNullPointerException() throws Throwable { ISOUtil.unPadRight(null, ' '); } @Test public void testXor() throws Throwable { byte[] op2 = new byte[0]; byte[] result = ISOUtil.xor(ISOUtil.str2bcd("testISOUtils", true), op2); assertEquals("result.length", 0, result.length); } @Test public void testXor1() throws Throwable { byte[] op2 = new byte[4]; byte[] op1 = new byte[0]; byte[] result = ISOUtil.xor(op1, op2); assertEquals("result.length", 0, result.length); } @Test public void testXor2() throws Throwable { byte[] op1 = new byte[3]; byte[] op2 = new byte[2]; byte[] result = ISOUtil.xor(op1, op2); assertEquals("result.length", 2, result.length); assertEquals("result[0]", (byte) 0, result[0]); } @Test public void testXor3() throws Throwable { byte[] op1 = new byte[3]; byte[] op2 = new byte[5]; byte[] result = ISOUtil.xor(op1, op2); assertEquals("result.length", 3, result.length); assertEquals("result[0]", (byte) 0, result[0]); } @Test(expected = NullPointerException.class) public void testXorThrowsNullPointerException() throws Throwable { byte[] op2 = new byte[0]; ISOUtil.xor(null, op2); } @Test public void testZeropad() throws Throwable { String result = ISOUtil.zeropad("testISOUtils", 100); assertEquals("result", "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000testISOUtils", result); } @Test public void testZeropadRight() throws Throwable { String result = ISOUtil.zeropadRight("testISOUtils", 0); assertEquals("result", "testISOUtils", result); } @Test public void testZeropadRight1() throws Throwable { String result = ISOUtil.zeropadRight("", 100); assertEquals("result", "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", result); } @Test(expected = NullPointerException.class) public void testZeropadRightThrowsNullPointerException() throws Throwable { ISOUtil.zeropadRight(null, 100); } @Test public void testZeropadThrowsISOException() throws Throwable { try { ISOUtil.zeropad("testISOUtils", 0); fail("Expected ISOException to be thrown"); } catch (ISOException ex) { assertEquals("ex.getMessage()", "invalid len 12/0", ex.getMessage()); assertNull("ex.nested", ex.nested); } } @Test(expected = NullPointerException.class) public void testZeropadThrowsNullPointerException() throws Throwable { ISOUtil.zeropad(null, 100); } @Test public void testZeroUnPad1() throws Throwable { String result = ISOUtil.zeroUnPad(""); assertEquals("result", "", result); } @Test(expected = NullPointerException.class) public void testZeroUnPadThrowsNullPointerException() throws Throwable { ISOUtil.zeroUnPad(null); } /** * Test of formatAmtConvRate method, of class CSSUtil. */ @Test public void testFormatAmtConvRate() throws Exception { double rate = 3456.78; String expResult = "33456780"; String result = ISOUtil.formatAmountConversionRate(rate); assertEquals(expResult, result); } /** * Test of formatAmtConvRate method, of class CSSUtil. */ @Test public void testFormatAmtConvRate2() throws Exception { double rate = 0.00345678; String expResult = "93456780"; String result = ISOUtil.formatAmountConversionRate(rate); assertEquals(expResult, result); } /** * Test of formatAmtConvRate method, of class CSSUtil. */ @Test public void testFormatAmtConvRate3() throws Exception { double rate = 0.0000345678; String expResult = "90034567"; String result = ISOUtil.formatAmountConversionRate(rate); assertEquals(expResult, result); } /** * Test of formatAmtConvRate method, of class CSSUtil. */ @Test public void testFormatAmtConvRate4() throws Exception { double rate = 0; String expResult = null; String result = ISOUtil.formatAmountConversionRate(rate); assertEquals(expResult, result); } /** * Test of formatAmtConvRate method, of class CSSUtil. */ @Test public void testFormatAmtConvRate5() throws Exception { double rate = 0.0000000001; String expResult = "90000000"; String result = ISOUtil.formatAmountConversionRate(rate); assertEquals(expResult, result); } /** * Test of parseAmtConvRate method, of class CSSUtil. */ @Test public void testParseAmtConvRate() { String rate = "93456780"; BigDecimal expResult = new BigDecimal(0.003456780, MathContext.DECIMAL64); BigDecimal result = new BigDecimal(ISOUtil.parseAmountConversionRate(rate), MathContext.DECIMAL64); assertEquals(expResult, result); } /** * Test of parseAmtConvRate method, of class CSSUtil. */ @Test public void testParseAmtConvRate2() { String rate = "90034567"; BigDecimal expResult = new BigDecimal(0.000034567, MathContext.DECIMAL64); BigDecimal result = new BigDecimal(ISOUtil.parseAmountConversionRate(rate), MathContext.DECIMAL64); assertEquals(expResult, result); } /** * Test of parseAmtConvRate method, of class CSSUtil. */ @Test public void testParseAmtConvRate3() { String rate = null; try { ISOUtil.parseAmountConversionRate(rate); fail(); } catch (IllegalArgumentException ex) { assertEquals("Invalid amount converion rate argument: '" + rate + "'", ex.getMessage()); } } /** * Test of parseAmtConvRate method, of class CSSUtil. */ @Test public void testParseAmtConvRate4() { String rate = "1234567"; try { ISOUtil.parseAmountConversionRate(rate); fail(); } catch (IllegalArgumentException ex) { assertEquals("Invalid amount converion rate argument: '" + rate + "'", ex.getMessage()); } } /** * Test of parseAmtConvRate method, of class CSSUtil. */ @Test public void testParseAmtConvRate5() { String rate = "123456789"; try { ISOUtil.parseAmountConversionRate(rate); fail(); } catch (IllegalArgumentException ex) { assertEquals("Invalid amount converion rate argument: '" + rate + "'", ex.getMessage()); } } /** * @see org.jpos.iso.ISOUtil#commaEncode(String[]) * @see org.jpos.iso.ISOUtil#commaDecode(String) */ @Test public void testCommaEncodeAndDecode() { assertEquals("error encoding \"\"", "", ISOUtil.commaEncode(new String[] {})); assertEquals("error encoding \"a,b,c\"", "a,b,c", ISOUtil.commaEncode(new String[] { "a", "b", "c" })); assertEquals("error encoding \"\\,,\\\\,c\"", "\\,,\\\\,c", ISOUtil.commaEncode(new String[] { ",", "\\", "c" })); assertArrayEquals("error decoding \"\"", new String[] {}, ISOUtil.commaDecode("")); assertArrayEquals("error decoding \"a,b,c\"", new String[] { "a", "b", "c" }, ISOUtil.commaDecode("a,b,c")); assertArrayEquals("error decoding \"\\,,\\\\,c\"", new String[] { ",", "\\", "c" }, ISOUtil.commaDecode("\\,,\\\\,c")); } @Test public void testMillisToString() { Calendar cal = new GregorianCalendar(2012, Calendar.JUNE, 29, 10, 51, 47); cal.setTimeZone(TimeZone.getTimeZone("GMT")); cal.set(Calendar.MILLISECOND, 16); String result = ISOUtil.millisToString(cal.getTimeInMillis()); assertThat(result, is("15520d 10:51:47.016")); } @Test public void testTakeFirstN() throws Exception { String result = ISOUtil.takeFirstN("abcdefgh", 3); assertThat(result, is("abc")); } @Test public void testTakeFirstNAndPad() throws Exception { String result = ISOUtil.takeFirstN("abc", 5); assertThat(result, is("00abc")); } @Test public void testTakeFirstNequal() throws Exception { String result = ISOUtil.takeFirstN("abc", 3); assertThat(result, is("abc")); } @Test public void testTakeLastN() throws Exception { String result = ISOUtil.takeLastN("abcdefgh", 3); assertThat(result, is("fgh")); } @Test public void testTakeLastNAndPad() throws Exception { String result = ISOUtil.takeLastN("abc", 5); assertThat(result, is("00abc")); } @Test public void testTakeLastNequal() throws Exception { String result = ISOUtil.takeLastN("abc", 3); assertThat(result, is("abc")); } @Test public void testToStringArray() throws Exception { String[] result = ISOUtil.toStringArray("a\tb\nc\rd\fe"); assertThat( result, allOf(hasItemInArray("a"), hasItemInArray("b"), hasItemInArray("c"), hasItemInArray("d"), hasItemInArray("e"))); } @Test public void testcalcLUHN() throws Exception { char check = ISOUtil.calcLUHN("411111111111111"); assertThat(check, is('1')); } @Test public void testEbcdicCharSet() throws Throwable { byte[] b = new byte[256]; for (int i=0; i<b.length; i++) { b[i] = ((byte) (i & 0xFF)); } String s = new String (b, ISOUtil.CHARSET); byte[] ebcdic = ISOUtil.asciiToEbcdic(s); byte[] ascii = ISOUtil.ebcdicToAsciiBytes(ebcdic); assertArrayEquals("arrays should be equal", b, ascii); Charset c = Charset.forName("IBM1047"); byte[] ebcdic1 = c.encode(s).array(); String s1 = c.decode(ByteBuffer.wrap(ebcdic1)).toString(); assertArrayEquals("arrays should match", ebcdic, ebcdic1); assertEquals ("ASCII strings should be the same", s, s1); assertArrayEquals ("byte[] should be the same as s1", b, s1.getBytes(ISOUtil.CHARSET)); assertArrayEquals ("byte[] should be the same as ascii", b, new String(ascii, ISOUtil.CHARSET).getBytes(ISOUtil.CHARSET)); } @Test public void testStringDLE() { byte[] b = new byte[32]; for (int i=0; i<32; i++) b[i] = (byte) i; String s = "The quick brown fox " + new String(b, ISOUtil.CHARSET) + " jumps over the lazy dog"; String normalized = ISOUtil.normalize (s); String stripped = ISOUtil.stripUnicode(normalized); assertEquals(s, stripped); } }
package automata.svpa; import java.io.FileWriter; import java.io.IOException; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Map; import automata.svpa.TaggedSymbol.SymbolTag; import theory.BooleanAlgebra; import utilities.Pair; import utilities.Quadruple; public abstract class VPAutomaton<P, S> { public boolean isEmpty; public boolean isDeterministic; public boolean isEpsilonFree; public boolean isTotal; public VPAutomaton() { isEmpty = false; isDeterministic = false; isEpsilonFree = true; isTotal = false; } /** * Returns the set of transitions starting set of states */ public Collection<SVPAMove<P, S>> getMoves() { return getMovesFrom(getStates()); } /** * Set of moves from state */ public abstract Collection<SVPAMove<P, S>> getMovesFrom(Integer state); /** * Set of moves from set of states */ public Collection<SVPAMove<P, S>> getMovesFrom(Collection<Integer> states) { Collection<SVPAMove<P, S>> transitions = new LinkedList<SVPAMove<P, S>>(); for (Integer state : states) transitions.addAll(getMovesFrom(state)); return transitions; } /** * Set of moves to state */ public abstract Collection<SVPAMove<P, S>> getMovesTo(Integer state); /** * Set of moves to set of states */ public Collection<SVPAMove<P, S>> getMovesTo(Collection<Integer> states) { Collection<SVPAMove<P, S>> transitions = new LinkedList<SVPAMove<P, S>>(); for (Integer state : states) transitions.addAll(getMovesTo(state)); return transitions; } /** * Returns the set of return transitions starting a state <code>s</code> */ public abstract Collection<Return<P, S>> getReturnsFrom(Pair<Integer, Integer> state); /** * Returns the set of return transitions to state <code>s</code> */ public abstract Collection<Return<P, S>> getReturnsTo(Pair<Integer, Integer> state); /** * Returns the set of return transitions starting a state <code>s</code> */ public abstract Collection<Return<P, S>> getReturnsFrom(Integer state, Integer stackState); /** * Returns the set of return transitions to state <code>s</code> */ public abstract Collection<Return<P, S>> getReturnsTo(Integer state, Integer stackState); /** * Returns the set of return transitions starting a state <code>s</code> */ public abstract Collection<Return<P, S>> getReturnsFrom(Integer state); /** * Returns the set of return transitions to state <code>s</code> */ public abstract Collection<Return<P, S>> getReturnsTo(Integer state); /** * Returns the set of return transitions starting a state <code>s</code> */ public abstract Collection<Return<P, S>> getReturnsFrom(Collection<Integer> stateSet); /** * Returns the set of return transitions starting in a state in * <code>stateSet</code> with stack state <code>stackState</code> */ public abstract Collection<Return<P, S>> getReturnsFrom(Collection<Integer> stateSet, Integer stackState); /** * Returns the set of return transitions to a state in <code>stateSet</code> */ public abstract Collection<Return<P, S>> getReturnsTo(Collection<Integer> stateSet); /** * Returns the set of call transitions starting a state <code>state</code> */ public abstract Collection<Call<P, S>> getCallsFrom(Integer state); /** * Returns the set of call transitions starting in state <code>state</code> * with stack state <code>stackState</code> */ public abstract Collection<Call<P, S>> getCallsFrom(Integer state, Integer stackState); /** * Returns the set of call transitions starting in a state in * <code>stateSet</code> with stack state <code>stackState</code> */ public abstract Collection<Call<P, S>> getCallsFrom(Collection<Integer> stateSet, Integer stackState); /** * Returns the set of return transitions starting a state <code>s</code> */ public abstract Collection<Call<P, S>> getCallsTo(Integer state); /** * Returns the set of return transitions starting a state <code>s</code> */ public abstract Collection<Call<P, S>> getCallsFrom(Collection<Integer> stateSet); /** * Returns the set of return transitions to state <code>s</code> */ public Collection<Call<P, S>> getCallsTo(Collection<Integer> stateSet) { Collection<Call<P, S>> returns = new HashSet<Call<P, S>>(); for (Integer st : stateSet) returns.addAll(getCallsTo(st)); return returns; } /** * Returns the set of return transitions starting a state <code>s</code> */ public abstract Collection<ReturnBS<P, S>> getReturnBSFrom(Integer state); /** * Returns the set of return transitions starting a state <code>s</code> */ public abstract Collection<ReturnBS<P, S>> getReturnBSTo(Integer state); /** * Returns the set of return transitions starting a state <code>s</code> */ public abstract Collection<ReturnBS<P, S>> getReturnBSFrom(Collection<Integer> stateSet); /** * Returns the set of return transitions to state <code>s</code> */ public abstract Collection<ReturnBS<P, S>> getReturnBSTo(Collection<Integer> stateSet); /** * Returns the set of return transitions starting a state <code>s</code> */ public abstract Collection<SVPAEpsilon<P, S>> getEpsilonsFrom(Integer state); /** * Returns the set of return transitions starting a state <code>s</code> */ public abstract Collection<SVPAEpsilon<P, S>> getEpsilonsTo(Integer state); /** * Returns the set of return transitions starting a state <code>s</code> */ public abstract Collection<SVPAEpsilon<P, S>> getEpsilonsFrom(Collection<Integer> stateSet); /** * Returns the set of return transitions to state <code>s</code> */ public abstract Collection<SVPAEpsilon<P, S>> getEpsilonsTo(Collection<Integer> stateSet); /** * Returns the set of return transitions starting a state <code>s</code> */ public abstract Collection<Internal<P, S>> getInternalsFrom(Integer state); /** * Returns the set of return transitions starting a state <code>s</code> */ public abstract Collection<Internal<P, S>> getInternalsTo(Integer state); /** * Returns the set of return transitions starting a state <code>s</code> */ public abstract Collection<Internal<P, S>> getInternalsFrom(Collection<Integer> stateSet); /** * Returns the set of return transitions to state <code>s</code> */ public abstract Collection<Internal<P, S>> getInternalsTo(Collection<Integer> stateSet); /** * Returns the set of states */ public abstract Collection<Integer> getStates(); /** * Returns the set of initial states */ public abstract Collection<Integer> getInitialStates(); /** * Returns the set of final states */ public abstract Collection<Integer> getFinalStates(); /** * Saves in the file <code>name</code> under the path <code>path</code> the * dot representation of the automaton. Adds .dot if necessary */ public boolean createDotFile(String name, String path) { try { FileWriter fw = new FileWriter(path + name + (name.endsWith(".dot") ? "" : ".dot")); fw.write("digraph " + name + "{\n rankdir=LR;\n"); for (Integer state : getStates()) { fw.write(state + "[label=" + state); if (getFinalStates().contains(state)) fw.write(",peripheries=2"); fw.write("]\n"); if (getInitialStates().contains(state)) fw.write("XX" + state + " [color=white, label=\"\"]"); } for (Integer state : getInitialStates()) { fw.write("XX" + state + " -> " + state + "\n"); } for (Integer state : getStates()) { for (SVPAMove<P, S> t : getMovesFrom(state)) fw.write(t.toDotString()); } fw.write("}"); fw.close(); } catch (IOException e) { System.out.println(e); return false; } return true; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ public String toString() { String s = ""; s = "Automaton: " + getMoves().size() + " transitions, " + getStates().size() + " states" + "\n"; s += "Transitions \n"; for (SVPAMove<P, S> t : getMoves()) s = s + t + "\n"; s += "Initial States \n"; for (Integer is : getInitialStates()) s = s + is + "\n"; s += "Final States \n"; for (Integer fs : getFinalStates()) s = s + fs + "\n"; return s; } /** * Generate a string in the language, null if language is empty * * @param ba * @return */ public LinkedList<TaggedSymbol<S>> getWitness(BooleanAlgebra<P, S> ba) { Collection<Integer> states = getStates(); Map<Integer, Integer> stateToId = new HashMap<Integer, Integer>(); Map<Integer, Integer> idToState = new HashMap<Integer, Integer>(); Map<Integer, Collection<Integer>> wmRelList = new HashMap<Integer, Collection<Integer>>(); boolean[][] wmReachRel = new boolean[states.size()][states.size()]; HashMap<Pair<Integer, Integer>, LinkedList<TaggedSymbol<S>>> witnesses = new HashMap<>(); Integer count = 0; for (Integer state : getStates()) { stateToId.put(state, count); idToState.put(count, state); wmReachRel[count][count] = true; Collection<Integer> reachableFromi = new HashSet<Integer>(); reachableFromi.add(state); wmRelList.put(state, reachableFromi); LinkedList<TaggedSymbol<S>> witness = new LinkedList<>(); witnesses.put(new Pair<Integer, Integer>(state, state), witness); for (int j = 0; j < wmReachRel.length; j++) if (count != j) wmReachRel[count][j] = false; if (getInitialStates().contains(state) && getFinalStates().contains(state)) return witness; count++; } // Build one step relation for (Integer state1 : states) { int id1 = stateToId.get(state1); // Epsilon Transition for (SVPAEpsilon<P, S> t : getEpsilonsFrom(state1)) { wmReachRel[id1][stateToId.get(t.to)] = true; wmRelList.get(state1).add(t.to); LinkedList<TaggedSymbol<S>> witness = new LinkedList<>(); witnesses.put(new Pair<Integer, Integer>(t.from, t.to), witness); if (getInitialStates().contains(t.from) && getFinalStates().contains(t.to)) return witness; } // Internal Transition for (Internal<P, S> t : getInternalsFrom(state1)) { wmReachRel[id1][stateToId.get(t.to)] = true; wmRelList.get(state1).add(t.to); LinkedList<TaggedSymbol<S>> witness = new LinkedList<>(); witness.add(new TaggedSymbol<S>(ba.generateWitness(t.guard), SymbolTag.Internal)); witnesses.put(new Pair<Integer, Integer>(t.from, t.to), witness); if (getInitialStates().contains(t.from) && getFinalStates().contains(t.to)) return witness; } } // Compute fixpoint of reachability relation boolean changed = true; while (changed) { changed = false; for (Integer state1 : states) { int id1 = stateToId.get(state1); Collection<Integer> fromState1 = wmRelList.get(state1); Collection<Integer> newStates = new HashSet<>(); // Calls and returns for (Call<P, S> tCall : getCallsFrom(state1)) { for (Integer toState : wmRelList.get(tCall.to)) for (Return<P, S> tReturn : getReturnsFrom(toState, tCall.stackState)) { int stId = stateToId.get(tReturn.to); if (!wmReachRel[id1][stId]) { P conj = ba.MkAnd(tCall.guard, tReturn.guard); if (ba.IsSatisfiable(conj)) { changed = true; wmReachRel[id1][stId] = true; newStates.add(tReturn.to); LinkedList<TaggedSymbol<S>> witness = new LinkedList<>( witnesses.get(new Pair<Integer, Integer>(tCall.to, tReturn.from))); Pair<S, S> elements = ba.generateWitnesses(conj); witness.addFirst(new TaggedSymbol<S>(elements.first, SymbolTag.Call)); witness.addLast(new TaggedSymbol<S>(elements.second, SymbolTag.Return)); witnesses.put(new Pair<Integer, Integer>(state1, tReturn.to), witness); if (getInitialStates().contains(state1) && getFinalStates().contains(tReturn.to)) return witness; } } } } // Closure for (Integer state2 : fromState1) { if (state1 != state2) { Collection<Integer> fromState2 = wmRelList.get(state2); for (int state3 : fromState2) { if (state3 != state2 && state3 != state1) { int id3 = stateToId.get(state3); if (!wmReachRel[id1][id3]) { changed = true; newStates.add(state3); wmReachRel[id1][id3] = true; LinkedList<TaggedSymbol<S>> witness = new LinkedList<>( witnesses.get(new Pair<Integer, Integer>(state1, state2))); witness.addAll(witnesses.get(new Pair<Integer, Integer>(state2, state3))); witnesses.put(new Pair<Integer, Integer>(state1, state3), witness); if (getInitialStates().contains(state1) && getFinalStates().contains(state3)) return witness; } } } } } fromState1.addAll(newStates); } } // Unmatched calls boolean[][] unCallRel = copyBoolMatrix(wmReachRel); Map<Integer, Collection<Integer>> uCallRelList = copyMap(wmRelList); HashMap<Pair<Integer, Integer>, LinkedList<TaggedSymbol<S>>> ucWitnesses = new HashMap<>(witnesses); // Calls Collection<Call<P, S>> calls = getCallsFrom(getStates()); for (Call<P, S> tCall : calls) { unCallRel[stateToId.get(tCall.from)][stateToId.get(tCall.to)] = true; uCallRelList.get(tCall.from).add(tCall.to); LinkedList<TaggedSymbol<S>> witness = new LinkedList<>(); witness.add(new TaggedSymbol<S>(ba.generateWitness(tCall.guard), SymbolTag.Call)); ucWitnesses.put(new Pair<Integer, Integer>(tCall.from, tCall.to), witness); if (getInitialStates().contains(tCall.from) && getFinalStates().contains(tCall.to)) return witness; } if (!calls.isEmpty()) { changed = true; while (changed) { changed = false; for (Integer state1 : states) { int id1 = stateToId.get(state1); Collection<Integer> fromState1 = uCallRelList.get(state1); Collection<Integer> newStates = new HashSet<>(); // Closure for (Integer state2 : fromState1) { Collection<Integer> fromState2 = uCallRelList.get(state2); for (int state3 : fromState2) { if (state3 != state2 && state3 != state1) { int id3 = stateToId.get(state3); if (!unCallRel[id1][id3]) { changed = true; newStates.add(state3); unCallRel[id1][id3] = true; LinkedList<TaggedSymbol<S>> witness = new LinkedList<>( witnesses.get(new Pair<Integer, Integer>(state1, state2))); witness.addAll(witnesses.get(new Pair<Integer, Integer>(state2, state3))); ucWitnesses.put(new Pair<Integer, Integer>(state1, state3), witness); if (getInitialStates().contains(state1) && getFinalStates().contains(state3)) return witness; } } } } fromState1.addAll(newStates); } } } // Unmatched returns boolean[][] unRetRel = copyBoolMatrix(wmReachRel); Map<Integer, Collection<Integer>> uRetRelList = copyMap(wmRelList); HashMap<Pair<Integer, Integer>, LinkedList<TaggedSymbol<S>>> urWitnesses = new HashMap<>(witnesses); // Returns Collection<ReturnBS<P, S>> returns = getReturnBSFrom(getStates()); for (ReturnBS<P, S> tRet : returns) { int idFrom = stateToId.get(tRet.from); int idTo = stateToId.get(tRet.to); if (!unRetRel[idFrom][idTo]) { unRetRel[idFrom][idTo] = true; uRetRelList.get(tRet.from).add(tRet.to); LinkedList<TaggedSymbol<S>> witness = new LinkedList<>(); witness.add(new TaggedSymbol<S>(ba.generateWitness(tRet.guard), SymbolTag.Return)); urWitnesses.put(new Pair<Integer, Integer>(tRet.from, tRet.to), witness); if (getInitialStates().contains(tRet.from) && getFinalStates().contains(tRet.to)) return witness; } } if (!returns.isEmpty()) { changed = true; while (changed) { changed = false; for (Integer state1 : states) { int id1 = stateToId.get(state1); Collection<Integer> fromState1 = uRetRelList.get(state1); Collection<Integer> newStates = new HashSet<>(); // Closure for (Integer state2 : fromState1) { if (state2 != state1) { Collection<Integer> fromState2 = uRetRelList.get(state2); for (int state3 : fromState2) { if (state3 != state2 && state3 != state1) { int id3 = stateToId.get(state3); if (!unRetRel[id1][id3]) { changed = true; newStates.add(state3); unRetRel[id1][id3] = true; LinkedList<TaggedSymbol<S>> witness = new LinkedList<>( urWitnesses.get(new Pair<Integer, Integer>(state1, state2))); witness.addAll(urWitnesses.get(new Pair<Integer, Integer>(state2, state3))); urWitnesses.put(new Pair<Integer, Integer>(state1, state3), witness); if (getInitialStates().contains(state1) && getFinalStates().contains(state3)) return witness; } } } } } fromState1.addAll(newStates); } } } // Full reachability relation for (Integer state1 : states) { for (Integer state2 : uRetRelList.get(state1)) { if (state1 != state2) { for (Integer state3 : uCallRelList.get(state2)) { if (state3 != state2 && state3 != state1) { if (getFinalStates().contains(state3)) { LinkedList<TaggedSymbol<S>> witness = new LinkedList<>( urWitnesses.get(new Pair<Integer, Integer>(state1, state2))); witness.addAll(ucWitnesses.get(new Pair<Integer, Integer>(state2, state3))); return witness; } } } } } } throw new IllegalArgumentException("The automaton can't be empty"); } private boolean[][] copyBoolMatrix(boolean[][] matrix) { boolean[][] myMatrix = new boolean[matrix.length][]; for (int i = 0; i < matrix.length; i++) { boolean[] aMatrix = matrix[i]; int aLength = aMatrix.length; myMatrix[i] = new boolean[aLength]; System.arraycopy(aMatrix, 0, myMatrix[i], 0, aLength); } return myMatrix; } private Map<Integer, Collection<Integer>> copyMap(Map<Integer, Collection<Integer>> matrix) { HashMap<Integer, Collection<Integer>> myMatrix = new HashMap<>(); for (Integer i : matrix.keySet()) { myMatrix.put(i, new HashSet<>(matrix.get(i))); } return myMatrix; } // Compute reachability relations between states (wm, ucall, uret, unm) protected Quadruple<Map<Integer, Collection<Integer>>, Map<Integer, Collection<Integer>>, Map<Integer, Collection<Integer>>, Map<Integer, Collection<Integer>>> getReachRel( BooleanAlgebra<P, S> ba) { Collection<Integer> states = getStates(); Map<Integer, Integer> stateToId = new HashMap<Integer, Integer>(); Map<Integer, Integer> idToState = new HashMap<Integer, Integer>(); Map<Integer, Collection<Integer>> wmRelList = new HashMap<Integer, Collection<Integer>>(); boolean[][] wmReachRel = new boolean[states.size()][states.size()]; Integer count = 0; for (Integer state : getStates()) { stateToId.put(state, count); idToState.put(count, state); wmReachRel[count][count] = true; Collection<Integer> reachableFromi = new HashSet<Integer>(); reachableFromi.add(state); wmRelList.put(state, reachableFromi); for (int j = 0; j < wmReachRel.length; j++) if (count != j) wmReachRel[count][j] = false; count++; } // Build one step relation for (Integer state1 : states) { int id1 = stateToId.get(state1); // Epsilon Transition for (SVPAEpsilon<P, S> t : getEpsilonsFrom(state1)) { wmReachRel[id1][stateToId.get(t.to)] = true; wmRelList.get(state1).add(t.to); } // Internal Transition for (Internal<P, S> t : getInternalsFrom(state1)) { wmReachRel[id1][stateToId.get(t.to)] = true; wmRelList.get(state1).add(t.to); } } // Compute fixpoint of reachability relation boolean changed = true; while (changed) { changed = false; for (Integer state1 : states) { int id1 = stateToId.get(state1); Collection<Integer> fromState1 = wmRelList.get(state1); Collection<Integer> newStates = new HashSet<>(); // Calls and returns for (Call<P, S> tCall : getCallsFrom(state1)) { for (Integer toState : wmRelList.get(tCall.to)) for (Return<P, S> tReturn : getReturnsFrom(toState, tCall.stackState)) { int stId = stateToId.get(tReturn.to); if (!wmReachRel[id1][stId]) if (ba.IsSatisfiable(ba.MkAnd(tCall.guard, tReturn.guard))) { changed = true; wmReachRel[id1][stId] = true; newStates.add(tReturn.to); } } } // Closure for (Integer state2 : fromState1) { if (state1 != state2) { Collection<Integer> fromState2 = wmRelList.get(state2); for (int state3 : fromState2) { if (state3 != state2 && state3 != state1) { int id3 = stateToId.get(state3); if (!wmReachRel[id1][id3]) { changed = true; newStates.add(state3); wmReachRel[id1][id3] = true; } } } } } fromState1.addAll(newStates); } } // Unmatched calls boolean[][] unCallRel = copyBoolMatrix(wmReachRel); Map<Integer, Collection<Integer>> uCallRelList = copyMap(wmRelList); // Calls Collection<Call<P, S>> calls = getCallsFrom(getStates()); for (Call<P, S> tCall : calls) { unCallRel[stateToId.get(tCall.from)][stateToId.get(tCall.to)] = true; uCallRelList.get(tCall.from).add(tCall.to); } if (!calls.isEmpty()) { changed = true; while (changed) { changed = false; for (Integer state1 : states) { int id1 = stateToId.get(state1); Collection<Integer> fromState1 = uCallRelList.get(state1); Collection<Integer> newStates = new HashSet<>(); // Closure for (Integer state2 : fromState1) { if (state1 != state2) { Collection<Integer> fromState2 = uCallRelList.get(state2); for (int state3 : fromState2) { if (state3 != state2 && state3 != state1) { int id3 = stateToId.get(state3); if (!unCallRel[id1][id3]) { changed = true; newStates.add(state3); unCallRel[id1][id3] = true; } } } } } fromState1.addAll(newStates); } } } // Unmatched returns boolean[][] unRetRel = copyBoolMatrix(wmReachRel); Map<Integer, Collection<Integer>> uRetRelList = copyMap(wmRelList); // Returns Collection<ReturnBS<P, S>> returns = getReturnBSFrom(getStates()); for (ReturnBS<P, S> tRet : returns) { unRetRel[stateToId.get(tRet.from)][stateToId.get(tRet.to)] = true; uRetRelList.get(tRet.from).add(tRet.to); } if (!returns.isEmpty()) { changed = true; while (changed) { changed = false; for (Integer state1 : states) { int id1 = stateToId.get(state1); Collection<Integer> fromState1 = uRetRelList.get(state1); Collection<Integer> newStates = new HashSet<>(); // Closure for (Integer state2 : fromState1) { if (state1 != state2) { Collection<Integer> fromState2 = uRetRelList.get(state2); for (int state3 : fromState2) { if (state3 != state2 && state3 != state1) { int id3 = stateToId.get(state3); if (!unRetRel[id1][id3]) { changed = true; newStates.add(state3); unRetRel[id1][id3] = true; } } } } } fromState1.addAll(newStates); } } } // Full reachability relation Map<Integer, Collection<Integer>> relList = copyMap(uRetRelList); for (Integer state1 : states) { Collection<Integer> newStates = new HashSet<>(); for (Integer state2 : uRetRelList.get(state1)) { newStates.addAll(uCallRelList.get(state2)); } relList.put(state1, newStates); } return new Quadruple<Map<Integer, Collection<Integer>>, Map<Integer, Collection<Integer>>, Map<Integer, Collection<Integer>>, Map<Integer, Collection<Integer>>>( wmRelList, uCallRelList, uRetRelList, relList); } }
package org.akvo.flow.events; import static com.gallatinsystems.common.util.MemCacheUtils.initCache; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import net.sf.jsr107cache.Cache; import org.akvo.flow.events.EventUtils.EventSourceType; import org.akvo.flow.events.EventUtils.EventTypes; import org.codehaus.jackson.map.ObjectMapper; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import com.gallatinsystems.framework.dao.BaseDAO; import com.google.appengine.api.datastore.DeleteContext; import com.google.appengine.api.datastore.PostDelete; import com.google.appengine.api.datastore.PostPut; import com.google.appengine.api.datastore.PutContext; public class EventLogger { private static Logger logger = Logger.getLogger(EventLogger.class.getName()); private static final String LAST_UPDATE_DATE_TIME_PROP = "lastUpdateDateTime"; private static final String CREATED_DATE_TIME_PROP = "createdDateTime"; private static final String UNIFIED_LOG_NOTIFIED = "unifiedLogNotified"; private static final String APP_ID_KEY = "appId"; private Cache cache; public EventLogger() { super(); cache = initCache(60); // cache notification for 1 minute } private void sendNotification(String appId) { try { URL url = new URL("http://flowdev1.akvo.org:3030/event_notification"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); Map<String, String> messageMap = new HashMap<String, String>(); messageMap.put(APP_ID_KEY, appId); ObjectMapper m = new ObjectMapper(); StringWriter w = new StringWriter(); m.writeValue(w, messageMap); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(w.toString()); writer.close(); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { logger.log(Level.SEVERE, "Unified log notification failed"); } } catch (MalformedURLException e) { logger.log(Level.SEVERE, "Unified log notification failed with malformed URL exception"); } catch (IOException e) { logger.log(Level.SEVERE, "Unified log notification failed with IO exception"); } } /* * Notify the log that a new event is ready to be downloaded. The cache has an expiry of 60 * seconds, so if another request was fired within that time, we don't do anything. */ private void notifyLog(String appId) { if (this.cache != null) { if (!cache.containsKey(UNIFIED_LOG_NOTIFIED)) { sendNotification(appId); cache.put(UNIFIED_LOG_NOTIFIED, null); return; } } else { // cache is not accessible, so we will notify anyway sendNotification(appId); } } @SuppressWarnings({ "unchecked", "rawtypes" }) private void storeEvent(Map<String, Object> event, Date timestamp, String appId) { try { ObjectMapper m = new ObjectMapper(); StringWriter w = new StringWriter(); m.writeValue(w, event); BaseDAO<EventQueue> eventDao = new BaseDAO(EventQueue.class); EventQueue eventQ = new EventQueue(timestamp, w.toString()); eventDao.save(eventQ); notifyLog(appId); } catch (Exception e) { // TODO Auto-generated catch block logger.log(Level.SEVERE, "could not store " + event.get("eventType") + " event"); e.printStackTrace(); } } @PostPut(kinds = { "SurveyGroup", "Survey", "QuestionGroup", "Question", "SurveyInstance", "QuestionAnswerStore", "SurveyedLocale" }) void logPut(PutContext context) { // determine type of event and type of action EventTypes types = EventUtils.getEventAndActionType(context.getCurrentElement().getKey() .getKind()); // determine if this entity was created or updated String actionType = EventUtils.ACTION_UPDATED; if (context.getCurrentElement().getProperty(LAST_UPDATE_DATE_TIME_PROP) == context .getCurrentElement().getProperty(CREATED_DATE_TIME_PROP)) { actionType = EventUtils.ACTION_CREATED; } // create event source // get the authentication information. This seems to contain the userId, but // according to the documentation, should hold the 'password' final Authentication authentication = SecurityContextHolder.getContext() .getAuthentication(); String cred = authentication.getCredentials().toString(); Map<String, Object> eventSource = EventUtils.newSource(EventSourceType.USER, cred); Date timestamp = (Date) context.getCurrentElement().getProperty(LAST_UPDATE_DATE_TIME_PROP); // create event context map Map<String, Object> eventContext = EventUtils.newContext(timestamp, eventSource); // create event entity Map<String, Object> eventEntity = EventUtils.newEntity(types.type, context .getCurrentElement() .getKey().getId()); EventUtils.populateEntityProperties(types.type, context.getCurrentElement(), eventEntity); // create event Map<String, Object> event = EventUtils.newEvent(context.getCurrentElement().getAppId(), types.action + actionType, eventEntity, eventContext); // store it storeEvent(event, timestamp, context.getCurrentElement().getAppId()); } @PostDelete(kinds = { "SurveyGroup", "Survey", "QuestionGroup", "Question", "SurveyInstance", "QuestionAnswerStore", "SurveyedLocale" }) void logDelete(DeleteContext context) { // determine type of event and type of action EventTypes types = EventUtils.getEventAndActionType(context.getCurrentElement().getKind()); // create event source // get the authentication information. This seems to contain the userId, but // according to the documentation, should hold the 'password' final Authentication authentication = SecurityContextHolder.getContext() .getAuthentication(); String cred = authentication.getCredentials().toString(); Map<String, Object> eventSource = EventUtils.newSource(EventSourceType.USER, cred); // create event context map // we create our own timestamp here, as we don't have one in the context Date timestamp = new Date(); Map<String, Object> eventContext = EventUtils.newContext(timestamp, eventSource); // create event entity Map<String, Object> eventEntity = EventUtils.newEntity(types.type, context .getCurrentElement().getId()); // create event Map<String, Object> event = EventUtils.newEvent(context.getCurrentElement().getAppId(), types.action + EventUtils.ACTION_DELETED, eventEntity, eventContext); // store it storeEvent(event, timestamp, context.getCurrentElement().getAppId()); } }
package org.json.junit; import static org.junit.Assert.*; import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONArray; import org.json.CDL; /** * Tests for {@link CDL}. * CDL provides an application level API, it is not actually used by the * reference app. To test it, strings will be converted to JSON-Java classes * and then converted back. But each row will be an unordered JSONObject, * so can't use a simple string compare. * @author JSON.org * @version 2015-03-16 * */ public class CDLTest { String lines = new String( "Col 1, Col 2, Col 3, Col 4, Col 5, Col 6, Col 7\n" + "val1, val2, val3, val4, val5, val6, val7\n" + "1, 2, 3, 4, 5, 6, 7\n" + "true, false, true, true, false, false, false\n" + "0.23, 57.42, 5e27, -234.879, 2.34e5, 0.0, 9e-3\n" + "\"va\tl1\", \"val2\", \"val\\b3\", \"val4\\n\", \"va\\rl5\", val6, val7\n" ); @Test(expected=NullPointerException.class) public void shouldThrowExceptionOnNullString() { String nullStr = null; CDL.toJSONArray(nullStr); } @Test /** * Note: This test reveals a bug in the method JavaDoc. It should * mention it might return null, or it should return an empty JSONArray. */ public void shouldHandleOnlyColumnNames() { String columnNameStr = "col1, col2, col3"; JSONArray jsonArray = CDL.toJSONArray(columnNameStr); assertTrue("CDL should return null when only 1 row is given", jsonArray == null); } @Test /** * Note: This test reveals a bug in the method JavaDoc. It should * mention it might return null, or it should return an empty JSONArray. */ public void shouldHandleEmptyString() { String emptyStr = ""; JSONArray jsonArray = CDL.toJSONArray(emptyStr); assertTrue("CDL should return null when the input string is empty", jsonArray == null); } @Test public void toStringShouldCheckSpecialChars() { /** * This is pretty clumsy, there should be a better way * to perform this test. Needs more debugging. The problem * may be that these chars are sanitized out by CDL when constructing * a JSONArray from a string. */ String singleStr = "\"Col 1\"\n1"; JSONArray jsonArray = CDL.toJSONArray(singleStr); JSONObject jsonObject = (JSONObject)(jsonArray.get(0)); jsonObject.put("Col \r4", "V4"); jsonObject.put("Col \0 a", "V5"); boolean doNotNormalize = false; List<List<String>> expectedLines = sortColumnsInLines("Col ,2\",Col 1,\"Col 4\",\"Col a\"\nV2,1,V4,V5,V3", doNotNormalize); List<List<String>> jsonArrayLines = sortColumnsInLines(CDL.toString(jsonArray), doNotNormalize); System.out.println("expected: " +expectedLines); System.out.println("jsonArray: " +jsonArrayLines); } @Test public void shouldConvertJSONArrayToCDLString() { /** * This is the first test of normal functionality. * The string contains a typical variety of values * that might be found in a real CDL. */ final boolean normalize = true; final boolean doNotNormalize = false; JSONArray jsonArray = CDL.toJSONArray(lines); String jsonStr = CDL.toString(jsonArray); // normal sorted List<List<String>> sortedLines = sortColumnsInLines(lines, normalize); // sorted, should already be normalized List<List<String>> sortedJsonStr = sortColumnsInLines(jsonStr, doNotNormalize); boolean result = sortedLines.equals(sortedJsonStr); if (!result) { System.out.println("lines: " +sortedLines); System.out.println("jsonStr: " +sortedJsonStr); assertTrue("CDL should convert JSONArray back to original string: " + lines.equals(jsonStr), false); } } @Test public void shouldConvertCDLToJSONArray() { JSONArray jsonArray = CDL.toJSONArray(lines); String resultStr = compareJSONArrayToString(jsonArray, lines); if (resultStr != null) { assertTrue("CDL should convert string to JSONArray: " + resultStr, false); } } /** * Compares a JSON array to the original string. The top row of the * string contains the JSONObject keys and the remaining rows contain * the values. The JSONObject in each JSONArray row is expected to have * an entry corresponding to each key/value pair in the string. * Each JSONObject row is unordered in its own way. * @param jsonArray the JSONArray which was created from the string * @param str the string which was used to create the JSONArray * @return null if equal, otherwise error description */ private String compareJSONArrayToString(JSONArray jsonArray, String str) { int rows = jsonArray.length(); StringReader sr = new StringReader(str); BufferedReader reader = new BufferedReader(sr); try { // first line contains the keys to the JSONObject array entries String columnNames = reader.readLine(); columnNames = normalizeString(columnNames); String[] keys = columnNames.split(","); /** * Each line contains the values for the corresponding * JSONObject array entry */ for (int i = 0; i < rows; ++i) { String line = reader.readLine(); line = normalizeString(line); String[] values = line.split(","); // need a value for every key to proceed if (keys.length != values.length) { System.out.println("keys: " + Arrays.toString(keys)); System.out.println("values: " + Arrays.toString(values)); return("row: " +i+ " key and value counts do not match"); } JSONObject jsonObject = jsonArray.getJSONObject(i); // need a key for every JSONObject entry to proceed if (keys.length != jsonObject.length()) { System.out.println("keys: " + Arrays.toString(keys)); System.out.println("jsonObject: " + jsonObject.toString()); return("row: " +i+ " key and jsonObject counts do not match"); } // convert string entries into a natural order map. Map<String, String> strMap = new TreeMap<String, String>(); for (int j = 0; j < keys.length; ++j) { strMap.put(keys[j], values[j]); } // put the JSONObjet key/value pairs in natural key order Iterator<String> keyIt = jsonObject.keys(); Map<String, String> jsonObjectMap = new TreeMap<String, String>(); while (keyIt.hasNext()) { String key = keyIt.next(); jsonObjectMap.put(key, jsonObject.get(key).toString()); } if (!strMap.equals(jsonObjectMap)) { System.out.println("strMap: " +strMap.toString()); System.out.println("jsonObjectMap: " +jsonObjectMap.toString()); return("row: " +i+ "string does not match jsonObject"); } } } catch (IOException ignore) { } catch (JSONException ignore) {} return null; } /** * Utility to trim and remove internal quotes from comma delimited strings. * Need to do this because JSONObject does the same thing * @param line the line to be normalized * @return the normalized line */ private String normalizeString(String line) { StringBuilder builder = new StringBuilder(); boolean comma = false; String[] values = line.split(","); for (int i = 0; i < values.length; ++i) { if (comma) { builder.append(","); } comma = true; values[i] = values[i].trim(); // strip optional surrounding quotes values[i] = values[i].replaceAll("^\"|\"$", ""); builder.append(values[i]); } return builder.toString(); } /** * Utility to sort the columns in a (possibly) multi-lined string. * The columns are column separated. Need to do this because * JSONObects are not ordered * @param string the string to be sorted * @param normalize flag, true if line should be normalized * @return a list of sorted lines, where each line is a list sorted * in natural key order */ private List<List<String>> sortColumnsInLines(String string, boolean normalizeFlag) { List<List<String>> lineList = new ArrayList<List<String>>(); StringReader sr = new StringReader(string); BufferedReader reader = new BufferedReader(sr); try { while (true) { String line = reader.readLine(); if (line == null) { break; } if (normalizeFlag) { line = normalizeString(line); } List<String> columnList = new ArrayList<String>(); String[] values = line.split(","); for (int i = 0; i < values.length; ++i) { columnList.add(values[i]); } Collections.sort(columnList); lineList.add(columnList); } } catch (IOException ignore) {} return lineList; } }
package org.json.junit; import static org.junit.Assert.*; import org.junit.Test; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONArray; import org.json.CDL; /** * Tests for CDL.java. * CDL provides an application level API, but it is not used by the * reference app. To test it, strings will be converted to JSON-Java classes * and then converted back. */ public class CDLTest { String lines = new String( "Col 1, Col 2, \tCol 3, Col 4, Col 5, Col 6, Col 7\n" + "val1, val2, val3, val4, val5, val6, val7\n" + "1, 2, 3, 4\t, 5, 6, 7\n" + "true, false, true, true, false, false, false\n" + "0.23, 57.42, 5e27, -234.879, 2.34e5, 0.0, 9e-3\n" + "\"va\tl1\", \"v\bal2\", \"val3\", \"val\f4\", \"val5\", va\'l6, val7\n" ); /** * CDL.toJSONArray() adds all values asstrings, with no filtering or * conversions. For testing, this means that the expected JSONObject * values all must be quoted in the cases where the JSONObject parsing * might normally convert the value into a non-string. */ String expectedLines = new String( "[{Col 1:val1, Col 2:val2, Col 3:val3, Col 4:val4, Col 5:val5, Col 6:val6, Col 7:val7}, "+ "{Col 1:\"1\", Col 2:\"2\", Col 3:\"3\", Col 4:\"4\", Col 5:\"5\", Col 6:\"6\", Col 7:\"7\"}, "+ "{Col 1:\"true\", Col 2:\"false\", Col 3:\"true\", Col 4:\"true\", Col 5:\"false\", Col 6:\"false\", Col 7:\"false\"}, "+ "{Col 1:\"0.23\", Col 2:\"57.42\", Col 3:\"5e27\", Col 4:\"-234.879\", Col 5:\"2.34e5\", Col 6:\"0.0\", Col 7:\"9e-3\"}, "+ "{Col 1:\"va\tl1\", Col 2:\"v\bal2\", Col 3:val3, Col 4:\"val\f4\", Col 5:val5, Col 6:va\'l6, Col 7:val7}]"); /** * Attempts to create a JSONArray from a null string. * Expect a NullPointerException. */ @Test(expected=NullPointerException.class) public void exceptionOnNullString() { String nullStr = null; CDL.toJSONArray(nullStr); } /** * Attempts to create a JSONArray from a string with unbalanced quotes * in column title line. Expects a JSONException. */ @Test public void unbalancedQuoteInName() { String badLine = "Col1, \"Col2\nVal1, Val2"; try { CDL.toJSONArray(badLine); assertTrue("Expecting an exception", false); } catch (JSONException e) { assertTrue("Expecting an exception message", "Missing close quote '\"'. at 12 [character 0 line 2]". equals(e.getMessage())); } } /** * Attempts to create a JSONArray from a string with unbalanced quotes * in value line. Expects a JSONException. */ @Test public void unbalancedQuoteInValue() { String badLine = "Col1, Col2\n\"Val1, Val2"; try { CDL.toJSONArray(badLine); assertTrue("Expecting an exception", false); } catch (JSONException e) { assertTrue("Expecting an exception message", "Missing close quote '\"'. at 23 [character 12 line 3]". equals(e.getMessage())); } } /** * Attempts to create a JSONArray from a string with null char * in column title line. Expects a JSONException. */ @Test public void nullInName() { String badLine = "C\0ol1, Col2\nVal1, Val2"; try { CDL.toJSONArray(badLine); assertTrue("Expecting an exception", false); } catch (JSONException e) { assertTrue("Expecting an exception message", "Bad character 'o' (111). at 3 [character 4 line 1]". equals(e.getMessage())); } } /** * call toString with a null array */ @Test(expected=NullPointerException.class) public void nullJSONArrayToString() { CDL.toString((JSONArray)null); } /** * Create a JSONArray from an empty string */ @Test public void emptyString() { String emptyStr = ""; JSONArray jsonArray = CDL.toJSONArray(emptyStr); assertTrue("CDL should return null when the input string is empty", jsonArray == null); } /** * Create a JSONArray with only 1 row */ @Test public void onlyColumnNames() { String columnNameStr = "col1, col2, col3"; JSONArray jsonArray = CDL.toJSONArray(columnNameStr); assertTrue("CDL should return null when only 1 row is given", jsonArray == null); } /** * Create a JSONArray from string containing only whitespace and commas */ @Test public void emptyLinesToJSONArray() { String str = " , , , \n , , , "; JSONArray jsonArray = CDL.toJSONArray(str); assertTrue("JSONArray should be null for no content", jsonArray == null); } /** * call toString with a null array */ @Test public void emptyJSONArrayToString() { JSONArray jsonArray = new JSONArray(); String str = CDL.toString(jsonArray); assertTrue("CDL should return null for toString(null)", str == null); } /** * call toString with a null arrays for names and values */ @Test public void nullJSONArraysToString() { String str = CDL.toString(null, null); assertTrue("CDL should return null for toString(null)", str == null); } /** * Given a JSONArray that was not built by CDL, some chars may be * found that would otherwise be filtered out by CDL. */ @Test public void checkSpecialChars() { JSONArray jsonArray = new JSONArray(); JSONObject jsonObject = new JSONObject(); jsonArray.put(jsonObject); // \r will be filtered from name jsonObject.put("Col \r1", "V1"); // \r will be filtered from value jsonObject.put("Col 2", "V2\r"); assertTrue("expected length should be 1",jsonArray.length() == 1); String cdlStr = CDL.toString(jsonArray); jsonObject = jsonArray.getJSONObject(0); assertTrue(cdlStr.contains("\"Col 1\"")); assertTrue(cdlStr.contains("Col 2")); assertTrue(cdlStr.contains("V1")); assertTrue(cdlStr.contains("\"V2\"")); } /** * Create a JSONArray from a string of lines */ @Test public void textToJSONArray() { JSONArray jsonArray = CDL.toJSONArray(lines); JSONArray expectedJsonArray = new JSONArray(expectedLines); Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); } /** * Create a JSONArray from a JSONArray of titles and a * string of value lines */ @Test public void jsonArrayToJSONArray() { String nameArrayStr = "[Col1, Col2]"; String values = "V1, V2"; JSONArray nameJSONArray = new JSONArray(nameArrayStr); JSONArray jsonArray = CDL.toJSONArray(nameJSONArray, values); JSONArray expectedJsonArray = new JSONArray("[{Col1:V1,Col2:V2}]"); Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); } /** * Create a JSONArray from a string of lines, * then convert to string and then back to JSONArray */ @Test public void textToJSONArrayAndBackToString() { JSONArray jsonArray = CDL.toJSONArray(lines); String jsonStr = CDL.toString(jsonArray); JSONArray finalJsonArray = CDL.toJSONArray(jsonStr); JSONArray expectedJsonArray = new JSONArray(expectedLines); Util.compareActualVsExpectedJsonArrays(finalJsonArray, expectedJsonArray); } }
package com.njust.regex; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexDemo { public static void main(String[] args) { test01(); test02(); test03(); test04(); } /** * Matcher.matchers */ private static void test01() { Pattern pattern = Pattern.compile("a*b", Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher("aB"); System.out.println(matcher.matches());// true } /** * Matcher.find() * <p> * , */ private static void test02() { Pattern pattern = Pattern.compile("a\\d*z"); Matcher matcher = pattern.matcher("a1234z,a9999z"); System.out.println(matcher.find());// true System.out.println(matcher.find());// true System.out.println(matcher.find());// false } /** * * <p> * group()find()0 */ private static void test03() { Pattern pattern = Pattern.compile("a\\d*z"); Matcher matcher = pattern.matcher("a1234z,a9999z"); while (matcher.find()) { System.out.println(matcher.group()); } // a1234z // a9999z } /** * * <p> * * <p> * 0 01 * <p> * A(B)C(D)E0ABCDE1B2D * <p> * A((B)C)(D)E0ABCDE1BC2B3C4D * * group(i)find()i */ private static void test04() { Pattern pattern = Pattern.compile("(a)\\d*(z)"); Matcher matcher = pattern.matcher("a1234z,a9999z"); while (matcher.find()) { System.out.println(matcher.groupCount()); StringBuilder sb = new StringBuilder(); sb.append(matcher.group(0)).append(" ~ "); sb.append(matcher.group(1)).append(" ~ "); sb.append(matcher.group(2)); System.out.println(sb); } // a1234z ~ a ~ z // a9999z ~ a ~ z } }
package test.ccn.data; import java.security.InvalidKeyException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.Security; import java.security.SignatureException; import java.security.cert.X509Certificate; import java.sql.Timestamp; import java.util.Arrays; import java.util.Date; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import test.ccn.data.util.XMLEncodableTester; import com.parc.ccn.data.ContentName; import com.parc.ccn.data.ContentObject; import com.parc.ccn.data.security.KeyLocator; import com.parc.ccn.data.security.PublisherKeyID; import com.parc.ccn.data.security.Signature; import com.parc.ccn.data.security.SignedInfo; import com.parc.security.crypto.certificates.BCX509CertificateGenerator; public class ContentObjectTest { static final String baseName = "test"; static final String subName2 = "smetters"; static final String document2 = "test2.txt"; static public byte [] document3 = new byte[]{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x1f, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x2e, 0x3c, 0x4a, 0x5c, 0x6d, 0x7e, 0xf}; static ContentName name; static final String rootDN = "C=US,O=Organization,OU=Organizational Unit,CN=Issuer"; static final String endDN = "C=US,O=Final Org,L=Locality,CN=Fred Jones,E=fred@final.org"; static final Date start = new Date(); static final Date end = new Date(start.getTime() + (60*60*24*365)); static final String keydoc = "key"; static ContentName keyname; static KeyPair pair = null; static X509Certificate cert = null; static KeyLocator nameLoc = null; static KeyLocator keyLoc = null; static public Signature signature; static public byte [] contenthash = new byte[32]; static public byte [] publisherid = new byte[32]; static PublisherKeyID pubkey = null; static SignedInfo auth = null; static SignedInfo authKey = null; @BeforeClass public static void setUpBeforeClass() throws Exception { try { name = ContentName.fromURI(new String[]{baseName, subName2, document2}); keyname = ContentName.fromURI(new String[]{baseName, subName2, keydoc}); Security.addProvider(new BouncyCastleProvider()); // generate key pair KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(512); // go for fast pair = kpg.generateKeyPair(); cert = BCX509CertificateGenerator.GenerateX509Certificate( pair.getPublic(), rootDN, endDN, null, start, end, null, pair.getPrivate(), null); nameLoc = new KeyLocator(keyname); keyLoc = new KeyLocator(pair.getPublic()); byte [] signaturebuf = new byte[64]; Arrays.fill(signaturebuf, (byte)1); signature = new Signature(signaturebuf); Arrays.fill(contenthash, (byte)2); Arrays.fill(publisherid, (byte)3); pubkey = new PublisherKeyID(publisherid); auth = new SignedInfo(pubkey, new Timestamp(System.currentTimeMillis()), SignedInfo.ContentType.LEAF, nameLoc); authKey = new SignedInfo(pubkey, new Timestamp(System.currentTimeMillis()), SignedInfo.ContentType.LEAF, keyLoc); } catch (Exception ex) { XMLEncodableTester.handleException(ex); System.out.println("Unable To Initialize Test!!!"); } } @Test public void testDecodeInputStream() { try { ContentObject co = new ContentObject(name, auth, document3, pair.getPrivate()); ContentObject tdco = new ContentObject(); ContentObject bdco = new ContentObject(); XMLEncodableTester.encodeDecodeTest("ContentObject", co, tdco, bdco); Assert.assertTrue(co.verify(pair.getPublic())); ContentObject cokey = new ContentObject(name, authKey, document3, pair.getPrivate()); ContentObject tdcokey = new ContentObject(); ContentObject bdcokey = new ContentObject(); XMLEncodableTester.encodeDecodeTest("ContentObjectKey", cokey, tdcokey, bdcokey); Assert.assertTrue(cokey.verify(pair.getPublic())); // Dump one to file for testing on the C side. // FileOutputStream fdump = new FileOutputStream("ContentObjectKey.ccnb"); // cokey.encode(fdump); // fdump.flush(); // fdump.close(); } catch (Exception e) { System.out.println("Exception : " + e.getClass().getName() + ": " + e.getMessage()); e.printStackTrace(); Assert.fail("Exception: " + e.getClass().getName() + ": " + e.getMessage()); } } @Test public void testImmutable() { try { ContentObject co = new ContentObject(name, auth, document2.getBytes(), pair.getPrivate()); byte [] bs = co.content(); bs[0] = 1; Signature sig = co.signature(); sig.signature()[0] = 2; } catch (InvalidKeyException e) { Assert.fail("Invalid key exception: " + e.getMessage()); } catch (SignatureException e) { Assert.fail("Signature exception: " + e.getMessage()); } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package net.domesdaybook.matcher.singlebyte; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author matt */ public class AllBitMaskMatcherTest { public AllBitMaskMatcherTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } /** * Test of matches method, of class AllBitMaskMatcher. */ @Test public void testMatches_byte() { AllBitMaskMatcher matcher = new AllBitMaskMatcher(b(255)); validateMatchInRange(matcher, 255, 255); validateNoMatchInRange(matcher, 0, 254); matcher = new AllBitMaskMatcher(b(0)); validateMatchInRange(matcher, 0, 256); matcher = new AllBitMaskMatcher(b(254)); validateMatchInRange(matcher, 254, 255); validateNoMatchInRange(matcher, 0, 253); matcher = new AllBitMaskMatcher(b(128)); validateMatchInRange(matcher, 128, 255); validateNoMatchInRange(matcher, 0, 127); // test all bit masks using different methods. for (int mask = 0; mask < 256; mask++) { matcher = new AllBitMaskMatcher(b(mask)); validateMatchBitsSet(matcher, b(mask)); validateNoMatchBitsNotSet(matcher, b(mask)); } } private void validateNoMatchInRange(AllBitMaskMatcher matcher, int from, int to) { for (int count = from; count <= to; count++) { assertEquals(false, matcher.matches(b(count))); } } private void validateMatchInRange(AllBitMaskMatcher matcher, int from, int to) { for (int count = from; count <= to; count++) { assertEquals(true, matcher.matches(b(count))); } } private void validateMatchBitsSet(AllBitMaskMatcher matcher, int bitmask) { String description = String.format("0x%02x", bitmask); for (int count = 0; count < 256; count++) { byte value = (byte) (count | bitmask); assertEquals(description, true, matcher.matches(value)); } } private void validateNoMatchBitsNotSet(AllBitMaskMatcher matcher, int bitmask) { if (bitmask > 0) { // This test won't work for a zero bitmask. String description = String.format("0x%02x", bitmask); final int invertedMask = bitmask ^ 0xFF; for (int count = 0; count < 256; count++) { // zero byte matches everything. byte value = (byte) (count & invertedMask); assertEquals(description, false, matcher.matches(value)); } } } /** * Test of toRegularExpression method, of class AllBitMaskMatcher. */ @Test public void testToRegularExpression() { for (int count = 0; count < 256; count++) { AllBitMaskMatcher matcher = new AllBitMaskMatcher(b(count)); String expected = String.format("&%02x", count); assertEquals(expected, matcher.toRegularExpression(false)); } } /** * Test of getMatchingBytes method, of class AllBitMaskMatcher. */ @Test public void testGetMatchingBytes() { AllBitMaskMatcher matcher = new AllBitMaskMatcher(b(255)); assertArrayEquals("0xFF matches [0xFF] only", new byte[] {b(255)}, matcher.getMatchingBytes()); matcher = new AllBitMaskMatcher(b(0)); assertArrayEquals("0x00 matches all bytes", ByteUtilities.getAllByteValues(), matcher.getMatchingBytes()); matcher = new AllBitMaskMatcher(b(254)); byte[] expected = new byte[] {b(254), b(255)}; assertArrayEquals("0xFE matches 0xFF and 0xFE only", expected, matcher.getMatchingBytes()); matcher = new AllBitMaskMatcher(b(3)); expected = new byte[64]; for (int count = 0; count < 64; count++) { expected[count] = (byte)((count << 2) | 3); } assertArrayEquals("0x03 matches 64 bytes with first two bits set", expected, matcher.getMatchingBytes()); matcher = new AllBitMaskMatcher(b(128)); expected = ByteUtilities.getBytesInRange(128, 255); assertArrayEquals("0x80 matches all bytes from 128 to 255", expected, matcher.getMatchingBytes()); } /** * Test of getNumberOfMatchingBytes method, of class AllBitMaskMatcher. */ @Test public void testGetNumberOfMatchingBytes() { AllBitMaskMatcher matcher = new AllBitMaskMatcher(b(255)); assertEquals("0xFF matches one byte", 1, matcher.getNumberOfMatchingBytes()); matcher = new AllBitMaskMatcher(b(0)); assertEquals("0x00 matches 256 bytes", 256, matcher.getNumberOfMatchingBytes()); matcher = new AllBitMaskMatcher(b(254)); assertEquals("0xFE matches 2 bytes", 2, matcher.getNumberOfMatchingBytes()); matcher = new AllBitMaskMatcher(b(3)); assertEquals("0x03 matches 64 bytes", 64, matcher.getNumberOfMatchingBytes()); matcher = new AllBitMaskMatcher(b(128)); assertEquals("0x80 matches 128 bytes", 128, matcher.getNumberOfMatchingBytes()); } private byte b(int i) { return (byte) i; } }
package org.sagebionetworks.bridge.stormpath; import static org.junit.Assert.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.Date; import java.util.HashMap; import java.util.SortedMap; import java.util.TreeMap; import org.junit.Before; import org.junit.Test; import org.sagebionetworks.bridge.crypto.Encryptor; import org.sagebionetworks.bridge.exceptions.BridgeServiceException; import org.sagebionetworks.bridge.models.studies.ConsentSignature; import org.sagebionetworks.bridge.models.studies.StudyIdentifier; import org.sagebionetworks.bridge.models.studies.StudyIdentifierImpl; import com.fasterxml.jackson.databind.ObjectMapper; import com.stormpath.sdk.account.Account; import com.stormpath.sdk.directory.CustomData; public class StormpathAccountTest { @SuppressWarnings("serial") private class StubCustomData extends HashMap<String,Object> implements CustomData { @Override public String getHref() { return null; } @Override public void save() {} @Override public void delete() {} @Override public Date getCreatedAt() { return null; } @Override public Date getModifiedAt() { return null; } } private StubCustomData data; private Account account; private StormpathAccount acct; private String legacySignature; @Before public void setUp() throws Exception { StudyIdentifier studyId = new StudyIdentifierImpl("foo"); account = mock(Account.class); data = new StubCustomData(); when(account.getCustomData()).thenReturn(data); String json = "{\"name\":\"Test\",\"birthdate\":\"1970-01-01\",\"imageData\":\"test\",\"imageMimeType\":\"image/png\"}"; Encryptor encryptor1 = mock(Encryptor.class); when(encryptor1.getVersion()).thenReturn(1); encryptDecryptValues(encryptor1, "111-222-3333", "111-222-3333-encryptor1encrypted"); encryptDecryptValues(encryptor1, "aHealthId", "aHealthId-encryptor1encrypted"); encryptDecryptValues(encryptor1, json, "json-encryptor1encrypted"); Encryptor encryptor2 = mock(Encryptor.class); when(encryptor2.getVersion()).thenReturn(2); encryptDecryptValues(encryptor2, "111-222-3333", "111-222-3333-encryptor2encrypted"); encryptDecryptValues(encryptor2, json, "json-encryptor2encrypted"); encryptDecryptValues(encryptor2, "555-555-5555", "555-555-5555-encryptor2encrypted"); // This must be a passthrough because we're not going to set the signature through // StormpathAccount, we're going to put a legacy state in the map that's stubbing out // The CustomData element, and then verify that we can retrieve and deserialize the consent // even without a version attribute. ConsentSignature sig = ConsentSignature.create("Test", "1970-01-01", "test", "image/png"); legacySignature = new ObjectMapper().writeValueAsString(sig); encryptDecryptValues(encryptor2, legacySignature, legacySignature); SortedMap<Integer,Encryptor> encryptors = new TreeMap<>(); encryptors.put(1, encryptor1); encryptors.put(2, encryptor2); acct = new StormpathAccount(studyId, account, encryptors); } private void encryptDecryptValues(Encryptor encryptor, String value, String encryptedValue) { when(encryptor.encrypt(value)).thenReturn(encryptedValue); when(encryptor.decrypt(encryptedValue)).thenReturn(value); } @Test public void basicFieldWorks() { when(account.getEmail()).thenReturn("test@test.com"); acct.setEmail("test@test.com"); assertEquals("test@test.com", acct.getEmail()); verify(account).setEmail("test@test.com"); } @Test public void basicFieldValueCanBeCleared() { when(account.getEmail()).thenReturn(null); acct.setEmail(null); assertNull(acct.getEmail()); verify(account).setEmail(null); } @Test public void newSensitiveValueIsEncryptedWithLastEncryptor() { acct.setPhone("111-222-3333"); assertEquals("111-222-3333-encryptor2encrypted", data.get("phone")); assertEquals("111-222-3333", acct.getPhone()); } @Test public void noValueSupported() { assertNull(acct.getPhone()); } @Test public void oldValuesDecryptedWithOldDecryptorAndEncryptedWithNewDecryptor() { data.put("phone", "111-222-3333-encryptor1encrypted"); data.put("phone_version", 1); assertEquals("111-222-3333", acct.getPhone()); acct.setPhone(acct.getPhone()); assertEquals("111-222-3333-encryptor2encrypted", data.get("phone")); assertEquals("111-222-3333", acct.getPhone()); } @Test public void consentSignatureStoredAndEncrypted() { ConsentSignature sig = ConsentSignature.create("Test", "1970-01-01", "test", "image/png"); acct.setConsentSignature(sig); ConsentSignature restoredSig = acct.getConsentSignature(); assertEquals("Test", restoredSig.getName()); assertEquals("1970-01-01", restoredSig.getBirthdate()); assertEquals("test", restoredSig.getImageData()); assertEquals("image/png", restoredSig.getImageMimeType()); } @Test public void canClearKeyValue() { acct.setPhone("111-222-3333"); acct.setPhone(null); assertNull(acct.getPhone()); } @Test public void healthIdRetrievedWithNewVersion() { data.put("foo_code", "aHealthId-encryptor1encrypted"); data.put("foo_code_version", 1); String healthId = acct.getHealthId(); assertEquals("aHealthId", healthId); } @Test public void healthIdRetrievedWithOldVersion() { data.put("foo_code", "aHealthId-encryptor1encrypted"); data.put("fooversion", 1); String healthId = acct.getHealthId(); assertEquals("aHealthId", healthId); } @Test public void consentSignatureRetrievedWithNoVersion() throws Exception { // There is no version attribute for this. Can still retrieve it. data.put("foo_consent_signature", legacySignature); ConsentSignature restoredSig = acct.getConsentSignature(); assertEquals("Test", restoredSig.getName()); assertEquals("1970-01-01", restoredSig.getBirthdate()); assertEquals("test", restoredSig.getImageData()); assertEquals("image/png", restoredSig.getImageMimeType()); } @Test public void failsIfNoEncryptorForVersion() { try { data.put("foo_code", "111"); data.put("fooversion", 3); acct.getHealthId(); } catch(BridgeServiceException e) { assertEquals("No encryptor can be found for version 3", e.getMessage()); } } @Test public void phoneRetrievedWithNoVersion() { data.put("phone", "555-555-5555-encryptor2encrypted"); // This must use version 2, there's no version listed. String phone = acct.getPhone(); assertEquals("555-555-5555", phone); } @Test public void phoneRetrievedWithCorrect() { data.put("phone", "555-555-5555-encryptor2encrypted"); data.put("phone_version", 2); // This must use version 2, there's no version listed. String phone = acct.getPhone(); assertEquals("555-555-5555", phone); } @Test(expected = BridgeServiceException.class) public void phoneNotRetrievedWithIncorrectVersion() { data.put("phone", "encryptedphonenumber"); data.put("phone_version", 3); acct.getPhone(); } @Test public void retrievingNullEncryptedFieldReturnsNull() { String phone = acct.getPhone(); assertNull(phone); } @Test public void canSetAndGetRoles() { acct.getRoles().add("aRole"); assertEquals(1, acct.getRoles().size()); assertEquals("aRole", acct.getRoles().iterator().next()); } }
package org.zstack.test.mevoco.logging; public class TestLogging1 { // CLogger logger = Utils.getLogger(TestLogging1.class); // Deployer deployer; // Api api; // ComponentLoader loader; // CloudBus bus; // DatabaseFacade dbf; // SessionInventory session; // LocalStorageSimulatorConfig config; // FlatNetworkServiceSimulatorConfig fconfig; // KVMSimulatorConfig kconfig; // PrimaryStorageOverProvisioningManager psRatioMgr; // HostCapacityOverProvisioningManager hostRatioMgr; // RESTFacade restf; // EventFacade evtf; // Log.Content logContent; // @Before // public void setUp() throws Exception { // DBUtil.reDeployDB(); // DBUtil.reDeployCassandra(LogConstants.KEY_SPACE); // WebBeanConstructor con = new WebBeanConstructor(); // deployer = new Deployer("deployerXml/OnlyOneZone.xml", con); // deployer.addSpringConfig("cassandra.xml"); // deployer.addSpringConfig("mevocoRelated.xml"); // deployer.addSpringConfig("logging.xml"); // deployer.load(); // loader = deployer.getComponentLoader(); // bus = loader.getComponent(CloudBus.class); // dbf = loader.getComponent(DatabaseFacade.class); // config = loader.getComponent(LocalStorageSimulatorConfig.class); // fconfig = loader.getComponent(FlatNetworkServiceSimulatorConfig.class); // kconfig = loader.getComponent(KVMSimulatorConfig.class); // psRatioMgr = loader.getComponent(PrimaryStorageOverProvisioningManager.class); // hostRatioMgr = loader.getComponent(HostCapacityOverProvisioningManager.class); // evtf = loader.getComponent(EventFacade.class); // restf = loader.getComponent(RESTFacade.class); // deployer.build(); // api = deployer.getApi(); // session = api.loginAsAdmin(); // @Test // public void test() throws ApiSenderException, IOException, InterruptedException { // Log log = new Log(Platform.getUuid()); // log.log(LogLabelTest.TEST1); // APIQueryLogMsg msg = new APIQueryLogMsg(); // msg.setType(LogType.RESOURCE.toString()); // msg.setResourceUuid(log.getResourceUuid()); // APIQueryLogReply reply = api.queryCassandra(msg, APIQueryLogReply.class); // Assert.assertEquals(1, reply.getInventories().size()); // LogInventory loginv = reply.getInventories().get(0); // Assert.assertEquals("1", loginv.getMessage()); // Assert.assertEquals(LogType.RESOURCE.toString(), loginv.getType()); // Assert.assertEquals(log.getResourceUuid(), loginv.getResourceUuid()); // api.deleteLog(loginv.getUuid(), null); // reply = api.queryCassandra(msg, APIQueryLogReply.class); // Assert.assertEquals(0, reply.getInventories().size()); // log = new Log(); // log.log(LogLabelTest.TEST1); // msg = new APIQueryLogMsg(); // msg.setType(LogType.SYSTEM.toString()); // msg.setResourceUuid(log.getResourceUuid()); // reply = api.queryCassandra(msg, APIQueryLogReply.class); // Assert.assertEquals(1, reply.getInventories().size()); // loginv = reply.getInventories().get(0); // Assert.assertEquals("1", loginv.getMessage()); // Assert.assertEquals(LogType.SYSTEM.toString(), loginv.getType()); // Assert.assertEquals(LogType.SYSTEM.toString(), loginv.getResourceUuid()); // api.deleteLog(loginv.getUuid(), null); // evtf.on(Event.EVENT_PATH, new EventCallback() { // @Override // protected void run(Map tokens, Object data) { // logContent = (Content) data; // new Event(AccountConstant.INITIAL_SYSTEM_ADMIN_UUID).log(LogLabelTest.TEST1); // TimeUnit.SECONDS.sleep(2); // Assert.assertNotNull(logContent); // msg = new APIQueryLogMsg(); // msg.setType(LogType.EVENT.toString()); // msg.setResourceUuid(AccountConstant.INITIAL_SYSTEM_ADMIN_UUID); // reply = api.queryCassandra(msg, APIQueryLogReply.class); // Assert.assertEquals(1, reply.getInventories().size()); // loginv = reply.getInventories().get(0); // Assert.assertEquals("1", loginv.getMessage()); // Assert.assertEquals(LogType.EVENT.toString(), loginv.getType()); // Assert.assertEquals(AccountConstant.INITIAL_SYSTEM_ADMIN_UUID, loginv.getResourceUuid()); // LogGlobalConfig.LOCALE.updateValue("en_US"); // log = new Log(Platform.getUuid()); // log.log(LogLabelTest.TEST2, ""); // msg = new APIQueryLogMsg(); // msg.setType(LogType.RESOURCE.toString()); // msg.setResourceUuid(log.getResourceUuid()); // reply = api.queryCassandra(msg, APIQueryLogReply.class); // Assert.assertEquals(1, reply.getInventories().size()); // loginv = reply.getInventories().get(0); // Assert.assertEquals(Platform.i18n(LogLabelTest.TEST2, LocaleUtils.toLocale("en_US"), ""), loginv.getMessage()); // api.deleteLog(loginv.getUuid(), null); // AnsibleLogCmd cmd = new AnsibleLogCmd(); // cmd.setLabel(LogLabelTest.TEST2); // cmd.setParameters(list("test")); // String uuid = Platform.getUuid(); // UriComponentsBuilder ub = UriComponentsBuilder.fromHttpUrl(restf.getBaseUrl()); // //ub.path(String.format("/kvm/ansiblelog/%s", uuid)); // ub.path(new StringBind(KVMConstant.KVM_ANSIBLE_LOG_PATH_FROMAT).bind("uuid", uuid).toString()); // String url = ub.build().toUriString(); // restf.syncJsonPost(url, cmd, Void.class); // msg = new APIQueryLogMsg(); // msg.setType(LogType.RESOURCE.toString()); // msg.setResourceUuid(uuid); // reply = api.queryCassandra(msg, APIQueryLogReply.class); // loginv = reply.getInventories().get(0); // Assert.assertEquals(uuid, loginv.getResourceUuid()); // Assert.assertEquals(Platform.i18n(LogLabelTest.TEST2, LocaleUtils.toLocale("en_US"), "test"), loginv.getMessage()); }
package com.hida.dao; import com.hida.model.Pid; import java.util.List; /** * This class is used to define the possible operations that Hibernate can * perform on Pid objects * * @author lruffin */ public interface PidDao { public Pid findByName(String name); public void savePid(Pid pid); public List<Pid> findAllPids(); public Pid findPidByRegex(String regex); }
package uk.ltd.getahead.dwrdemo.game; /** * Something someone typed */ public class Message { /** * @param newtext * @param author Who wrote this? * @param trusted Is the string trusted */ public Message(String newtext, Person author, boolean trusted) { text = newtext; if (!trusted) { text = BattleshipUtil.makeSafe(text, 256); } text = BattleshipUtil.autolink(text); this.setAuthor(author); } /** * @param id the id to set */ public void setId(long id) { this.id = id; } /** * @return the id */ public long getId() { return id; } /** * @param text the text to set */ public void setText(String text) { this.text = text; } /** * @return the text */ public String getText() { return text; } /** * @param author the author to set */ public void setAuthor(Person author) { this.author = author; } /** * @return the author */ public Person getAuthor() { return author; } private long id = System.currentTimeMillis(); private String text; private Person author; }
package de.javagl.obj; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Utility methods for handling {@link Obj}s.<br> * <br> * Unless otherwise noted, none of the parameters to these methods * may be <code>null</code> */ public class ObjUtils { /** * Convert the given {@link ReadableObj} into an {@link Obj} that has * a structure appropriate for rendering it with OpenGL: * <ul> * <li>{@link #triangulate(ReadableObj) Triangulate} it</li> * <li> * {@link #makeTexCoordsUnique(ReadableObj) * Make the texture coordinates unique} * </li> * <li> * {@link #makeNormalsUnique(ReadableObj) * Make the normals unique} * </li> * <li> * Make the result {@link #makeVertexIndexed(ReadableObj) * vertex-indexed} * </li> * </ul> * * @param input The input {@link ReadableObj} * @return The resulting {@link Obj} */ public static Obj convertToRenderable(ReadableObj input) { return convertToRenderable(input, Objs.create()); } /** * Convert the given {@link ReadableObj} into an {@link Obj} that has * a structure appropriate for rendering it with OpenGL: * <ul> * <li>{@link #triangulate(ReadableObj) Triangulate} it</li> * <li> * {@link #makeTexCoordsUnique(ReadableObj) * Make the texture coordinates unique} * </li> * <li> * {@link #makeNormalsUnique(ReadableObj) * Make the normals unique} * </li> * <li> * Make the result {@link #makeVertexIndexed(ReadableObj) * vertex-indexed} * </li> * </ul> * * @param <T> The type of the output * @param input The input {@link ReadableObj} * @param output The output {@link WritableObj} * @return The given output */ public static <T extends WritableObj> T convertToRenderable( ReadableObj input, T output) { Obj obj = triangulate(input); obj = makeTexCoordsUnique(obj); obj = makeNormalsUnique(obj); return makeVertexIndexed(obj, output); } /** * Triangulates the given input {@link ReadableObj} and returns the * result.<br> * <br> * This method will simply subdivide faces with more than 3 vertices so * that all faces in the output will be triangles. * * @param input The input {@link ReadableObj} * @return The resulting {@link Obj} */ public static Obj triangulate(ReadableObj input) { return triangulate(input, Objs.create()); } /** * Triangulates the given input {@link ReadableObj} and stores the result * in the given {@link WritableObj}.<br> * <br> * This method will simply subdivide faces with more than 3 vertices so * that all faces in the output will be triangles. * * @param <T> The type of the output * @param input The input {@link ReadableObj} * @param output The output {@link WritableObj} * @return The given output */ public static <T extends WritableObj> T triangulate( ReadableObj input, T output) { output.setMtlFileNames(input.getMtlFileNames()); addAll(input, output); for (int i=0; i<input.getNumFaces(); i++) { ObjFace face = input.getFace(i); output.setActiveGroupNames( input.getActivatedGroupNames(face)); output.setActiveMaterialGroupName( input.getActivatedMaterialGroupName(face)); if (face.getNumVertices() == 3) { output.addFace(face); } else { for(int j = 0; j < face.getNumVertices() - 2; j++) { DefaultObjFace triangle = ObjFaces.create(face, 0, j + 1, j + 2); output.addFace(triangle); } } } return output; } /** * Returns the given group of the given {@link ReadableObj} as a new * {@link Obj}.<br> * <br> * The <code>vertexIndexMapping</code> may be <code>null</code>. If it * is not <code>null</code>, <code>vertexIndexMapping.get(i)</code> * afterwards stores the index that vertex <code>i</code> had in the * input. * * @param input The input {@link ReadableObj} * @param inputGroup The group of the input * @param vertexIndexMapping The optional index mapping * @return The resulting {@link Obj} */ public static Obj groupToObj( ReadableObj input, ObjGroup inputGroup, List<Integer> vertexIndexMapping) { return groupToObj(input, inputGroup, vertexIndexMapping, Objs.create()); } /** * Stores the given group of the given {@link ReadableObj} * in the given output {@link WritableObj}.<br> * <br> * The <code>vertexIndexMapping</code> may be <code>null</code>. If it * is not <code>null</code>, <code>vertexIndexMapping.get(i)</code> * afterwards stores the index that vertex <code>i</code> had in the * input. * * @param <T> The type of the output * @param input The input {@link ReadableObj} * @param inputGroup The group of the input * @param vertexIndexMapping The optional index mapping * @param output The output {@link WritableObj} * @return The given output */ public static <T extends WritableObj> T groupToObj( ReadableObj input, ObjGroup inputGroup, List<Integer> vertexIndexMapping, T output) { output.setMtlFileNames(input.getMtlFileNames()); // vertexIndexMap[i] contains the index that vertex i of the // original Obj will have in the output int vertexIndexMap[] = new int[input.getNumVertices()]; int texCoordIndexMap[] = new int[input.getNumTexCoords()]; int normalIndexMap[] = new int[input.getNumNormals()]; Arrays.fill(vertexIndexMap, -1); Arrays.fill(texCoordIndexMap, -1); Arrays.fill(normalIndexMap, -1); int vertexCounter = 0; int texCoordCounter = 0; int normalCounter = 0; for(int i = 0; i < inputGroup.getNumFaces(); i++) { // Clone the face info from the input ObjFace face = inputGroup.getFace(i); DefaultObjFace resultFace = ObjFaces.create(face); output.setActiveGroupNames( input.getActivatedGroupNames(face)); output.setActiveMaterialGroupName( input.getActivatedMaterialGroupName(face)); // The indices of the cloned face have to be adjusted, // so that they point to the correct vertices in the output for(int j = 0; j < face.getNumVertices(); j++) { int vertexIndex = face.getVertexIndex(j); if(vertexIndexMap[vertexIndex] == -1) { vertexIndexMap[vertexIndex] = vertexCounter; output.addVertex(input.getVertex(vertexIndex)); vertexCounter++; } resultFace.setVertexIndex(j, vertexIndexMap[vertexIndex]); } if(face.containsTexCoordIndices()) { for(int j = 0; j < face.getNumVertices(); j++) { int texCoordIndex = face.getTexCoordIndex(j); if(texCoordIndexMap[texCoordIndex] == -1) { texCoordIndexMap[texCoordIndex] = texCoordCounter; output.addTexCoord(input.getTexCoord(texCoordIndex)); texCoordCounter++; } resultFace.setTexCoordIndex( j, texCoordIndexMap[texCoordIndex]); } } if(face.containsNormalIndices()) { for(int j = 0; j < face.getNumVertices(); j++) { int normalIndex = face.getNormalIndex(j); if(normalIndexMap[normalIndex] == -1) { normalIndexMap[normalIndex] = normalCounter; output.addNormal(input.getNormal(normalIndex)); normalCounter++; } resultFace.setNormalIndex(j, normalIndexMap[normalIndex]); } } // Add the cloned face with the adjusted indices to the output output.addFace(resultFace); } // Compute the vertexIndexMapping, so that vertexIndexMapping.get(i) // afterwards stores the index that vertex i had in the input if(vertexIndexMapping != null) { for(int i = 0; i < vertexCounter; i++) { vertexIndexMapping.add(-1); } for(int i = 0; i < input.getNumVertices(); i++) { if(vertexIndexMap[i] != -1) { vertexIndexMapping.set(vertexIndexMap[i], i); } } } return output; } /** * Interface for accessing a property index (vertex, texture coordinate * or normal) from a {@link ReadableObj} */ private interface PropertyIndexAccessor { /** * Returns the index of the specified property from the given * {@link ReadableObj} * * @param input The {@link ReadableObj} * @param face The face * @param vertexNumber The number of the vertex in the face * @return The index of the property * @throws IndexOutOfBoundsException If the index is out of bounds */ int getPropertyIndex( ReadableObj input, ObjFace face, int vertexNumber); /** * Returns whether the given face has indices for the property * that may be queries with this accessor * * @param face The face * @return Whether the face has the property */ boolean hasProperty(ObjFace face); } /** * Ensures that two vertices with different texture coordinates are * actually two different vertices with different indices.<br> * <br> * Two faces may reference the same vertex in the OBJ file. But different * texture coordinates may be assigned to the same vertex in * both faces. The vertex that requires two different properties will be * be duplicated in the output, and the indices in one face will be updated * appropriately.<br> * <br> * This process solely operates on the <i>indices</i> of the properties. * It will not check whether the <i>value</i> of two properties (with * different indices) are actually equal. * * @param input The input {@link ReadableObj} * @return The resulting {@link Obj} */ public static Obj makeTexCoordsUnique(ReadableObj input) { return makeTexCoordsUnique(input, null, Objs.create()); } /** * Ensures that two vertices with different texture coordinates are * actually two different vertices with different indices.<br> * <br> * Two faces may reference the same vertex in the OBJ file. But different * texture coordinates may be assigned to the same vertex in * both faces. The vertex that requires two different properties will be * be duplicated in the output, and the indices in one face will be updated * appropriately.<br> * <br> * This process solely operates on the <i>indices</i> of the properties. * It will not check whether the <i>value</i> of two properties (with * different indices) are actually equal. * <br> * The indexMapping may be <code>null</code>. Otherwise it is assumed that * it already contains the index mapping that was obtained by a call * to {@link #groupToObj(ReadableObj, ObjGroup, List, WritableObj)}, and * this mapping will be updated appropriately. * * @param <T> The type of the output * @param input The input {@link ReadableObj} * @param indexMapping The optional index mapping * @param output The output {@link WritableObj} * @return The given output */ public static <T extends WritableObj> T makeTexCoordsUnique( ReadableObj input, List<Integer> indexMapping, T output) { PropertyIndexAccessor accessor = new PropertyIndexAccessor() { @Override public int getPropertyIndex( ReadableObj input, ObjFace face, int vertexNumber) { return face.getTexCoordIndex(vertexNumber); } @Override public boolean hasProperty(ObjFace face) { return face.containsTexCoordIndices(); } }; makePropertiesUnique(input, accessor, indexMapping, output); return output; } /** * Ensures that two vertices with different normals are * actually two different vertices with different indices.<br> * <br> * Two faces may reference the same vertex in the OBJ file. But different * normals may be assigned to the same vertex in * both faces. The vertex that requires two different properties will be * be duplicated in the output, and the indices in one face will be updated * appropriately.<br> * <br> * This process solely operates on the <i>indices</i> of the properties. * It will not check whether the <i>value</i> of two properties (with * different indices) are actually equal. * * @param input The input {@link ReadableObj} * @return The resulting {@link Obj} */ public static Obj makeNormalsUnique(ReadableObj input) { return makeNormalsUnique(input, null, Objs.create()); } /** * Ensures that two vertices with different normals are * actually two different vertices with different indices.<br> * <br> * Two faces may reference the same vertex in the OBJ file. But different * normals may be assigned to the same vertex in * both faces. The vertex that requires two different properties will be * be duplicated in the output, and the indices in one face will be updated * appropriately.<br> * <br> * This process solely operates on the <i>indices</i> of the properties. * It will not check whether the <i>value</i> of two properties (with * different indices) are actually equal. * <br> * The indexMapping may be <code>null</code>. Otherwise it is assumed that * it already contains the index mapping that was obtained by a call * to {@link #groupToObj(ReadableObj, ObjGroup, List, WritableObj)}, and * this mapping will be updated appropriately. * * @param <T> The type of the output * @param input The input {@link ReadableObj} * @param indexMapping The optional index mapping * @param output The output {@link WritableObj} * @return The given output */ public static <T extends WritableObj> T makeNormalsUnique( ReadableObj input, List<Integer> indexMapping, T output) { PropertyIndexAccessor accessor = new PropertyIndexAccessor() { @Override public int getPropertyIndex( ReadableObj input, ObjFace face, int vertexNumber) { return face.getNormalIndex(vertexNumber); } @Override public boolean hasProperty(ObjFace face) { return face.containsNormalIndices(); } }; makePropertiesUnique(input, accessor, indexMapping, output); return output; } /** * Ensures that two vertices with different properties are * actually two different vertices with different indices.<br> * <br> * Two faces may reference the same vertex in the OBJ file. But different * normals or texture coordinates may be assigned to the same vertex in * both faces. The vertex that requires two different properties will be * be duplicated in the output, and the indices in one face will be updated * appropriately.<br> * <br> * This process solely operates on the <i>indices</i> of the properties. * It will not check whether the <i>value</i> of two properties (with * different indices) are actually equal. * <br> * The indexMapping may be <code>null</code>. Otherwise it is assumed that * it already contains the index mapping that was obtained by a call * to {@link #groupToObj(ReadableObj, ObjGroup, List, WritableObj)}, and * this mapping will be updated appropriately. * * @param input The input {@link ReadableObj} * @param propertyIndexAccessor The accessor for the property index * @param indexMapping The optional index mapping * @param output The output {@link WritableObj} */ private static void makePropertiesUnique( ReadableObj input, PropertyIndexAccessor propertyIndexAccessor, List<Integer> indexMapping, WritableObj output) { output.setMtlFileNames(input.getMtlFileNames()); addAll(input, output); int usedPropertyIndices[] = new int[input.getNumVertices()]; Arrays.fill(usedPropertyIndices, -1); List<FloatTuple> extendedVertices = new ArrayList<FloatTuple>(); for(int i = 0; i < input.getNumFaces(); i++) { ObjFace inputFace = input.getFace(i); output.setActiveGroupNames( input.getActivatedGroupNames(inputFace)); output.setActiveMaterialGroupName( input.getActivatedMaterialGroupName(inputFace)); ObjFace outputFace = inputFace; if (propertyIndexAccessor.hasProperty(inputFace)) { DefaultObjFace extendedOutputFace = null; for(int j = 0; j < outputFace.getNumVertices(); j++) { int vertexIndex = outputFace.getVertexIndex(j); int propertyIndex = propertyIndexAccessor.getPropertyIndex( input, outputFace, j); // Check if the property of the vertex with the current // index already has been used, and it is not equal to // the property that it has in the current face if(usedPropertyIndices[vertexIndex] != -1 && usedPropertyIndices[vertexIndex] != propertyIndex) { FloatTuple vertex = input.getVertex(vertexIndex); // Add the vertex which has multiple properties once // more to the output, and update all indices that // now have to point to the "new" vertex int extendedVertexIndex = input.getNumVertices() + extendedVertices.size(); extendedVertices.add(vertex); output.addVertex(vertex); if (extendedOutputFace == null) { extendedOutputFace = ObjFaces.create(inputFace); } extendedOutputFace.setVertexIndex( j, extendedVertexIndex); if(indexMapping != null) { int indexInObj = indexMapping.get(vertexIndex); indexMapping.add(indexInObj); } } else { usedPropertyIndices[vertexIndex] = propertyIndex; } } if (extendedOutputFace != null) { outputFace = extendedOutputFace; } } output.addFace(outputFace); } } /** * Add all vertices, texture coordinates and normals of the given * {@link ReadableObj} to the given {@link WritableObj} * * @param input The {@link ReadableObj} * @param output The {@link WritableObj} */ private static void addAll(ReadableObj input, WritableObj output) { for (int i=0; i<input.getNumVertices(); i++) { output.addVertex(input.getVertex(i)); } for (int i=0; i<input.getNumTexCoords(); i++) { output.addTexCoord(input.getTexCoord(i)); } for (int i=0; i<input.getNumNormals(); i++) { output.addNormal(input.getNormal(i)); } } /** * Converts the given {@link ReadableObj} data into data that uses the * same indices for vertices, texture coordinates and normals, and * returns the result.<br> * <br> * Note that the result may contain ambiguous texture coordinates and * normals, unless they have been made unique in the input before with * {@link #makeTexCoordsUnique(ReadableObj)} and * {@link #makeNormalsUnique(ReadableObj)}, respectively. * * @param input The input {@link ReadableObj} * @return The resulting {@link Obj} */ public static Obj makeVertexIndexed(ReadableObj input) { return makeVertexIndexed(input, Objs.create()); } /** * Converts the given {@link ReadableObj} data into data that uses the * same indices for vertices, texture coordinates and normals, and * stores the result in the given {@link WritableObj}.<br> * <br> * Note that the result may contain ambiguous texture coordinates and * normals, unless they have been made unique in the input before with * {@link #makeTexCoordsUnique(ReadableObj)} and * {@link #makeNormalsUnique(ReadableObj)}, respectively. * * @param <T> The type of the output * @param input The input {@link ReadableObj} * @param output The output {@link WritableObj} * @return The given output */ public static <T extends WritableObj> T makeVertexIndexed( ReadableObj input, T output) { output.setMtlFileNames(input.getMtlFileNames()); for (int i=0; i<input.getNumVertices(); i++) { output.addVertex(input.getVertex(i)); } boolean foundTexCoords = false; boolean foundNormals = false; int texCoordIndicesForVertexIndices[] = new int[input.getNumVertices()]; int normalIndicesForVertexIndices[] = new int[input.getNumVertices()]; for(int i = 0; i < input.getNumFaces(); i++) { ObjFace inputFace = input.getFace(i); for(int j = 0; j < inputFace.getNumVertices(); j++) { int vertexIndex = inputFace.getVertexIndex(j); if (inputFace.containsTexCoordIndices()) { int texCoordIndex = inputFace.getTexCoordIndex(j); texCoordIndicesForVertexIndices[vertexIndex] = texCoordIndex; foundTexCoords = true; } if (inputFace.containsNormalIndices()) { int normalIndex = inputFace.getNormalIndex(j); normalIndicesForVertexIndices[vertexIndex] = normalIndex; foundNormals = true; } } } if (foundTexCoords) { for (int i=0; i<input.getNumVertices(); i++) { int texCoordIndex = texCoordIndicesForVertexIndices[i]; FloatTuple texCoord = input.getTexCoord(texCoordIndex); output.addTexCoord(texCoord); } } if (foundNormals) { for (int i=0; i<input.getNumVertices(); i++) { int normalIndex = normalIndicesForVertexIndices[i]; FloatTuple normal = input.getNormal(normalIndex); output.addNormal(normal); } } for(int i = 0; i < input.getNumFaces(); i++) { ObjFace inputFace = input.getFace(i); output.setActiveGroupNames( input.getActivatedGroupNames(inputFace)); output.setActiveMaterialGroupName( input.getActivatedMaterialGroupName(inputFace)); DefaultObjFace outputFace = ObjFaces.create(inputFace); if (inputFace.containsTexCoordIndices()) { for (int j=0; j<inputFace.getNumVertices(); j++) { outputFace.setTexCoordIndex(j, outputFace.getVertexIndex(j)); } } if (inputFace.containsNormalIndices()) { for (int j=0; j<inputFace.getNumVertices(); j++) { outputFace.setNormalIndex(j, outputFace.getVertexIndex(j)); } } output.addFace(outputFace); } return output; } /** * Create a multi-line, formatted string containing information about * the given {@link ReadableObj}. This method is solely intended for * debugging. It should not be considered as part of the public API. * The exact output is not specified. * * @param obj The {@link ReadableObj} * @return The info string */ public static String createInfoString(ReadableObj obj) { StringBuilder sb = new StringBuilder(); sb.append("Obj:"+"\n"); sb.append(" mtlFileNames : "+obj.getMtlFileNames()+"\n"); sb.append(" numVertices : "+obj.getNumVertices()+"\n"); sb.append(" numTexCoords : "+obj.getNumTexCoords()+"\n"); sb.append(" numNormals : "+obj.getNumNormals()+"\n"); sb.append(" numFaces : "+obj.getNumFaces()+"\n"); sb.append(" numGroups : "+obj.getNumGroups()+"\n"); for (int i=0; i<obj.getNumGroups(); i++) { ObjGroup objGroup = obj.getGroup(i); sb.append(" Group "+i+":"+"\n"); sb.append(" name : "+objGroup.getName()+"\n"); sb.append(" numFaces: "+objGroup.getNumFaces()+"\n"); } sb.append(" numMaterialGroups: "+obj.getNumMaterialGroups()+"\n"); for (int i=0; i<obj.getNumMaterialGroups(); i++) { ObjGroup objGroup = obj.getMaterialGroup(i); sb.append(" MaterialGroup "+i+":"+"\n"); sb.append(" name : "+objGroup.getName()+"\n"); sb.append(" numFaces: "+objGroup.getNumFaces()+"\n"); } return sb.toString(); } /** * Private constructor to prevent instantiation. */ private ObjUtils() { // Private constructor to prevent instantiation. } }
package com.jmrapp.terralegion; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.jmrapp.terralegion.engine.utils.Settings; import com.jmrapp.terralegion.engine.utils.Timer; import com.jmrapp.terralegion.engine.views.drawables.ResourceManager; import com.jmrapp.terralegion.engine.views.screens.ScreenManager; import com.jmrapp.terralegion.game.utils.ThreadManager; import com.jmrapp.terralegion.game.views.screen.MainScreen; public class PhysicsGame implements ApplicationListener { protected SpriteBatch sb; protected boolean paused; protected long lastBack; @Override public void create() { sb = new SpriteBatch(150); sb.enableBlending(); instantiateSettings(); Gdx.input.setCatchBackKey(true); //Stops from exiting when back button pressed //MENU ResourceManager.getInstance().loadSprite("menuBg", "menu/bg.png", .588f, .625f); ResourceManager.getInstance().loadSprite("btnBg", "ui/btnBg.png", .75f, .75f); //GAME ResourceManager.getInstance().loadTexture("joystickBg", "ui/joystickBg.png"); ResourceManager.getInstance().loadTexture("joystickKnob", "ui/joystickKnob.png"); ResourceManager.getInstance().loadTexture("bg", "bg.png"); ResourceManager.getInstance().loadTexture("player", "player.png"); ResourceManager.getInstance().loadTexture("playerAnimated", "player_animated.png"); ResourceManager.getInstance().loadTexture("leftBtn", "ui/leftBtn.png"); ResourceManager.getInstance().loadTexture("rightBtn", "ui/rightBtn.png"); ResourceManager.getInstance().loadTexture("upBtn", "ui/upBtn.png"); ResourceManager.getInstance().loadTexture("bunny", "entities/bunny.png"); ResourceManager.getInstance().loadTexture("inventoryBox", "ui/inventoryBox.png"); ResourceManager.getInstance().loadTexture("selectedInventoryBox", "ui/selectedInventoryBox.png"); ResourceManager.getInstance().loadTexturedDrawable("cancelBtn", "ui/cancelBtn.png"); ResourceManager.getInstance().loadTexturedDrawable("unselectedCraftingBtn", "ui/unselectedCraftingBtn.png"); ResourceManager.getInstance().loadTexturedDrawable("unselectedInvBtn", "ui/unselectedInvBtn.png"); ResourceManager.getInstance().loadTexturedDrawable("selectedInvBtn", "ui/selectedInvBtn.png"); ResourceManager.getInstance().loadTexturedDrawable("dropItemBtn", "ui/dropItemBtn.png"); ResourceManager.getInstance().loadTexturedDrawable("splitItemBtn", "ui/splitItemBtn.png"); ResourceManager.getInstance().loadTexture("heart", "ui/heart.png"); //INVENTORY SCREEN ResourceManager.getInstance().loadTexture("inventoryBg", "inventory/invBg.png"); ResourceManager.getInstance().loadTexture("invStageBg", "inventory/stageBg.png"); ResourceManager.getInstance().loadTexturedDrawable("inventoryBtn", "ui/inventoryBtn.png"); //CRAFTING SCREEN ResourceManager.getInstance().loadTexture("craftingBg", "inventory/craftingBg.png"); ResourceManager.getInstance().loadTexturedDrawable("selectedCraftingBtn", "ui/selectedCraftingBtn.png"); ResourceManager.getInstance().loadTexture("selectedToolCategoryBtn", "ui/selectedToolCategoryBtn.png"); ResourceManager.getInstance().loadTexture("unselectedToolCategoryBtn", "ui/unselectedToolCategoryBtn.png"); ResourceManager.getInstance().loadTexturedDrawable("craftBtn", "ui/craftBtn.png"); TextureAtlas atlas = new TextureAtlas(Gdx.files.internal("tiles/tiles.atlas")); //TILES ResourceManager.getInstance().loadAtlasRegionDrawable("grass", atlas, "grass"); ResourceManager.getInstance().loadAtlasRegionDrawable("dirt", atlas, "dirt"); ResourceManager.getInstance().loadAtlasRegionDrawable("stone", atlas, "stone"); ResourceManager.getInstance().loadAtlasRegionDrawable("diamond", atlas, "diamond"); ResourceManager.getInstance().loadAtlasRegionDrawable("torch", atlas, "torch"); ResourceManager.getInstance().loadAtlasRegionDrawable("coal", atlas, "coal"); ResourceManager.getInstance().loadAtlasRegionDrawable("stoneWall", atlas, "stoneWall"); ResourceManager.getInstance().loadAtlasRegionDrawable("dirtWall", atlas, "dirtWall"); ResourceManager.getInstance().loadAtlasRegionDrawable("leaves", atlas, "leaves"); ResourceManager.getInstance().loadAtlasRegionDrawable("wood", atlas, "wood"); ResourceManager.getInstance().loadAtlasRegionDrawable("dummyTile", atlas, "dummyTile"); ResourceManager.getInstance().loadAtlasRegionDrawable("blankTile", atlas, "blankTile"); ResourceManager.getInstance().loadAtlasRegionDrawable("chest", atlas, "chest"); //DROPS ResourceManager.getInstance().loadAtlasRegionDrawable("dirtDrop", atlas, "dirtDrop"); ResourceManager.getInstance().loadAtlasRegionDrawable("grassDrop", atlas, "grassDrop"); ResourceManager.getInstance().loadAtlasRegionDrawable("stoneDrop", atlas, "stoneDrop"); ResourceManager.getInstance().loadAtlasRegionDrawable("torchDrop", atlas, "torchDrop"); ResourceManager.getInstance().loadAtlasRegionDrawable("diamondDrop", atlas, "diamondDrop"); ResourceManager.getInstance().loadAtlasRegionDrawable("coalDrop", atlas, "coalDrop"); ResourceManager.getInstance().loadAtlasRegionDrawable("leavesDrop", atlas, "leavesDrop"); ResourceManager.getInstance().loadAtlasRegionDrawable("woodDrop", atlas, "woodDrop"); ResourceManager.getInstance().loadTexturedDrawable("stickDrop", "tiles/drops/stickDrop.png"); //ITEMS ResourceManager.getInstance().loadTexturedDrawable("woodenPickaxe", "items/woodenPickaxe.png"); ResourceManager.getInstance().loadTexturedDrawable("sword", "items/sword.png"); ResourceManager.getInstance().loadTexturedDrawable("stick", "items/stick.png"); //FONTS ResourceManager.getInstance().loadFont("font", "fonts/source-sans-pro-regular.ttf", Color.WHITE, 20); ResourceManager.getInstance().loadFont("smallFont", "fonts/source-sans-pro-regular.ttf", Color.WHITE, 12); //SOUNDS //SoundManager.getInstance().loadSound("buttonClick", "sounds/buttonClick.wav"); /*if (!PrefManager.stringPrefExists("levelCompleted11")) { PrefManager.putEncodedString("levelCompleted11", "1-1"); }*/ //ItemManager.getInstance(); //LOAD THE INSTANCE //DropManager.getInstance(); //LOAD THE INSTANCE ScreenManager.setScreen(new MainScreen()); } @Override public void render() { if (!paused) { Timer.getInstance().update(); if (ScreenManager.getCurrent() != null) ScreenManager.getCurrent().update(); } if (Gdx.input.isKeyPressed(Input.Keys.BACK) && System.currentTimeMillis() - lastBack > 300) { if (ScreenManager.getCurrent() != null) { ScreenManager.getCurrent().onBackPressed(); } lastBack = System.currentTimeMillis(); } Gdx.gl20.glClear(GL20.GL_COLOR_BUFFER_BIT); Gdx.gl20.glClearColor(0f, 0f, 0f, 1); if (ScreenManager.getCurrent() != null) { sb.begin(); ScreenManager.getCurrent().render(sb); sb.end(); } } @Override public void resize(int width, int height) { if (ScreenManager.getCurrent() != null) ScreenManager.getCurrent().resize(width, height); } @Override public void pause() { paused = true; if (ScreenManager.getCurrent() != null) ScreenManager.getCurrent().pause(); } @Override public void resume() { paused = false; if (ScreenManager.getCurrent() != null) ScreenManager.getCurrent().resume(); } @Override public void dispose() { sb.dispose(); ResourceManager.getInstance().dispose(); ThreadManager.getInstance().shutdown(); } public static void instantiateSettings() { Settings.addSetting("width", 800); Settings.addSetting("height", 480); } }
// Triple Play - utilities for use in PlayN-based games package tripleplay.util; import java.io.StringWriter; import playn.core.Json; import playn.core.PlayN; /** * Facilities for parsing JSON data */ public class JsonUtil { /** * @return the Enum whose name corresponds to string for the given key, or {@code defaultVal} * if the key doesn't exist. */ public static <T extends Enum<T>> T getEnum (Json.Object json, String key, Class<T> enumType, T defaultVal) { return Enum.valueOf(enumType, getString(json, key, defaultVal.toString())); } /** * @return the Enum whose name corresponds to string for the given key. * Throws a RuntimeException if the key doesn't exist. */ public static <T extends Enum<T>> T requireEnum (Json.Object json, String key, Class<T> enumType) { return Enum.valueOf(enumType, requireString(json, key)); } /** * @return the boolean value at the given key, or {@code defaultVal} if the key * doesn't exist. */ public static boolean getBoolean (Json.Object json, String key, boolean defaultVal) { return (json.containsKey(key) ? json.getBoolean(key) : defaultVal); } /** * @return the boolean value at the given key. * @throws a RuntimeException if the key doesn't exist. */ public static boolean requireBoolean (Json.Object json, String key) { requireKey(json, key); return json.getBoolean(key); } /** * @return the double value at the given key, or {@code defaultVal} if the key * doesn't exist. */ public static double getNumber (Json.Object json, String key, double defaultVal) { return (json.containsKey(key) ? json.getNumber(key) : defaultVal); } /** * @return the double value at the given key. * @throws a RuntimeException if the key doesn't exist. */ public static double requireNumber (Json.Object json, String key) { requireKey(json, key); return json.getNumber(key); } /** * @return the float value at the given key, or {@code defaultVal} if the key * doesn't exist. */ public static float getFloat (Json.Object json, String key, float defaultVal) { return (float) getNumber(json, key, defaultVal); } /** * @return the float value at the given key. * @throws a RuntimeException if the key doesn't exist. */ public static float requireFloat (Json.Object json, String key) { return (float) requireNumber(json, key); } /** * @return the int value at the given key, or {@code defaultVal} if the key * doesn't exist. */ public static int getInt (Json.Object json, String key, int defaultVal) { return (json.containsKey(key) ? json.getInt(key) : defaultVal); } /** * @return the int value at the given key. * @throws a RuntimeException if the key doesn't exist. */ public static int requireInt (Json.Object json, String key) { requireKey(json, key); return json.getInt(key); } /** * @return the String value at the given key, or {@code defaultVal} if the key * doesn't exist. */ public static String getString (Json.Object json, String key, String defaultVal) { return (json.containsKey(key) ? json.getString(key) : defaultVal); } /** * @return the String value at the given key. * @throws a RuntimeException if the key doesn't exist. */ public static String requireString (Json.Object json, String key) { requireKey(json, key); return json.getString(key); } /** * @return the Json.Object value at the given key, or {@code defaultVal} if the key * doesn't exist. */ public static Json.Object getObject (Json.Object json, String key, Json.Object defaultVal) { return (json.containsKey(key) ? json.getObject(key) : defaultVal); } /** * @return the Json.Object at the given key. * @throws a RuntimeException if the key doesn't exist. */ public static Json.Object requireObject (Json.Object json, String key) { requireKey(json, key); return json.getObject(key); } /** * @return the Json.Object value at the given key, or {@code defaultVal} if the key * doesn't exist. */ public static Json.Array getArray (Json.Object json, String key, Json.Array defaultVal) { return (json.containsKey(key) ? json.getArray(key) : defaultVal); } /** * @return the Json.Array at the given key. * @throws a RuntimeException if the key doesn't exist. */ public static Json.Array requireArray (Json.Object json, String key) { requireKey(json, key); return json.getArray(key); } /** * @returns a String representation of the given Json */ public static String toString (Json.Object json, boolean verbose) { Json.Writer writer = PlayN.json().newWriter().useVerboseFormat(verbose); writer.object(); json.write(writer); writer.end(); StringWriter out = new StringWriter(); out.write(writer.write()); return out.toString(); } protected static void requireKey (Json.Object json, String key) { if (!json.containsKey(key)) { throw new RuntimeException("Missing required key [name=" + key + "]"); } } }
package controllers.api; import gov.nrel.util.SearchUtils; import gov.nrel.util.Utility; import java.io.IOException; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import javax.xml.parsers.ParserConfigurationException; import models.DataTypeEnum; import models.Entity; import models.EntityGroup; import models.EntityGroupXref; import models.EntityUser; import models.KeyToTableName; import models.PermissionType; import models.RoleMapping; import models.SdiColumn; import models.SdiColumnProperty; import models.SecureResource; import models.SecureResourceGroupXref; import models.SecureSchema; import models.SecureTable; import models.SecurityGroup; import models.message.DatasetColumnModel; import models.message.DatasetColumnSemanticModel; import models.message.DatasetType; import models.message.RegisterMessage; import models.message.RegisterResponseMessage; import models.message.SearchableParent; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.solr.client.solrj.SolrServer; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.request.AbstractUpdateRequest; import org.apache.solr.client.solrj.request.CoreAdminRequest; import org.apache.solr.client.solrj.request.UpdateRequest; import org.apache.solr.client.solrj.response.CoreAdminResponse; import org.apache.solr.common.SolrException; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.params.CoreAdminParams.CoreAdminAction; import org.joda.time.LocalDateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.SAXException; import play.Play; import play.mvc.Util; import play.mvc.results.BadRequest; import com.alvazan.orm.api.base.NoSqlEntityManager; import com.alvazan.orm.api.z8spi.meta.DboColumnCommonMeta; import com.alvazan.orm.api.z8spi.meta.DboColumnIdMeta; import com.alvazan.orm.api.z8spi.meta.DboColumnMeta; import com.alvazan.orm.api.z8spi.meta.DboColumnToOneMeta; import com.alvazan.orm.api.z8spi.meta.DboTableMeta; import com.alvazan.orm.api.z8spi.meta.TypedColumn; import com.alvazan.play.NoSql; import controllers.SearchPosting; import controllers.SecurityUtil; public class ApiRegistrationImpl { private static final Logger log = LoggerFactory.getLogger(ApiRegistrationImpl.class); public static int divisor = Integer.MAX_VALUE / 10; public static RegisterResponseMessage registerImpl(RegisterMessage msg, String username, String apiKey) { String mode = (String) Play.configuration.get("upgrade.mode"); String requestUrl = null; if(mode == null) { } if(mode.startsWith("http")) { requestUrl = mode; } else if("NEW".equals(mode)) { DatasetType type = msg.getDatasetType(); if(type == DatasetType.STREAM) msg.setDatasetType(DatasetType.TIME_SERIES); } if (log.isInfoEnabled()) log.info("Registering table="+msg.getModelName()); if(msg.getDatasetType() != DatasetType.STREAM && msg.getDatasetType() != DatasetType.RELATIONAL_TABLE && msg.getDatasetType() != DatasetType.TIME_SERIES) { if (log.isInfoEnabled()) log.info("only supporting type of STREAM or RELATIONAL_TABLE or TIME_SERIES right now"); throw new BadRequest("only supporting type of STREAM or RELATIONAL_TABLE or TIME_SERIES right now"); } else if(msg.getModelName() == null) { if (log.isInfoEnabled()) log.info("model name was null and is required"); throw new BadRequest("model name was null and is required"); } else if(!DboTableMeta.isValidTableName(msg.getModelName())) { if (log.isInfoEnabled()) log.info("modelName is invalid, it much match regular expression=[a-zA-Z_][a-zA-Z_0-9]*"); throw new BadRequest("modelName is invalid, it much match regular expression=[a-zA-Z_][a-zA-Z_0-9]*"); } String schemaName = null; if((msg.getGroups()!=null && msg.getGroups().size()!=0) && msg.getSchema() != null) { if (log.isInfoEnabled()) log.info("use supplied groups and schema attribute...this is not allowed"); throw new BadRequest("Cannot supply schema AND list of groups. groups is deprecated, use schema only"); } else if(msg.getGroups() != null && msg.getGroups().size() > 0) { if(msg.getGroups().size() > 1) { if (log.isInfoEnabled()) log.info("more than one group is not allowed"); throw new BadRequest("Cannot have more than one group anymore. That is deprecated"); } schemaName = msg.getGroups().get(0); } else if(msg.getSchema() != null) { schemaName = msg.getSchema(); } else { if (log.isInfoEnabled()) log.info("missing schema attribute"); throw new BadRequest("Missing the schema attribute which is required"); } DatasetType type = msg.getDatasetType(); validateColumnsForDatasetType(msg); ensureTableDoesNotAlreadyExist(msg); EntityUser user = SecurityUtil.fetchUser(username, apiKey); SecureSchema schema = SecureSchema.findByName(NoSql.em(), schemaName); if(schema == null) throw new BadRequest("you must specify an existing schema or group"); // Setup the table meta DboTableMeta tm = new DboTableMeta(); if(msg.getDatasetType() != DatasetType.TIME_SERIES) { tm.setup(msg.getModelName(), "nreldata", false); } else { List<DatasetColumnModel> columns = msg.getColumns(); if(columns.size() != 2) throw new BadRequest("TIME_SERIES table can only have two columns, the primary key of long(time since epoch) and value of any type"); String modelName = msg.getModelName(); String realCf = Utility.createCfName(modelName); long partitionSize = TimeUnit.MILLISECONDS.convert(30, TimeUnit.DAYS); tm.setTimeSeries(true); tm.setTimeSeriesPartionSize(partitionSize); tm.setup(msg.getModelName(), realCf, false); tm.setColNameType(long.class); } // create new Table here and add to security group as well SecureTable t = new SecureTable(); if(msg.getDatasetType() == DatasetType.RELATIONAL_TABLE) { t.setTypeOfData(DataTypeEnum.RELATIONAL); } else if(msg.getDatasetType() == DatasetType.TIME_SERIES) { t.setTypeOfData(DataTypeEnum.TIME_SERIES); } t.setTableName(msg.getModelName()); t.setDateCreated(new LocalDateTime()); t.setTableMeta(tm); t.setCreator(user); t.setIsForLogging(msg.getIsForLogging()); t.setSearchable(msg.getIsSearchable()); if (schema != null) schema.addTable(t); NoSql.em().fillInWithKey(t); tm.setForeignKeyToExtensions(t.getId()); setupEachColumn(msg, t, type); setupParentTables(msg, t, type); NoSqlEntityManager mgr = NoSql.em(); if (log.isInfoEnabled()) log.info("table id = '" + tm.getColumnFamily() + "'"); setApiKeysForEntities(schema.getEntitiesWithAccess(), t, tm); mgr.put(schema); mgr.put(tm); mgr.put(t); if(t.isSearchable()) { try { ArrayList<SolrInputDocument> solrDocs = new ArrayList<SolrInputDocument>(); SearchUtils.indexTable(t, tm, solrDocs); SearchPosting.saveSolr("table id = '" + tm.getColumnFamily() + "'", solrDocs, "databusmeta"); solrDocs = new ArrayList<SolrInputDocument>(); } catch(Exception e) { if (log.isInfoEnabled()) log.info("Got an exception preparing solr for a new searchable table - "+e.getMessage()); throw new RuntimeException("Got an exception preparing solr for a new searchable table, cancelling creation of table. Try to reregister at a later time when solr is back online or make your table isSearchable=false..", e); } } mgr.flush(); if (log.isInfoEnabled()) log.info("Registered table="+msg.getModelName()); // Construct the response message RegisterResponseMessage rmsg = new RegisterResponseMessage(); rmsg.setModelName(msg.getModelName()); return rmsg; } private static void setupParentTables(RegisterMessage msg, SecureTable t, DatasetType type) { List<SearchableParent> parents = msg.getSearchableParent(); //we're only allowing one for now: if (parents!=null && parents.size()!=0) { SearchableParent sp = parents.get(0); //it's ok if they are all blank: if (!allOrNoneBlank(sp.getParentFKField(), sp.getParentTable(), sp.getChildFKField())) throw new BadRequest("If searchableParent is specified then all fields must be specified: parentTable, childFKField, parentFKField"); t.setSearchableParentTable(sp.getParentTable()); t.setSearchableParentParentCol(sp.getParentFKField()); t.setSearchableParentChildCol(sp.getChildFKField()); } } private static boolean allOrNoneBlank(String... strings) { boolean firstTime = true; boolean checkingNulls = false; for (String s:strings) { if (firstTime) { if (StringUtils.isBlank(s)) checkingNulls=true; firstTime=false; } else if (checkingNulls && !StringUtils.isBlank(s)) { return false; } else if (!checkingNulls && StringUtils.isBlank(s)) { return false; } } return true; } private static void validateColumnsForDatasetType(RegisterMessage msg) { //a STREAM dataset type must only contain columns 'time' of type bigInteger and 'value' of type bigDecimal: if(msg.getDatasetType() == DatasetType.STREAM) { if (msg.getColumns().size() == 2) { DatasetColumnModel c1=msg.getColumns().get(0); DatasetColumnModel c2=msg.getColumns().get(1); if("time".equalsIgnoreCase(c1.getName()) && "BigInteger".equalsIgnoreCase(c1.getDataType()) && "value".equalsIgnoreCase(c2.getName()) && "BigDecimal".equalsIgnoreCase(c2.getDataType())) return; if("time".equalsIgnoreCase(c2.getName()) && "BigInteger".equalsIgnoreCase(c2.getDataType()) && "value".equalsIgnoreCase(c1.getName()) && "BigDecimal".equalsIgnoreCase(c1.getDataType())) return; } throw new BadRequest("When registering a STREAM the only columns allowed are 'time' of type 'BigInteger' and 'value' of type 'BigDecimal'"); } } private static void setApiKeysForEntities(List<SecureResourceGroupXref> entitiesWithAccess, SecureTable table, DboTableMeta tm) { Set<String> usedIds = new HashSet<String>(); for(SecureResourceGroupXref ref : entitiesWithAccess) { Entity userOrGroup = ref.getUserOrGroup(); setNonMatchingApiKeys(userOrGroup, table, tm, usedIds); } } private static void setNonMatchingApiKeys(Entity e, SecureTable table, DboTableMeta tm, Set<String> usedIds) { //The following code is ONLY if groups have a circular reference which should never //happen but it protects on circular reference if group A belongs to group B belongs to //groupC belongs to groupA... String id = e.getId(); if(usedIds.contains(id)) return; //skip already processed entities usedIds.add(id); if (e.getClassType().equals("userImpl")) { EntityUser u = (EntityUser)e; String rowKey2 = KeyToTableName.formKey(table.getTableName(), u.getUsername(), u.getApiKey()); KeyToTableName k2 = createKeyToTable(rowKey2, tm, table); NoSql.em().put(k2); } else if(e.getClassType().equals("group")) { EntityGroup group = (EntityGroup) e; List<EntityGroupXref> children = group.getChildren(); for(EntityGroupXref xref : children) { Entity entity = xref.getEntity(); setNonMatchingApiKeys(entity, table, tm, usedIds); } } } private static KeyToTableName createKeyToTable(String rowKey, DboTableMeta tm, SecureTable t) { KeyToTableName k2t = new KeyToTableName(); k2t.setTableMeta(tm); k2t.setSdiTableMeta(t); k2t.setKey(rowKey); return k2t; } private static void ensureTableDoesNotAlreadyExist(RegisterMessage msg) { SecureResource t2 = SecureTable.findByName(NoSql.em(), msg.getModelName()); DboTableMeta table = NoSql.em().find(DboTableMeta.class, msg.getModelName()); if(t2 != null) { if (log.isInfoEnabled()) log.info("Sorry, table with tablename='"+msg.getModelName()+"' is already in use"); throw new BadRequest("Sorry, table with tablename='"+msg.getModelName()+"' is already in use"); } else if (table != null) { if (log.isInfoEnabled()) log.info("Table '" + msg.getModelName() + "' already exists (is there a bug here?)."); throw new BadRequest("Table '" + msg.getModelName() + "' already exists (is there a bug here?)."); } } //remove after 12/12/12 private static Map<String, SecurityGroup> formAdminGroups( List<RoleMapping> roles) { Map<String, SecurityGroup> nameToGroup = new HashMap<String, SecurityGroup>(); for(RoleMapping r : roles) { if(r.getPermission() == PermissionType.ADMIN) nameToGroup.put(r.getGroup().getName(), r.getGroup()); } return nameToGroup; } private static void setupEachColumn(RegisterMessage msg, SecureTable t, DatasetType type) { boolean hasPrimaryKey = false; NoSqlEntityManager mgr = NoSql.em(); DboTableMeta tm = t.getTableMeta(); boolean tableIsIndexed = false; // Setup the column meta for (DatasetColumnModel c : msg.getColumns()) { if(c.isPrimaryKey) { if(hasPrimaryKey) { if (log.isInfoEnabled()) log.info("You cannot have two columns set to primary key at this time"); throw new BadRequest("You cannot have two columns set to primary key at this time"); } hasPrimaryKey = true; } if(c.isIndex) tableIsIndexed = true; if(!DboColumnMeta.isValidColumnName(c.getName())) { if (log.isInfoEnabled()) log.info("col name="+c.getName()+" is not valid. must match regex=[a-zA-Z_][a-zA-Z_0-9]*"); throw new BadRequest("col name="+c.getName()+" is not valid. must match regex=[a-zA-Z_][a-zA-Z_0-9]*"); } // Set up the semantic meta for this particular column String semanticType = c.getSemanticType(); SdiColumn col = new SdiColumn(); col.setColumnName(c.getName()); if (c.isFacet) t.setFacetFields(t.getFacetFields()+","+c.getName()); col.setSemanticType(semanticType); setupSemanticData(mgr, c, col); Class dataType = null; if (c.getDataType().equalsIgnoreCase("BigDecimal") ||c.getDataType().equalsIgnoreCase("Decimal")) { dataType = BigDecimal.class; } else if (c.getDataType().equalsIgnoreCase("BigInteger") ||c.getDataType().equalsIgnoreCase("Integer")) { dataType = BigInteger.class; } else if (c.getDataType().equalsIgnoreCase("String")) { dataType = String.class; } else if (c.getDataType().equalsIgnoreCase("Boolean")) { dataType = Boolean.class; } else if (c.getDataType().equalsIgnoreCase("bytes")) { dataType = byte[].class; } else { if (log.isInfoEnabled()) log.info("user trying to register stream with type="+c.getDataType()+" which is not allowed"); throw new BadRequest("Datatype="+c.getDataType()+" is not allowed. Allowed values are bigdecimal/decimal, biginteger/integer, string, boolean, bytes(in hex)"); } DboColumnMeta colMeta; if(c.getIsPrimaryKey()) { DboColumnIdMeta cm = formPrimaryKeyMeta(tm, c, dataType, type); t.setPrimaryKey(col); colMeta = cm; if (log.isInfoEnabled()) log.info("col '" + cm.getColumnName() + "' is a pk " + cm.getId()+" isIndexed="+c.isIndex); } else { DboColumnMeta cm = formCommonColMeta(tm, c, dataType); t.getNameToField().put(c.getName(), col); colMeta = cm; if (log.isInfoEnabled()) log.info("col '" + cm.getColumnName() + "' is NOT a pk " + cm.getId()+" isIndexed="+c.isIndex); } mgr.put(col); mgr.put(colMeta); } // for if(!tableIsIndexed) { if (log.isInfoEnabled()) log.info("In your json request, NONE of the columns had isIndexed set to true and we require ONE index(and it can be primary key but doesn't have to be"); throw new BadRequest("In your json request, NONE of the columns had isIndexed set to true and we require ONE index(and it can be primary key but doesn't have to be"); } else if(!hasPrimaryKey) { if (log.isInfoEnabled()) log.info("In your json request, NONE of the columns had primaryKey set to true and we require ONE primary key"); throw new BadRequest("In your json request, NONE of the columns had primaryKey set to true and we require ONE primary key"); } } private static DboColumnIdMeta formPrimaryKeyMeta(DboTableMeta tm, DatasetColumnModel c, Class dataType, DatasetType type ) { if(dataType != BigInteger.class && type == DatasetType.STREAM) { if (log.isInfoEnabled()) log.info("primary key column was not of type integer yet this is time series data"); throw new BadRequest("primary key column was not of type integer yet this is time series data"); } boolean indexed = c.isIndex; if(type == DatasetType.TIME_SERIES) indexed = false; DboColumnIdMeta idMeta = new DboColumnIdMeta(); idMeta.setup(tm, c.getName(), dataType, indexed); return idMeta; } private static DboColumnMeta formCommonColMeta(DboTableMeta tm, DatasetColumnModel c, Class dataType) { DboColumnMeta result; String table = c.getForeignKeyTablename(); if(table != null) { DboTableMeta fkTable = lookupFkTable(tm, table); DboColumnToOneMeta cm = new DboColumnToOneMeta(); cm.setup(tm, c.getName(), fkTable, c.isIndex, false); result = cm; } else { DboColumnCommonMeta cm = new DboColumnCommonMeta(); cm.setup(tm, c.getName(), dataType, c.isIndex, false); result = cm; } return result; } private static DboTableMeta lookupFkTable(DboTableMeta tm, String table) { DboTableMeta fkTable; if(table.equals(tm.getColumnFamily())) { fkTable = tm; } else { fkTable = NoSql.em().find(DboTableMeta.class, table); if(fkTable == null) { if (log.isInfoEnabled()) log.info("They tried to create a table="+tm.getColumnFamily()+" that has fk to table="+table+" but that fk table does not exist and is not this table"); throw new BadRequest("table="+table+" does not exist AND it's not this table so you can't create a foreign key to non-existent table"); } } return fkTable; } private static void setupSemanticData(NoSqlEntityManager mgr, models.message.DatasetColumnModel c, SdiColumn col) { // Set up the additional semantic meta for this column, if any for (DatasetColumnSemanticModel s : c.getSemantics()) { final String property = s.getProperty(); final String value = s.getValue(); SdiColumnProperty cp = new SdiColumnProperty() { { setName(property); setValue(value); } }; mgr.put(cp); col.getProperties().put(property, cp); } // for } }
package com.dmdirc.addons.dcc; import java.net.Socket; import java.net.ServerSocket; import java.io.IOException; import java.util.concurrent.Semaphore; /** * This class handles the main "grunt work" of DCC, subclasses process the data * received by this class. * * @author Shane 'Dataforce' McCormack */ public abstract class DCC implements Runnable { /** Address. */ protected long address = 0; /** Port. */ protected int port = 0; /** Socket used to communicate with. */ protected Socket socket; /** The Thread in use for this. */ private volatile Thread myThread; /** Are we already running? */ protected boolean running = false; /** Are we a listen socket? */ protected boolean listen = false; /** * The current socket in use if this is a listen socket. * This reference may be changed if and only if exactly one permit from the * <code>serverSocketSem</code> and <code>serverListenignSem</code> * semaphores is held by the thread doing the modification. */ private ServerSocket serverSocket; /** * Semaphore to control write access to ServerSocket. * If an object acquires a permit from the <code>serverSocketSem</code>, then * <code>serverSocket</code> is <em>guaranteed</em> not to be externally * modified until that permit is released, <em>unless</em> the object also * acquires a permit from the <code>serverListeningSem</code>. */ private final Semaphore serverSocketSem = new Semaphore(1); /** * Semaphore used when we're blocking waiting for connections. * If an object acquires a permit from the <code>serverListeningSem</code>, * then it is <em>guaranteed</em> that the {@link #run()} method is blocking * waiting for incoming connections. In addition, it is <em>guaranteed</em> * that the {@link #run()} method is holding the <code>serverSocketSem</code> * permit, and it will continue holding that permit until it can reaquire * the <code>serverListeningSem</code> permit. */ private final Semaphore serverListeningSem = new Semaphore(0); /** * Creates a new instance of DCC. */ public DCC() { super(); } /** * Connect this dcc. */ public void connect() { try { if (listen) { address = 0; port = serverSocket.getLocalPort(); } else { // socket = new Socket(longToIP(address), port, bindIP, 0); socket = new Socket(longToIP(address), port); socketOpened(); } } catch (IOException ioe) { socketClosed(); return; } myThread = new Thread(this); myThread.start(); } /** * Start a listen socket rather than a connect socket. * * @throws IOException If the listen socket can't be created */ public void listen() throws IOException { serverSocketSem.acquireUninterruptibly(); serverSocket = new ServerSocket(0, 1); serverSocketSem.release(); listen = true; connect(); } /** * Start a listen socket rather than a connect socket, use a port from the * given range. * * @param startPort Port to try first * @param endPort Last port to try. * @throws IOException If no sockets were available in the given range */ public void listen(final int startPort, final int endPort) throws IOException { listen = true; for (int i = startPort; i <= endPort; ++i) { try { serverSocketSem.acquireUninterruptibly(); serverSocket = new ServerSocket(i, 1); serverSocketSem.release(); // Found a socket we can use! break; } catch (IOException ioe) { // Try next socket. } catch (SecurityException se) { // Try next socket. } } if (serverSocket == null) { throw new IOException("No available sockets in range " + startPort + ":" + endPort); } else { connect(); } } /** * This handles the socket to keep it out of the main thread */ @Override public void run() { if (running) { return; } running = true; // handleSocket is implemented by sub classes, and should return false // when the socket is closed. Thread thisThread = Thread.currentThread(); while (myThread == thisThread) { serverSocketSem.acquireUninterruptibly(); if (serverSocket == null) { serverSocketSem.release(); if (!handleSocket()) { close(); break; } } else { try { serverListeningSem.release(); socket = serverSocket.accept(); serverSocket.close(); socketOpened(); } catch (IOException ioe) { socketClosed(); break; } finally { serverListeningSem.acquireUninterruptibly(); serverSocket = null; serverSocketSem.release(); } } // Sleep for a short period of time to reduce CPU usage. try { Thread.yield(); Thread.sleep(100); } catch (InterruptedException ie) { } } // Socket closed thisThread = null; running = false; } /** * Called to close the socket */ protected void close() { boolean haveSLS = false; while (!serverSocketSem.tryAcquire() && !(haveSLS = serverListeningSem.tryAcquire())) { try { Thread.sleep(100); } catch (InterruptedException ex) { // Do we care? I doubt we do! Should be unchecked damnit. } } if (serverSocket != null) { try { if (!serverSocket.isClosed()) { serverSocket.close(); } } catch (IOException ioe) { } serverSocket = null; } if (haveSLS) { serverListeningSem.release(); } else { serverSocketSem.release(); } if (socket != null) { try { if (!socket.isClosed()) { socket.close(); } } catch (IOException ioe) { } socketClosed(); socket = null; } } /** * Called when the socket is first opened, before any data is handled. */ protected void socketOpened() { } /** * Called when the socket is closed, before the thread terminates. */ protected void socketClosed() { } /** * Check if this socket can be written to. * * @return True if the socket is writable, false otehrwise */ public boolean isWriteable() { return false; } /** * Handle the socket. * * @return false when socket is closed, true will cause the method to be * called again. */ protected abstract boolean handleSocket(); /** * Set the address to connect to for this DCC * * @param address Address as an int (Network Byte Order, as specified in the DCC CTCP) * @param port Port to connect to */ public void setAddress(final long address, final int port) { this.address = address; this.port = port; } /** * Is this a listening socket * * @return True if this is a listening socket */ public boolean isListenSocket() { return listen; } /** * Get the host this socket is listening on/connecting to * * @return The IP that this socket is listening on/connecting to. */ public String getHost() { return longToIP(address); } /** * Get the port this socket is listening on/connecting to * * @return The port that this socket is listening on/connecting to. */ public int getPort() { return port; } /** * Convert the given IP Address to a long * * @param ip Input IP Address * @return ip as a long */ public static long ipToLong(final String ip) { final String bits[] = ip.split("\\."); if (bits.length > 3) { return (Long.parseLong(bits[0]) << 24) + (Long.parseLong(bits[1]) << 16) + (Long.parseLong(bits[2]) << 8) + Long.parseLong(bits[3]); } return 0; } /** * Convert the given long to an IP Address * * @param in Input long * @return long as an IP */ public static String longToIP(final long in) { return ((in & 0xff000000) >> 24) + "." + ((in & 0x00ff0000) >> 16) + "." + ((in & 0x0000ff00) >> 8) + "." + (in & 0x000000ff); } }
package com.ecyrd.jspwiki; /** * Contains release and version information. * * @author Janne Jalkanen */ public class Release { /** * This is the default application name. */ public static final String APPNAME = "JSPWiki"; /** * This should be empty when doing a release - otherwise * keep it as "cvs" so that whenever someone checks out the code, * they know it is a bleeding-edge version. Other possible * values are "-alpha" and "-beta" for alpha and beta versions, * respectively. */ private static final String POSTFIX = "-cvs"; /** * This should be increased every time you do a release. * @deprecated */ public static final String RELEASE = "R9"; public static final int VERSION = 2; public static final int REVISION = 3; public static final int MINORREVISION = 28; /** * This is the generic version string you should use * when printing out the version. It is of the form "x.y.z-ttt". */ public static final String VERSTR = VERSION+"."+REVISION+"."+MINORREVISION+POSTFIX; /** * This method is useful for templates, because hopefully it will * not be inlined, and thus any change to version number does not * need recompiling the pages. * * @since 2.1.26. */ public static String getVersionString() { return VERSTR; } /** * Executing this class directly from command line prints out * the current version. It is very useful for things like * different command line tools. * <P>Example: * <PRE> * % java com.ecyrd.jspwiki.Release * 1.9.26-cvs * </PRE> */ public static void main( String argv[] ) { System.out.println(VERSTR); } }
package com.ecyrd.jspwiki; /** * Contains release information. * * @author Janne Jalkanen */ public class Release { /** * This is the default application name. */ public static final String APPNAME = "JSPWiki"; /** This should be empty when doing a release - otherwise keep it as "cvs" so that whenever someone checks out the code, they know it is a bleeding-edge version. */ private static final String POSTFIX = "-cvs"; /** * This should be increased every time you do a release. */ public static final String RELEASE = "R5"; public static final int VERSION = 1; public static final int REVISION = 7; public static final int MINORREVISION = 7; /** * This is the generic version string you should use * when printing out the version. */ public static final String VERSTR = VERSION+"."+REVISION+"."+MINORREVISION+POSTFIX; }
package com.ecyrd.jspwiki; import org.apache.commons.lang.StringUtils; /** * Contains release and version information. You may also invoke this * class directly, in which case it prints out the version string. This * is a handy way of checking which JSPWiki version you have - just type * from a command line: * <pre> * % java -cp JSPWiki.jar com.ecyrd.jspwiki.Release * 2.5.38 * </pre> * <p> * As a historical curiosity, this is the oldest JSPWiki file. According * to the CVS history, it dates from 6.7.2001, and it really hasn't changed * much since. * </p> * @author Janne Jalkanen * @since 1.0 */ public final class Release { private static final String VERSION_SEPARATORS = ".-"; /** * This is the default application name. */ public static final String APPNAME = "JSPWiki"; /** * This should be empty when doing a release - otherwise * keep it as "cvs" so that whenever someone checks out the code, * they know it is a bleeding-edge version. Other possible * values are "-alpha" and "-beta" for alpha and beta versions, * respectively. */ private static final String POSTFIX = "-alpha"; /** The JSPWiki major version. */ public static final int VERSION = 2; /** The JSPWiki revision. */ public static final int REVISION = 5; /** The minor revision, or a "build number", if you wish. */ public static final int MINORREVISION = 88; /** * This is the generic version string you should use * when printing out the version. It is of the form "x.y.z-ttt". */ public static final String VERSTR = VERSION+"."+REVISION+"."+MINORREVISION+POSTFIX; /** * Private constructor prevents instantiation. */ private Release() {} /** * This method is useful for templates, because hopefully it will * not be inlined, and thus any change to version number does not * need recompiling the pages. * * @since 2.1.26. * @return The version string (e.g. 2.5.23). */ public static String getVersionString() { return VERSTR; } public static boolean isNewerOrEqual( String version ) throws IllegalArgumentException { if( version == null ) return true; String[] versionComponents = StringUtils.split(version,VERSION_SEPARATORS); int reqVersion = versionComponents.length > 0 ? Integer.parseInt(versionComponents[0]) : Release.VERSION; int reqRevision = versionComponents.length > 1 ? Integer.parseInt(versionComponents[1]) : Release.REVISION; int reqMinorRevision = versionComponents.length > 2 ? Integer.parseInt(versionComponents[2]) : Release.MINORREVISION; if( VERSION == reqVersion ) { if( REVISION == reqRevision ) { if( MINORREVISION == reqMinorRevision ) { return true; } return MINORREVISION > reqMinorRevision; } return REVISION > reqVersion; } return VERSION > reqVersion; } public static boolean isOlderOrEqual( String version ) throws IllegalArgumentException { if( version == null ) return true; String[] versionComponents = StringUtils.split(version,VERSION_SEPARATORS); int reqVersion = versionComponents.length > 0 ? Integer.parseInt(versionComponents[0]) : Release.VERSION; int reqRevision = versionComponents.length > 1 ? Integer.parseInt(versionComponents[1]) : Release.REVISION; int reqMinorRevision = versionComponents.length > 2 ? Integer.parseInt(versionComponents[2]) : Release.MINORREVISION; if( VERSION == reqVersion ) { if( REVISION == reqRevision ) { if( MINORREVISION == reqMinorRevision ) { return true; } return MINORREVISION < reqMinorRevision; } return REVISION < reqVersion; } return VERSION < reqVersion; } /** * Executing this class directly from command line prints out * the current version. It is very useful for things like * different command line tools. * <P>Example: * <PRE> * % java com.ecyrd.jspwiki.Release * 1.9.26-cvs * </PRE> * * @param argv The argument string. This class takes in no arguments. */ public static void main( String[] argv ) { System.out.println(VERSTR); } }
package com.njackson; import android.app.Activity; import android.app.ActivityManager; import android.app.Dialog; import android.app.PendingIntent; import android.content.*; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.*; import com.actionbarsherlock.app.SherlockFragment; import com.getpebble.android.kit.PebbleKit; import com.getpebble.android.kit.util.PebbleDictionary; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesClient; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.location.ActivityRecognitionClient; import com.google.android.gms.location.DetectedActivity; import com.njackson.util.AltitudeGraphReduce; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; public class HomeActivity extends SherlockFragment { private static final String TAG = "PB-HomeActivity"; OnButtonPressListener _callback; // Container Activity must implement this interface public interface OnButtonPressListener { public void onPressed(int sender, boolean value); } private RelativeLayout _view; @Override public void onAttach(Activity activity){ super.onAttach(activity); try { _callback = (OnButtonPressListener)activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnButtonPressListener"); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState == null) { // During initial setup, plug in the details fragment. AltitudeFragment alt = new AltitudeFragment(); getFragmentManager().beginTransaction().add(R.id.MAIN_ALTITUDE, alt,"altitude_fragment").commit(); } else { AltitudeFragment alt = (AltitudeFragment)getFragmentManager().findFragmentByTag("altitude_fragment"); getFragmentManager().beginTransaction().replace(R.id.MAIN_ALTITUDE,alt).commit(); } } @Override public void onSaveInstanceState(Bundle instanceState) { TextView timeView = (TextView)_view.findViewById(R.id.MAIN_TIME_TEXT); instanceState.putString("Time", timeView.getText().toString()); TextView avgSpeedView = (TextView)_view.findViewById(R.id.MAIN_AVG_SPEED_TEXT); instanceState.putString("AvgSpeed",avgSpeedView.getText().toString()); TextView speedView = (TextView)_view.findViewById(R.id.MAIN_SPEED_TEXT); instanceState.putString("Speed",speedView.getText().toString()); TextView distanceView = (TextView)_view.findViewById(R.id.MAIN_DISTANCE_TEXT); instanceState.putString("Distance",distanceView.getText().toString()); ArrayList<Integer> graphData = AltitudeGraphReduce.getInstance().getCache(); instanceState.putIntegerArrayList("Altitude", graphData); Toast.makeText(getActivity(),"onSave",1); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment _view = (RelativeLayout)inflater.inflate(R.layout.home, container, false); if(savedInstanceState != null){ TextView timeView = (TextView)_view.findViewById(R.id.MAIN_TIME_TEXT); timeView.setText(savedInstanceState.getString("Time")); TextView avgSpeedView = (TextView)_view.findViewById(R.id.MAIN_AVG_SPEED_TEXT); avgSpeedView.setText(savedInstanceState.getString("AvgSpeed")); TextView speedView = (TextView)_view.findViewById(R.id.MAIN_SPEED_TEXT); speedView.setText(savedInstanceState.getString("Speed")); TextView distanceView = (TextView)_view.findViewById(R.id.MAIN_DISTANCE_TEXT); distanceView.setText(savedInstanceState.getString("Distance")); ArrayList<Integer> graphData = savedInstanceState.getIntegerArrayList("Altitude"); AltitudeGraphReduce.getInstance().setCache(graphData); setAltitude( AltitudeGraphReduce.getInstance().getGraphData(), AltitudeGraphReduce.getInstance().getMax(), AltitudeGraphReduce.getInstance().getMin() ); } final Button _startButton = (Button)_view.findViewById(R.id.MAIN_START_BUTTON); final ImageView _settingsButton = (ImageView)_view.findViewById(R.id.MAIN_SETTINGS_IMAGE); final Context context = this.getActivity(); _settingsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { context.startActivity(new Intent(context,SettingsActivity.class)); } }); _startButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { _callback.onPressed(R.id.MAIN_START_BUTTON,_startButton.getText().equals("Start")); if(_startButton.getText().equals("Start")) { setStartButtonText("Stop"); } else { setStartButtonText("Start"); } } }); // if we are using activity recognition hide the start button setStartButtonVisibility(!MainActivity.getInstance().activityRecognitionEnabled()); if(MainActivity.getInstance().checkServiceRunning()) setStartButtonText(getString(R.string.START_BUTTON_STOP)); else setStartButtonText(getString(R.string.START_BUTTON_START)); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext()); int units = Integer.valueOf(prefs.getString("UNITS_OF_MEASURE", "0")); setUnits(units); Toast.makeText(getActivity(),"onCreateView",1); return _view; } public void setStartButtonVisibility(Boolean shown) { if (_view == null) { Log.e(TAG, "setStartButtonVisibility: _view == null : exit"); // BUG! This could happen if the system is low on memory and choose to kill the app. // All views are not correctly reconstructed when the app restarts, causing the present bug // Waiting for a fix for this bug. In the meantime, force the app to close to avoid the "NullPointerException" crash // Note: when GPS is running, it is not likely to happen: it runs in a foreground service with a sticky notification for the user System.exit(0); } Button startButton = (Button)_view.findViewById(R.id.MAIN_START_BUTTON); if(shown) startButton.setVisibility(View.VISIBLE); else startButton.setVisibility(View.GONE); } public void setActivityText(String activity) { //TextView textView = (TextView)_view.findViewById(R.id.MAIN_ACTIVITY_TYPE); //textView.setText("Activity: " + activity); } public void setStartButtonText(String text) { Button button = (Button)_view.findViewById(R.id.MAIN_START_BUTTON); button.setText(text); if (text.equals("Start")) { button.setBackgroundColor(getResources().getColor(R.color.START_START)); } else { button.setBackgroundColor(getResources().getColor(R.color.START_STOP)); } } public void setSpeed(String text) { TextView textView = (TextView)_view.findViewById(R.id.MAIN_SPEED_TEXT); textView.setText(text); } public void setAvgSpeed(String text) { TextView textView = (TextView)_view.findViewById(R.id.MAIN_AVG_SPEED_TEXT); textView.setText(text); } public void setDistance(String text) { TextView textView = (TextView)_view.findViewById(R.id.MAIN_DISTANCE_TEXT); textView.setText(text); } public void setTime(String text) { TextView textView = (TextView)_view.findViewById(R.id.MAIN_TIME_TEXT); textView.setText(text); } public void setAltitude(int[] altitude, int maxAltitude, int minAltitude) { AltitudeFragment altitudeFragment = (AltitudeFragment)getFragmentManager().findFragmentByTag("altitude_fragment"); altitudeFragment.setAltitude(altitude,maxAltitude,true); } // Sets the display units based upon user preference public void setUnits(int units) { TextView avgSpeedView = (TextView)_view.findViewById(R.id.MAIN_AVG_SPEED_LABEL); if(units == Constants.IMPERIAL) { avgSpeedView.setText(R.string.AVG_SPEED_TEXT_IMPERIAL); } else { avgSpeedView.setText(R.string.AVG_SPEED_TEXT_METRIC); } } }
package com.rapid.actions; import org.json.JSONObject; import com.rapid.core.Action; import com.rapid.core.Application; import com.rapid.core.Page; import com.rapid.server.RapidHttpServlet; import com.rapid.server.RapidRequest; /* This action runs JQuery against a specified control. Can be entered with or without the leading "." Such as hide(), or .css("disabled","disabled"); */ public class Control extends Action { // parameterless constructor (required for jaxb) public Control() { super(); } // designer constructor public Control(RapidHttpServlet rapidServlet, JSONObject jsonAction) throws Exception { super(rapidServlet, jsonAction); } // methods @Override public String getJavaScript(RapidRequest rapidRequest, Application application, Page page, com.rapid.core.Control control, JSONObject jsonDetails) { // get the control Id and command String controlId = getProperty("control"); // get the action type String actionType = getProperty("actionType"); // prepare the js String js = ""; // if we have a control id if (controlId != null && !"".equals(controlId)) { // update the js to use the control js = "$(\"#" + getProperty("control") + "\")."; // check the type if ("custom".equals(actionType) || actionType == null) { // get the command String command = getProperty("command"); // check command if (command != null) { // trim command = command.trim(); // check length and whether only comments if (command.length() == 0 || ((command.startsWith("//") || (command.startsWith("/*") && command.endsWith("*/"))) && command.indexOf("\n") == -1)) { // set to null, if empty or only comments command = null; } else { // command can be cleaned up - remove starting dot (we've already got it above) if (command.startsWith(".")) command = command.substring(1); // add brackets if there aren't any at the end if (!command.endsWith(")") && !command.endsWith(");")) command += "();"; // add a semi colon if there isn't one on the end if (!command.endsWith(";")) command += ";"; } } // check for null / empty if (command == null) { // show that there's no command js = "/* no command for custom control action " + getId() + " */"; } else { // add the command js += command; } } else if ("focus".equals(actionType)) { js += actionType + "('rapid');"; } else if ("slideUp".equals(actionType) || "slideDown".equals(actionType) || "slideToggle".equals(actionType)) { js += actionType + "(" + getProperty("duration") + ");"; } else if ("fadeOut".equals(actionType) || "fadeIn".equals(actionType) || "fadeToggle".equals(actionType)) { js += actionType + "(" + getProperty("duration") + ");"; } else if ("enable".equals(actionType)) { js += "enable();"; } else if ("disable".equals(actionType)) { js += "disable();"; } else if ("addClass".equals(actionType)) { js += "addClass('" + getProperty("styleClass") + "');"; } else if ("removeClass".equals(actionType)) { js += "removeClass('" + getProperty("styleClass") + "');"; } else if ("toggleClass".equals(actionType)) { js += "toggleClass('" + getProperty("styleClass") + "');"; } else if ("removeChildClasses".equals(actionType)) { String styleClass = getProperty("styleClass"); js += "find('." + styleClass + "').removeClass('" + styleClass + "');"; } else if ("showError".equals(actionType)) { js += "showError(server, status, message);"; } else if ("scrollTo".equals(actionType)) { // check if page if (page.getId().equals(controlId)) { // scroll to top of page js = "$('html, body').scrollTop(0);"; } else { // scroll to control y position, if present js = "if (js.length) $('html, body').scrollTop(" + js + "offset().top);"; } } else if ("hideDialogue".equals(actionType)) { js += "hideDialogue(false,'" + controlId + "');"; } else { // just call the action type (hide/show/toggle) js += actionType + "();"; } // add a line break; js += "\n"; // if the stopPropagation is checked if (Boolean.parseBoolean(getProperty("stopPropagation"))) { js += "ev.stopImmediatePropagation();"; } } else { js = "/* no control specified for control action " + getId() + " */"; } // return the js return js; } }
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.Properties; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; public class Database { /** The name of the MySQL account to use (or empty for anonymous) */ private final String userName = "root"; /** The password for the MySQL account (or empty for anonymous) */ private final String password = "root"; /** The name of the computer running MySQL */ private final String serverName = "localhost"; /** The port of the MySQL server (default is 3306) */ private final int portNumber = 3306; /** * The name of the database we are testing with (this default is installed * with MySQL) */ private final String dbName = "test"; /** The name of the table we are testing with */ private String tableName = "JDBC_TEST"; /** The name of the Connection **/ private Connection conn = null; /** * Get a new database connection * * @return * @throws SQLException */ public boolean getConnection() throws SQLException { Properties connectionProps = new Properties(); connectionProps.put("user", this.userName); connectionProps.put("password", this.password); conn = DriverManager.getConnection("jdbc:mysql://" + this.serverName + ":" + this.portNumber + "/" + this.dbName, connectionProps); return true; } /** * Run a SQL command which does not return a recordset: * CREATE/INSERT/UPDATE/DELETE/DROP/etc. * * @throws SQLException * If something goes wrong */ public boolean executeUpdate(Connection conn, String command) throws SQLException { Statement stmt = null; try { stmt = conn.createStatement(); stmt.executeUpdate(command); // This will throw a SQLException if it // fails return true; } finally { // This will run whether we throw an exception or not if (stmt != null) { stmt.close(); } } } public boolean createTable(String newTableName) { tableName = newTableName; try { String createString = "CREATE TABLE " + this.tableName + " ( " + "ID INT NOT NULL AUTO_INCREMENT, " + "NAME varchar(40) NOT NULL, " + "EMAIL varchar(100) NOT NULL, " + "PASSWORD varchar(100) NOT NULL," + "PRIMARY KEY (ID))"; this.executeUpdate(conn, createString); System.out.println("Created a table"); return true; } catch (SQLException e) { System.out.println("ERROR: Could not create the table"); e.printStackTrace(); return false; } } public boolean deleteTable(String newTableName) throws SQLException { tableName = newTableName; try { String dropString = "DROP TABLE " + this.tableName; this.executeUpdate(conn, dropString); System.out.println("Dropped the table"); return true; } catch (SQLException e) { System.out.println("ERROR: Could not drop the table"); e.printStackTrace(); return false; } } /* * Create form in Database * * INSERT INTO `test`.`Forms` (`Patient`, `Doctor`, `Priority`, `Comments`, `Nausea`, `Pain`, `Fatigue`, `Anxiety`, `ShortnessOfBreath`) * VALUES ('a', 's', '4', 'd', '1', '3', '3', '3', '3'); */ public void createForm(Form f1) throws SQLException { // TODO Auto-generated method stub this.tableName = "Forms"; String createForm = "INSERT INTO " + this.dbName + " . " + this.tableName + " (`Patient`, `Priority`, `Comments`, `Nausea`, `Pain`, `Fatigue`, `Anxiety`, `ShortnessOfBreath`, `Status`) " + "VALUES ('" + f1.getPatient() + "', '" + f1.getPriority() + "', '" + f1.getComments() + "', '" + f1.getPain() + "', '" + f1.getPain() + "', '" + f1.getFatigue() + "', '" + f1.getAnxiety() + "', '" +f1.getShortnessOfBreath() + "', '" + f1.getStatus() + "');"; System.out.println(createForm); this.executeUpdate(conn, createForm); } /* * Update form with diagnose and doctor * UPDATE `test`.`Forms` SET `Doctor`='Anybody', `Diagnose`='I sent a prescibtion to the pharmacy' WHERE `idForms`='5'; */ public void updateForm(Form f1) throws SQLException{ this.tableName = "Forms"; String updateString = "UPDATE " + this.dbName + " . " + this.tableName + "SET `Doctor`='" + f1.getDoctor() + "', `Diagnose`='"+ f1.getDiagnosis() + "', `Status`='" + f1.getStatus() + "' WHERE `idForms`='" + f1.getId() + "';"; this.executeUpdate(conn, updateString); } public List<Form> retrieveListofForms(Person user, String status) throws SQLException{ String retrieveString; if(user instanceof Doctor){ if(status.equals("Completed")){ retrieveString = "SELECT * FROM test . Forms WHERE Doctor = '" + user.getName() + "' AND Status = '" + status + "';"; System.out.println(retrieveString); }else{ retrieveString = "SELECT * FROM test . Forms WHERE Priority > '" + ((Doctor) user).getThreshold() + "' AND Status = '" + status + "';"; System.out.println(retrieveString); } }else{ retrieveString = "SELECT * FROM test . Forms WHERE Patient = '" + user.getName() + "' AND Status = '" + status + "';"; System.out.println(retrieveString); } Statement st = conn.createStatement(); ResultSet rs = st.executeQuery(retrieveString); List<Form> l1 = new ArrayList<Form>(); while(rs.next()){ //(int newid, int i, int j, int k, int l,int m, String comments, String diagnosis, String status, String patient, String doctor) Form F = new Form(rs.getInt("idForms"), rs.getInt("Nausea"), rs.getInt("Pain"), rs.getInt("Fatigue"), rs.getInt("Anxiety"), rs.getInt("ShortnessOfBreath"), rs.getString("Comments"), rs.getString("Diagnose"), rs.getString("Status"), rs.getString("Patient"), rs.getString("Doctor")); l1.add(F); } return l1; } public Form retrieveNextPatient(Person user) throws SQLException { String retrieveString = "SELECT * FROM test . Forms WHERE Priority > '" + ((Doctor) user).getThreshold() + "' AND Status = 'Pending';"; System.out.println(retrieveString); Statement st = conn.createStatement(); ResultSet rs = st.executeQuery(retrieveString); if(rs.next()){ //(int newid, int i, int j, int k, int l,int m, String comments, String diagnosis, String status, String patient, String doctor) Form F = new Form(rs.getInt("idForms"), rs.getInt("Nausea"), rs.getInt("Pain"), rs.getInt("Fatigue"), rs.getInt("Anxiety"), rs.getInt("ShortnessOfBreath"), rs.getString("Comments"), rs.getString("Diagnose"), rs.getString("Status"), rs.getString("Patient"), rs.getString("Doctor")); System.out.println(F.toString()); return F; }else{ return null; } } public Form retrieveForm(int id){ return null; } /* * INSERT INTO `test`.`Patients` (`NAME`, `EMAIL`, `PASSWORD`) VALUES * ('Hey', 'dsds', 'dsds'); */ public void insertData(String newName, String newEmail, String newPassword) throws SQLException { this.tableName = "Patients"; String inputString = "INSERT INTO " + this.dbName + " . " + this.tableName + " (`NAME`, `EMAIL`, `PASSWORD`) " + " VALUES ('" + newName + "', '" + newEmail + "', '" + newPassword + "');"; System.out.println(inputString); this.executeUpdate(conn, inputString); } /* * Update Database with person *UPDATE `test`.`Patients` SET `NAME`='Ddav', `EMAIL`='da' WHERE `ID`='1'; *UPDATE 'test'.'Doctors' SET `NAME`='Ddav', `EMAIL`='da', 'Threshold'='3' WHERE `ID`='1' */ public void updatePerson(Person user) throws SQLException{ String updateString; if(user instanceof Patient){ this.tableName = "Patients"; updateString = "UPDATE " + this.dbName + " . " + this.tableName + "SET `NAME`='" + user.getName() + "', `PASSWORD`='" + user.getPassword() + "' WHERE `ID`='" + user.getId() + "';"; }else{ this.tableName = "Doctors"; Doctor temp = (Doctor) user; updateString = "UPDATE " + this.dbName + " . " + this.tableName + " SET `NAME`='" + temp.getName() + "', `PASSWORD`='" + temp.getPassword() + "', `Threshold`='"+ temp.getThreshold() + "' WHERE `ID`='" + user.getId() + "';"; } System.out.println(updateString); this.executeUpdate(conn, updateString); } /* * Retrieves Passward and other data */ public Person retrievePerson(String newTableName, String username, String password) throws SQLException, AddressException { String retrieveString = "SELECT * FROM test . " + newTableName + " WHERE email = '" + username + "' AND password = '" + password + "';"; System.out.println(retrieveString); Statement st = conn.createStatement(); ResultSet rs = st.executeQuery(retrieveString); if (rs.next()) { //UUID id = UUID.fromString(rs.getString("ID")); // Possible data fields int id; String name; InternetAddress email; if(newTableName.equals("Doctors")){ id = rs.getInt("ID"); name = rs.getString("NAME"); email = new InternetAddress(rs.getString("EMAIL")); int threshold = rs.getInt("Threshold"); Person temp = new Doctor(name, id, email, password, threshold); return temp; }else{ id = rs.getInt("ID"); name = rs.getString("NAME"); email = new InternetAddress(rs.getString("EMAIL")); Person temp = new Person(name, id, email, password); return temp; } }else { return null; } } public Person searchEmail(String email) throws SQLException{ String str = "SELECT * FROM test . Patients WHERE email = '" + email + "';"; System.out.println(str); Statement st = conn.createStatement(); ResultSet rs = st.executeQuery(str); if(rs.next()){ int id = rs.getInt("ID"); String name = rs.getString("NAME"); String pw = rs.getString("PASSWORD"); InternetAddress e = null; try { e = new InternetAddress(email); } catch (AddressException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } Person temp = new Person(name, id, e, pw); return temp; }else{ System.out.println("Not in Patients table"); String str2 = "SELECT * FROM test . Doctors WHERE email = '" + email + "';"; System.out.println(str2); Statement st2 = conn.createStatement(); ResultSet rs2 = st2.executeQuery(str2); if(rs2.next()){ int id = rs2.getInt("ID"); String name = rs2.getString("NAME"); int threshold = rs2.getInt("Threshold"); String pw = rs2.getString("PASSWORD"); InternetAddress e = null; try { e = new InternetAddress(email); } catch (AddressException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } Person temp = new Doctor(name, id, e, pw, threshold); return temp; }else{ return null; } } } }
package pt.promatik.moss.utils; import java.util.Calendar; import java.util.Date; import java.util.Timer; import java.util.TimerTask; public class Delegate { private Timer timer = null; private long startTime, cancelTime = 0; public Delegate(Runnable runnable, int delay) { this(runnable, delay, 0); } public Delegate(Runnable runnable, Date delay) { this(runnable, delay, 0); } public Delegate(Runnable runnable, Calendar delay) { this(runnable, delay.getTime(), 0); } public Delegate(Runnable runnable, int delay, int period) { _delegate(runnable, delay, null, period); } public Delegate(Runnable runnable, Date delay, int period) { _delegate(runnable, 0, delay, period); } public Delegate(Runnable runnable, Calendar delay, int period) { _delegate(runnable, 0, delay.getTime(), period); } private void _delegate(Runnable runnable, int delayInt, Date delayDate, int period) { timer = null; try { timer = new Timer(); TimerTask t = new TimerTask() { @Override public void run() { try { runnable.run(); } catch (Exception e) { Utils.log("Delegate run exception", e); } } }; // Save start time startTime = System.nanoTime(); if(period > 0) { if(delayDate != null) timer.schedule(t, delayDate, period); else timer.schedule(t, delayInt, period); } else { if(delayDate != null) timer.schedule(t, delayDate); else timer.schedule(t, delayInt); } } catch (Exception e) { Utils.log("Delegate timer run exception", e); } } public void cancel() { timer.cancel(); cancelTime = System.nanoTime(); } public int elapsedTime() { return Math.round(((cancelTime == 0 ? System.nanoTime() : cancelTime) - startTime) / 1000000f); } public static Delegate run(Runnable runnable, int delay) { return new Delegate(runnable, delay); } public static Delegate run(Runnable runnable, int delay, int period) { return new Delegate(runnable, delay, period); } public static Delegate run(Runnable runnable, Date time) { return new Delegate(runnable, time); } public static Delegate run(Runnable runnable, Date time, int period) { return new Delegate(runnable, time, period); } public static Delegate run(Runnable runnable, Calendar time) { return new Delegate(runnable, time.getTime()); } public static Delegate run(Runnable runnable, Calendar time, int period) { return new Delegate(runnable, time.getTime(), period); } }
/** * ComplexMath.java * A set of basic functions provided for operations on Complex objects * * @author William Woodruff <woodrufw @ bxscience.edu> * @version 0.9 * @since 2013-3-15 */ public class ComplexMath { /** * Finds the conjugate of the given Complex. * * The conjugate of any Complex represented as "a + bi" is given as "a - bi". * * @param c the Complex whose conjugate is to be found. * @return a new Complex whose value is the conjugate of c */ public static Complex conjugate(Complex c) { return new Complex(c.getReal(), -c.getImag()); } /** * Finds the reciprocal of the given Complex. * * The reciprocal of any Complex represented as "a + bi" is given as "1 / (a + bi)". * * @param c the Complex whose reciprocal is to be found. * @return a new Complex whose value is the reciprocal of c */ public static Complex reciprocal(Complex c) { double scale = (c.getReal() * c.getReal()) + (c.getImag() * c.getImag()); double re = c.getReal() / scale; double im = c.getImag() / scale; return new Complex(re, im); } /** * Finds the sum of the given Complexes. * * The sum of any two Complexes "a + bi" and "x + yi" will always be equal to * "(a+x) + (b+y)i". * * @param c1 the first Complex * @param c2 the second Complex * @return a new Complex whose value is the sum of c1 and c2 */ public static Complex add(Complex c1, Complex c2) { double re = c1.getReal() + c2.getReal(); double im = c1.getImag() + c2.getImag(); return new Complex(re, im); } /** * Finds the sum of the given Complex and a non-complex number. * * The sum of any Complex ("a + bi") and any non-complex number ("x") will always * be equal to "(a+x) + bi" * * @param c the Complex * @param num the non-complex number * @return a new Complex whose value is the sum of c and num */ public static Complex add(Complex c, double num) { return new Complex(c.getReal() + num, c.getImag()); } /** * Finds the difference between two Complexes * * The difference between any two Complexes will be the differences between * their real and imaginary parts. * * @param c the Complex * @param num the non-complex number * @return a new Complex whose value is the sum of c and num */ public static Complex subtract(Complex c1, Complex c2) { double re = c1.getReal() - c2.getReal(); double im = c1.getImag() - c2.getImag(); return new Complex(re, im); } /** * Finds the difference between the given Complex and a non-complex number. * * The difference between any Complex and a non-complex number will always be * the Complex's real value minus the number, with the imaginary value unchanged. * * @param c the Complex * @param num the non-complex number * @return a new Complex whose value is the difference between c and num */ public static Complex subtract(Complex c, double num) { return new Complex(c.getReal() - num, c.getImag()); } /** * Finds the product of two Complexes. * * If a Complex is multiplied by it's conjugate Complex, the resulting value will * ALWAYS be real, with no imaginary part. * Otherwise, the resulting product will likely contain an imaginary part. * * @param c1 the first Complex * @param c2 the second Complex * @return a new Complex whose value is the product of c1 and c2 */ public static Complex multiply(Complex c1, Complex c2) { double re = c1.getReal() * c2.getReal() - c1.getImag() * c2.getImag(); double im = c1.getReal() * c2.getImag() + c1.getImag() * c2.getReal(); return new Complex(re, im); } /** * Finds the product of a Complex and a non-complex number. * * The product of a Complex and a non-complex number will always be the non-complex * number distributed across the Complex's real and imaginary parts. * * @param c the Complex * @param num the non-complex number * @return a new Complex whose value is the product of c and num */ public static Complex multiply(Complex c, double num) { return new Complex(c.getReal() * num, c.getImag() * num); } /** * Finds the quotient of two Complexes. * * The quotient of two Complexes is always equal to the following: * The multiplication of the first Complex and the conjugate of the second Complex, * all divided by the the multiplication of the second Complex and it's conjugate. * * @param c1 the first Complex and the numerator * @param c2 the second Complex and the denominator * @return a new Complex whose value is the quotient of c1 over c2 */ public static Complex divide(Complex c1, Complex c2) { Complex conj = ComplexMath.conjugate(c2); Complex numerator = ComplexMath.multiply(c1, conj); double denominator = ComplexMath.multiply(c2, conj).toDouble(); return ComplexMath.divide(numerator, denominator); } /** * Finds the quotient of a Complex and a non-complex number. * * The quotient of a Complex and a non-complex number will always be the non-complex * number distributed across the Complex's real and imaginary parts. * * @param c the Complex * @param num the non-complex number * @return a new Complex whose value is the quotient of c over num */ public static Complex divide(Complex c, double num) { return new Complex(c.getReal() / num, c.getImag() / num); } /** * Finds the result of a Complex raised to a certain number * * @param c the Complex * @param raise the value that the Complex is raised to * @return a new Complex whose value is c to the power of raise */ public static Complex pow(Complex c, int raise) { Complex ret = new Complex(c.getReal(), c.getImag()); Complex orig = new Complex(c.getReal(), c.getImag()); if (raise == 1) ret = new Complex(c.getReal(), c.getImag()); else if (raise == 0) ret = new Complex(1, 0); else { for (int i = 1; i < Math.abs(raise); i++) ret = ComplexMath.multiply(orig, ret); } if (raise < 0) ret = ComplexMath.divide(ComplexMath.reciprocal(ret), 1); return ret; } /** * Finds the magnitude of a Complex number. * * The magnitude (also known as the hypotenuse, rho, Z, etc) of any complex number * is equal to the square root of the sum of the squares of the Complex's * real and imaginary parts. * * @param c the Complex * @return a double whose value is the magnitude (hypotenuse) of c */ public static double mag(Complex c) { return Math.hypot(c.getReal(), c.getImag()); } /** * Finds the sine of a Complex number. * * @param c the Complex * @return a Complex whose value is the sine of c */ public static Complex sin(Complex c) { double re = Math.sin(c.getReal()) * Math.cosh(c.getImag()); double im = Math.cos(c.getReal()) * Math.sinh(c.getImag()); return new Complex(re, im); } /** * Finds the hyperbolic sine of a Complex number. * * @param c the Complex * @return a Complex whose value is the hyperbolic sine of c */ public static Complex sinh(Complex c) { double re = Math.cos(c.getImag()) * Math.sinh(c.getReal()); double im = Math.sin(c.getImag()) * Math.cosh(c.getReal()); return new Complex(re, im); } /** * Finds the cosine of a Complex number. * * @param c the Complex * @return a Complex whose value is the cosine of c */ public static Complex cos(Complex c) { double re = Math.cos(c.getReal()) * Math.cosh(c.getImag()); double im = Math.sin(c.getReal()) * Math.sinh(c.getImag()); return new Complex(re, im); } /** * Finds the hyperbolic cosine of a Complex number. * * @param c the Complex * @return a Complex whose value is the hyperbolic cosine of c */ public static Complex cosh(Complex c) { double re = Math.cos(c.getImag()) * Math.cosh(c.getReal()); double im = Math.sin(c.getImag()) * Math.sinh(c.getReal()); return new Complex(re, im); } /** * Finds the tangent of a Complex number. * * @param c the Complex * @return a Complex whose value is the tangent of c */ public static Complex tan(Complex c) { return ComplexMath.divide(ComplexMath.sin(c), ComplexMath.cos(c)); } /** * Finds the hyperbolic tangent of a Complex number. * * @param c the Complex * @return a Complex whose value is the hyperbolic tangent of c */ public static Complex tanh(Complex c) { return ComplexMath.divide(ComplexMath.sinh(c), ComplexMath.cosh(c)); } }
package Engine; import java.util.ArrayList; public class Shoe { private ArrayList<Card> deck; private int numberOfDecks; public Shoe(int numberOfDecks) { this.numberOfDecks = numberOfDecks; initDeck(); } public int getNumberOfDecks() { return numberOfDecks; } public void shuffle() { initDeck(); long seed = System.nanoTime(); deck = Collections.shuffle(deck, new Random(seed)); } private void initDeck() { deck = new ArrayList<Card>(); for (int j = 0; j < numberOfDecks * 4; j++) for (int i = 1; i < 14; i++) { if (i == 1) deck.add(new Card("A")); else if (i == 11) deck.add(new Card("J")); else if (i == 12) deck.add(new Card("Q")); else if (i == 13) deck.add(new Card("K")); else deck.add(new Card(Integer.toString(i))); } } public ArrayList<Card> getHand(int size) { ArrayList<Card> hand = new ArrayList<Card>(); for (int i = 0; i < size; i++) hand.add(deck.remove((int) (Math.random() * deck.size()))); return hand; } public String toString() { String toReturn = ""; for (Card card : deck) toReturn += card.toString() + ","; return toReturn; } public Card removeTopCard() { if (deck.size() == 1) shuffle(); return deck.remove(deck.size() - 1); } }
package year2014; import java.util.Scanner; public class DigitalRoot { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter a non-negative integer number: "); final int input = Math.abs(scanner.nextInt()); scanner.close(); int digitalRoot = input; while (digitalRoot > 9) digitalRoot = sumIndividualDigits(digitalRoot); System.out.println("The digital root of " + input + " is " + digitalRoot); } private static int sumIndividualDigits(int input) { if (input < 0) throw new IllegalArgumentException("Input must be positive"); int sum = 0; while (input > 0) { sum += input % 10; input /= 10; } return sum; //String approach method /*char[] chars = String.valueOf(input).toCharArray(); return IntStream.range(0, chars.length) .map(i -> Character.getNumericValue(chars[i])).sum();*/ } }
package com.innovattic.font; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.Resources.Theme; import android.content.res.TypedArray; import android.content.res.XmlResourceParser; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.Typeface; import android.util.AttributeSet; import android.util.Log; import android.view.InflateException; import android.widget.TextView; public class TypefaceManager { private static final String TAG = TypefaceManager.class.getSimpleName(); private static TypefaceManager INSTANCE; // Different tags used in XML file. private static final String TAG_FAMILY = "family"; private static final String TAG_NAMESET = "nameset"; private static final String TAG_NAME = "name"; private static final String TAG_FILESET = "fileset"; private static final String TAG_FILE = "file"; private static final byte INVALID = -1; private static final byte NONE = 0; private static final byte REGULAR = 1; private static final byte BOLD = 2; private static final byte ITALIC = 4; private static final byte BOLD_ITALIC = 8; /** The style map, used to map a missing style to another style. */ private static final Map<Byte, List<Byte>> styleMap; /** The Typeface cache, keyed by their asset file name. */ private static final Map<String, Typeface> mCache = new HashMap<String, Typeface>(); private final Context mContext; /** The xml file in which the fonts are defined. */ private final int mXmlResource; /** The mapping of font names to Font objects as defined in the xml file. */ private final Map<String, Font> mFonts; static { // Initialize the style map // The style map is used to determine which font style must be used if // the requested style is not available. styleMap = new HashMap<Byte, List<Byte>>(); styleMap.put(REGULAR, Arrays.asList(BOLD, ITALIC, BOLD_ITALIC)); styleMap.put(BOLD, Arrays.asList(REGULAR, BOLD_ITALIC, ITALIC)); styleMap.put(ITALIC, Arrays.asList(REGULAR, BOLD_ITALIC, BOLD)); styleMap.put(BOLD_ITALIC, Arrays.asList(BOLD, ITALIC, REGULAR)); } private static class Font { public List<String> names = new ArrayList<String>(); public Map<Byte, String> styles = new HashMap<Byte, String>(); } /** * Initializes the singleton instance of the TypefaceManager. It will read * the given xml font file pointed to by xmlResource, but doesn't yet load * the fonts. */ public static synchronized void initialize(Context context, int xmlResource) { if (INSTANCE == null) INSTANCE = new TypefaceManager(context, xmlResource); if (INSTANCE.mXmlResource != xmlResource) Log.w(TAG, "Singleton instance of TypefaceManager was initialized" + " with a different xml font file previously. " + "Re-initialization will not occur."); if (!INSTANCE.mContext.equals(context)) Log.w(TAG, "Singleton instance of TypefaceManager was initialized" + " with a different context previously. Re-initialization will" + " not occur."); } /** * Returns the singleton instance of the TypefaceManager. It will throw an * exception if it is called before {@link #initialize(Context, int) * initialization}. * * @return The TypefaceManager */ public static TypefaceManager getInstance() { if (INSTANCE == null) throw new IllegalStateException("Cannot use " + "TypefaceManager.getInstance() before it is initialized. Use " + "TypefaceManager.initialize(Context, int) to initialize the " + "TypefaceManager."); return INSTANCE; } /** * Initializes the typeface manager with the given xml font file. * * @param context A context with which the xml font file and the assets can * be accessed. * @param xmlResource The resource id of an xml file that specifies the * fonts that are present in the assets. * @return The number of unique font files in the xml file that exist. The * font files are not yet opened or verified, it only means that * they exist. */ private TypefaceManager(Context context, int xmlResource) { mFonts = new HashMap<String, Font>(); this.mXmlResource = xmlResource; mContext = context; parse(); } /** * Returns the typeface identified by the given font name and style. The * font must be a name defined in any nameset in the font xml file. The * style must be one of the constants defined by {@link Typeface}. * * @param name * @return */ public Typeface getTypeface(String name) { return getTypeface(name, Typeface.NORMAL); } /** * Returns the typeface identified by the given font name and style. The * font must be a name defined in any nameset in the font xml file. The * style must be one of the constants defined by {@link Typeface}. * * @param name * @param style * @return */ public Typeface getTypeface(String name, int style) { Font font = mFonts.get(name.toLowerCase()); String file = font.styles.get(toInternalStyle(style)); synchronized (mCache) { if (!mCache.containsKey(file)) { Log.i(TAG, String.format("Inflating font %s (style %d) with " + "file %s", name, style, file)); Typeface t = Typeface.createFromAsset(mContext.getAssets(), String.format("fonts/%s", file)); mCache.put(file, t); } } return mCache.get(font.styles.get(toInternalStyle(style))); } /** * Convenience method to set the typeface of the target view to the font * identified by fontName. The text style that will be used is {@code * Typeface#NORMAL}. Returns false if the font wasn't found or couldn't be * loaded, returns true otherwise. * * @param target A TextView in which the font must be used. * @param fontName The name of the font. Must match a name defined in a name * tag in the xml font file. * @return {@code true} if the font could was set in the target, {@code * false} otherwise. */ public boolean setTypeface(TextView target, String fontName) { return setTypeface(target, fontName, Typeface.NORMAL); } /** * Convenience method to set the typeface of the target view to the font * identified by fontName using the textStyle. The textStyle must be one of * the constants defined by {@code Typeface}. Returns false if the font * wasn't found or couldn't be loaded, returns true otherwise. * * @param target A TextView in which the font must be used. * @param fontName The name of the font. Must match a name defined in a name * tag in the xml font file. * @param textStyle A text style: normal, bold, italic or bold_italic. * @return {@code true} if the font could was set in the target, {@code * false} otherwise. */ public boolean setTypeface(TextView target, String fontName, int textStyle) { Typeface tf = null; try { tf = getTypeface(fontName, textStyle); } catch (Exception e) { Log.e(TAG, "Could not get typeface "+fontName); return false; } target.setTypeface(tf); return true; } /** * Parses the xml font file. After this method, {@link #mFonts} will contain * all fonts encountered in the xml font file for which at least one of the * defined font file(s) exist. */ private void parse() { XmlResourceParser parser = null; try { String[] fontAssets = getAvailableFontfiles(); parser = mContext.getResources().getXml(mXmlResource); String tag; Font font = null; byte style = INVALID; boolean isName = false; boolean isFile = false; int eventType = parser.getEventType(); do { tag = parser.getName(); switch (eventType) { case XmlPullParser.START_TAG: // One of the font-families. if (tag.equals(TAG_FAMILY)) font = new Font(); else if (tag.equals(TAG_NAMESET)) ; // nothing to do for namesets else if (tag.equals(TAG_FILESET)) style = NONE; // A name that maps to this font-family. else if (tag.equals(TAG_NAME)) isName = true; // A font file to be used for this font-family. else if (tag.equals(TAG_FILE)) isFile = true; break; case XmlPullParser.END_TAG: if (tag.equals(TAG_FAMILY)) { // Family is fully defined, process it. // Add all missing style mappings addMissingStyles(font); // Add all the font names to the lookup tbl, // but only if any font files were defined. if (!font.styles.isEmpty()) for (String name : font.names) // Don't override fonts (as defined by the if (!mFonts.containsKey(name)) mFonts.put(name, font); // And reset the font for the next family font = null; } // Done reading a name for this family. else if (tag.equals(TAG_NAME)) isName = false; // Done reading a font file for this family. else if (tag.equals(TAG_FILE)) isFile = false; else if (tag.equals(TAG_FILESET)) style = INVALID; break; case XmlPullParser.TEXT: String text = parser.getText(); if (isName) { // Value is a font name font.names.add(text.toLowerCase()); } else if (isFile) { // Value is a font file String ttf = text; // Determine which style file this is style = next(style); // Check if the file exists if (Arrays.binarySearch(fontAssets, ttf) < 0) Log.w(TAG, "Couldn't find font in the assets: "+ ttf); // Add the style else font.styles.put(style, ttf); } } eventType = parser.next(); } while (eventType != XmlPullParser.END_DOCUMENT); } catch (XmlPullParserException e) { throw new InflateException("Error inflating font XML", e); } catch (IOException e) { throw new InflateException("Error inflating font XML", e); } finally { if (parser != null) parser.close(); } } private static byte next(byte style) { switch (style) { case NONE: return REGULAR; case REGULAR: return BOLD; case BOLD: return ITALIC; case ITALIC: return BOLD_ITALIC; default: return INVALID; } } /** * Converts a style constant from {@link Typeface} to a style constant from * the {@link TypefaceManager}. * * @param typefaceStyle * @return */ private static byte toInternalStyle(int typefaceStyle) { switch (typefaceStyle) { case Typeface.NORMAL: return REGULAR; case Typeface.BOLD: return BOLD; case Typeface.ITALIC: return ITALIC; case Typeface.BOLD_ITALIC: return BOLD_ITALIC; default: return INVALID; } } /** * Adds style mappings for all styles that are not loaded in the given font. * A font may be defined without all four styles regular, bold, italic and * bold-italic. In that case, the missing styles will be mapped to the most * preferred style that is present. * * @param font */ private static void addMissingStyles(Font font) { byte availableStyles = 0; Map<Byte, String> styles = font.styles; for (byte style : styles.keySet()) availableStyles |= style; for (byte style : styleMap.keySet()) if (isMissing(style, availableStyles)) for (byte replacement : styleMap.get(style)) if (!isMissing(replacement, availableStyles)) { styles.put(style, styles.get(replacement)); break; } } /** * Returns a list of all file names in the asset folder "fonts". * * @return */ private String[] getAvailableFontfiles() { try { String[] fontAssets = mContext.getAssets().list("fonts"); Arrays.sort(fontAssets); return fontAssets; } catch (IOException e) { Log.e(TAG, "Couldn't access assets; fonts are not available"); return new String[0]; } } /** * Returns if all set bits in the needle are not set in the haystack. In * other words, if the haystack is missing all the bits from the needle, * this returns {@code true}. * * @param needle All bits set to 1 in this byte will be checked. * @param haystack The bits in this byte will be checked. * @return {@code true} iff all bits that need to be checked in the * haystack are 0. */ private static boolean isMissing(byte needle, byte haystack) { return (haystack&needle) == 0; } /** * Applies the font and all related custom properties found in the * attributes of the given AttributeSet or the default style to the given * target. Typically, the AttributeSet consists of the attributes contained * in the xml tag that defined the target. The target can be any TextView or * subclass thereof. The read properties will be stored in an {@link * ExtraFontData} instance stored as a tag with id {@link * R.id#fonts_extra_data} in the target view. If an instance was already set * as a tag in the target view, it will be reused. All encountered * properties are overridden. The properties in the data holder can be * changed later, but it will depend on the nature of the property whether * or not this change will take effect. Properties that are applied at * initialization will not be applied when changed and properties that are * applied during the render cycle will be applied when changed. * * @param target A TextView, or any UI element that inherits from TextView. * @param attrs The attributes from the xml tag that defined the target. * @param defStyle The style that is applied to the target element. This may * either be an attribute resource, whose value will be retrieved * from the current theme, or an explicit style resource. */ public static void applyFont(TextView target, AttributeSet attrs, int defStyle) { if (target == null || target.isInEditMode()) return; ExtraFontData data = (ExtraFontData)target.getTag(R.id.fonts_extra_data); if (data == null) { data = new ExtraFontData(); target.setTag(R.id.fonts_extra_data, data); // By default, the font is not changed data.font = null; // By default, we apply a regular typeface data.style = Typeface.NORMAL; // By default, we don't add a border around the text data.borderWidth = 0; // By default, *if* there is a border, it will be black data.borderColor = Color.BLACK; } // First get the font attribute from the textAppearance: Theme theme = target.getContext().getTheme(); // Get the text appearance that's currently in use TypedArray a = theme.obtainStyledAttributes(attrs, new int[] {android.R.attr.textAppearance}, defStyle, 0); int textAppearanceStyle = -1; try { textAppearanceStyle = a.getResourceId(0, -1); } finally { a.recycle(); } // Get the font and style defined in the text appearance TypedArray appearance = null; if (textAppearanceStyle != -1) appearance = theme.obtainStyledAttributes(textAppearanceStyle, R.styleable.Fonts); getAttributes(appearance, data); // Then get the font attribute from the FontTextView itself: a = theme.obtainStyledAttributes(attrs, R.styleable.Fonts, defStyle, 0); getAttributes(a, data); // Now we have the font, apply it if (data.font != null) { getInstance().setTypeface(target, data.font, data.style); } } /** * Fetches the font attributes from the given typed array and overrides all * properties in the given data holder that are present in the typed array. * * @param a A TypedArray from which the attributes will be fetched. It will * be recycled if not null. * @param data The data holder in which all read properties are stored. */ private static void getAttributes(final TypedArray a, final ExtraFontData data) { if (a == null) return; try { // Iterate over all attributes in 'Android-style' // (similar to the implementation of the TextView constructor) int n = a.getIndexCount(); for (int i = 0; i < n; i++) { int attr = a.getIndex(i); switch (attr) { case R.styleable.Fonts_font: data.font = a.getString(attr); break; case R.styleable.Fonts_android_textStyle: data.style = a.getInt(attr, Typeface.NORMAL); break; case R.styleable.Fonts_borderWidth: data.borderWidth = a.getDimensionPixelSize(attr, 0); break; case R.styleable.Fonts_borderColor: data.borderColor = a.getColor(attr, Color.BLACK); break; } } } finally { a.recycle(); } } public static void onDrawHelper(Canvas canvas, TextView target, DrawCallback drawCallback) { if (target.isInEditMode()) return; final ExtraFontData data = (ExtraFontData)target.getTag(R.id.fonts_extra_data); if (data == null) return; if (data.borderWidth > 0) { final Paint paint = target.getPaint(); // setup stroke final Style oldStyle = paint.getStyle(); final ColorStateList oldTextColors = target.getTextColors(); final float oldStrokeWidth = paint.getStrokeWidth(); target.setTextColor(data.borderColor); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(data.borderWidth); callDrawCallback(drawCallback, canvas); target.setTextColor(oldTextColors); paint.setStyle(oldStyle); paint.setStrokeWidth(oldStrokeWidth); } } /** * Calls the draw callback with the given canvas. Use this method instead of * calling it yourself, as lint is fooled by the method name 'onDraw' and * thinks we are intervening with the render cycle. With this method, we can * isolate the suppress lint annotation to the only warning we want to * suppress. * * @param drawCallback * @param canvas */ @SuppressLint("WrongCall") private static void callDrawCallback(DrawCallback drawCallback, Canvas canvas) { drawCallback.onDraw(canvas); } /** * A data holder in which properties are stored that are not part of the * default text view attributes, but which are applicable to all custom Font * widgets. By storing this data holder in the corresponding view instance, * we can apply the properties at any time with a shared static method. * * @author Jelle Fresen <jelle@innovattic.com> */ public static class ExtraFontData { public String font; public int style; public int borderWidth; public int borderColor; } public static interface DrawCallback { public void onDraw(Canvas canvas); } }
import javax.imageio.ImageIO; import javax.sound.sampled.*; import javax.swing.*; import javax.swing.Timer; import java.awt.*; import java.awt.event.*; import java.awt.image.BufferedImage; import java.io.*; import java.util.*; public class GameEngine extends JPanel implements MouseListener, MouseMotionListener, ActionListener, KeyListener { private int movementSpeed = 25; private Vector<Integer> rnglist; private int gameSpeed = 1; private int worldSize = 1; // Defines Overworld dimensions private Overworld currentOverWorld = null; private Tile currentTile = null; private int currentTileX = 0; private int currentTileY = 0; private int tileBrushIndex = 0; private String tileBrush = "grass"; private int npcBrushIndex = 0; private String npcBrush = "SHEEP"; private Item currentItem = null; private int currentItemIndex = 0; private int currentItemRow = 0; private int currentItemColumn = 0; private Item currentHoverItem = null; private int actionTick = 0; // Ticker for player actions. private final Timer timer = new Timer(gameSpeed, this); // GAME CLOCK TIMER private Timer animationTimer0 = new Timer(1000, this); private int animation_frame = 0; private Player player1; private Npc currentNpc; // Selected Npc pointer FileOutputStream fileOut; FileInputStream fileIn; private boolean debugMenuVisible = false; private boolean inventoryMenuVisible = false; private boolean startMenuVisible = false; private boolean viewMenuVisible = false; private boolean mapVisible = false; private boolean worldExists = false; private boolean shiftPressed = false; private boolean controlPressed = false; private boolean altPressed = false; private Font font1_8 = new Font("Consola", Font.PLAIN, 8); private Font font2_16 = new Font("Consola", Font.BOLD, 16); private Font font3_24 = new Font("Consola", Font.BOLD, 24); private Font font4_22 = new Font("Arial", Font.BOLD, 22); private Font font4_20 = new Font("Arial", Font.BOLD, 20); private Overworld[][] overWorld = new Overworld[worldSize][worldSize]; double nextTime = (double) System.nanoTime() / 1000000000.0; Map<String, BufferedImage> bufferedImageMap; int rainVector = 1; private boolean raining; Point[] rainDrops; int numberOfRainDrops = 15; Deque<Point> bufferSplashAnimations = new LinkedList<>(); private ArrayList<String> BrushTileList = new ArrayList<>(); private ArrayList<String> brushNpcList = new ArrayList<>(); AudioInputStream audioInputStream; Clip movementSound; Clip rainSound; Clip woodsSound; Clip menuSound; private boolean rainSoundLoaded = false; private boolean woodsSoundLoaded = false; private boolean menuSoundLoaded = false; private boolean craftingMenuVisible = false; int mouseDragX = 0; int mouseDragY = 0; boolean engagedSuccessfully = false; // flag to determine real-time whether the key press triggers a successful harvest action private boolean TRIGGER_endOfCombat = false; private int storeXPos = 0; private int storeYPos = 0; private String storeOrientation = ""; private boolean attackStyleChooserVisible = false; int[] abilities = new int[3]; private boolean stuckInDialogue = false; private Npc currentDialogueNpc = null; String npcDialogue = "npcdialogue"; String playerResponse1 = "playerresponse1"; String playerResponse2 = "playerresponse2"; String playerResponse3 = "playerresponse3"; int TRIGGER_dialogueState = 0; int mousedOverDialogue = 0; public GameEngine() { addMouseListener(this); addMouseMotionListener(this); addKeyListener(this); // Adds keyboard listener. setFocusable(true); // Setting required for keyboard listener. run(); } private void startUp() { rnglist = rngSeeder(); // Loads pre-generated RNG numbers from file to a Vector. generatePlayer();// Player is created. developerCheats(); // currentItem = player1.playerInventory.itemArray[0]; buildOverworld(); // adds worldSize x worldSize OverWorlds to the Overworld array. currentOverWorld = overWorld[0][0]; // Points currentOverWorld pointer to start map. dummyWorld(); // initializes currentOverWorld.tilemap list and fills it with an empty grass world. // currentTile = currentOverWorld.tilemap[0][0]; // points to the currently selected tile. loadSprites(); loadSpritesReworked(); indexTiles(); indexNpc(); loadMenuSound(); raining = true; generateRainPattern(); timer.start(); animationTimer0.start(); fillWorld(); loadRainSound(); loadWoodsSound(); generateTestingEnvironment0(); worldExists = true; startMenuVisible = false; // this is how the menu hides other windows. mapVisible = true; } private void developerCheats() { for (int j = 0; j < 10; j++) { player1.playerInventory.addItem(1); player1.playerInventory.addItem(2); } } private void generateTestingEnvironment0() { generateNpc(currentOverWorld.npcList.size() + 1, 5, 5, 10, Color.black, "LUMBERJACK"); generateNpc(currentOverWorld.npcList.size() + 1, 5, 8, 10, Color.black, "CASTLEGUARD"); generateNpc(currentOverWorld.npcList.size() + 1, 5, 11, 10, Color.black, "CHEF"); currentOverWorld.tilemap[10][10] = new Tile("t0stone", false, true, false); currentOverWorld.tilemap[11][10] = new Tile("t1stone", false, true, false); currentOverWorld.tilemap[12][10] = new Tile("t2stone", false, true, false); currentOverWorld.tilemap[13][10] = new Tile("t3stone", false, true, false); currentOverWorld.tilemap[14][10] = new Tile("t4stone", false, true, false); generate1x2Rock(17, 10, "t0stone_1x2"); generate1x2Rock(19, 10, "t1stone_1x2"); generate1x2Rock(21, 10, "t2stone_1x2"); currentOverWorld.tilemap[15][15] = new Tile("furnace", false, false, true); currentOverWorld.tilemap[16][15] = new Tile("cookingpot", false, false, true); } private void generate1x2Rock(int x, int y, String rockType) { if (!currentOverWorld.tilemap[x][y].occupied && !currentOverWorld.tilemap[x + 1][y].occupied && !currentOverWorld.tilemap[x][y - 1].occupied && !currentOverWorld.tilemap[x + 1][y + 1].occupied) { currentOverWorld.tilemap[x][y] = new Tile(rockType + "_a", false, true, false); currentOverWorld.tilemap[x + 1][y] = new Tile(rockType + "_b", false, true, false); } } private void loadSpritesReworked() { loadBufferedImage("Grass0.png", "GRASS0"); loadBufferedImage("Grass1.png", "GRASS1"); loadBufferedImage("Grass2.png", "GRASS2"); loadBufferedImage("Grass3.png", "GRASS3"); loadBufferedImage("Grass4.png", "GRASS4"); loadBufferedImage("Grass5.png", "GRASS5"); loadBufferedImage("Grass6.png", "GRASS6"); loadBufferedImage("Grass7.png", "GRASS7"); loadBufferedImage("Grass8.png", "GRASS8"); loadBufferedImage("Grass9.png", "GRASS9"); loadBufferedImage("Grass10.png", "GRASS10"); loadBufferedImage("Grass11.png", "GRASS11"); loadBufferedImage("T0Stone0_1x2.png", "T0STONE0_1x2"); loadBufferedImage("T0Stone1_1x2.png", "T0STONE1_1x2"); loadBufferedImage("T1Stone0_1x2.png", "T1STONE0_1x2"); loadBufferedImage("T1Stone1_1x2.png", "T1STONE1_1x2"); loadBufferedImage("T2Stone0_1x2.png", "T2STONE0_1x2"); loadBufferedImage("T2Stone1_1x2.png", "T2STONE1_1x2"); loadBufferedImage("Cobblestone.png", "COBBLESTONE"); loadBufferedImage("YellowOre.png", "YELLOW_ORE"); loadBufferedImage("BlueOre.png", "BLUE_ORE"); loadBufferedImage("GreenOre.png", "GREEN_ORE"); loadBufferedImage("RedOre.png", "RED_ORE"); loadBufferedImage("YellowOre.png", "YELLOW_ORE"); loadBufferedImage("BlueOre.png", "BLUE_ORE"); loadBufferedImage("GreenOre.png", "GREEN_ORE"); loadBufferedImage("RedOre.png", "RED_ORE"); loadBufferedImage("YellowBar.png", "YELLOW_BAR"); loadBufferedImage("BlueBar.png", "BLUE_BAR"); loadBufferedImage("GreenBar.png", "GREEN_BAR"); loadBufferedImage("RedBar.png", "RED_BAR"); loadBufferedImage("FurnaceUnlit.png", "FURNACE_UNLIT"); loadBufferedImage("FurnaceLit.png", "FURNACE_LIT"); loadBufferedImage("CookingPot.png", "COOKING_POT"); loadBufferedImage("T0Stone0.png", "T0STONE0"); loadBufferedImage("T0Stone1.png", "T0STONE1"); loadBufferedImage("T1Stone0.png", "T1STONE0"); loadBufferedImage("T1Stone1.png", "T1STONE1"); loadBufferedImage("T2Stone0.png", "T2STONE0"); loadBufferedImage("T2Stone1.png", "T2STONE1"); loadBufferedImage("T3Stone0.png", "T3STONE0"); loadBufferedImage("T3Stone1.png", "T3STONE1"); loadBufferedImage("T4Stone0.png", "T4STONE0"); loadBufferedImage("T4Stone1.png", "T4STONE1"); loadBufferedImage("FarmerShovelE.png", "FARMER_SHOVEL_EAST"); loadBufferedImage("FarmerShovelW.png", "FARMER_SHOVEL_WEST"); loadBufferedImage("WaterCanE.png", "WATER_CAN_EAST"); loadBufferedImage("WaterCanW.png", "WATER_CAN_WEST"); loadBufferedImage("LumberjackAxeE.png", "LUMBERJACK_AXE_EAST"); loadBufferedImage("LumberjackAxeW.png", "LUMBERJACK_AXE_WEST"); loadBufferedImage("MinerPickaxeE.png", "MINER_PICKAXE_EAST"); loadBufferedImage("MinerPickaxeW.png", "MINER_PICKAXE_WEST"); loadBufferedImage("YellowPickaxeE.png", "YELLOW_PICKAXE_EAST"); loadBufferedImage("YellowPickaxeW.png", "YELLOW_PICKAXE_WEST"); loadBufferedImage("BluePickaxeE.png", "BLUE_PICKAXE_EAST"); loadBufferedImage("BluePickaxeW.png", "BLUE_PICKAXE_WEST"); loadBufferedImage("GreenPickaxeE.png", "GREEN_PICKAXE_EAST"); loadBufferedImage("GreenPickaxeW.png", "GREEN_PICKAXE_WEST"); loadBufferedImage("RedPickaxeE.png", "RED_PICKAXE_EAST"); loadBufferedImage("RedPickaxeW.png", "RED_PICKAXE_WEST"); loadBufferedImage("EastChef.png", "EAST_CHEF"); loadBufferedImage("RaggedShirt.png", "RAGGEDSHIRT"); loadBufferedImage("EastLumberjack.png", "EAST_LUMBERJACK"); loadBufferedImage("EastCastleGuard.png", "EAST_CASTLEGUARD"); loadBufferedImage("GearWorksLogo.png", "GEARWORKS_LOGO"); loadBufferedImage("GearWorksLogoSmall.png", "GEARWORKS_LOGO_SMALL"); loadBufferedImage("GenericShieldBack.png", "GENERIC_SHIELD_BACK"); loadBufferedImage("BrownPlatebodyPlayerModelNorth.png", "BROWN_PLATEBODY_PLAYERMODEL_NORTH"); loadBufferedImage("BrownPlatebodyTrimmedPlayerModelNorth.png", "BROWN_PLATEBODY_TRIMMED_PLAYERMODEL_NORTH"); loadBufferedImage("BluePlatebodyPlayerModelNorth.png", "BLUE_PLATEBODY_PLAYERMODEL_NORTH"); loadBufferedImage("BluePlatebodyTrimmedPlayerModelNorth.png", "BLUE_PLATEBODY_TRIMMED_PLAYERMODEL_NORTH"); loadBufferedImage("GreenPlatebodyPlayerModelNorth.png", "GREEN_PLATEBODY_PLAYERMODEL_NORTH"); loadBufferedImage("GreenPlatebodyTrimmedPlayerModelNorth.png", "GREEN_PLATEBODY_TRIMMED_PLAYERMODEL_NORTH"); loadBufferedImage("ABILITY_MHAND_SLICE.png", "ABILITY_MHAND_SLICE"); loadBufferedImage("ABILITY_MHAND_STAB.png", "ABILITY_MHAND_STAB"); loadBufferedImage("ABILITY_OHAND_BLOCK.png", "ABILITY_OHAND_BLOCK"); loadBufferedImage("RedDaggerW.png", "RED_DAGGER_WEST"); loadBufferedImage("RedDaggerE.png", "RED_DAGGER_EAST"); loadBufferedImage("BlueDaggerE.png", "BLUE_DAGGER_EAST"); loadBufferedImage("GreenDaggerW.png", "GREEN_DAGGER_WEST"); loadBufferedImage("GreenDaggerE.png", "GREEN_DAGGER_EAST"); loadBufferedImage("JunkscrapLegguardsPlayerModelNorth.png", "JUNKSCRAP_LEGGUARDS_PLAYERMODEL_NORTH"); loadBufferedImage("JunkscrapLegguardsPlayerModelEast.png", "JUNKSCRAP_LEGGUARDS_PLAYERMODEL_EAST"); loadBufferedImage("JunkscrapLegguardsPlayerModelWest.png", "JUNKSCRAP_LEGGUARDS_PLAYERMODEL_WEST"); loadBufferedImage("JunkscrapLegguardsTrimmedPlayerModelEast.png", "JUNKSCRAP_LEGGUARDS_TRIMMED_PLAYERMODEL_EAST"); loadBufferedImage("JunkscrapLegguardsTrimmedPlayerModelNorth.png", "JUNKSCRAP_LEGGUARDS_TRIMMED_PLAYERMODEL_NORTH"); loadBufferedImage("JunkscrapLegguardsTrimmedPlayerModelWest.png", "JUNKSCRAP_LEGGUARDS_TRIMMED_PLAYERMODEL_WEST"); loadBufferedImage("BlueLegguardsPlayerModelEast.png", "BLUE_LEGGUARDS_PLAYERMODEL_EAST"); loadBufferedImage("BlueLegguardsPlayerModelNorth.png", "BLUE_LEGGUARDS_PLAYERMODEL_NORTH"); loadBufferedImage("BlueLegguardsPlayerModelWest.png", "BLUE_LEGGUARDS_PLAYERMODEL_WEST"); loadBufferedImage("BlueLegguardsTrimmedPlayerModelNorth.png", "BLUE_LEGGUARDS_TRIMMED_PLAYERMODEL_NORTH"); loadBufferedImage("BlueLegguardsTrimmedPlayerModelEast.png", "BLUE_LEGGUARDS_TRIMMED_PLAYERMODEL_EAST"); loadBufferedImage("BlueLegguardsTrimmedPlayerModelEast.png", "BLUE_LEGGUARDS_TRIMMED_PLAYERMODEL_WEST"); loadBufferedImage("GreenLegguardsPlayerModelEast.png", "GREEN_LEGGUARDS_PLAYERMODEL_EAST"); loadBufferedImage("GreenLegguardsPlayerModelNorth.png", "GREEN_LEGGUARDS_PLAYERMODEL_NORTH"); loadBufferedImage("GreenLegguardsPlayerModelWest.png", "GREEN_LEGGUARDS_PLAYERMODEL_WEST"); loadBufferedImage("GreenLegguardsTrimmedPlayerModelNorth.png", "GREEN_LEGGUARDS_TRIMMED_PLAYERMODEL_NORTH"); loadBufferedImage("GreenLegguardsTrimmedPlayerModelEast.png", "GREEN_LEGGUARDS_TRIMMED_PLAYERMODEL_EAST"); loadBufferedImage("GreenLegguardsTrimmedPlayerModelEast.png", "GREEN_LEGGUARDS_TRIMMED_PLAYERMODEL_WEST"); loadBufferedImage("RatskinPantsPlayerModelEast.png", "RATSKIN_PANTS_PLAYERMODEL_EAST"); loadBufferedImage("RatskinPantsPlayerModelNorth.png", "RATSKIN_PANTS_PLAYERMODEL_NORTH"); loadBufferedImage("RatskinPantsPlayerModelWest.png", "RATSKIN_PANTS_PLAYERMODEL_WEST"); loadBufferedImage("RaggedShirtPlayerModelSouth.png", "RAGGED_SHIRT_PLAYERMODEL_SOUTH"); loadBufferedImage("RaggedShirtPlayerModelEast.png", "RAGGED_SHIRT_PLAYERMODEL_EAST"); loadBufferedImage("RaggedShirtPlayerModelWest.png", "RAGGED_SHIRT_PLAYERMODEL_WEST"); loadBufferedImage("RaggedShirtPlayerModelNorth.png", "RAGGED_SHIRT_PLAYERMODEL_NORTH"); loadBufferedImage("BrownPlatebodyPlayerModelEast.png", "BROWN_PLATEBODY_PLAYERMODEL_EAST"); loadBufferedImage("BrownPlatebodyPlayerModelWest.png", "BROWN_PLATEBODY_PLAYERMODEL_WEST"); loadBufferedImage("BrownPlatebodyTrimmedPlayerModelEast.png", "BROWN_PLATEBODY_TRIMMED_PLAYERMODEL_EAST"); loadBufferedImage("BrownPlatebodyTrimmedPlayerModelWest.png", "BROWN_PLATEBODY_TRIMMED_PLAYERMODEL_WEST"); loadBufferedImage("bluePlatebodyPlayerModelEast.png", "BLUE_PLATEBODY_PLAYERMODEL_EAST"); loadBufferedImage("bluePlatebodyPlayerModelWest.png", "BLUE_PLATEBODY_PLAYERMODEL_WEST"); loadBufferedImage("bluePlatebodyPlayerTrimmedPlayerModelEast.png", "BLUE_PLATEBODY_TRIMMED_PLAYERMODEL_EAST"); loadBufferedImage("bluePlatebodyPlayerTrimmedPlayeModelWest.png", "BLUE_PLATEBODY_TRIMMED_PLAYERMODEL_WEST"); loadBufferedImage("greenPlatebodyPlayerModelEast.png", "GREEN_PLATEBODY_PLAYERMODEL_EAST"); loadBufferedImage("greenPlatebodyPlayerModelWest.png", "GREEN_PLATEBODY_PLAYERMODEL_WEST"); loadBufferedImage("GreenPlatebodyTrimmedPlayerModelEast.png", "GREEN_PLATEBODY_TRIMMED_PLAYERMODEL_EAST"); loadBufferedImage("GreenPlatebodyTrimmedPlayerModelWest.png", "GREEN_PLATEBODY_TRIMMED_PLAYERMODEL_WEST"); loadBufferedImage("BagIcon.png", "BAG_ICON"); loadBufferedImage("CraftingIcon.png", "CRAFTING_ICON"); loadBufferedImage("BACKGROUNDIMG_COMBAT_0.png", "BACKGROUNDIMG_COMBAT_0"); loadBufferedImage("GreenPlatebodyTrimmed.png", "GREEN_PLATEBODY_TRIMMED"); loadBufferedImage("GreenPlatebodyTrimmedPlayerModelSouth.png", "GREEN_PLATEBODY_TRIMMED_PLAYERMODEL_SOUTH"); loadBufferedImage("BrownPlatebody.png", "BROWN_PLATEBODY"); loadBufferedImage("BrownPlatebodyPlayerModelSouth.png", "BROWN_PLATEBODY_PLAYERMODEL_SOUTH"); loadBufferedImage("BluePlatebodyTrimmed.png", "BLUE_PLATEBODY_TRIMMED"); loadBufferedImage("BluePlatebodyTrimmedPlayerModelSouth.png", "BLUE_PLATEBODY_TRIMMED_PLAYERMODEL_SOUTH"); loadBufferedImage("BluePlatebody.png", "BLUE_PLATEBODY"); loadBufferedImage("BluePlatebodyPlayerModelSouth.png", "BLUE_PLATEBODY_PLAYERMODEL_SOUTH"); loadBufferedImage("BrownPlatebody.png", "BROWN_PLATEBODY"); loadBufferedImage("BrownPlatebodyPlayerModelSouth.png", "BROWN_PLATEBODY_PLAYERMODEL_SOUTH"); loadBufferedImage("GreenPlatebody.png", "GREEN_PLATEBODY"); loadBufferedImage("GreenPlatebodyPlayerModelSouth.png", "GREEN_PLATEBODY_PLAYERMODEL_SOUTH"); loadBufferedImage("BrownPlatebodyTrimmed.png", "BROWN_PLATEBODY_TRIMMED"); loadBufferedImage("BrownPlatebodyTrimmedPlayerModelSouth.png", "BROWN_PLATEBODY_TRIMMED_PLAYERMODEL_SOUTH"); loadBufferedImage("BlueLegguardsTrimmed.png", "BLUE_LEGGUARDS_TRIMMED"); loadBufferedImage("BlueLegguardsTrimmedPlayerModelSouth.png", "BLUE_LEGGUARDS_TRIMMED_PLAYERMODEL_SOUTH"); loadBufferedImage("BlueLegguards.png", "BLUE_LEGGUARDS"); loadBufferedImage("BlueLegguardsPlayerModelSouth.png", "BLUE_LEGGUARDS_PLAYERMODEL_SOUTH"); loadBufferedImage("GreenLegguards.png", "GREEN_LEGGUARDS"); loadBufferedImage("GreenLegguardsPlayerModelSouth.png", "GREEN_LEGGUARDS_PLAYERMODEL_SOUTH"); loadBufferedImage("GreenLegguardsTrimmed.png", "GREEN_LEGGUARDS_TRIMMED"); loadBufferedImage("GreenLegguardsTrimmedPlayerModelSouth.png", "GREEN_LEGGUARDS_TRIMMED_PLAYERMODEL_SOUTH"); loadBufferedImage("JunkscrapLegguards.png", "JUNKSCRAP_LEGGUARDS"); loadBufferedImage("JunkscrapLegguardsPlayerModelSouth.png", "JUNKSCRAP_LEGGUARDS_PLAYERMODEL_SOUTH"); loadBufferedImage("JunkscrapLegguardsTrimmed.png", "JUNKSCRAP_LEGGUARDS_TRIMMED"); loadBufferedImage("JunkscrapLegguardsTrimmedPlayerModelSouth.png", "JUNKSCRAP_LEGGUARDS_TRIMMED_PLAYERMODEL_SOUTH"); loadBufferedImage("RatskinPants.png", "Ratskin_Pants"); loadBufferedImage("RatskinPantsPlayerModelSouth.png", "RATSKIN_PANTS_PLAYERMODEL_SOUTH"); loadBufferedImage("GreenBucklerTrimmed.png", "GREEN_BUCKLER_TRIMMED"); loadBufferedImage("JunkscrapBuckler.png", "JUNKSCRAP_BUCKLER"); loadBufferedImage("JunkscrapBucklerTrimmed.png", "JUNKSCRAP_BUCKLER_TRIMMED"); } private void loadBufferedImage(String filePath, String syntaxName) { BufferedImage bi; try { bi = ImageIO.read((new File("Data/GFX/" + filePath))); bufferedImageMap.put(syntaxName, bi); } catch (IOException ignored) { } } private void reset() { player1 = null; cleanWorld(); generatePlayer(); } private void loadRainSound() { File rain = new File("Data/Sound/Rain.wav"); try { audioInputStream = AudioSystem.getAudioInputStream(rain); } catch (UnsupportedAudioFileException | IOException e) { e.printStackTrace(); } try { rainSound = AudioSystem.getClip(); rainSound.open(audioInputStream); rainSound.start(); rainSound.loop(999); rainSoundLoaded = true; } catch (LineUnavailableException | IOException e) { e.printStackTrace(); } } private void loadWoodsSound() { File woods = new File("Data/Sound/Woods.wav"); try { audioInputStream = AudioSystem.getAudioInputStream(woods); } catch (UnsupportedAudioFileException | IOException e) { e.printStackTrace(); } try { woodsSound = AudioSystem.getClip(); woodsSound.open(audioInputStream); woodsSound.start(); woodsSound.loop(999); woodsSoundLoaded = true; } catch (LineUnavailableException | IOException e) { e.printStackTrace(); } } private void loadMenuSound() { File menu1 = new File("Data/Sound/Menu1.wav"); try { audioInputStream = AudioSystem.getAudioInputStream(menu1); } catch (UnsupportedAudioFileException | IOException e) { e.printStackTrace(); } try { menuSound = AudioSystem.getClip(); menuSound.open(audioInputStream); menuSound.start(); menuSound.loop(999); menuSoundLoaded = true; } catch (LineUnavailableException | IOException e) { e.printStackTrace(); } } private void generateRainPattern() { rainDrops = new Point[numberOfRainDrops]; for (int i = 0; i < rainDrops.length; i++) { int x = (int) (Math.random() * (Main.WIDTH)); int y = (int) (Math.random() * (Main.HEIGHT)); rainDrops[i] = new Point(x, y); } } private void loadSprites() { bufferedImageMap = new HashMap<>(); BufferedImage greenBuckler; BufferedImage blueDagger; BufferedImage blueBuckler; BufferedImage blueBucklerTrimmed; BufferedImage woodenClubW; BufferedImage woodenClubE; BufferedImage woodenShield; BufferedImage northPlayer; BufferedImage eastPlayer; BufferedImage southPlayer; BufferedImage westPlayer; BufferedImage sand; BufferedImage woodenFenceNECorner; BufferedImage woodenFenceSWCorner; BufferedImage woodenFenceSECorner; BufferedImage woodenFenceNWCorner; BufferedImage ratSkinHood; BufferedImage ratSkinChest; BufferedImage ratSkinPants; BufferedImage WoodFloorDoorNorth; BufferedImage WoodFloorDoorEast; BufferedImage WoodFloorDoorSouth; BufferedImage WoodFloorDoorWest; BufferedImage stonePathGrass; BufferedImage northAdventurer; BufferedImage southAdventurer; BufferedImage eastAdventurer; BufferedImage westAdventurer; BufferedImage errorImg; BufferedImage northFrog; BufferedImage southFrog; BufferedImage eastFrog; BufferedImage westFrog; BufferedImage dirt; BufferedImage water; BufferedImage rakedDirt; BufferedImage plankWall; BufferedImage woodFloor; BufferedImage tree; BufferedImage inventoryLumber; BufferedImage northZombie; BufferedImage southZombie; BufferedImage eastZombie; BufferedImage westZombie; BufferedImage northSheep; BufferedImage southSheep; BufferedImage eastSheep; BufferedImage westSheep; BufferedImage upArrow; BufferedImage downArrow; BufferedImage woodenFenceHorizontal; BufferedImage woodenFenceVertical; try { blueDagger = ImageIO.read((new File("Data/GFX/BlueDaggerW.png"))); blueBucklerTrimmed = ImageIO.read((new File("Data/GFX/BlueBucklerTrimmed.png"))); greenBuckler = ImageIO.read((new File("Data/GFX/GreenBuckler.png"))); blueBuckler = ImageIO.read((new File("Data/GFX/BlueBuckler.png"))); woodenClubW = ImageIO.read((new File("Data/GFX/woodenClubW.png"))); woodenClubE = ImageIO.read((new File("Data/GFX/woodenClubE.png"))); woodenShield = ImageIO.read((new File("Data/GFX/WoodenShield.png"))); westPlayer = ImageIO.read((new File("Data/GFX/westPlayer.png"))); northPlayer = ImageIO.read((new File("Data/GFX/NorthPlayer.png"))); eastPlayer = ImageIO.read((new File("Data/GFX/EastPlayer.png"))); southPlayer = ImageIO.read((new File("Data/GFX/SouthPlayer.png"))); sand = ImageIO.read((new File("Data/GFX/Sand.png"))); woodenFenceNECorner = ImageIO.read(new File("Data/GFX/woodenFenceNECorner.png")); woodenFenceSWCorner = ImageIO.read(new File("Data/GFX/woodenFenceSWCorner.png")); woodenFenceSECorner = ImageIO.read(new File("Data/GFX/woodenFenceSECorner.png")); woodenFenceNWCorner = ImageIO.read(new File("Data/GFX/woodenFenceNWCorner.png")); woodenFenceHorizontal = ImageIO.read(new File("Data/GFX/woodenFenceHorizontal.png")); woodenFenceVertical = ImageIO.read(new File("Data/GFX/woodenFenceVertical.png")); ratSkinHood = ImageIO.read(new File("Data/GFX/ratSkinHood.png")); ratSkinChest = ImageIO.read(new File("Data/GFX/ratSkinChest.png")); ratSkinPants = ImageIO.read(new File("Data/GFX/ratSkinPants.png")); WoodFloorDoorNorth = ImageIO.read(new File("Data/GFX/WoodFloorDoorNorth.png")); WoodFloorDoorEast = ImageIO.read(new File("Data/GFX/WoodFloorDoorEast.png")); WoodFloorDoorSouth = ImageIO.read(new File("Data/GFX/WoodFloorDoorSouth.png")); WoodFloorDoorWest = ImageIO.read(new File("Data/GFX/WoodFloorDoorWest.png")); stonePathGrass = ImageIO.read(new File("Data/GFX/StonePathGrass.png")); upArrow = ImageIO.read(new File("Data/GFX/upArrow.png")); downArrow = ImageIO.read(new File("Data/GFX/downArrow.png")); northAdventurer = ImageIO.read(new File("Data/GFX/NorthAdventurer.png")); eastAdventurer = ImageIO.read(new File("Data/GFX/EastAdventurer.png")); southAdventurer = ImageIO.read(new File("Data/GFX/SouthAdventurer.png")); westAdventurer = ImageIO.read(new File("Data/GFX/WestAdventurer.png")); errorImg = ImageIO.read(new File("Data/GFX/ErrorImg.jpg")); northFrog = ImageIO.read(new File("Data/GFX/NorthFroggy.png")); southFrog = ImageIO.read(new File("Data/GFX/SouthFroggy.png")); eastFrog = ImageIO.read(new File("Data/GFX/EastFroggy.png")); // reads tree sprite westFrog = ImageIO.read(new File("Data/GFX/WestFroggy.png")); dirt = ImageIO.read(new File("Data/GFX/Dirt.png")); rakedDirt = ImageIO.read(new File("Data/GFX/RakedDirt.png")); woodFloor = ImageIO.read(new File("Data/GFX/WoodFloor.png")); plankWall = ImageIO.read(new File("Data/GFX/PlanksWall.png")); water = ImageIO.read(new File("Data/GFX/Water.png")); tree = ImageIO.read(new File("Data/GFX/Tree.png")); // reads tree sprite inventoryLumber = ImageIO.read(new File("Data/GFX/InventoryLumber.png")); // reads stone sprite. northSheep = ImageIO.read(new File("Data/GFX/NorthSheep.png")); southSheep = ImageIO.read(new File("Data/GFX/SouthSheep.png")); eastSheep = ImageIO.read(new File("Data/GFX/EastSheep.png")); westSheep = ImageIO.read(new File("Data/GFX/WestSheep.png")); northZombie = ImageIO.read(new File("Data/GFX/NorthZombie.png")); southZombie = ImageIO.read(new File("Data/GFX/SouthZombie.png")); eastZombie = ImageIO.read(new File("Data/GFX/EastZombie.png")); westZombie = ImageIO.read(new File("Data/GFX/WestZombie.png")); bufferedImageMap.put("GREEN_BUCKLER", greenBuckler); bufferedImageMap.put("BLUE_DAGGER_WEST", blueDagger); bufferedImageMap.put("BLUE_BUCKLER_TRIMMED", blueBucklerTrimmed); bufferedImageMap.put("WOODEN_CLUB_W", woodenClubW); bufferedImageMap.put("WOODEN_CLUB_E", woodenClubE); bufferedImageMap.put("BLUE_BUCKLER", blueBuckler); bufferedImageMap.put("WOODEN_SHIELD", woodenShield); bufferedImageMap.put("NORTH_PLAYER", northPlayer); bufferedImageMap.put("EAST_PLAYER", eastPlayer); bufferedImageMap.put("SOUTH_PLAYER", southPlayer); bufferedImageMap.put("WEST_PLAYER", westPlayer); bufferedImageMap.put("SAND", sand); bufferedImageMap.put("WOODENFENCENWCORNER", woodenFenceNWCorner); bufferedImageMap.put("WOODENFENCENECORNER", woodenFenceNECorner); bufferedImageMap.put("WOODENFENCESWCORNER", woodenFenceSWCorner); bufferedImageMap.put("WOODENFENCESECORNER", woodenFenceSECorner); bufferedImageMap.put("WOODENFENCEHORIZONTAL", woodenFenceHorizontal); bufferedImageMap.put("WOODENFENCEVERTICAL", woodenFenceVertical); bufferedImageMap.put("RATSKINCHEST", ratSkinChest); bufferedImageMap.put("RATSKINHOOD", ratSkinHood); bufferedImageMap.put("RATSKINPANTS", ratSkinPants); bufferedImageMap.put("WOODFLOORDOORNORTH", WoodFloorDoorNorth); bufferedImageMap.put("WOODFLOORDOOREAST", WoodFloorDoorEast); bufferedImageMap.put("WOODFLOORDOORSOUTH", WoodFloorDoorSouth); bufferedImageMap.put("WOODFLOORDOORWEST", WoodFloorDoorWest); bufferedImageMap.put("STONEPATHGRASS", stonePathGrass); bufferedImageMap.put("ARROW_UP", upArrow); bufferedImageMap.put("ARROW_DOWN", downArrow); bufferedImageMap.put("NORTH_ADVENTURER", northAdventurer); bufferedImageMap.put("SOUTH_ADVENTURER", southAdventurer); bufferedImageMap.put("EAST_ADVENTURER", eastAdventurer); bufferedImageMap.put("WEST_ADVENTURER", westAdventurer); bufferedImageMap.put("INVENTORY_LUMBER", inventoryLumber); bufferedImageMap.put("ERROR_IMG", errorImg); bufferedImageMap.put("NORTH_FROG", northFrog); bufferedImageMap.put("SOUTH_FROG", southFrog); bufferedImageMap.put("EAST_FROG", eastFrog); bufferedImageMap.put("WEST_FROG", westFrog); bufferedImageMap.put("DIRT", dirt); bufferedImageMap.put("WOODFLOOR", woodFloor); bufferedImageMap.put("RAKEDDIRT", rakedDirt); bufferedImageMap.put("WATER", water); bufferedImageMap.put("PLANKWALL", plankWall); bufferedImageMap.put("TREE", tree); bufferedImageMap.put("NORTH_SHEEP", northSheep); bufferedImageMap.put("SOUTH_SHEEP", southSheep); bufferedImageMap.put("EAST_SHEEP", eastSheep); bufferedImageMap.put("WEST_SHEEP", westSheep); bufferedImageMap.put("NORTH_CHASER", northZombie); bufferedImageMap.put("SOUTH_CHASER", southZombie); bufferedImageMap.put("EAST_CHASER", eastZombie); bufferedImageMap.put("WEST_CHASER", westZombie); } catch (IOException ignored) { } } private boolean paint() { // convert the time to seconds double currTime = (double) System.nanoTime() / 1000000000.0; boolean paintScreen; if (currTime >= nextTime) { // assign the time for the next update double delta = 0.04; nextTime += delta; paintScreen = true; } else { int sleepTime = (int) (1000.0 * (nextTime - currTime)); // sanity check paintScreen = false; if (sleepTime > 0) { // sleep until the next update try { Thread.sleep(sleepTime); } catch (InterruptedException e) { // do nothing } } } return paintScreen; } private void run() { startUp(); } private Vector<Integer> rngSeeder() { FileReader file = null; try { file = new FileReader("Data/RNG.txt"); // creats a pointer to the the file Data/RNG.txt } catch (FileNotFoundException e) { e.printStackTrace(); } int rng; Vector<Integer> rnglist = new Vector<>(); // creates a Vector of type int to store RNG values. try { Scanner input = null; // creates a scanning stream pointing to file. if (file != null) { input = new Scanner(file); } if (input != null) { while (input.hasNext()) { // loops until file has no more text numbers. rng = input.nextInt(); // loads next integer in list. rnglist.add(rng); // adds the loaded integer to vector. } } if (input != null) { input.close(); // closes stream. } } catch (Exception e) { e.printStackTrace(); } return rnglist; // Returns the int list. } private int rotateRng() { int r = rnglist.firstElement(); rnglist.remove(0); rnglist.addElement(r); // Uses the rnglist vector as a circular buffer and rotates it. return r; //returns rotated integer. } private void dummyWorld() { for (int i = 0; i < 32; i++) { for (int j = 0; j < 24; j++) { currentOverWorld.tilemap[i][j] = new Tile(); // creates a default tile on every coordinate of the current Overworld. } } } private void generateWorldImproved() { for (int i = 0; i < 32; i++) { for (int j = 0; j < 24; j++) { int r = rotateRng(); // sets r to a new rng value. if (r > 99) { // Dirt spawn rate. currentOverWorld.tilemap[i][j].type = "dirt"; } r = rotateRng(); if (currentOverWorld.tilemap[i][j].type.equals("grass") && r > 96) { // tree spawn rate/condition. currentOverWorld.tilemap[i][j].type = "tree"; } else if ((currentOverWorld.tilemap[i][j].type.equals("dirt") && r > 96)) { // sand spawn rate/condition. currentOverWorld.tilemap[i][j].type = "sand"; } r = rotateRng(); if (r > 98) { currentOverWorld.tilemap[i][j].type = "t0stone"; currentOverWorld.tilemap[i][j].rockPermutation = (int) (Math.random() * 2); } if (currentOverWorld.tilemap[i][j].type.equals("rakeddirt")) { // Makes all rakedDirt farmable currentOverWorld.tilemap[i][j].farmable = true; } } collisionMeshGenerator(); // generates a collision mesh for the current Overworld. } } private void collisionMeshGenerator() { int i; int j; for (i = 0; i < 32; i++) { // First, iterate through the entire tilemap of the current Overworld for (j = 0; j < 24; j++) { // and flag any non passable tiles as occupied. flag every passable tile as !occupied. currentOverWorld.tilemap[i][j].occupied = (currentOverWorld.tilemap[i][j].type.equals("tree")) || (currentOverWorld.tilemap[i][j].type.equals("t0stone")) || (currentOverWorld.tilemap[i][j].type.equals("t1stone")) || (currentOverWorld.tilemap[i][j].type.equals("t2stone")) || (currentOverWorld.tilemap[i][j].type.equals("t3stone")) || (currentOverWorld.tilemap[i][j].type.equals("t4stone")) || (currentOverWorld.tilemap[i][j].type.equals("water")) || (currentOverWorld.tilemap[i][j].type.equals("woodfloordoornorth")) || (currentOverWorld.tilemap[i][j].type.equals("woodfloordooreast")) || (currentOverWorld.tilemap[i][j].type.equals("woodfloordoorsouth")) || (currentOverWorld.tilemap[i][j].type.equals("woodfloordoorwest")) || (currentOverWorld.tilemap[i][j].type.equals("woodenfencevertical")) || (currentOverWorld.tilemap[i][j].type.equals("woodenfencehorizontal")) || (currentOverWorld.tilemap[i][j].type.equals("woodenfencenecorner")) || (currentOverWorld.tilemap[i][j].type.equals("woodenfencenwcorner")) || (currentOverWorld.tilemap[i][j].type.equals("woodenfencesecorner")) || (currentOverWorld.tilemap[i][j].type.equals("woodenfenceswcorner")) || (currentOverWorld.tilemap[i][j].type.equals("t0stone_1x2_a")) || (currentOverWorld.tilemap[i][j].type.equals("t0stone_1x2_b")) || (currentOverWorld.tilemap[i][j].type.equals("t1stone_1x2_a")) || (currentOverWorld.tilemap[i][j].type.equals("t1stone_1x2_b")) || (currentOverWorld.tilemap[i][j].type.equals("t2stone_1x2_a")) || (currentOverWorld.tilemap[i][j].type.equals("t2stone_1x2_b")) || (currentOverWorld.tilemap[i][j].type.equals("furnace")) || (currentOverWorld.tilemap[i][j].type.equals("cookingpot")) || (currentOverWorld.tilemap[i][j].type.equals("plankwall")); } currentOverWorld.tilemap[player1.xPos / 25][player1.yPos / 25].occupied = true; // flags current player position as occupied. for (Npc n : currentOverWorld.npcList) { // flags coordinate of every npc in the currentOverworld.npclist vector as occupied. currentOverWorld.tilemap[n.xPos / 25][n.yPos / 25].occupied = true; } } } private void naturalProcesses() { int i; int j; for (i = 0; i < 32; i++) { // First, iterate through the entire tilemap of the current Overworld for (j = 0; j < 24; j++) { if (currentOverWorld.tilemap[i][j].type.equals("dirt")) { currentOverWorld.tilemap[i][j].growth++; } if (currentOverWorld.tilemap[i][j].growth == 150) { if (currentOverWorld.tilemap[i][j].type.equals("dirt")) { currentOverWorld.tilemap[i][j].type = "grass"; currentOverWorld.tilemap[i][j].growth = 0; } } if (currentOverWorld.tilemap[i][j].type.equals("rakeddirt")) { currentOverWorld.tilemap[i][j].farmable = true; } } } } private void fillWorld() { int x; int y; for (x = 0; x < worldSize; x++) { // iterates through the entire overWorlds array. for (y = 0; y < worldSize; y++) { currentOverWorld = overWorld[x][y]; // moves currentOverWorlds pointer. dummyWorld(); // initializes current Overworld tilemap. generateWorldImproved(); // generates RNG world and serializes to file. if (currentOverWorld.idX < 10 && currentOverWorld.idY < 10) { System.out.println("World0" + currentOverWorld.idX + "0" + currentOverWorld.idY + " generated"); } else if (currentOverWorld.idX < 10) { System.out.println("World0" + currentOverWorld.idX + currentOverWorld.idY + " generated"); } else if (currentOverWorld.idY < 10) { System.out.println("World" + currentOverWorld.idX + "0" + currentOverWorld.idY + " generated"); } else { System.out.println("World" + currentOverWorld.idX + currentOverWorld.idY + " generated"); } // populateWorld(); // initializes and populates currentOverWorld.npclist with RNG Npc's. saveWorld(); } } currentOverWorld = overWorld[0][0]; // resets currentOverWorld pointer. } private void cleanWorld() { int x; int y; for (x = 0; x < worldSize; x++) { // iterates through the entire overWorlds array. for (y = 0; y < worldSize; y++) { overWorld[x][y].npcList = null; overWorld[x][y].tilemap = null; System.out.println("World" + x + y + " cleaned"); } } buildOverworld(); currentOverWorld = overWorld[0][0]; dummyWorld(); } private void saveWorld() { try { if (currentOverWorld.idX < 10 && currentOverWorld.idY < 10) { fileOut = new FileOutputStream("Data/Maps/WORLD0" + currentOverWorld.idX + "0" + currentOverWorld.idY + ".ser"); } else if (currentOverWorld.idX < 10) { fileOut = new FileOutputStream("Data/Maps/WORLD0" + currentOverWorld.idX + currentOverWorld.idY + ".ser"); } else if (currentOverWorld.idY < 10) { fileOut = new FileOutputStream("Data/Maps/WORLD" + currentOverWorld.idX + "0" + currentOverWorld.idY + ".ser"); } else { fileOut = new FileOutputStream("Data/Maps/WORLD" + currentOverWorld.idX + currentOverWorld.idY + ".ser"); } ObjectOutputStream out = new ObjectOutputStream(fileOut); // creates output stream pointed to file. out.writeObject(overWorld[currentOverWorld.idX][currentOverWorld.idY]); // serialize currentOverWorld. out.close(); fileOut.close(); // closes stream and file pointers. } catch (IOException i) { i.printStackTrace(); } } public void saveCustomWorld(String name) { try { Writer writer = new BufferedWriter(new OutputStreamWriter( // First create a new textfile. new FileOutputStream("Data/CustomMaps/" + name + ".ser"), "utf-8")); writer.close(); } catch (IOException e) { e.printStackTrace(); } try { // Then serialize an Overworld object to it. FileOutputStream fileOut = new FileOutputStream("Data/CustomMaps/" + name + ".ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); // creates output stream pointed to file. out.writeObject(overWorld[currentOverWorld.idX][currentOverWorld.idY]); // serialize currentOverWorld. out.close(); fileOut.close(); // closes stream and file pointers. } catch (IOException i) { i.printStackTrace(); } } public void reloadOverWorld() { int x; int y; for (x = 0; x < worldSize; x++) { for (y = 0; y < worldSize; y++) { currentOverWorld = overWorld[x][y]; // moves currentOverWorlds pointer. dummyWorld(); readWorld(x, y); for (Npc n : currentOverWorld.npcList) { // Todo; this does nothing atm n = new Npc(n.ID, n.xPos, n.yPos, n.HP, Color.black, n.ai); // refreshes all loaded nps. with newly constructed versions. to avoid bugs related to out dated npcs. } } } currentOverWorld = overWorld[0][0]; } public void readWorld(int idX, int idY) { try { if (idX < 10 && idY < 10) { fileIn = new FileInputStream("Data/Maps/WORLD0" + idX + "0" + idY + ".ser"); } else if (currentOverWorld.idX < 10) { fileIn = new FileInputStream("Data/Maps/WORLD0" + idX + idY + ".ser"); } else if (currentOverWorld.idY < 10) { fileIn = new FileInputStream("Data/Maps/WORLD" + idX + "0" + idY + ".ser"); } else { fileIn = new FileInputStream("Data/Maps/WORLD" + idX + idY + ".ser"); } // point to file. ObjectInputStream in = new ObjectInputStream(fileIn); // open stream. overWorld[idX][idY] = (Overworld) in.readObject(); in.close(); fileIn.close(); if (idX < 10 && idY < 10) { System.out.println("World0" + idX + "0" + idY + " loaded"); } else if (currentOverWorld.idX < 10) { System.out.println("World0" + idX + idY + " loaded"); } else if (currentOverWorld.idY < 10) { System.out.println("World" + idX + "0" + idY + " loaded"); } else { System.out.println("World" + idX + idY + " loaded"); } } catch (IOException | ClassNotFoundException i) { i.printStackTrace(); } } public void readCustomWorld(String name) { try { FileInputStream fileIn = new FileInputStream("Data/CustomMaps/" + name + ".ser"); // point to file. ObjectInputStream in = new ObjectInputStream(fileIn); // open stream. overWorld[currentOverWorld.idX][currentOverWorld.idY] = (Overworld) in.readObject(); //read Overworld object from file and write to currentOverWorld pointer. in.close(); fileIn.close(); System.out.println("Data/CustomMaps/" + name + ".ser"); } catch (IOException | ClassNotFoundException i) { i.printStackTrace(); } } private void buildOverworld() { for (int i = 0; i < worldSize; i++) { for (int j = 0; j < worldSize; j++) { overWorld[i][j] = new Overworld(i, j); // iterates through Overworld array and intializes it. } } } private void generatePlayer() { player1 = new Player(0, 14, 9, 66, 100, Color.RED); System.out.println("Created new player1 - ID: " + player1.ID + " - X: " + player1.xPos + " - Y: " + player1.yPos + " Empty Inventory Slots: " + player1.playerInventory.itemArray.length); } private void generateNpc(int setID, int setxPos, int setyPos, float setHP, Color setColor, String setAi) { Npc n = new Npc(setID, setxPos, setyPos, setHP, setColor, setAi); System.out.println("Created new " + setAi + " - ID: " + n.ID + " - X: " + n.xPos + " - Y: " + n.yPos); currentOverWorld.npcList.addElement(n); // works just like generate player but adds generated Npc to currentOverWorld.npclist. collisionMeshGenerator(); // Perhaps unneeded code but might prove itself useful in the future } private void populateWorld() { int r; int counter; int pop = 4; // amount of npc's generated per Overworld. int x; // position. int y; // position Color color; // npc color. String type; // ai type. for (counter = 0; counter < pop; counter++) { // run as many times as population allows. r = rotateRng(); x = rotateRng() % 29 + 1; // generates RNG value between 1 and 30 y = rotateRng() % 21 + 1; // generates RNG value bet // ween 1 and 22. ( edge protection. ) if (r < 50) { // cloin flip between Sheep and Chaser npc. type = "SHEEP"; color = Color.yellow; } else { type = "CHASER"; color = Color.black; } generateNpc(counter, x, y, 50, color, type); // creates npc with RNG generated values as attributes. } } @Override public void paintComponent(Graphics g) { // paints and controls what is currently painted on screen. super.paintComponent(g); if (engagedSuccessfully) { paintCombatSequence(g); } if (!engagedSuccessfully) { Layer0(g); Layer1(g); Layer2(g); if (debugMenuVisible && !engagedSuccessfully) { paintTileCoordinates(g); paintTileLines(g); paintDebugMenu(g); paintPalleteMenu(g); } if (stuckInDialogue) { paintDialogueScreen(g); } paintQuickslotGUI(g); if (attackStyleChooserVisible) { paintAttackStyleChooser(g); paintChosenAbilities(g); } if (inventoryMenuVisible && !engagedSuccessfully) { paintInventory(g); paintPlayerGearInterface(g); } if (viewMenuVisible) { paintViewMenu(g); } if (craftingMenuVisible) { paintCraftingMenu(g); } if (currentTile != null) { paintCurrentlySelectedTileHighlights(g); } if (currentItem != null) { paintCurrentlySelectedItemHighlights(g); paintCurrentlySelectedItemOnMouse(g); } if (shiftPressed && currentHoverItem != null && inventoryMenuVisible) { // && 5 seconds rested on item paintInventoryItemTooltip(g); } } if (startMenuVisible) { paintStartMenu(g); } else { g.drawImage(bufferedImageMap.get("GEARWORKS_LOGO_SMALL"), 0, 0, 28 * 2, 28 * 2, this); } } private void Layer2(Graphics g) { if (raining) { paintRain(g); // paintRain2(g); if (!bufferSplashAnimations.isEmpty()) { paintSplash(g); } } } private void paintDialogueScreen(Graphics g) { Graphics2D g2d = (Graphics2D) g; updateDialogueState(); updateMouseOverState(); g2d.setColor(Color.black); g2d.fillRect(0, 395, 800, 600 - 395); g2d.setColor(Color.white); g2d.setStroke(new BasicStroke(5)); g2d.drawRoundRect(0, 395, 800, 205, 20, 20); g2d.setStroke(new BasicStroke(1)); g2d.drawImage(bufferedImageMap.get("EAST_" + currentDialogueNpc.ai), 16, 419, 100, 180, this); g2d.setColor(Color.white); g2d.setFont(font4_22); g2d.drawString(npcDialogue, 116, 419); // g2d.drawString("H (placeholder)", 116, 446); g2d.setColor(Color.gray); g2d.setFont(font4_20); if (mousedOverDialogue == 1) { g2d.setColor(Color.yellow); } g2d.drawString(playerResponse1, 151, 464); // g2d.drawString("H (placeholder)", 151, 489); g2d.setColor(Color.gray); if (mousedOverDialogue == 2) { g2d.setColor(Color.yellow); } g2d.drawString(playerResponse2, 151, 515); // g2d.drawString("H (placeholder)", 151, 541); g2d.setColor(Color.gray); if (mousedOverDialogue == 3) { g2d.setColor(Color.yellow); } g2d.drawString(playerResponse3, 151, 567); // g2d.drawString("H (placeholder)", 151, 593); g2d.setColor(Color.red); g2d.setFont(font1_8); g2d.drawString("#Dialogue State = " + TRIGGER_dialogueState, 711, 408); g2d.drawString("#MousedOverDialogue = " + mousedOverDialogue, 698, 424); } private void updateMouseOverState() { if (mouseDragY > 393) { // if mouse is in dialogue window if (mouseDragY > 450 && mouseDragY < 494) { mousedOverDialogue = 1; } else if (mouseDragY > 494 && mouseDragY < 544) { mousedOverDialogue = 2; } else if (mouseDragY > 544) { mousedOverDialogue = 3; } } else { mousedOverDialogue = 0; } } private void updateDialogueState() { /* DIALOGUE STATE CHEAT-SHEET Dialogue State : Npc Type : Q- "Question" . A1- "Answer1" . A2- "Answer2" . A3- "Answer3". : 0 : LUMBERJACK : Q- "Hello traveller." . A1- "Hello" . A2- "Actually, never mind." . A3- null. : */ if (currentDialogueNpc.ai.equals("LUMBERJACK")) { switch (TRIGGER_dialogueState) { case 0: boolean hasQuest0 = false; boolean hasQuest1 = false; for (Quest q : player1.personalQuestLog) { if (q.questID == 0) { hasQuest0 = true; } if (q.questID == 1) { hasQuest1 = true; } } if (player1.personalQuestsCompleted.contains(0) && !hasQuest1) { // )f played already has completed the quest TRIGGER_dialogueState = 5; } else { if (hasQuest1) { TRIGGER_dialogueState = 9; } else if (hasQuest0) { TRIGGER_dialogueState = 3; } else { npcDialogue = currentDialogueNpc.dialogue[0]; playerResponse1 = "- " + currentDialogueNpc.dialogue[1]; playerResponse2 = "- " + currentDialogueNpc.dialogue[2]; playerResponse3 = "- "; } } break; case 1: npcDialogue = currentDialogueNpc.dialogue[3]; playerResponse1 = "- " + currentDialogueNpc.dialogue[4]; playerResponse2 = "- " + currentDialogueNpc.dialogue[5]; playerResponse3 = "- " + currentDialogueNpc.dialogue[2]; break; case 2: npcDialogue = currentDialogueNpc.dialogue[6]; playerResponse1 = "- " + currentDialogueNpc.dialogue[7]; playerResponse2 = "- " + currentDialogueNpc.dialogue[5]; playerResponse3 = "- " + currentDialogueNpc.dialogue[2]; break; case 3: npcDialogue = currentDialogueNpc.dialogue[11]; playerResponse1 = "- " + currentDialogueNpc.dialogue[2]; playerResponse2 = "- " + currentDialogueNpc.dialogue[7]; playerResponse3 = "- "; break; case 4: npcDialogue = currentDialogueNpc.dialogue[9]; playerResponse1 = "- " + currentDialogueNpc.dialogue[8]; playerResponse2 = "- " + currentDialogueNpc.dialogue[10]; playerResponse3 = "- "; break; case 5: npcDialogue = currentDialogueNpc.dialogue[20]; playerResponse1 = "- " + currentDialogueNpc.dialogue[1]; playerResponse2 = "- " + currentDialogueNpc.dialogue[2]; playerResponse3 = "- "; break; case 6: npcDialogue = currentDialogueNpc.dialogue[3]; playerResponse1 = "- " + currentDialogueNpc.dialogue[4]; playerResponse2 = "- " + currentDialogueNpc.dialogue[5]; playerResponse3 = "- " + currentDialogueNpc.dialogue[2]; break; case 7: npcDialogue = currentDialogueNpc.dialogue[18]; playerResponse1 = "- " + currentDialogueNpc.dialogue[7]; playerResponse2 = "- " + currentDialogueNpc.dialogue[5]; playerResponse3 = "- "; break; case 8: npcDialogue = currentDialogueNpc.dialogue[19]; playerResponse1 = "- " + currentDialogueNpc.dialogue[7]; playerResponse2 = "- "; playerResponse3 = "- "; break; case 9: npcDialogue = currentDialogueNpc.dialogue[21]; playerResponse1 = "- " + currentDialogueNpc.dialogue[7]; playerResponse2 = "- "; playerResponse3 = "- "; break; default: npcDialogue = "- "; playerResponse1 = "- "; playerResponse2 = "- "; playerResponse3 = "- "; } } else if (currentDialogueNpc.ai.equals("CASTLEGUARD")) { switch (TRIGGER_dialogueState) { case 0: boolean hasQuest1 = false; for (Quest q : player1.personalQuestLog) { if (q.questID == 1) { hasQuest1 = true; } } if (false) { // )f played already has completed the quest } else { if (hasQuest1) { TRIGGER_dialogueState = 1; } else { npcDialogue = currentDialogueNpc.dialogue[0]; playerResponse1 = "- " + currentDialogueNpc.dialogue[1]; playerResponse2 = "- "; playerResponse3 = "- "; } } break; case 1: npcDialogue = currentDialogueNpc.dialogue[2]; playerResponse1 = "- " + currentDialogueNpc.dialogue[3]; playerResponse2 = "- " + currentDialogueNpc.dialogue[4]; playerResponse3 = "- "; break; case 2: npcDialogue = currentDialogueNpc.dialogue[5]; playerResponse1 = "- " + currentDialogueNpc.dialogue[6]; playerResponse2 = "- " + currentDialogueNpc.dialogue[4]; playerResponse3 = "- "; break; case 3: npcDialogue = currentDialogueNpc.dialogue[0]; playerResponse1 = "- " + currentDialogueNpc.dialogue[1]; playerResponse2 = "- "; playerResponse3 = "- "; break; } } } private void paintRain2(Graphics g) { } private void paintInventoryItemTooltip(Graphics g) { Graphics2D g2d = (Graphics2D) g; int borderWidth = 120; int borderHeight = 60; if (mouseDragX > 677 && mouseDragY < 767) { g2d.setColor(Color.lightGray); g2d.fillRect(mouseDragX - borderWidth, mouseDragY - borderHeight, borderWidth, borderHeight); g2d.setStroke(new BasicStroke(3)); g2d.setColor(Color.black); g2d.drawRect(mouseDragX - borderWidth, mouseDragY - borderHeight, borderWidth, borderHeight); g2d.setFont(font2_16); g2d.drawString("ID: " + String.valueOf(currentHoverItem.ID), mouseDragX - borderWidth + 5, mouseDragY - borderHeight + 17); } else { // g2d.drawRect(mouseDragX, mouseDragY - borderHeight, borderWidth, borderHeight); g2d.setColor(Color.lightGray); g2d.fillRect(mouseDragX, mouseDragY - borderHeight, borderWidth, borderHeight); g2d.setStroke(new BasicStroke(3)); g2d.setColor(Color.black); g2d.drawRect(mouseDragX, mouseDragY - borderHeight, borderWidth, borderHeight); g2d.setFont(font2_16); g2d.drawString("ID: " + String.valueOf(currentHoverItem.ID), mouseDragX + 5, mouseDragY - borderHeight + 17); } } private void paintChosenAbilities(Graphics g) { for (int i = 0; i < 3; i++) { g.drawRect(24 + (30 * i), 440, 30, 30); } switch (abilities[0]) { case 1: g.drawImage(bufferedImageMap.get("ABILITY_MHAND_SLICE"), 24, 440, 30, 30, this); break; case 2: g.drawImage(bufferedImageMap.get("ABILITY_MHAND_STAB"), 24, 440, 30, 30, this); break; case 3: g.drawImage(bufferedImageMap.get("ABILITY_OHAND_BLOCK"), 24, 440, 30, 30, this); break; } switch (abilities[1]) { case 1: g.drawImage(bufferedImageMap.get("ABILITY_MHAND_SLICE"), 24 + 30, 440, 30, 30, this); break; case 2: g.drawImage(bufferedImageMap.get("ABILITY_MHAND_STAB"), 24 + 30, 440, 30, 30, this); break; case 3: g.drawImage(bufferedImageMap.get("ABILITY_OHAND_BLOCK"), 24 + 30, 440, 30, 30, this); break; } switch (abilities[2]) { case 1: g.drawImage(bufferedImageMap.get("ABILITY_MHAND_SLICE"), 24 + 60, 440, 30, 30, this); break; case 2: g.drawImage(bufferedImageMap.get("ABILITY_MHAND_STAB"), 24 + 60, 440, 30, 30, this); break; case 3: g.drawImage(bufferedImageMap.get("ABILITY_OHAND_BLOCK"), 24 + 60, 440, 30, 30, this); break; } } private void paintAttackStyleChooser(Graphics g) { g.setColor(Color.lightGray); g.fillRect(25, 356, 300, 120); g.setColor(Color.black); g.setFont(font2_16); g.drawString("Choose your skills", 25, 376); g.drawString("Active Skills", 25, 433); for (int i = 0; i < 8; i++) { g.drawRect(25 + (30 * i), 386, 30, 30); } g.drawImage(bufferedImageMap.get("ABILITY_MHAND_SLICE"), 30, 386, this); g.drawImage(bufferedImageMap.get("ABILITY_MHAND_STAB"), 60, 386, this); g.drawImage(bufferedImageMap.get("ABILITY_OHAND_BLOCK"), 90, 386, this); } private void paintQuickslotGUI(Graphics g) { if (mouseDragX > 730 && mouseDragX < 773 && mouseDragY > 26 && mouseDragY < 62) { g.drawImage(bufferedImageMap.get("BAG_ICON"), 730 - 10, 20 - 10, 60, 60, this); } else { g.drawImage(bufferedImageMap.get("BAG_ICON"), 730, 20, 40, 40, this); } if (mouseDragX > 678 && mouseDragX < 728 && mouseDragY > 26 && mouseDragY < 62) { g.drawImage(bufferedImageMap.get("CRAFTING_ICON"), 688 - 15, 20 - 17, 60, 60, this); } else { g.drawImage(bufferedImageMap.get("CRAFTING_ICON"), 678, 15, 40, 40, this); } if (mouseDragX > 626 && mouseDragX < 666 && mouseDragY > 26 && mouseDragY < 62) { g.drawImage(bufferedImageMap.get("RED_DAGGER_WEST"), 616, 20 - 17, 60, 60, this); } else { g.drawImage(bufferedImageMap.get("RED_DAGGER_WEST"), 628, 15, 40, 40, this); } } private void paintCombatSequence(Graphics g) { if (checkForEndOfTurnTrigger()) { return; } g.drawImage(bufferedImageMap.get("BACKGROUNDIMG_COMBAT_0"), 0, 0, this); player1.xPos = 340; player1.yPos = 100; player1.orientation = "SOUTH"; paintPlayer(g, 5); if (Objects.equals(currentNpc.ai, "SHEEP")) { if (animation_frame % 2 == 0) { g.drawImage(bufferedImageMap.get("NORTH_SHEEP"), 351, 311, 400, 400, this); } else { g.drawImage(bufferedImageMap.get("NORTH_SHEEP"), 351, 311 - 50, 400, 400, this); } } } private void paintPlayerGearInterface(Graphics g) { g.setColor(Color.white); g.fillRect(663, 512, 25, 25); // HELM LOCATION g.fillRect(663, 542, 25, 25); // CHEST LOCATION g.fillRect(663, 572, 25, 25); // PANTS LOCATION g.fillRect(693, 542, 25, 25); // OFFHAND LOCATION g.fillRect(633, 542, 25, 25); // MAINHAND LOCATION g.setColor(Color.black); g.drawRect(663, 512, 25, 25); g.drawRect(663, 542, 25, 25); g.drawRect(663, 572, 25, 25); g.drawRect(693, 542, 25, 25); g.drawRect(633, 542, 25, 25); g.setFont(font1_8); switch (player1.gearInterface.itemArray[0].ID) { // HELMET ZONE case 5: g.drawImage(bufferedImageMap.get("RATSKINHOOD"), 663, 512, 25, 25, this); break; case 0: break; default: g.drawString("ERROR", 663, 512); break; } switch (player1.gearInterface.itemArray[1].ID) { // CHEST ZONE case 6: g.drawImage(bufferedImageMap.get("RAGGEDSHIRT"), 661, 545, 30, 30, this); break; case 24: g.drawImage(bufferedImageMap.get("GREEN_PLATEBODY_TRIMMED"), 663, 542, 25, 25, this); break; case 23: g.drawImage(bufferedImageMap.get("GREEN_PLATEBODY"), 663, 542, 25, 25, this); break; case 29: g.drawImage(bufferedImageMap.get("BROWN_PLATEBODY"), 663, 542, 25, 25, this); break; case 30: g.drawImage(bufferedImageMap.get("BROWN_PLATEBODY_TRIMMED"), 663, 542, 25, 25, this); break; case 16: g.drawImage(bufferedImageMap.get("BLUE_PLATEBODY"), 663, 542, 25, 25, this); break; case 17: g.drawImage(bufferedImageMap.get("BLUE_PLATEBODY_TRIMMED"), 663, 542, 25, 25, this); break; case 0: break; default: g.drawString("ERROR", 663, 542); break; } switch (player1.gearInterface.itemArray[2].ID) { // LEG ZONE case 7: g.drawImage(bufferedImageMap.get("RATSKINPANTS"), 663, 572, 25, 25, this); break; case 14: g.drawImage(bufferedImageMap.get("BLUE_LEGGUARDS"), 663, 572, 25, 25, this); break; case 15: g.drawImage(bufferedImageMap.get("BLUE_LEGGUARDS_TRIMMED"), 663, 572, 25, 25, this); break; case 21: g.drawImage(bufferedImageMap.get("GREEN_LEGGUARDS"), 663, 572, 25, 25, this); break; case 22: g.drawImage(bufferedImageMap.get("GREEN_LEGGUARDS_TRIMMED"), 663, 572, 25, 25, this); break; case 27: g.drawImage(bufferedImageMap.get("JUNKSCRAP_LEGGUARDS"), 663, 572, 25, 25, this); break; case 28: g.drawImage(bufferedImageMap.get("JUNKSCRAP_LEGGUARDS_TRIMMED"), 663, 572, 25, 25, this); break; case 0: break; default: g.drawString("ERROR", 663, 572); break; } switch (player1.gearInterface.itemArray[3].ID) { // Todo: BOOT ZONE (NOT YET IMPLEMENTED) case 8: break; default: // g.drawString("ERROR",663,572); break; } switch (player1.gearInterface.itemArray[4].ID) { //OFFHAND ZONE case 10: g.drawImage(bufferedImageMap.get("WOODEN_SHIELD"), 694, 543, 25, 25, this); break; case 11: g.drawImage(bufferedImageMap.get("BLUE_BUCKLER"), 694, 543, 25, 25, this); break; case 12: g.drawImage(bufferedImageMap.get("BLUE_BUCKLER_TRIMMED"), 694, 543, 25, 25, this); break; case 18: g.drawImage(bufferedImageMap.get("GREEN_BUCKLER"), 694, 543, 25, 25, this); break; case 19: g.drawImage(bufferedImageMap.get("GREEN_BUCKLER_TRIMMED"), 694, 543, 25, 25, this); break; case 25: g.drawImage(bufferedImageMap.get("JUNKSCRAP_BUCKLER"), 694, 543, 25, 25, this); break; case 26: g.drawImage(bufferedImageMap.get("JUNKSCRAP_BUCKLER_TRIMMED"), 694, 543, 25, 25, this); break; case 0: break; default: g.drawString("ERROR", 693, 543); break; } switch (player1.gearInterface.itemArray[5].ID) { // MAINHAND ZONE case 9: g.drawImage(bufferedImageMap.get("WOODEN_CLUB_W"), 633, 543, 25, 25, this); break; case 13: g.drawImage(bufferedImageMap.get("BLUE_DAGGER_WEST"), 633, 543, 25, 25, this); break; case 31: g.drawImage(bufferedImageMap.get("RED_DAGGER_WEST"), 633, 543, 25, 25, this); break; case 20: g.drawImage(bufferedImageMap.get("GREEN_DAGGER_WEST"), 633, 543, 25, 25, this); break; case 32: g.drawImage(bufferedImageMap.get("LUMBERJACK_AXE_WEST"), 633, 543, 25, 25, this); break; case 33: g.drawImage(bufferedImageMap.get("MINER_PICKAXE_WEST"), 633, 543, 25, 25, this); break; case 38: g.drawImage(bufferedImageMap.get("YELLOW_PICKAXE_WEST"), 633, 543, 25, 25, this); break; case 39: g.drawImage(bufferedImageMap.get("BLUE_PICKAXE_WEST"), 633, 543, 25, 25, this); break; case 40: g.drawImage(bufferedImageMap.get("GREEN_PICKAXE_WEST"), 633, 543, 25, 25, this); break; case 41: g.drawImage(bufferedImageMap.get("RED_PICKAXE_WEST"), 633, 543, 25, 25, this); break; case 46: g.drawImage(bufferedImageMap.get("FARMER_SHOVEL_WEST"), 633, 543, 25, 25, this); break; case 0: break; default: g.drawString("ERROR", 633, 543); break; } } private void paintSplash(Graphics g) { Point p = bufferSplashAnimations.pollFirst(); /* for(int i = 0; i < 100; i++){ g.fillOval(p.x,p.y,i,i); } */ // System.out.println("Paintdrop Destroyed @" +p.x + ", " + p.y); } private void paintCurrentlySelectedItemOnMouse(Graphics g) { if (currentItem.ID == 1) { g.drawImage(bufferedImageMap.get("INVENTORY_LUMBER"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 2) { g.drawImage(bufferedImageMap.get("T0STONE0"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 3) { g.drawImage(bufferedImageMap.get("SAND"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 4) { g.drawImage(bufferedImageMap.get("PLANKWALL"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 5) { g.drawImage(bufferedImageMap.get("RATSKINHOOD"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 6) { g.drawImage(bufferedImageMap.get("RATSKINCHEST"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 7) { g.drawImage(bufferedImageMap.get("RATSKINPANTS"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 8) { g.drawImage(bufferedImageMap.get("RATSKIN_BOOTS"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 9) { g.drawImage(bufferedImageMap.get("WOODEN_CLUB"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 10) { g.drawImage(bufferedImageMap.get("WOODEN_SHIELD"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 11) { g.drawImage(bufferedImageMap.get("BLUE_BUCKLER"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 12) { g.drawImage(bufferedImageMap.get("BLUE_BUCKLER_TRIMMED"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 13) { g.drawImage(bufferedImageMap.get("BLUE_DAGGER"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 14) { g.drawImage(bufferedImageMap.get("BLUE_LEGGUARDS"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 15) { g.drawImage(bufferedImageMap.get("BLUE_LEGGUARDS_TRIMMED"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 16) { g.drawImage(bufferedImageMap.get("BLUE_PLATEBODY"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 17) { g.drawImage(bufferedImageMap.get("BLUE_PLATEBODY_TRIMMED"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 18) { g.drawImage(bufferedImageMap.get("GREEN_BUCKLER"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 19) { g.drawImage(bufferedImageMap.get("GREEN_BUCKLER_TRIMMED"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 20) { g.drawImage(bufferedImageMap.get("GREEN_DAGGER"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 21) { g.drawImage(bufferedImageMap.get("GREEN_LEGGUARDS"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 22) { g.drawImage(bufferedImageMap.get("GREEN_LEGGUARDS_TRIMMED"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 23) { g.drawImage(bufferedImageMap.get("GREEN_PLATEBODY"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 24) { g.drawImage(bufferedImageMap.get("GREEN_PLATEBODY_TRIMMED"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 25) { g.drawImage(bufferedImageMap.get("JUNKSCRAP_BUCKLER"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 26) { g.drawImage(bufferedImageMap.get("JUNKSCRAP_BUCKLER_TRIMMED"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 27) { g.drawImage(bufferedImageMap.get("JUNKSCRAP_LEGGUARDS"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 28) { g.drawImage(bufferedImageMap.get("JUNKSCRAP_LEGGUARDS_TRIMMED"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 29) { g.drawImage(bufferedImageMap.get("BROWN_PLATEBODY"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 30) { g.drawImage(bufferedImageMap.get("BROWN_PLATEBODY_TRIMMED"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 31) { g.drawImage(bufferedImageMap.get("RED_DAGGER"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 32) { g.drawImage(bufferedImageMap.get("LUMBERJACK_AXE_WEST"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 33) { g.drawImage(bufferedImageMap.get("MINER_PICKAXE_WEST"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 34) { g.drawImage(bufferedImageMap.get("YELLOW_ORE"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 35) { g.drawImage(bufferedImageMap.get("BLUE_ORE"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 36) { g.drawImage(bufferedImageMap.get("GREEN_ORE"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 37) { g.drawImage(bufferedImageMap.get("RED_ORE"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 38) { g.drawImage(bufferedImageMap.get("YELLOW_PICKAXE"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 39) { g.drawImage(bufferedImageMap.get("BLUE_PICKAXE"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 40) { g.drawImage(bufferedImageMap.get("GREEN_PICKAXE"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 41) { g.drawImage(bufferedImageMap.get("RED_PICKAXE"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 42) { g.drawImage(bufferedImageMap.get("YELLOW_BAR"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 43) { g.drawImage(bufferedImageMap.get("BLUE_BAR"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 44) { g.drawImage(bufferedImageMap.get("GREEN_BAR"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 45) { g.drawImage(bufferedImageMap.get("RED_BAR"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 46) { g.drawImage(bufferedImageMap.get("FARMER_SHOVEL"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } } private void paintPalleteMenu(Graphics g) { g.setColor(Color.lightGray); g.fillRect(62, 15, 250, 80); g.drawImage(bufferedImageMap.get("ARROW_UP"), 80, 20, 30, 30, this); g.drawImage(bufferedImageMap.get("ARROW_DOWN"), 80, 50, 30, 30, this); g.drawImage(bufferedImageMap.get("ARROW_UP"), 197, 20, 30, 30, this); g.drawImage(bufferedImageMap.get("ARROW_DOWN"), 197, 50, 30, 30, this); g.drawImage(bufferedImageMap.get(BrushTileList.get(tileBrushIndex)), 132, 44, 30, 30, this); g.drawImage(bufferedImageMap.get("EAST_" + brushNpcList.get(npcBrushIndex)), 250, 44, 30, 30, this); } private void paintCraftingMenu(Graphics g) { g.setColor(Color.lightGray); g.fillRect(25, 125, 200, 200); g.setColor(Color.white); g.fillRect(34, 149, 90, 90); g.fillRect(157, 183, 30, 30); g.setColor(Color.black); g.fillRect(151, 233, 59, 15); // "CRAFT BUTTON" g.fillRect(151, 253, 71, 15); // "RETURN" BUTTON g.setFont(font2_16); g.drawString("Crafting", 34, 142); int counter = 0; int row = 0; for (int i = 0; i < player1.playerCrafter.itemArray.length - 1; i++) { if (counter == 3) { counter = 0; row++; } g.drawRect(34 + (counter * 30), 149 + (row * 30), 30, 30); if (player1.playerCrafter.itemArray[i].ID == 1) { g.drawImage(bufferedImageMap.get("INVENTORY_LUMBER"), 34 + (counter * 30), 149 + (row * 30), 25, 22, this); } else if (player1.playerCrafter.itemArray[i].ID == 2) { g.drawImage(bufferedImageMap.get("COBBLESTONE"), 34 + (counter * 30), 149 + (row * 30), 25, 22, this); } counter++; } g.drawRect(157, 183, 30, 30); g.setColor(Color.white); g.setFont(font2_16); g.drawString("CRAFT", 153, 247); g.drawString("CANCEL", 153, 266); if (player1.playerCrafter.itemArray[9].ID == 4) { g.drawImage(bufferedImageMap.get("PLANKWALL"), 157, 183, 30, 30, this); } else if (player1.playerCrafter.itemArray[9].ID == 32) { g.drawImage(bufferedImageMap.get("LUMBERJACK_AXE_WEST"), 157, 183, 30, 30, this); } else if (player1.playerCrafter.itemArray[9].ID == 33) { g.drawImage(bufferedImageMap.get("MINER_PICKAXE_WEST"), 157, 183, 30, 30, this); } else if (player1.playerCrafter.itemArray[9].ID == 35) { g.drawImage(bufferedImageMap.get("FARMER_SHOVEL_WEST"), 157, 183, 30, 30, this); } } private void Layer0(Graphics g) { // Tile Rendering System Npc n = new Npc(0, 0, 0, 0, Color.BLACK, ""); assert bufferedImageMap != null : "ERROR: bufferedImageMap is null"; for (int i = 0; i < 32; i++) { // foreach tile outer loop for (int j = 0; j < 24; j++) { // foreach tile inner loop String tileTypeToPaint = currentOverWorld.tilemap[i][j].type; // store tile type as string switch (tileTypeToPaint) { // Rendering unit for each tile type case "grass": g.setColor(Color.green); g.fillRect(i * 25, j * 25, 25, 25); int grassPermutation = currentOverWorld.tilemap[i][j].grassPermutation; g.drawImage(bufferedImageMap.get("GRASS" + grassPermutation), i * 25, j * 25, 25, 25, this); // draws a grass on top of each "grass" ti break; case "woodfloor": g.drawImage(bufferedImageMap.get("WOODFLOOR"), i * 25, j * 25, 25, 25, this); // draws a grass on top of each "grass" ti break; case "water": g.setColor(Color.blue); g.drawImage(bufferedImageMap.get("WATER"), i * 25, j * 25, 25, 25, this); break; case "tree": g.setColor(Color.green); g.fillRect(i * 25, j * 25, 25, 25); g.drawImage(bufferedImageMap.get("GRASS0"), i * 25, j * 25, 25, 25, this); // draws a grass g.drawImage(bufferedImageMap.get("TREE"), i * 25 - 19, j * 25 - 80, 65, 100, this); // draws a tree break; case "t0stone": g.drawImage(bufferedImageMap.get("GRASS0"), i * 25, j * 25, 25, 25, this); // draws a grass break; case "t1stone": g.drawImage(bufferedImageMap.get("GRASS0"), i * 25, j * 25, 25, 25, this); // draws a grass break; case "t2stone": g.drawImage(bufferedImageMap.get("GRASS0"), i * 25, j * 25, 25, 25, this); // draws a grass break; case "t3stone": g.drawImage(bufferedImageMap.get("GRASS0"), i * 25, j * 25, 25, 25, this); // draws a grass break; case "t4stone": g.drawImage(bufferedImageMap.get("GRASS0"), i * 25, j * 25, 25, 25, this); // draws a grass break; case "sand": g.drawImage(bufferedImageMap.get("SAND"), i * 25, j * 25, 25, 25, this); break; case "rakeddirt": g.drawImage(bufferedImageMap.get("RAKEDDIRT"), i * 25, j * 25, 25, 25, this); break; case "dirt": g.drawImage(bufferedImageMap.get("DIRT"), i * 25, j * 25, 25, 25, this); break; case "plankwall": g.drawImage(bufferedImageMap.get("GRASS0"), i * 25, j * 25, 25, 25, this); // draws a grass g.drawImage(bufferedImageMap.get("PLANKWALL"), i * 25, j * 25, 25, 25, this); break; case "stonepathgrass": g.drawImage(bufferedImageMap.get("STONEPATHGRASS"), i * 25, j * 25, 25, 25, this); break; case "woodfloordooreast": g.drawImage(bufferedImageMap.get("WOODFLOORDOOREAST"), i * 25, j * 25, 25, 25, this); break; case "woodfloordoornorth": g.drawImage(bufferedImageMap.get("WOODFLOORDOORNORTH"), i * 25, j * 25, 25, 25, this); break; case "woodfloordoorsouth": g.drawImage(bufferedImageMap.get("WOODFLOORDOORSOUTH"), i * 25, j * 25, 25, 25, this); break; case "woodfloordoorwest": g.drawImage(bufferedImageMap.get("WOODFLOORDOORWEST"), i * 25, j * 25, 25, 25, this); break; case "openwoodfloordooreast": g.drawImage(bufferedImageMap.get("WOODFLOORDOORSOUTH"), i * 25, j * 25, 25, 25, this); break; case "openwoodfloordoornorth": g.drawImage(bufferedImageMap.get("WOODFLOORDOOREAST"), i * 25, j * 25, 25, 25, this); break; case "openwoodfloordoorsouth": g.drawImage(bufferedImageMap.get("WOODFLOORDOORWEST"), i * 25, j * 25, 25, 25, this); break; case "openwoodfloordoorwest": g.drawImage(bufferedImageMap.get("WOODFLOORDOORNORTH"), i * 25, j * 25, 25, 25, this); break; case "woodenfencehorizontal": g.drawImage(bufferedImageMap.get("GRASS"), i * 25, j * 25, 25, 25, this); // draws a grass break; case "woodenfencevertical": g.drawImage(bufferedImageMap.get("GRASS"), i * 25, j * 25, 25, 25, this); // draws a grass break; case "woodenfencenwcorner": g.drawImage(bufferedImageMap.get("GRASS0"), i * 25, j * 25, 25, 25, this); // draws a grass break; case "woodenfencenecorner": g.drawImage(bufferedImageMap.get("GRASS0"), i * 25, j * 25, 25, 25, this); // draws a grass break; case "woodenfencesecorner": g.drawImage(bufferedImageMap.get("GRASS0"), i * 25, j * 25, 25, 25, this); // draws a grass break; case "woodenfenceswcorner": g.drawImage(bufferedImageMap.get("GRASS0"), i * 25, j * 25, 25, 25, this); // draws a grass break; case "t0stone_1x2_a": g.drawImage(bufferedImageMap.get("GRASS0"), i * 25, j * 25, 25, 25, this); // draws a grass break; case "t0stone_1x2_b": g.drawImage(bufferedImageMap.get("GRASS0"), i * 25, j * 25, 25, 25, this); // draws a grass break; case "t1stone_1x2_a": g.drawImage(bufferedImageMap.get("GRASS0"), i * 25, j * 25, 25, 25, this); // draws a grass break; case "t1stone_1x2_b": g.drawImage(bufferedImageMap.get("GRASS0"), i * 25, j * 25, 25, 25, this); // draws a grass break; case "t2stone_1x2_a": g.drawImage(bufferedImageMap.get("GRASS0"), i * 25, j * 25, 25, 25, this); // draws a grass break; case "t2stone_1x2_b": g.drawImage(bufferedImageMap.get("GRASS0"), i * 25, j * 25, 25, 25, this); // draws a grass break; case "furnace": g.drawImage(bufferedImageMap.get("GRASS0"), i * 25, j * 25, 25, 25, this); // draws a grass break; case "cookingpot": g.drawImage(bufferedImageMap.get("GRASS0"), i * 25, j * 25, 25, 25, this); // draws a grass break; default: g.setColor(Color.red); g.drawString("ERR", i * 25, j * 25 + 25); break; } } } } private void Layer1(Graphics g) { assert bufferedImageMap != null : "ERROR: bufferedImageMap is null"; for (int j = 0; j < 24; j++) { // foreach tile outer loop for (int i = 31; i > 0; i--) { // foreach tile inner loop String tileTypeToPaint = currentOverWorld.tilemap[i][j].type; // store tile type as string switch (tileTypeToPaint) { // Rendering unit for each tile type case "tree": g.drawImage(bufferedImageMap.get("TREE"), i * 25 - 19, j * 25 - 80, 65, 100, this); // draws a tree break; case "t0stone": g.drawImage(bufferedImageMap.get("T0STONE" + String.valueOf(currentOverWorld.tilemap[i][j].rockPermutation)), i * 25, j * 25 - 5, 25, 25, this); // draws a tree break; case "t1stone": g.drawImage(bufferedImageMap.get("T1STONE" + String.valueOf(currentOverWorld.tilemap[i][j].rockPermutation)), i * 25, j * 25 - 5, 25, 25, this); // draws a tree break; case "t2stone": g.drawImage(bufferedImageMap.get("T2STONE" + String.valueOf(currentOverWorld.tilemap[i][j].rockPermutation)), i * 25, j * 25 - 5, 25, 25, this); // draws a tree break; case "t3stone": g.drawImage(bufferedImageMap.get("T3STONE" + String.valueOf(currentOverWorld.tilemap[i][j].rockPermutation)), i * 25, j * 25 - 5, 25, 25, this); // draws a tree break; case "t4stone": g.drawImage(bufferedImageMap.get("T4STONE" + String.valueOf(currentOverWorld.tilemap[i][j].rockPermutation)), i * 25, j * 25 - 5, 25, 25, this); // draws a tree break; case "woodenfencehorizontal": g.drawImage(bufferedImageMap.get("WOODENFENCEHORIZONTAL"), i * 25, j * 25, 25, 25, this); break; case "woodenfencevertical": g.drawImage(bufferedImageMap.get("WOODENFENCEVERTICAL"), i * 25, j * 25, 25, 25, this); break; case "woodenfencenwcorner": g.drawImage(bufferedImageMap.get("WOODENFENCENWCORNER"), i * 25, j * 25, 25, 25, this); break; case "woodenfenceswcorner": g.drawImage(bufferedImageMap.get("WOODENFENCESWCORNER"), i * 25, j * 25, 25, 25, this); break; case "woodenfencenecorner": g.drawImage(bufferedImageMap.get("WOODENFENCENECORNER"), i * 25, j * 25, 25, 25, this); break; case "woodenfencesecorner": g.drawImage(bufferedImageMap.get("WOODENFENCESECORNER"), i * 25, j * 25, 25, 25, this); break; case "t0stone_1x2_a": g.drawImage(bufferedImageMap.get("T0STONE" + currentOverWorld.tilemap[i][j].rockPermutation + "_1x2"), i * 25 + 5, j * 25 - 8, 35, 35, this); break; case "t1stone_1x2_a": g.drawImage(bufferedImageMap.get("T1STONE" + currentOverWorld.tilemap[i][j].rockPermutation + "_1x2"), i * 25 + 5, j * 25 - 8, 35, 35, this); break; case "t2stone_1x2_a": g.drawImage(bufferedImageMap.get("T2STONE" + currentOverWorld.tilemap[i][j].rockPermutation + "_1x2"), i * 25, j * 25 - 8, 35, 35, this); break; case "furnace": if (currentOverWorld.tilemap[i][j].activeState) { g.drawImage(bufferedImageMap.get("FURNACE_LIT"), i * 25, j * 25 - 25, this); } else { g.drawImage(bufferedImageMap.get("FURNACE_UNLIT"), i * 25, j * 25 - 25, this); } break; case "cookingpot": g.drawImage(bufferedImageMap.get("COOKING_POT"), i * 25, j * 25, 25, 25, this); break; } if (player1.xPos / 25 == i && player1.yPos / 25 == j) { paintPlayer(g, 1); } for (Npc n : currentOverWorld.npcList) { if (j == n.yPos / 25 && i == n.xPos / 25) { paintNpcs(g, n); } } } } } private void paintRain(Graphics g) { Graphics2D g2d = (Graphics2D) g; g2d.setColor(Color.red); g2d.setStroke(new BasicStroke(2)); g.setColor(Color.blue); for (Point p : rainDrops) { g2d.drawLine(p.x, p.y, p.x + 10, p.y + 10); } moveRain(); g2d.setStroke(new BasicStroke(1)); } private void moveRain() { for (int i = 0; i < rainDrops.length; i++) { int gravity = (rotateRng() % (12)); rainDrops[i].x += gravity; rainDrops[i].y += gravity; } for (int i = 0; i < rainDrops.length; i++) { int wind = (rotateRng() % (6)); rainDrops[i].x += wind * rainVector; } destroyRandomRaindrops(); replaceOutOfScreenRain(); } private void destroyRandomRaindrops() { int rng = (int) (Math.random() * (5000)); if (rng > 4990) { rainVector = -rainVector; } if (rng > 2500) { int rainDropIndexToDestroy = (int) (Math.random() * (rainDrops.length)); // bufferSplashAnimations.offerFirst(new Point(rainDrops[rainDropIndexToDestroy].x, rainDrops[rainDropIndexToDestroy].y)); rainDrops[rainDropIndexToDestroy].x = (int) (Math.random() * (Main.WIDTH)); rainDrops[rainDropIndexToDestroy].y = (int) (Math.random() * (Main.WIDTH)); } } private void replaceOutOfScreenRain() { for (int i = 0; i < rainDrops.length; i++) { if (rainDrops[i].x > Main.WIDTH || rainDrops[i].y > Main.HEIGHT) { rainDrops[i].x = (int) (Math.random() * (Main.WIDTH)); rainDrops[i].y = (int) (Math.random() * (Main.HEIGHT)); } } } private void paintCurrentlySelectedItemHighlights(Graphics g) { Graphics2D g2d = (Graphics2D) g; g2d.setColor(Color.red); g2d.setStroke(new BasicStroke(2)); if (inventoryMenuVisible && currentItem != null && currentItem.equals(player1.playerCrafter.itemArray[9])) { g2d.drawRect(156, 183, 30, 30); } else if (inventoryMenuVisible && currentItem != null) { g2d.drawRect(587 + ((currentItemColumn - 1) * 30), 176 + ((currentItemRow - 1) * 30), 30, 30); } g2d.setStroke(new BasicStroke(1)); } private void paintCurrentlySelectedTileHighlights(Graphics g) { Graphics2D g2d = (Graphics2D) g; g2d.setColor(Color.yellow); g2d.setStroke(new BasicStroke(2)); g2d.drawRect(currentTileX * 25, currentTileY * 25, 25, 25); g2d.setStroke(new BasicStroke(1)); } private void paintInventory(Graphics g) { g.setColor(Color.lightGray); g.fillRect(575, 149, 200, 600); g.setFont(font3_24); g.setColor(Color.black); g.drawString("Inventory", 585, 167); g.setColor(Color.white); g.fillRect(588, 176, 180, 329); g.setColor(Color.black); int counter = 0; int row = 0; for (int i = 0; i < player1.playerInventory.itemArray.length; i++) { if (counter == 6) { counter = 0; row++; } if (player1.playerInventory.itemArray[i].ID == 1) { g.drawImage(bufferedImageMap.get("INVENTORY_LUMBER"), 593 + (counter * 30) - 5, 183 + (row * 30) - 5, 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 2) { g.drawImage(bufferedImageMap.get("COBBLESTONE"), 593 + (counter * 30) - 5, 183 + (row * 30) - 5, 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 3) { g.drawImage(bufferedImageMap.get("SAND"), 593 + (counter * 30) - 5, 183 + (row * 30) - 5, 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 4) { g.drawImage(bufferedImageMap.get("PLANKWALL"), 593 + (counter * 30), 183 + (row * 30), 20, 20, this); } else if (player1.playerInventory.itemArray[i].ID == 5) { g.drawImage(bufferedImageMap.get("RATSKINHOOD"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 6) { g.drawImage(bufferedImageMap.get("RAGGEDSHIRT"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 7) { g.drawImage(bufferedImageMap.get("RATSKINPANTS"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 8) { g.drawImage(bufferedImageMap.get("ERROR_IMG"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); // g.drawImage(bufferedImageMap.get("RATSKIN_BOOTS"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 9) { g.drawImage(bufferedImageMap.get("WOODEN_CLUB_W"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 10) { g.drawImage(bufferedImageMap.get("WOODEN_SHIELD"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 11) { g.drawImage(bufferedImageMap.get("BLUE_BUCKLER"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 12) { g.drawImage(bufferedImageMap.get("BLUE_BUCKLER_TRIMMED"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 13) { g.drawImage(bufferedImageMap.get("BLUE_DAGGER_EAST"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 14) { g.drawImage(bufferedImageMap.get("BLUE_LEGGUARDS"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 15) { g.drawImage(bufferedImageMap.get("BLUE_LEGGUARDS_TRIMMED"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 16) { g.drawImage(bufferedImageMap.get("BLUE_PLATEBODY"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 17) { g.drawImage(bufferedImageMap.get("BLUE_PLATEBODY_TRIMMED"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 18) { g.drawImage(bufferedImageMap.get("GREEN_BUCKLER"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 19) { g.drawImage(bufferedImageMap.get("GREEN_BUCKLER_TRIMMED"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 20) { g.drawImage(bufferedImageMap.get("GREEN_DAGGER_EAST"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 21) { g.drawImage(bufferedImageMap.get("GREEN_LEGGUARDS"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 22) { g.drawImage(bufferedImageMap.get("GREEN_LEGGUARDS_TRIMMED"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 23) { g.drawImage(bufferedImageMap.get("GREEN_PLATEBODY"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 24) { g.drawImage(bufferedImageMap.get("GREEN_PLATEBODY_TRIMMED"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 25) { g.drawImage(bufferedImageMap.get("JUNKSCRAP_BUCKLER"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 26) { g.drawImage(bufferedImageMap.get("JUNKSCRAP_BUCKLER_TRIMMED"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 27) { g.drawImage(bufferedImageMap.get("JUNKSCRAP_LEGGUARDS"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 28) { g.drawImage(bufferedImageMap.get("JUNKSCRAP_LEGGUARDS_TRIMMED"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 29) { g.drawImage(bufferedImageMap.get("BROWN_PLATEBODY"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 30) { g.drawImage(bufferedImageMap.get("BROWN_PLATEBODY_TRIMMED"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 31) { g.drawImage(bufferedImageMap.get("RED_DAGGER_EAST"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 32) { g.drawImage(bufferedImageMap.get("LUMBERJACK_AXE_EAST"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 33) { g.drawImage(bufferedImageMap.get("MINER_PICKAXE_EAST"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 34) { g.drawImage(bufferedImageMap.get("YELLOW_ORE"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 35) { g.drawImage(bufferedImageMap.get("BLUE_ORE"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 36) { g.drawImage(bufferedImageMap.get("GREEN_ORE"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 37) { g.drawImage(bufferedImageMap.get("RED_ORE"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 38) { g.drawImage(bufferedImageMap.get("YELLOW_PICKAXE_EAST"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 39) { g.drawImage(bufferedImageMap.get("BLUE_PICKAXE_EAST"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 40) { g.drawImage(bufferedImageMap.get("GREEN_PICKAXE_EAST"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 41) { g.drawImage(bufferedImageMap.get("RED_PICKAXE_EAST"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 42) { g.drawImage(bufferedImageMap.get("YELLOW_BAR"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 43) { g.drawImage(bufferedImageMap.get("BLUE_BAR"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 44) { g.drawImage(bufferedImageMap.get("GREEN_BAR"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 45) { g.drawImage(bufferedImageMap.get("RED_BAR"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 46) { g.drawImage(bufferedImageMap.get("FARMER_SHOVEL_EAST"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } g.setColor(Color.black); g.drawRect(587 + (counter * 30), 176 + (row * 30), 30, 30); counter++; } paintGold(g); } private void paintGold(Graphics g) { g.setColor(Color.black); g.drawString("Gold: " + player1.gold, 690, 528); } private void paintOrientationArrow(Graphics g) { g.setColor(Color.black); switch (player1.orientation) { case "EAST": g.drawLine(player1.xPos + 10, player1.yPos + 10, player1.xPos + 20, player1.yPos + 10); break; case "WEST": g.drawLine(player1.xPos + 10, player1.yPos + 10, player1.xPos, player1.yPos + 10); break; case "NORTH": g.drawLine(player1.xPos + 10, player1.yPos + 10, player1.xPos + 10, player1.yPos); break; case "SOUTH": g.drawLine(player1.xPos + 10, player1.yPos + 10, player1.xPos + 10, player1.yPos + 20); break; } } private void paintDebugMenu(Graphics g) { g.setColor(Color.gray); g.fillRect(24, 450, 300, 124); g.setColor(Color.black); g.setFont(font2_16); g.drawString("player1 TrueCoords: (" + player1.xPos + ", " + player1.yPos + ")", 37, 465); g.drawString("player1 TileCoords: (" + (player1.xPos / 25) + ", " + (player1.yPos / 25) + ")", 37, 490); int player1_TileCoordinated_xPos = (player1.xPos / 25); int player1_TileCoordinated_yPos = (player1.yPos / 25); g.drawString("player1 standing on tile: " + currentOverWorld.tilemap[player1_TileCoordinated_xPos][player1_TileCoordinated_yPos].type, 37, 515); g.drawString("Farmable? " + (currentOverWorld.tilemap[player1_TileCoordinated_xPos][player1_TileCoordinated_yPos].farmable ? "yes" : "no"), 88, 532); g.drawString("action ticker: (" + actionTick + ")", 39, 556); } private void paintStartMenu(Graphics g) { g.setColor(Color.gray); g.fillRect(24, 1, 750, 600); g.setColor(Color.black); g.setFont(font2_16); if (worldExists) { g.drawString("World ready", 87, 220); } else { g.drawString("No world spawned", 87, 220); } g.drawImage(bufferedImageMap.get("GEARWORKS_LOGO"), 0, 275, Main.WIDTH, 325, this); } private void paintViewMenu(Graphics g) { g.setColor(Color.gray); g.fillRect(363, 452, 300, 100); g.setColor(Color.black); g.setFont(font2_16); if (currentTile != null) { g.drawString(currentTile.type, 373, 468); if (currentTile.farmable) { g.drawString("Farmable", 373, 488); } if (currentTile.occupied) { g.drawString("Obstacle", 373, 508); } } } private void paintNpcs(Graphics g, Npc n) { if (n.ai.equals("SHEEP")) { int xOffset = 0; int yOffset = 0; if (n.orientation.equals("NORTH")) { xOffset = 4; yOffset = 6; } else if (n.orientation.equals("SOUTH")) { xOffset = 5; yOffset = 6; } else if (n.orientation.equals("WEST")) { xOffset = 6; yOffset = 5; } else if (n.orientation.equals("EAST")) { xOffset = 4; yOffset = 3; } g.drawImage(bufferedImageMap.get(n.orientation + "_" + n.ai), n.xPos - xOffset, n.yPos - yOffset, 30, 30, this); } else if (n.ai.equals("CHASER")) { int xOffset = 0; int yOffset = 0; if (n.orientation.equals("NORTH")) { xOffset = 4; yOffset = 20; } else if (n.orientation.equals("SOUTH")) { xOffset = 5; yOffset = 20; } else if (n.orientation.equals("WEST")) { xOffset = 6; yOffset = 19; } else if (n.orientation.equals("EAST")) { xOffset = 4; yOffset = 19; } g.drawImage(bufferedImageMap.get(n.orientation + "_" + n.ai), n.xPos - xOffset, n.yPos - yOffset, 30, 45, this); } else if (n.ai.equals("LUMBERJACK")) { int xOffset = 0; int yOffset = 0; switch (n.orientation) { case "NORTH": xOffset = 0; yOffset = 0; break; case "SOUTH": xOffset = 0; yOffset = 0; break; case "WEST": xOffset = 0; yOffset = 0; break; case "EAST": xOffset = 0; yOffset = +18; break; } g.drawImage(bufferedImageMap.get(n.orientation + "_" + n.ai), n.xPos - xOffset, n.yPos - yOffset, 40,40, this); } else if (n.ai.equals("CASTLEGUARD")) { int xOffset = 0; int yOffset = 0; switch (n.orientation) { case "NORTH": xOffset = 0; yOffset = 0; break; case "SOUTH": xOffset = 0; yOffset = 0; break; case "WEST": xOffset = 0; yOffset = 0; break; case "EAST": xOffset = 0; yOffset = +18; break; } g.drawImage(bufferedImageMap.get(n.orientation + "_" + n.ai), n.xPos - xOffset, n.yPos - yOffset, 40, 40, this); } else if (n.ai.equals("CHEF")) { int xOffset = 0; int yOffset = 0; switch (n.orientation) { case "NORTH": xOffset = 0; yOffset = 0; break; case "SOUTH": xOffset = 0; yOffset = 0; break; case "WEST": xOffset = 0; yOffset = 0; break; case "EAST": xOffset = 0; yOffset = 27; break; } g.drawImage(bufferedImageMap.get(n.orientation + "_" + n.ai), n.xPos - xOffset, n.yPos - yOffset, this); } } private void paintPlayer(Graphics g, int magnitude) { assert bufferedImageMap != null : "ERROR: bufferedImageMap is null"; // paintOrientationArrow(g); switch (player1.orientation) { // DRAWS A NAKED PLAYER CHARACTER case "NORTH": paintShield(g, magnitude); paintWeapon(g, magnitude); g.drawImage(bufferedImageMap.get("NORTH_PLAYER"), player1.xPos - 4, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); paintArmor(g, magnitude); paintLegs(g, magnitude); break; case "SOUTH": g.drawImage(bufferedImageMap.get("SOUTH_PLAYER"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); paintArmor(g, magnitude); paintLegs(g, magnitude); paintShield(g, magnitude); paintWeapon(g, magnitude); break; case "EAST": paintShield(g, magnitude); g.drawImage(bufferedImageMap.get("EAST_PLAYER"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); paintArmor(g, magnitude); paintLegs(g, magnitude); paintWeapon(g, magnitude); break; case "WEST": paintWeapon(g, magnitude); g.drawImage(bufferedImageMap.get("WEST_PLAYER"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); paintArmor(g, magnitude); paintLegs(g, magnitude); paintShield(g, magnitude); break; default: g.setColor(player1.pallete); g.fillOval(player1.xPos, player1.yPos, 20, 20); break; } } private void paintLegs(Graphics g, int magnitude) { if (magnitude == 1) { switch (player1.orientation) { // SOUTH-FACING RENDERING UNIT case "SOUTH": { switch (player1.gearInterface.itemArray[2].ID) { // SOUTH-FACING PANTS RENDERING UNIT case 7: g.drawImage(bufferedImageMap.get("RATSKIN_PANTS_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; case 14: g.drawImage(bufferedImageMap.get("BLUE_LEGGUARDS_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; case 21: g.drawImage(bufferedImageMap.get("GREEN_LEGGUARDS_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; case 22: g.drawImage(bufferedImageMap.get("GREEN_LEGGUARDS_TRIMMED_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; case 27: g.drawImage(bufferedImageMap.get("JUNKSCRAP_LEGGUARDS_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 19, this); break; case 28: g.drawImage(bufferedImageMap.get("JUNKSCRAP_LEGGUARDS_TRIMMED_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 19, this); break; } break; } case "EAST": { switch (player1.gearInterface.itemArray[2].ID) { // EAST-FACING ARMOR RENDERING UNIT case 7: g.drawImage(bufferedImageMap.get("RATSKIN_PANTS_PLAYERMODEL_EAST"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; case 14: g.drawImage(bufferedImageMap.get("BLUE_LEGGUARDS_PLAYERMODEL_EAST"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; case 21: g.drawImage(bufferedImageMap.get("GREEN_LEGGUARDS_PLAYERMODEL_EAST"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; case 22: g.drawImage(bufferedImageMap.get("GREEN_LEGGUARDS_TRIMMED_PLAYERMODEL_EAST"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; case 27: g.drawImage(bufferedImageMap.get("JUNKSCRAP_LEGGUARDS_PLAYERMODEL_EAST"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; case 28: g.drawImage(bufferedImageMap.get("JUNKSCRAP_LEGGUARDS_TRIMMED_PLAYERMODEL_EAST"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; } break; } case "NORTH": { switch (player1.gearInterface.itemArray[2].ID) { // EAST-FACING ARMOR RENDERING UNIT case 7: g.drawImage(bufferedImageMap.get("RATSKIN_PANTS_PLAYERMODEL_NORTH"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; case 14: g.drawImage(bufferedImageMap.get("BLUE_LEGGUARDS_PLAYERMODEL_NORTH"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; case 21: g.drawImage(bufferedImageMap.get("GREEN_LEGGUARDS_PLAYERMODEL_NORTH"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; case 22: g.drawImage(bufferedImageMap.get("GREEN_LEGGUARDS_TRIMMED_PLAYERMODEL_NORTH"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; case 27: g.drawImage(bufferedImageMap.get("JUNKSCRAP_LEGGUARDS_PLAYERMODEL_NORTH"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; case 28: g.drawImage(bufferedImageMap.get("JUNKSCRAP_LEGGUARDS_TRIMMED_PLAYERMODEL_NORTH"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; } break; } case "WEST": { switch (player1.gearInterface.itemArray[2].ID) { // EAST-FACING ARMOR RENDERING UNIT case 7: g.drawImage(bufferedImageMap.get("RATSKIN_PANTS_PLAYERMODEL_WEST"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; case 14: g.drawImage(bufferedImageMap.get("BLUE_LEGGUARDS_PLAYERMODEL_WEST"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; case 21: g.drawImage(bufferedImageMap.get("GREEN_LEGGUARDS_PLAYERMODEL_WEST"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; case 22: g.drawImage(bufferedImageMap.get("GREEN_LEGGUARDS_TRIMMED_PLAYERMODEL_WEST"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; case 27: g.drawImage(bufferedImageMap.get("JUNKSCRAP_LEGGUARDS_PLAYERMODEL_WEST"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; case 28: g.drawImage(bufferedImageMap.get("JUNKSCRAP_LEGGUARDS_TRIMMED_PLAYERMODEL_WEST"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; } } break; } } if (magnitude == 5) { switch (player1.orientation) { // SOUTH-FACING RENDERING UNIT case "SOUTH": { switch (player1.gearInterface.itemArray[2].ID) { // SOUTH-FACING PANTS RENDERING UNIT case 7: g.drawImage(bufferedImageMap.get("RATSKIN_PANTS_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; case 14: g.drawImage(bufferedImageMap.get("BLUE_LEGGUARDS_PLAYERMODEL_SOUTH"), player1.xPos - 4, player1.yPos - 12, 25 * magnitude, 40 * magnitude, this); break; case 21: g.drawImage(bufferedImageMap.get("GREEN_LEGGUARDS_PLAYERMODEL_SOUTH"), player1.xPos - 4, player1.yPos - 12, 25 * magnitude, 40 * magnitude, this); break; case 22: g.drawImage(bufferedImageMap.get("GREEN_LEGGUARDS_TRIMMED_PLAYERMODEL_SOUTH"), player1.xPos - 4, player1.yPos - 12, 25 * magnitude, 40 * magnitude, this); break; case 27: // *jt Todo: ASSET IS MISSING A (MODEL/FILE) // g.drawImage(bufferedImageMap.get("JUNKSCRAP_LEGGUARDS_PLAYERMODEL_SOUTH"), player1.xPos - 5, player1.yPos - 20, this); break; case 28: // *jt Todo: ASSET IS MISSING A (MODEL/FILE) // g.drawImage(bufferedImageMap.get("JUNKSCRAP_LEGGUARDS_TRIMMED_PLAYERMODEL_SOUTH"), player1.xPos -5, player1.yPos -20, this); break; } break; } case "EAST": { switch (player1.gearInterface.itemArray[2].ID) { // EAST-FACING ARMOR RENDERING UNIT case 10: break; } break; } case "NORTH": { switch (player1.gearInterface.itemArray[2].ID) { // EAST-FACING ARMOR RENDERING UNIT case 10: break; } break; } case "WEST": { switch (player1.gearInterface.itemArray[2].ID) { // EAST-FACING ARMOR RENDERING UNIT case 10: break; } } break; } } } private void paintArmor(Graphics g, int magnitude) { if (magnitude == 1) { switch (player1.orientation) { // SOUTH-FACING RENDERING UNIT case "SOUTH": { switch (player1.gearInterface.itemArray[1].ID) { // SOUTH-FACING ARMOR RENDERING UNIT case 6: g.drawImage(bufferedImageMap.get("RAGGED_SHIRT_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 24: g.drawImage(bufferedImageMap.get("GREEN_PLATEBODY_TRIMMED_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 17: g.drawImage(bufferedImageMap.get("BLUE_PLATEBODY_TRIMMED_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 30: g.drawImage(bufferedImageMap.get("BROWN_PLATEBODY_TRIMMED_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 23: g.drawImage(bufferedImageMap.get("GREEN_PLATEBODY_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 16: g.drawImage(bufferedImageMap.get("BLUE_PLATEBODY_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 29: g.drawImage(bufferedImageMap.get("BROWN_PLATEBODY_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; } break; } case "EAST": { switch (player1.gearInterface.itemArray[1].ID) { // EAST-FACING ARMOR RENDERING UNIT case 6: g.drawImage(bufferedImageMap.get("RAGGED_SHIRT_PLAYERMODEL_EAST"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 24: g.drawImage(bufferedImageMap.get("GREEN_PLATEBODY_TRIMMED_PLAYERMODEL_EAST"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 17: g.drawImage(bufferedImageMap.get("BLUE_PLATEBODY_TRIMMED_PLAYERMODEL_EAST"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 30: g.drawImage(bufferedImageMap.get("BROWN_PLATEBODY_TRIMMED_PLAYERMODEL_EAST"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 23: g.drawImage(bufferedImageMap.get("GREEN_PLATEBODY_PLAYERMODEL_EAST"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 16: g.drawImage(bufferedImageMap.get("BLUE_PLATEBODY_PLAYERMODEL_EAST"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 29: g.drawImage(bufferedImageMap.get("BROWN_PLATEBODY_PLAYERMODEL_EAST"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; } break; } case "NORTH": { switch (player1.gearInterface.itemArray[1].ID) { // NORTH-FACING ARMOR RENDERING UNIT case 6: g.drawImage(bufferedImageMap.get("RAGGED_SHIRT_PLAYERMODEL_NORTH"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 24: g.drawImage(bufferedImageMap.get("GREEN_PLATEBODY_TRIMMED_PLAYERMODEL_NORTH"), player1.xPos - 4, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 17: g.drawImage(bufferedImageMap.get("BLUE_PLATEBODY_TRIMMED_PLAYERMODEL_NORTH"), player1.xPos - 4, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 30: g.drawImage(bufferedImageMap.get("BROWN_PLATEBODY_TRIMMED_PLAYERMODEL_NORTH"), player1.xPos - 4, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 23: g.drawImage(bufferedImageMap.get("GREEN_PLATEBODY_PLAYERMODEL_NORTH"), player1.xPos - 4, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 16: g.drawImage(bufferedImageMap.get("BLUE_PLATEBODY_PLAYERMODEL_NORTH"), player1.xPos - 4, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 29: g.drawImage(bufferedImageMap.get("BROWN_PLATEBODY_PLAYERMODEL_NORTH"), player1.xPos - 4, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; } break; } case "WEST": { switch (player1.gearInterface.itemArray[1].ID) { // WEST-FACING ARMOR RENDERING UNIT case 6: g.drawImage(bufferedImageMap.get("RAGGED_SHIRT_PLAYERMODEL_WEST"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 24: g.drawImage(bufferedImageMap.get("GREEN_PLATEBODY_TRIMMED_PLAYERMODEL_WEST"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 17: g.drawImage(bufferedImageMap.get("BLUE_PLATEBODY_TRIMMED_PLAYERMODEL_WEST"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 30: g.drawImage(bufferedImageMap.get("BROWN_PLATEBODY_TRIMMED_PLAYERMODEL_WEST"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 23: g.drawImage(bufferedImageMap.get("GREEN_PLATEBODY_PLAYERMODEL_WEST"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 16: g.drawImage(bufferedImageMap.get("BLUE_PLATEBODY_PLAYERMODEL_WEST"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 29: g.drawImage(bufferedImageMap.get("BROWN_PLATEBODY_PLAYERMODEL_WEST"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; } } break; } } if (magnitude == 5) { switch (player1.orientation) { // SOUTH-FACING RENDERING UNIT case "SOUTH": { switch (player1.gearInterface.itemArray[1].ID) { // SOUTH-FACING SHIELD RENDERING UNIT case 6: g.drawImage(bufferedImageMap.get("RAGGED_SHIRT_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 24: g.drawImage(bufferedImageMap.get("GREEN_PLATEBODY_TRIMMED_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 17: g.drawImage(bufferedImageMap.get("BLUE_PLATEBODY_TRIMMED_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 30: g.drawImage(bufferedImageMap.get("BROWN_PLATEBODY_TRIMMED_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 23: g.drawImage(bufferedImageMap.get("GREEN_PLATEBODY_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 16: g.drawImage(bufferedImageMap.get("BLUE_PLATEBODY_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 29: g.drawImage(bufferedImageMap.get("BROWN_PLATEBODY_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; } break; } } } } private void paintWeapon(Graphics g, int magnitude) { if (magnitude == 1) { switch (player1.orientation) { // SOUTH-FACING RENDERING UNIT case "SOUTH": { switch (player1.gearInterface.itemArray[5].ID) { // SOUTH-FACING WEAPON RENDERING UNIT case 9: g.drawImage(bufferedImageMap.get("WOODEN_CLUB_W"), player1.xPos - 15, player1.yPos - 13, 25 * magnitude, 25 * magnitude, this); break; case 13: g.drawImage(bufferedImageMap.get("BLUE_DAGGER_WEST"), player1.xPos - 15, player1.yPos - 13, 25 * magnitude, 25 * magnitude, this); break; case 20: g.drawImage(bufferedImageMap.get("GREEN_DAGGER_WEST"), player1.xPos - 15, player1.yPos - 13, 25 * magnitude, 25 * magnitude, this); break; case 31: g.drawImage(bufferedImageMap.get("RED_DAGGER_WEST"), player1.xPos - 15, player1.yPos - 13, 25 * magnitude, 25 * magnitude, this); break; case 32: g.drawImage(bufferedImageMap.get("LUMBERJACK_AXE_WEST"), player1.xPos - 15, player1.yPos - 13, 25 * magnitude, 25 * magnitude, this); break; case 33: g.drawImage(bufferedImageMap.get("MINER_PICKAXE_WEST"), player1.xPos - 15, player1.yPos - 13, 25 * magnitude, 25 * magnitude, this); break; case 38: g.drawImage(bufferedImageMap.get("YELLOW_PICKAXE_WEST"), player1.xPos - 15, player1.yPos - 13, 25 * magnitude, 25 * magnitude, this); break; case 39: g.drawImage(bufferedImageMap.get("BLUE_PICKAXE_WEST"), player1.xPos - 15, player1.yPos - 13, 25 * magnitude, 25 * magnitude, this); break; case 40: g.drawImage(bufferedImageMap.get("GREEN_PICKAXE_WEST"), player1.xPos - 15, player1.yPos - 13, 25 * magnitude, 25 * magnitude, this); break; case 41: g.drawImage(bufferedImageMap.get("RED_PICKAXE_WEST"), player1.xPos - 15, player1.yPos - 13, 25 * magnitude, 25 * magnitude, this); break; case 46: g.drawImage(bufferedImageMap.get("FARMER_SHOVEL_WEST"), player1.xPos - 15, player1.yPos - 13, 25 * magnitude, 25 * magnitude, this); break; } break; } case "EAST": { switch (player1.gearInterface.itemArray[5].ID) { // EAST-FACING WEAPON RENDERING UNIT case 9: g.drawImage(bufferedImageMap.get("WOODEN_CLUB_E"), player1.xPos + 5, player1.yPos - 15, 25 * magnitude, 25 * magnitude, this); break; case 13: g.drawImage(bufferedImageMap.get("BLUE_DAGGER_EAST"), player1.xPos + 5, player1.yPos - 15, 25 * magnitude, 25 * magnitude, this); break; case 20: g.drawImage(bufferedImageMap.get("GREEN_DAGGER_EAST"), player1.xPos + 5, player1.yPos - 15, 25 * magnitude, 25 * magnitude, this); break; case 31: g.drawImage(bufferedImageMap.get("RED_DAGGER_EAST"), player1.xPos + 5, player1.yPos - 15, 25 * magnitude, 25 * magnitude, this); break; case 32: g.drawImage(bufferedImageMap.get("LUMBERJACK_AXE_EAST"), player1.xPos + 5, player1.yPos - 15, 25 * magnitude, 25 * magnitude, this); break; case 33: g.drawImage(bufferedImageMap.get("MINER_PICKAXE_EAST"), player1.xPos + 5, player1.yPos - 15, 25 * magnitude, 25 * magnitude, this); break; case 38: g.drawImage(bufferedImageMap.get("YELLOW_PICKAXE_EAST"), player1.xPos + 5, player1.yPos - 15, 25 * magnitude, 25 * magnitude, this); break; case 39: g.drawImage(bufferedImageMap.get("BLUE_PICKAXE_EAST"), player1.xPos + 5, player1.yPos - 15, 25 * magnitude, 25 * magnitude, this); break; case 40: g.drawImage(bufferedImageMap.get("GREEN_PICKAXE_EAST"), player1.xPos + 5, player1.yPos - 15, 25 * magnitude, 25 * magnitude, this); break; case 41: g.drawImage(bufferedImageMap.get("RED_PICKAXE_EAST"), player1.xPos + 5, player1.yPos - 15, 25 * magnitude, 25 * magnitude, this); break; case 46: g.drawImage(bufferedImageMap.get("FARMER_SHOVEL_EAST"), player1.xPos + 5, player1.yPos - 15, 25 * magnitude, 25 * magnitude, this); break; } break; } case "NORTH": { switch (player1.gearInterface.itemArray[5].ID) { // NORTH-FACING WEAPON RENDERING UNIT case 9: g.drawImage(bufferedImageMap.get("WOODEN_CLUB_W"), player1.xPos - 17, player1.yPos - 12, 25 * magnitude, 25 * magnitude, this); break; case 13: g.drawImage(bufferedImageMap.get("BLUE_DAGGER_WEST"), player1.xPos - 17, player1.yPos - 12, 25 * magnitude, 25 * magnitude, this); break; case 20: g.drawImage(bufferedImageMap.get("GREEN_DAGGER_WEST"), player1.xPos - 17, player1.yPos - 12, 25 * magnitude, 25 * magnitude, this); break; case 31: g.drawImage(bufferedImageMap.get("RED_DAGGER_WEST"), player1.xPos - 17, player1.yPos - 12, 25 * magnitude, 25 * magnitude, this); break; case 32: g.drawImage(bufferedImageMap.get("LUMBERJACK_AXE_WEST"), player1.xPos - 17, player1.yPos - 12, 25 * magnitude, 25 * magnitude, this); break; case 33: g.drawImage(bufferedImageMap.get("MINER_PICKAXE_WEST"), player1.xPos - 17, player1.yPos - 12, 25 * magnitude, 25 * magnitude, this); break; case 38: g.drawImage(bufferedImageMap.get("YELLOW_PICKAXE_WEST"), player1.xPos - 17, player1.yPos - 12, 25 * magnitude, 25 * magnitude, this); break; case 39: g.drawImage(bufferedImageMap.get("BLUE_PICKAXE_WEST"), player1.xPos - 17, player1.yPos - 12, 25 * magnitude, 25 * magnitude, this); break; case 40: g.drawImage(bufferedImageMap.get("GREEN_PICKAXE_WEST"), player1.xPos - 17, player1.yPos - 12, 25 * magnitude, 25 * magnitude, this); break; case 41: g.drawImage(bufferedImageMap.get("RED_PICKAXE_WEST"), player1.xPos - 17, player1.yPos - 12, 25 * magnitude, 25 * magnitude, this); break; case 46: g.drawImage(bufferedImageMap.get("FARMER_SHOVEL_WEST"), player1.xPos - 17, player1.yPos - 12, 25 * magnitude, 25 * magnitude, this); break; } break; } case "WEST": { switch (player1.gearInterface.itemArray[5].ID) { // EAST-FACING WEAPON RENDERING UNIT case 9: g.drawImage(bufferedImageMap.get("WOODEN_CLUB_W"), player1.xPos - 14, player1.yPos - 12, 25 * magnitude, 25 * magnitude, this); break; case 13: g.drawImage(bufferedImageMap.get("BLUE_DAGGER_WEST"), player1.xPos - 14, player1.yPos - 12, 25 * magnitude, 25 * magnitude, this); break; case 20: g.drawImage(bufferedImageMap.get("GREEN_DAGGER_WEST"), player1.xPos - 14, player1.yPos - 12, 25 * magnitude, 25 * magnitude, this); break; case 31: g.drawImage(bufferedImageMap.get("RED_DAGGER_WEST"), player1.xPos - 14, player1.yPos - 12, 25 * magnitude, 25 * magnitude, this); break; case 32: g.drawImage(bufferedImageMap.get("LUMBERJACK_AXE_WEST"), player1.xPos - 14, player1.yPos - 12, 25 * magnitude, 25 * magnitude, this); break; case 33: g.drawImage(bufferedImageMap.get("MINER_PICKAXE_WEST"), player1.xPos - 14, player1.yPos - 12, 25 * magnitude, 25 * magnitude, this); break; case 38: g.drawImage(bufferedImageMap.get("YELLOW_PICKAXE_WEST"), player1.xPos - 14, player1.yPos - 12, 25 * magnitude, 25 * magnitude, this); break; case 39: g.drawImage(bufferedImageMap.get("BLUE_PICKAXE_WEST"), player1.xPos - 14, player1.yPos - 12, 25 * magnitude, 25 * magnitude, this); break; case 40: g.drawImage(bufferedImageMap.get("GREEN_PICKAXE_WEST"), player1.xPos - 14, player1.yPos - 12, 25 * magnitude, 25 * magnitude, this); break; case 41: g.drawImage(bufferedImageMap.get("RED_PICKAXE_WEST"), player1.xPos - 14, player1.yPos - 12, 25 * magnitude, 25 * magnitude, this); break; case 46: g.drawImage(bufferedImageMap.get("FARMER_SHOVEL_WEST"), player1.xPos - 14, player1.yPos - 12, 25 * magnitude, 25 * magnitude, this); break; } } break; } } if (magnitude == 5) { switch (player1.orientation) { // SOUTH-FACING RENDERING UNIT case "SOUTH": { switch (player1.gearInterface.itemArray[5].ID) { // SOUTH-FACING WEAPON RENDERING UNIT case 9: g.drawImage(bufferedImageMap.get("WOODEN_CLUB_W"), player1.xPos - 70, player1.yPos - 5, 25 * magnitude, 25 * magnitude, this); break; case 13: g.drawImage(bufferedImageMap.get("BLUE_DAGGER_WEST"), player1.xPos - 70, player1.yPos - 5, 25 * magnitude, 25 * magnitude, this); break; case 20: g.drawImage(bufferedImageMap.get("GREEN_DAGGER_WEST"), player1.xPos - 70, player1.yPos - 5, 25 * magnitude, 25 * magnitude, this); break; case 31: g.drawImage(bufferedImageMap.get("RED_DAGGER_WEST"), player1.xPos - 70, player1.yPos - 5, 25 * magnitude, 25 * magnitude, this); break; case 32: g.drawImage(bufferedImageMap.get("LUMBERJACK_AXE_WEST"), player1.xPos - 70, player1.yPos - 5, 25 * magnitude, 25 * magnitude, this); break; case 33: g.drawImage(bufferedImageMap.get("MINER_PICKAXE_WEST"), player1.xPos - 70, player1.yPos - 5, 25 * magnitude, 25 * magnitude, this); break; case 38: g.drawImage(bufferedImageMap.get("YELLOW_PICKAXE_WEST"), player1.xPos - 70, player1.yPos - 5, 25 * magnitude, 25 * magnitude, this); break; case 39: g.drawImage(bufferedImageMap.get("BLUE_PICKAXE_WEST"), player1.xPos - 70, player1.yPos - 5, 25 * magnitude, 25 * magnitude, this); break; case 40: g.drawImage(bufferedImageMap.get("GREEN_PICKAXE_WEST"), player1.xPos - 70, player1.yPos - 5, 25 * magnitude, 25 * magnitude, this); break; case 41: g.drawImage(bufferedImageMap.get("RED_PICKAXE_WEST"), player1.xPos - 70, player1.yPos - 5, 25 * magnitude, 25 * magnitude, this); break; case 46: g.drawImage(bufferedImageMap.get("FARMER_SHOVEL_WEST"), player1.xPos - 70, player1.yPos - 5, 25 * magnitude, 25 * magnitude, this); break; } } break; } } } private void paintShield(Graphics g, int magnitude) { if (magnitude == 1) { switch (player1.orientation) { // SOUTH-FACING RENDERING UNIT case "SOUTH": { switch (player1.gearInterface.itemArray[4].ID) { // SOUTH-FACING SHIELD RENDERING UNIT case 10: g.drawImage(bufferedImageMap.get("WOODEN_SHIELD"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 11: g.drawImage(bufferedImageMap.get("BLUE_BUCKLER"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 12: g.drawImage(bufferedImageMap.get("BLUE_BUCKLER_TRIMMED"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 18: g.drawImage(bufferedImageMap.get("GREEN_BUCKLER"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 19: g.drawImage(bufferedImageMap.get("GREEN_BUCKLER_TRIMMED"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 25: g.drawImage(bufferedImageMap.get("JUNKSCRAP_BUCKLER"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 26: g.drawImage(bufferedImageMap.get("JUNKSCRAP_BUCKLER_TRIMMED"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; } } break; case "EAST": { if (player1.gearInterface.itemArray[4].ID != 0) { g.drawImage(bufferedImageMap.get("GENERIC_SHIELD_BACK"), player1.xPos - 1, player1.yPos - 12, 25 * magnitude, 25 * magnitude, this); } /* switch (player1.gearInterface.itemArray[4].ID) { // EAST-FACING SHIELD RENDERING UNIT case 10: g.drawImage(bufferedImageMap.get("WOODEN_SHIELD"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 11: g.drawImage(bufferedImageMap.get("BLUE_BUCKLER"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 12: g.drawImage(bufferedImageMap.get("BLUE_BUCKLER_TRIMMED"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 18: g.drawImage(bufferedImageMap.get("GREEN_BUCKLER"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 19: g.drawImage(bufferedImageMap.get("GREEN_BUCKLER_TRIMMED"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 25: g.drawImage(bufferedImageMap.get("JUNKSCRAP_BUCKLER"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 26: g.drawImage(bufferedImageMap.get("JUNKSCRAP_BUCKLER_TRIMMED"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; } */ } break; case "NORTH": { if (player1.gearInterface.itemArray[4].ID != 0) { g.drawImage(bufferedImageMap.get("GENERIC_SHIELD_BACK"), player1.xPos + 1, player1.yPos - 10, 25 * magnitude, 25 * magnitude, this); } /* switch (player1.gearInterface.itemArray[4].ID) { // EAST-FACING SHIELD RENDERING UNIT case 10: g.drawImage(bufferedImageMap.get("WOODEN_SHIELD"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 11: g.drawImage(bufferedImageMap.get("BLUE_BUCKLER"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 12: g.drawImage(bufferedImageMap.get("BLUE_BUCKLER_TRIMMED"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 18: g.drawImage(bufferedImageMap.get("GREEN_BUCKLER"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 19: g.drawImage(bufferedImageMap.get("GREEN_BUCKLER_TRIMMED"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 25: g.drawImage(bufferedImageMap.get("JUNKSCRAP_BUCKLER"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 26: g.drawImage(bufferedImageMap.get("JUNKSCRAP_BUCKLER_TRIMMED"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; } */ } break; case "WEST": { switch (player1.gearInterface.itemArray[4].ID) { // EAST-FACING SHIELD RENDERING UNIT case 10: g.drawImage(bufferedImageMap.get("WOODEN_SHIELD"), player1.xPos - 2, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 11: g.drawImage(bufferedImageMap.get("BLUE_BUCKLER"), player1.xPos - 2, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 12: g.drawImage(bufferedImageMap.get("BLUE_BUCKLER_TRIMMED"), player1.xPos - 2, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 18: g.drawImage(bufferedImageMap.get("GREEN_BUCKLER"), player1.xPos - 2, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 19: g.drawImage(bufferedImageMap.get("GREEN_BUCKLER_TRIMMED"), player1.xPos - 2, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 25: g.drawImage(bufferedImageMap.get("JUNKSCRAP_BUCKLER"), player1.xPos - 2, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 26: g.drawImage(bufferedImageMap.get("JUNKSCRAP_BUCKLER_TRIMMED"), player1.xPos - 2, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; } } break; } } if (magnitude == 5) { switch (player1.orientation) { // SOUTH-FACING RENDERING UNIT case "SOUTH": { switch (player1.gearInterface.itemArray[4].ID) { // SOUTH-FACING SHIELD RENDERING UNIT case 10: g.drawImage(bufferedImageMap.get("WOODEN_SHIELD"), player1.xPos + 30, player1.yPos + 35, 25 * magnitude, 25 * magnitude, this); break; case 11: g.drawImage(bufferedImageMap.get("BLUE_BUCKLER"), player1.xPos + 30, player1.yPos + 35, 25 * magnitude, 25 * magnitude, this); break; case 12: g.drawImage(bufferedImageMap.get("BLUE_BUCKLER_TRIMMED"), player1.xPos + 30, player1.yPos + 35, 25 * magnitude, 25 * magnitude, this); break; case 18: g.drawImage(bufferedImageMap.get("GREEN_BUCKLER"), player1.xPos + 30, player1.yPos + 35, 25 * magnitude, 25 * magnitude, this); break; case 19: g.drawImage(bufferedImageMap.get("GREEN_BUCKLER_TRIMMED"), player1.xPos + 30, player1.yPos + 35, 25 * magnitude, 25 * magnitude, this); break; case 25: g.drawImage(bufferedImageMap.get("JUNKSCRAP_BUCKLER"), player1.xPos + 30, player1.yPos + 35, 25 * magnitude, 25 * magnitude, this); break; case 26: g.drawImage(bufferedImageMap.get("JUNKSCRAP_BUCKLER_TRIMMED"), player1.xPos + 30, player1.yPos + 35, 25 * magnitude, 25 * magnitude, this); break; } break; } } } } private void paintTileCoordinates(Graphics g) { g.setFont(font1_8); g.setColor(Color.black); for (int i = 0; i < 32; i++) { for (int j = 0; j < 24; j++) { g.drawString("" + i + ", " + j, i * 25 + 2, j * 25 + 13); } } } private void paintTileLines(Graphics g) { int counter = 0; int row = 0; for (int i = 0; i < 768; i++) { if (counter == 32) { row++; counter = 0; } g.setColor(Color.black); g.drawRect(counter * 25, row * 25, 25, 25); counter++; } } private void npcBehaviour() { int r; for (Npc n : currentOverWorld.npcList) { // iterater through current Overworld npc list. int counter; switch (n.ai) { // reads ai type from each Npc. case "SHEEP": // Sheep ai. moves every 5 actions. random walks through passable tiles. wont leave edge of map. counter = (actionTick % 5); if (counter == 0) { r = rotateRng(); if (r <= 25) { if (n.yPos / 25 != 22) { if (!currentOverWorld.tilemap[n.xPos / 25][n.yPos / 25 + 1].occupied) { n.yPos += movementSpeed; n.orientation = "SOUTH"; } } } else if (r > 25 && r < 50) { if (n.yPos / 25 != 1) { if (!currentOverWorld.tilemap[n.xPos / 25][n.yPos / 25 - 1].occupied) { n.yPos -= movementSpeed; n.orientation = "NORTH"; } } } else if (r > 50 && r < 75) { if (n.xPos / 25 != 31) { if (!currentOverWorld.tilemap[n.xPos / 25 + 1][n.yPos / 25].occupied) { n.xPos += movementSpeed; n.orientation = "EAST"; } } } else if (r >= 75) { if (n.xPos / 25 != 1) { if (!currentOverWorld.tilemap[n.xPos / 25 - 1][n.yPos / 25].occupied) { n.xPos -= movementSpeed; n.orientation = "WEST"; } } } } r = rotateRng(); if (r > 98 && currentOverWorld.tilemap[n.xPos / 25][n.yPos / 25].type.equals("grass")) { currentOverWorld.tilemap[n.xPos / 25][n.yPos / 25].type = "dirt"; currentOverWorld.tilemap[n.xPos / 25][n.yPos / 25].growth = 0; } break; case "CHASER": // Chaser ai. moves every 4 actions. compares own position to player's and attempt to equalize y and x coordinates. Won't leave map. counter = (actionTick % 4); if (counter == 0) { if (player1.yPos / 25 < n.yPos / 25) { if (n.yPos / 25 != 1) { if (!currentOverWorld.tilemap[n.xPos / 25][n.yPos / 25 - 1].occupied) { n.yPos -= movementSpeed; n.orientation = "NORTH"; } else if (n.yPos / 25 - 1 == player1.yPos / 25 && n.xPos / 25 == player1.xPos / 25) { n.orientation = "NORTH"; System.out.println("the chaser hits you for 10 damage"); player1.HP = player1.HP - 10; } else { n.orientation = "NORTH"; } } } else if (player1.yPos / 25 > n.yPos / 25) { if (n.yPos / 25 != 22) { if (!currentOverWorld.tilemap[n.xPos / 25][n.yPos / 25 + 1].occupied) { n.yPos += movementSpeed; n.orientation = "SOUTH"; } else if (n.yPos / 25 + 1 == player1.yPos / 25 && n.xPos / 25 == player1.xPos / 25) { n.orientation = "SOUTH"; System.out.println("the chaser hits you for 10 damage"); player1.HP = player1.HP - 10; } else { n.orientation = "SOUTH"; } } } if (player1.xPos / 25 < n.xPos / 25) { if (n.xPos / 25 != 1) { if (!currentOverWorld.tilemap[n.xPos / 25 - 1][n.yPos / 25].occupied) { n.xPos -= movementSpeed; n.orientation = "WEST"; } else if (n.xPos / 25 - 1 == player1.xPos / 25 && n.yPos / 25 == player1.yPos / 25) { n.orientation = "WEST"; System.out.println("the chaser hits you for 10 damage"); player1.HP = player1.HP - 10; } else { n.orientation = "WEST"; } } } else if (player1.xPos / 25 > n.xPos / 25) { if (n.xPos / 25 != 30) { if (!currentOverWorld.tilemap[n.xPos / 25 + 1][n.yPos / 25].occupied) { n.xPos += movementSpeed; n.orientation = "EAST"; } else if (n.xPos / 25 + 1 == player1.xPos / 25 && n.yPos / 25 == player1.yPos / 25) { n.orientation = "EAST"; System.out.println("the chaser hits you for 10 damage"); player1.HP = player1.HP - 10; } else { n.orientation = "EAST"; } } } } break; } collisionMeshGenerator(); // Re-generates collision mesh after each Npc takes action. } } private void mapChange(int direction) { // controls the change of map as player reaches map edge. if (direction == 0) { // 0=up. 1=right 2=down 3=left if (currentOverWorld.idY == worldSize - 1) // checks for top edge of Overworld. { if (!overWorld[currentOverWorld.idX][0].tilemap[player1.xPos / 25][22].occupied && !overWorld[currentOverWorld.idX][0].tilemap[player1.xPos / 25][23].occupied) { currentOverWorld.tilemap[player1.xPos / 25][player1.yPos / 25].occupied = false; currentOverWorld = overWorld[currentOverWorld.idX][0]; // load bottom edge of Overworld. ( world is currently round. ) player1.yPos = 22 * 25; // sets player y coordinate to bottom edge of tilemap } } else { if (!overWorld[currentOverWorld.idX][currentOverWorld.idY + 1].tilemap[player1.xPos / 25][22].occupied && !overWorld[currentOverWorld.idX][currentOverWorld.idY + 1].tilemap[player1.xPos / 25][23].occupied) { currentOverWorld.tilemap[player1.xPos / 25][player1.yPos / 25].occupied = false; player1.yPos = 22 * 25; currentOverWorld = overWorld[currentOverWorld.idX][currentOverWorld.idY + 1]; // Otherwise loads next Overworld up. } } } else if (direction == 1) { if (currentOverWorld.idX == worldSize - 1) // same concept for every direction. { if (!overWorld[0][currentOverWorld.idY].tilemap[1][player1.yPos / 25].occupied && !overWorld[0][currentOverWorld.idY].tilemap[0][player1.yPos / 25].occupied) { currentOverWorld.tilemap[player1.xPos / 25][player1.yPos / 25].occupied = false; currentOverWorld = overWorld[0][currentOverWorld.idY]; player1.xPos = 1 * 25; } } else { if (!overWorld[currentOverWorld.idX + 1][currentOverWorld.idY].tilemap[1][player1.yPos / 25].occupied && !overWorld[currentOverWorld.idX + 1][currentOverWorld.idY].tilemap[0][player1.yPos / 25].occupied) { currentOverWorld.tilemap[player1.xPos / 25][player1.yPos / 25].occupied = false; player1.xPos = 1 * 25; currentOverWorld = overWorld[currentOverWorld.idX + 1][currentOverWorld.idY]; } } } else if (direction == 2) { if (currentOverWorld.idY == 0) { if (!overWorld[currentOverWorld.idX][worldSize - 1].tilemap[player1.xPos / 25][1].occupied && !overWorld[currentOverWorld.idX][worldSize - 1].tilemap[player1.xPos / 25][0].occupied) { currentOverWorld.tilemap[player1.xPos / 25][player1.yPos / 25].occupied = false; player1.yPos = 1 * 25; currentOverWorld = overWorld[currentOverWorld.idX][worldSize - 1]; } } else { if (!overWorld[currentOverWorld.idX][currentOverWorld.idY - 1].tilemap[player1.xPos / 25][1].occupied && !overWorld[currentOverWorld.idX][currentOverWorld.idY - 1].tilemap[player1.xPos / 25][0].occupied) { currentOverWorld.tilemap[player1.xPos / 25][player1.yPos / 25].occupied = false; player1.yPos = 1 * 25; currentOverWorld = overWorld[currentOverWorld.idX][currentOverWorld.idY - 1]; } } } else if (direction == 3) { if (currentOverWorld.idX == 0) { if (!overWorld[worldSize - 1][currentOverWorld.idY].tilemap[30][player1.yPos / 25].occupied && !overWorld[worldSize - 1][currentOverWorld.idY].tilemap[31][player1.yPos / 25].occupied) { currentOverWorld.tilemap[player1.xPos / 25][player1.yPos / 25].occupied = false; currentOverWorld = overWorld[worldSize - 1][currentOverWorld.idY]; player1.xPos = 30 * 25; } } else { if (!overWorld[currentOverWorld.idX - 1][currentOverWorld.idY].tilemap[30][player1.yPos / 25].occupied && !overWorld[currentOverWorld.idX - 1][currentOverWorld.idY].tilemap[31][player1.yPos / 25].occupied) { currentOverWorld.tilemap[player1.xPos / 25][player1.yPos / 25].occupied = false; player1.xPos = 30 * 25; currentOverWorld = overWorld[currentOverWorld.idX - 1][currentOverWorld.idY]; } } } if (currentOverWorld.idX < 10 && currentOverWorld.idY < 10) { System.out.println("Overworld0" + currentOverWorld.idX + "0" + currentOverWorld.idY + " loaded"); } else if (currentOverWorld.idX < 10) { System.out.println("Overworld0" + currentOverWorld.idX + +currentOverWorld.idY + " loaded"); } else if (currentOverWorld.idY < 10) { System.out.println("Overworld" + currentOverWorld.idX + "0" + currentOverWorld.idY + " loaded"); } else { System.out.println("Overworld" + currentOverWorld.idX + +currentOverWorld.idY + " loaded"); } } private void tick() { actionTick++; // ticks action counter and runs any subroutines that should run for each tick. npcBehaviour(); naturalProcesses(); collisionMeshGenerator(); if (player1.HP < 0) { System.out.println("GAME OVER,!!!!!"); startMenuVisible = true; mapVisible = false; inventoryMenuVisible = false; debugMenuVisible = false; craftingMenuVisible = false; reset(); worldExists = false; } } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == timer && paint()) { this.repaint(); } if (engagedSuccessfully && e.getSource() == animationTimer0) { animation_frame++; if (animation_frame == 100) { animation_frame = 0; } } } private boolean checkForEndOfTurnTrigger() { if (TRIGGER_endOfCombat) { player1.xPos = storeXPos; player1.yPos = storeYPos; player1.orientation = storeOrientation; TRIGGER_endOfCombat = false; engagedSuccessfully = false; return true; } return false; } @Override public void keyTyped(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { switch (e.getKeyCode()) { // Keyboard switch -> e.getKeyCode() returns a virtual keyboard int value /* MOVEMENT AND ORIENTATION */ case KeyEvent.VK_H: break; case KeyEvent.VK_Q: if (player1.personalQuestLog.isEmpty()) { System.out.println("You have no quests"); } for (Quest q : player1.personalQuestLog) { System.out.println(q); } break; case KeyEvent.VK_CONTROL: controlPressed = true; break; case KeyEvent.VK_SHIFT: shiftPressed = true; break; case KeyEvent.VK_ALT: altPressed = true; break; case KeyEvent.VK_C: craftingMenuVisible = !craftingMenuVisible; break; case KeyEvent.VK_UP: // User presses the up key if (!stuckInDialogue) { loadMovementSound(); if (mapVisible && !engagedSuccessfully) { player1.orientation = "NORTH"; // set the player1 orientation state to "NORTH" if (!currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25) - 1].occupied) { if (player1.yPos / 25 != 1) { player1.yPos -= movementSpeed; //update ypos currentOverWorld.tilemap[player1.xPos / 25][player1.yPos / 25].occupied = true; // set's player position to occupied. // ( needed for npc actions that might occur before a new collision mesh is generated) } else { mapChange(0); // edge detection and map scrolling. } } } } break; case KeyEvent.VK_DOWN: // Tries to move down if (!stuckInDialogue) { loadMovementSound(); if (mapVisible && !engagedSuccessfully) { player1.orientation = "SOUTH"; if (!currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25) + 1].occupied) { if (player1.yPos / 25 != 22) { player1.yPos += movementSpeed; //update ypos currentOverWorld.tilemap[player1.xPos / 25][player1.yPos / 25].occupied = true; } else { mapChange(2); // edge detection. } } } } break; case KeyEvent.VK_LEFT: // Tries to move left if (!stuckInDialogue) { loadMovementSound(); if (mapVisible && !engagedSuccessfully) { player1.orientation = "WEST"; if (!currentOverWorld.tilemap[player1.xPos / 25 - 1][(player1.yPos / 25)].occupied) { if (player1.xPos / 25 != 1) { player1.xPos -= movementSpeed; //update ypos currentOverWorld.tilemap[player1.xPos / 25][player1.yPos / 25].occupied = true; } else { mapChange(3); // edge detection. } } } } break; case KeyEvent.VK_RIGHT: // Tries to move right if (!stuckInDialogue) { loadMovementSound(); if (mapVisible && !engagedSuccessfully) { player1.orientation = "EAST"; if (!currentOverWorld.tilemap[player1.xPos / 25 + 1][(player1.yPos / 25)].occupied) { if (player1.xPos / 25 != 30) { player1.xPos += movementSpeed; //update ypos currentOverWorld.tilemap[player1.xPos / 25][player1.yPos / 25].occupied = true; } else { mapChange(1); } } } } break; case KeyEvent.VK_M: if (menuSoundLoaded && rainSoundLoaded && woodsSoundLoaded) { menuSound.stop(); rainSound.stop(); woodsSound.stop(); menuSoundLoaded = false; rainSoundLoaded = false; woodsSoundLoaded = false; } else { loadMenuSound(); loadWoodsSound(); loadRainSound(); } break; /* DEBUG MENU/INDICATORS OPEN/CLOSE Open all debug menus and indicators */ case KeyEvent.VK_X: // keyboard press X -> Shows debug menu if (!startMenuVisible) { debugMenuVisible = !debugMenuVisible; // reverse the debug menu boolean state System.out.println(printTileSet(currentOverWorld.tilemap)); } break; /* Player Actions */ /* Harvesting: Requirements -> 1. Player's inventory is not full 2. Player's orientation faces a harvestable tile/entity. 3. The tile harvested by the player is harvestable. Outcomes -> 1. (IFF Successful) The player receives an item to his inventory on his next free slot. -> "receives an item" means the ID state of the player's item inventory array changes from 0 ("empty") to another ID related to the harvested tile. 2. (IFF Successful) The tile harvested by the player can be modified (eg: if cut tree -> tile becomes grass) 3. (IFF Failure) The tile the player attempted to harvest remains unchanged. */ case KeyEvent.VK_1: // keyboard press 1 -> attempt to harvest block currentItem = null; int xOffsetCheck = 0; int yOffsetCheck = 0; if (player1.orientation.equals("NORTH")) { yOffsetCheck = -1; } else if (player1.orientation.equals("EAST")) { xOffsetCheck = 1; } else if (player1.orientation.equals("SOUTH")) { yOffsetCheck = 1; } else if (player1.orientation.equals("WEST")) { xOffsetCheck = -1; } if (!startMenuVisible) { System.out.println("1- Block Harvesting"); System.out.println(currentOverWorld.tilemap[player1.xPos / 25 + xOffsetCheck][(player1.yPos / 25 + yOffsetCheck)].type); if (!player1.playerInventory.isFull() && ( currentOverWorld.tilemap[player1.xPos / 25 + xOffsetCheck][(player1.yPos / 25 + yOffsetCheck)].type.equals("t0stone") || currentOverWorld.tilemap[player1.xPos / 25 + xOffsetCheck][(player1.yPos / 25 + yOffsetCheck)].type.equals("t1stone") || currentOverWorld.tilemap[player1.xPos / 25 + xOffsetCheck][(player1.yPos / 25 + yOffsetCheck)].type.equals("t2stone") || currentOverWorld.tilemap[player1.xPos / 25 + xOffsetCheck][(player1.yPos / 25 + yOffsetCheck)].type.equals("t3stone") || currentOverWorld.tilemap[player1.xPos / 25 + xOffsetCheck][(player1.yPos / 25 + yOffsetCheck)].type.equals("tree") ) ) { // Allows harvesting process to happen only if the inventory isnt full and if the tile is a harvestable tile boolean harvestedSuccessfully = false; // flag to determine real-time whether the key press triggers a successful harvest action String harvestedItem = ""; System.out.println("XXX"); /* T0STONE GATHERING */ if (player1.gearInterface.itemArray[5].ID == 33 && player1.orientation.equals("EAST") && currentOverWorld.tilemap[player1.xPos / 25 + 1][(player1.yPos / 25)].type.equals("t0stone")) { currentOverWorld.tilemap[player1.xPos / 25 + 1][(player1.yPos / 25)].type = "dirt"; harvestedItem = "cobblestone"; currentOverWorld.tilemap[player1.xPos / 25 + 1][(player1.yPos / 25)].farmable = true; harvestedSuccessfully = true; player1.miningXP += 1; } else if (player1.gearInterface.itemArray[5].ID == 33 && player1.orientation.equals("WEST") && currentOverWorld.tilemap[player1.xPos / 25 - 1][(player1.yPos / 25)].type.equals("t0stone")) { currentOverWorld.tilemap[player1.xPos / 25 - 1][(player1.yPos / 25)].type = "dirt"; harvestedItem = "cobblestone"; currentOverWorld.tilemap[player1.xPos / 25 - 1][(player1.yPos / 25)].farmable = true; harvestedSuccessfully = true; player1.miningXP += 1; } else if (player1.gearInterface.itemArray[5].ID == 33 && player1.orientation.equals("NORTH") && currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 - 1)].type.equals("t0stone")) { currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 - 1)].type = "dirt"; currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 - 1)].farmable = true; harvestedSuccessfully = true; harvestedItem = "cobblestone"; player1.miningXP += 1; } else if (player1.gearInterface.itemArray[5].ID == 33 && player1.orientation.equals("SOUTH") && currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 + 1)].type.equals("t0stone")) { currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 + 1)].type = "dirt"; harvestedItem = "cobblestone"; currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 + 1)].farmable = true; harvestedSuccessfully = true; player1.miningXP += 1; } /* T1STONE GATHERING */ else if (player1.gearInterface.itemArray[5].ID == 33 && player1.orientation.equals("EAST") && currentOverWorld.tilemap[player1.xPos / 25 + 1][(player1.yPos / 25)].type.equals("t1stone")) { int storeRockPermutation = currentOverWorld.tilemap[player1.xPos / 25 + 1][(player1.yPos / 25 + 1)].rockPermutation; currentOverWorld.tilemap[player1.xPos / 25 + 1][(player1.yPos / 25)] = new Tile("t0stone", false, true, false); currentOverWorld.tilemap[player1.xPos / 25 + 1][(player1.yPos / 25)].rockPermutation = storeRockPermutation; harvestedItem = "yellow ore"; player1.miningXP += 55; harvestedSuccessfully = true; } else if (player1.gearInterface.itemArray[5].ID == 33 && player1.orientation.equals("WEST") && currentOverWorld.tilemap[player1.xPos / 25 - 1][(player1.yPos / 25)].type.equals("t1stone")) { int storeRockPermutation = currentOverWorld.tilemap[player1.xPos / 25 - 1][(player1.yPos / 25 - 1)].rockPermutation; currentOverWorld.tilemap[player1.xPos / 25 - 1][(player1.yPos / 25)] = new Tile("t0stone", false, true, false); currentOverWorld.tilemap[player1.xPos / 25 - 1][(player1.yPos / 25)].rockPermutation = storeRockPermutation; harvestedItem = "yellow ore"; player1.miningXP += 55; harvestedSuccessfully = true; } else if (player1.gearInterface.itemArray[5].ID == 33 && player1.orientation.equals("NORTH") && currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 - 1)].type.equals("t1stone")) { int storeRockPermutation = currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 - 1)].rockPermutation; currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 - 1)] = new Tile("t0stone", false, true, false); currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 - 1)].rockPermutation = storeRockPermutation; harvestedSuccessfully = true; harvestedItem = "yellow ore"; player1.miningXP += 55; } else if (player1.gearInterface.itemArray[5].ID == 33 && player1.orientation.equals("SOUTH") && currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 + 1)].type.equals("t1stone")) { int storeRockPermutation = currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 + 1)].rockPermutation; currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 + 1)] = new Tile("t0stone", false, true, false); currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 + 1)].rockPermutation = storeRockPermutation; player1.miningXP += 55; harvestedItem = "yellow ore"; harvestedSuccessfully = true; } /* TREE/WOOD GATHERING */ else if (player1.gearInterface.itemArray[5].ID == 32 && player1.orientation.equals("EAST") && currentOverWorld.tilemap[player1.xPos / 25 + 1][(player1.yPos / 25)].type.equals("tree")) { currentOverWorld.tilemap[player1.xPos / 25 + 1][(player1.yPos / 25)].type = "grass"; harvestedItem = "lumber"; player1.woodcuttingXP += 1; harvestedSuccessfully = true; } else if (player1.gearInterface.itemArray[5].ID == 32 && player1.orientation.equals("WEST") && currentOverWorld.tilemap[player1.xPos / 25 - 1][(player1.yPos / 25)].type.equals("tree")) { currentOverWorld.tilemap[player1.xPos / 25 - 1][(player1.yPos / 25)].type = "grass"; harvestedItem = "lumber"; player1.woodcuttingXP += 1; harvestedSuccessfully = true; } else if (player1.gearInterface.itemArray[5].ID == 32 && player1.orientation.equals("NORTH") && currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 - 1)].type.equals("tree")) { currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 - 1)].type = "grass"; harvestedSuccessfully = true; player1.woodcuttingXP += 1; harvestedItem = "lumber"; } else if (player1.gearInterface.itemArray[5].ID == 32 && player1.orientation.equals("SOUTH") && currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 + 1)].type.equals("tree")) { currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 + 1)].type = "grass"; harvestedItem = "lumber"; player1.woodcuttingXP += 1; harvestedSuccessfully = true; } if (harvestedSuccessfully) { // Iff the tile is flagged to be successfully harvested, find an empty slot and fill it with a given item. for (int i = 0; i < 64; i++) { if (player1.playerInventory.itemArray[i].ID == 0) { if (harvestedItem.equals("lumber")) { loadChopSound(); player1.playerInventory.itemArray[i].ID = 1; break; } else if (harvestedItem.equals("cobblestone")) { player1.playerInventory.itemArray[i].ID = 2; break; } else if (harvestedItem.equals("yellow ore")) { player1.playerInventory.itemArray[i].ID = 34; break; } } } tick(); } } else if ((currentOverWorld.tilemap[player1.xPos / 25 + xOffsetCheck][(player1.yPos / 25 + yOffsetCheck)].type.equals("dirt")) || (currentOverWorld.tilemap[player1.xPos / 25 + xOffsetCheck][(player1.yPos / 25 + yOffsetCheck)].type.equals("grass"))) { if (player1.gearInterface.itemArray[5].ID == 46 && (currentOverWorld.tilemap[player1.xPos / 25 + xOffsetCheck][(player1.yPos / 25 + yOffsetCheck)].type.equals("dirt"))) { currentOverWorld.tilemap[player1.xPos / 25 + xOffsetCheck][(player1.yPos / 25 + yOffsetCheck)].type = "rakeddirt"; player1.farmingExperience += 1; } else if (player1.gearInterface.itemArray[5].ID == 46 && (currentOverWorld.tilemap[player1.xPos / 25 + xOffsetCheck][(player1.yPos / 25 + yOffsetCheck)].type.equals("grass"))) { System.out.println("x"); currentOverWorld.tilemap[player1.xPos / 25 + xOffsetCheck][(player1.yPos / 25 + yOffsetCheck)].type = "dirt"; player1.farmingExperience += 1; } break; } } /* ITEM PLACEMENT */ case KeyEvent.VK_2: if (currentItem != null && currentItem.ID == 2) { if (player1.orientation.equals("NORTH") && !currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 - 1)].occupied) { currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 - 1)].type = "t0stone"; player1.playerInventory.itemArray[currentItemIndex].ID = 0; tick(); } else if (player1.orientation.equals("EAST") && !currentOverWorld.tilemap[player1.xPos / 25 + 1][(player1.yPos / 25)].occupied) { currentOverWorld.tilemap[player1.xPos / 25 + 1][(player1.yPos / 25)].type = "t0stone"; player1.playerInventory.itemArray[currentItemIndex].ID = 0; tick(); } if (player1.orientation.equals("SOUTH") && !currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 + 1)].occupied) { currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 + 1)].type = "t0stone"; player1.playerInventory.itemArray[currentItemIndex].ID = 0; tick(); } else if (player1.orientation.equals("WEST") && !currentOverWorld.tilemap[player1.xPos / 25 - 1][(player1.yPos / 25)].occupied) { currentOverWorld.tilemap[player1.xPos / 25 - 1][(player1.yPos / 25)].type = "t0stone"; player1.playerInventory.itemArray[currentItemIndex].ID = 0; tick(); } } else if (currentItem != null && currentItem.ID == 4) { if (player1.orientation.equals("NORTH") && !currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 - 1)].occupied) { currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 - 1)].type = "plankwall"; player1.playerInventory.itemArray[currentItemIndex].ID = 0; tick(); } else if (player1.orientation.equals("EAST") && !currentOverWorld.tilemap[player1.xPos / 25 + 1][(player1.yPos / 25)].occupied) { currentOverWorld.tilemap[player1.xPos / 25 + 1][(player1.yPos / 25)].type = "plankwall"; player1.playerInventory.itemArray[currentItemIndex].ID = 0; tick(); } if (player1.orientation.equals("SOUTH") && !currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 + 1)].occupied) { currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 + 1)].type = "plankwall"; player1.playerInventory.itemArray[currentItemIndex].ID = 0; tick(); } else if (player1.orientation.equals("WEST") && !currentOverWorld.tilemap[player1.xPos / 25 - 1][(player1.yPos / 25)].occupied) { currentOverWorld.tilemap[player1.xPos / 25 - 1][(player1.yPos / 25)].type = "plankwall"; player1.playerInventory.itemArray[currentItemIndex].ID = 0; tick(); } } break; case KeyEvent.VK_3: break; case KeyEvent.VK_R: raining = !raining; break; case KeyEvent.VK_K: rainVector = -rainVector; break; case KeyEvent.VK_F: System.out.println("F- fighting"); if (player1.orientation.equals("EAST")) { for (Npc n : currentOverWorld.npcList) { if (player1.xPos / 25 + 1 == n.xPos / 25 && player1.yPos / 25 == n.yPos / 25) { currentNpc = n; engagedSuccessfully = true; storeOrientation = player1.orientation; storeXPos = player1.xPos; // STORES WHERE THE COMBAT WAS INITIATED IN ORDER TO RETURN THE PLAYER TO THAT COORDINATE storeYPos = player1.yPos; // STORES WHERE THE COMBAT WAS INITIATED IN ORDER TO RETURN THE PLAYER TO THAT COORDINATE } } } if (player1.orientation.equals("WEST")) { for (Npc n : currentOverWorld.npcList) { if (player1.xPos / 25 - 1 == n.xPos / 25 && player1.yPos / 25 == n.yPos / 25) { currentNpc = n; engagedSuccessfully = true; storeOrientation = player1.orientation; storeXPos = player1.xPos; // STORES WHERE THE COMBAT WAS INITIATED IN ORDER TO RETURN THE PLAYER TO THAT COORDINATE storeYPos = player1.yPos; // STORES WHERE THE COMBAT WAS INITIATED IN ORDER TO RETURN THE PLAYER TO THAT COORDINATE } } } if (player1.orientation.equals("NORTH")) { for (Npc n : currentOverWorld.npcList) { if (player1.yPos / 25 - 1 == n.yPos / 25 && player1.xPos / 25 == n.xPos / 25) { currentNpc = n; engagedSuccessfully = true; storeOrientation = player1.orientation; storeXPos = player1.xPos; // STORES WHERE THE COMBAT WAS INITIATED IN ORDER TO RETURN THE PLAYER TO THAT COORDINATE storeYPos = player1.yPos; // STORES WHERE THE COMBAT WAS INITIATED IN ORDER TO RETURN THE PLAYER TO THAT COORDINATE } } } if (player1.orientation.equals("SOUTH")) { for (Npc n : currentOverWorld.npcList) { if (player1.yPos / 25 + 1 == n.yPos / 25 && player1.xPos / 25 == n.xPos / 25) { currentNpc = n; engagedSuccessfully = true; storeOrientation = player1.orientation; storeXPos = player1.xPos; // STORES WHERE THE COMBAT WAS INITIATED IN ORDER TO RETURN THE PLAYER TO THAT COORDINATE storeYPos = player1.yPos; // STORES WHERE THE COMBAT WAS INITIATED IN ORDER TO RETURN THE PLAYER TO THAT COORDINATE } } } System.out.println(engagedSuccessfully); if (engagedSuccessfully) { System.out.println("engaged"); currentNpc.HP -= 20; if (currentNpc.HP < 0) { TRIGGER_endOfCombat = true; currentNpc.HP = 100F; } break; } case KeyEvent.VK_I: currentTile = null; if (!startMenuVisible) { inventoryMenuVisible = !inventoryMenuVisible; System.out.println(player1.playerInventory); System.out.println("Inventory is full: " + player1.playerInventory.isFull()); break; } case KeyEvent.VK_V: if (!startMenuVisible) { viewMenuVisible = !viewMenuVisible; break; } case KeyEvent.VK_L: currentOverWorld.npcList = new Vector<>(); // overwrites current Overworld npclist with an empty one. break; case KeyEvent.VK_W: tick(); break; case KeyEvent.VK_P: String nameR; nameR = getUserInput(); readCustomWorld(nameR); break; case KeyEvent.VK_4: if (currentOverWorld.idX < 10 && currentOverWorld.idY < 10) { saveCustomWorld("WORLD0" + currentOverWorld.idX + "0" + currentOverWorld.idY); } else if (currentOverWorld.idX < 10) { saveCustomWorld("WORLD0" + currentOverWorld.idX + currentOverWorld.idY); } else if (currentOverWorld.idY < 10) { saveCustomWorld("WORLD" + currentOverWorld.idX + "0" + currentOverWorld.idY); } else { saveCustomWorld("WORLD" + currentOverWorld.idX + currentOverWorld.idY); } System.out.println(currentOverWorld.idX + " " + currentOverWorld.idY); break; case KeyEvent.VK_5: reloadOverWorld(); break; case KeyEvent.VK_6: currentOverWorld.npcList = new Vector<>(); dummyWorld(); break; case KeyEvent.VK_ESCAPE: currentItem = null; currentTile = null; currentTileX = 0; currentTileY = 0; break; case KeyEvent.VK_A: System.out.println("WELCOME TO THE DEBUG CONSOLE"); String inputString = JOptionPane.showInputDialog("Please input a command \n set id [mhand/ohand/chest/legs/head] [itemID] \n weather rain toggle \n weather rain setVector [x] \n add inv [itemId] "); if (inputString != null && inputString.length() > 7) { /* SET ID ARMOR */ if (inputString.substring(0, 7).equals("add inv")) { if (inputString.length() == 9) { for (int i = 0; i < 64; i++) { if (player1.playerInventory.itemArray[i].ID == 0) { player1.playerInventory.itemArray[i].ID = Integer.valueOf(inputString.substring(8, 9)); break; } } } else if (inputString.length() == 10) { for (int i = 0; i < 64; i++) { if (player1.playerInventory.itemArray[i].ID == 0) { player1.playerInventory.itemArray[i].ID = Integer.valueOf(inputString.substring(8, 10)); break; } } } } else if (inputString.substring(0, 12).equals("set id chest")) { if (inputString.length() < 15) { // case for if the user inputs a number less than 2 digits player1.gearInterface.itemArray[1].ID = Integer.valueOf(inputString.substring(13, 14)); } else if (inputString.length() < 16) { // case for if the user inputs a number less than 3 digits player1.gearInterface.itemArray[1].ID = Integer.valueOf(inputString.substring(13, 15)); } /* SET ID LEGS */ } else if (inputString.substring(0, 11).equals("set id legs")) { if (inputString.length() < 14) { // case for if the user inputs a number less than 2 digits player1.gearInterface.itemArray[2].ID = Integer.valueOf(inputString.substring(12, 13)); } else if (inputString.length() < 15) { // case for if the user inputs a number less than 3 digits player1.gearInterface.itemArray[2].ID = Integer.valueOf(inputString.substring(12, 14)); } /* SET ID OFFHAND */ } else if (inputString.substring(0, 12).equals("set id ohand")) { System.out.println(player1.gearInterface.itemArray[4].ID); if (inputString.length() < 15) { // case for if the user inputs a number less than 2 digits player1.gearInterface.itemArray[4].ID = Integer.valueOf(inputString.substring(13, 14)); } else if (inputString.length() < 16) { // case for if the user inputs a number less than 3 digits player1.gearInterface.itemArray[4].ID = Integer.valueOf(inputString.substring(13, 15)); } } /* SET ID MAINHAND */ else if (inputString.substring(0, 12).equals("set id mhand")) { System.out.println("EDIT MHAND"); System.out.println(player1.gearInterface.itemArray[5].ID); if (inputString.length() < 15) { // case for if the user inputs a number less than 2 digits player1.gearInterface.itemArray[5].ID = Integer.valueOf(inputString.substring(13, 14)); } else if (inputString.length() < 16) { // case for if the user inputs a number less than 3 digits player1.gearInterface.itemArray[5].ID = Integer.valueOf(inputString.substring(13, 15)); } System.out.println(player1.gearInterface.itemArray[4].ID); /* WEATHER RAIN TOGGLE */ } else if (Objects.equals(inputString, "weather rain toggle")) { raining = !raining; /* WEATHER RAIN SET VECTOR */ } else if (inputString.length() > 22 && inputString.substring(0, 22).equals("weather rain setVector")) { if (inputString.length() < 25) { rainVector = Integer.valueOf(inputString.substring(23, 24)); } else if (inputString.length() < 26) { rainVector = Integer.valueOf(inputString.substring(23, 25)); } } } } if (!stuckInDialogue && (e.getKeyCode() == KeyEvent.VK_UP || e.getKeyCode() == KeyEvent.VK_DOWN || e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_RIGHT)) { if (mapVisible) { tick(); } } } private void loadMovementSound() { File Step1 = new File("Data/Sound/Step1.wav"); File Step2 = new File("Data/Sound/Step2.wav"); File Step3 = new File("Data/Sound/Step3.wav"); File Step4 = new File("Data/Sound/Step4.wav"); int stepCounter = rotateRng() % 3; try { if (stepCounter == 0) { audioInputStream = AudioSystem.getAudioInputStream(Step1); } else if (stepCounter == 1) { audioInputStream = AudioSystem.getAudioInputStream(Step2); } else if (stepCounter == 2) { audioInputStream = AudioSystem.getAudioInputStream(Step3); } } catch (UnsupportedAudioFileException | IOException e) { e.printStackTrace(); } try { movementSound = AudioSystem.getClip(); movementSound.open(audioInputStream); movementSound.start(); } catch (LineUnavailableException | IOException e) { e.printStackTrace(); } } private void loadChopSound() { File woodChoop = new File("Data/Sound/WoodChop.wav"); try { audioInputStream = AudioSystem.getAudioInputStream(woodChoop); } catch (UnsupportedAudioFileException | IOException e) { e.printStackTrace(); } try { Clip woodsSound = AudioSystem.getClip(); woodsSound.open(audioInputStream); woodsSound.start(); } catch (LineUnavailableException | IOException e) { e.printStackTrace(); } } @Override public void keyReleased(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_SHIFT: shiftPressed = false; break; case KeyEvent.VK_CONTROL: controlPressed = false; break; case KeyEvent.VK_ALT: altPressed = false; break; } } @Override public void mouseClicked(MouseEvent e) { requestFocusInWindow(); int x = e.getX(); int y = e.getY(); System.out.println("==CLICK=="); System.out.println(x + ", " + y); System.out.println("" + (x / 25) + ", " + (y / 25)); System.out.println("========="); if (e.getButton() == MouseEvent.BUTTON3) { // ON LEFT MOUSE CLICK if (inventoryMenuVisible) { onMouseClickEquipItems(x, y); } currentItem = null; currentItemIndex = 0; currentItemColumn = 0; currentItemRow = 0; } else if (e.getButton() == MouseEvent.BUTTON1) { // ON RIGHT MOUSE CLICK if (craftingMenuVisible) { putCurrentItemIntoCraftingInterface(x, y); } if (inventoryMenuVisible) { currentItem = onMouseClickSelectItem(x, y); } if (debugMenuVisible && x > 81 && x < 107 && y > 23 && y < 50) { rotateTileBrush(true); } if (debugMenuVisible && x > 81 && x < 107 && y > 55 && y < 81) { rotateTileBrush(false); } if (debugMenuVisible && x > 196 && x < 228 && y > 23 && y < 50) { rotateNpcBrush(true); } if (debugMenuVisible && x > 196 && x < 228 && y > 55 && y < 81) { rotateNpcBrush(false); } if (shiftPressed && controlPressed) { paintWithTileBrush(x, y); } if (shiftPressed && altPressed) { paintWithNpcBrush(x, y); } if (inventoryMenuVisible && x > 151 && x < 151 + 59 && y > 233 && y < 233 + 15) { // Todo: adjust range of clicking to craft INTERACTS WITH BUTTON -> g.fillRect(151, 233, 59, 15); // "CRAFT BUTTON" craftItem(); } if (inventoryMenuVisible && x > 151 && x < 151 + 71 && y > 253 && y < 253 + 15) { // Todo: adjust range of clicking to return INTERACTS WITH BUTTON -> g.fillRect(151,253,71,15); // "RETURN" BUTTON returnAllItemsFromCraftingInterface(); } } if (!inventoryMenuVisible && !debugMenuVisible && !startMenuVisible) { currentTile = onMouseClickSelectTile(x, y); onMouseClickOpenDoor(x, y); } onMouseClickInteractWithNpc(x, y); if (attackStyleChooserVisible) { onMouseClickAddAbility(x, y); } if (stuckInDialogue && mousedOverDialogue != 0) { changeDialogueState(); } /* QUICKSLOT GUI INTERFACE */ if (x > 730 && x < 773 && y > 26 && y < 62) { inventoryMenuVisible = !inventoryMenuVisible; } else if (x > 678 && x < 728 && y > 26 && y < 62) { craftingMenuVisible = !craftingMenuVisible; } else if (x > 626 && x < 666 && y > 26 && y < 62) { attackStyleChooserVisible = !attackStyleChooserVisible; } } private void paintWithNpcBrush(int x, int y) { currentTileX = x / 25; currentTileY = y / 25; generateNpc(currentOverWorld.npcList.size() + 1, currentTileX, currentTileY, 50, Color.black, npcBrush.toUpperCase()); } private void paintWithTileBrush(int x, int y) { currentTileX = x / 25; currentTileY = y / 25; currentOverWorld.tilemap[currentTileX][currentTileY].type = tileBrush; if (tileBrush.equals("t0stone0")) { currentOverWorld.tilemap[currentTileX][currentTileY] = new Tile("t0stone", false, true, false); } else if (tileBrush.equals("grass0")) { currentOverWorld.tilemap[currentTileX][currentTileY] = new Tile("grass", false, true, false); } else if (tileBrush.equals("t1stone0")) { currentOverWorld.tilemap[currentTileX][currentTileY] = new Tile("t1stone", false, true, false); } else if (tileBrush.equals("t2stone0")) { currentOverWorld.tilemap[currentTileX][currentTileY] = new Tile("t2stone", false, true, false); } else if (tileBrush.equals("t3stone0")) { currentOverWorld.tilemap[currentTileX][currentTileY] = new Tile("t3stone", false, true, false); } else if (tileBrush.equals("t4stone0")) { currentOverWorld.tilemap[currentTileX][currentTileY] = new Tile("t4stone", false, true, false); } else if (tileBrush.equals("t0stone0_1x2")) { currentOverWorld.tilemap[currentTileX][currentTileY] = new Tile("t0stone_1x2_a", false, true, false); currentOverWorld.tilemap[currentTileX + 1][currentTileY] = new Tile("t0stone_1x2_b", false, true, false); } else if (tileBrush.equals("t1stone0_1x2")) { currentOverWorld.tilemap[currentTileX][currentTileY] = new Tile("t1stone_1x2_a", false, true, false); currentOverWorld.tilemap[currentTileX + 1][currentTileY] = new Tile("t1stone_1x2_b", false, true, false); } else if (tileBrush.equals("t2stone0_1x2")) { currentOverWorld.tilemap[currentTileX][currentTileY] = new Tile("t2stone_1x2_a", false, true, false); currentOverWorld.tilemap[currentTileX + 1][currentTileY] = new Tile("t1stone_1x2_b", false, true, false); } else if (tileBrush.equals("furnace_unlit")) { currentOverWorld.tilemap[currentTileX][currentTileY] = new Tile("furnace", false, true, false); } else if (tileBrush.equals("furnace_lit")) { currentOverWorld.tilemap[currentTileX][currentTileY] = new Tile("furnace", false, true, true); } else if (tileBrush.equals("cookingpot")) { currentOverWorld.tilemap[currentTileX][currentTileY] = new Tile("cookingpot", false, true, true); } } private void returnAllItemsFromCraftingInterface() { for (int i = 0; i < player1.playerCrafter.itemArray.length - 1; i++) { player1.playerInventory.addItem(player1.playerCrafter.itemArray[i].ID); } player1.playerCrafter = new CraftingInterface(10); } private void craftItem() { for (int i = 0; i < 64; i++) { if (player1.playerInventory.itemArray[i].ID == 0) { player1.playerInventory.itemArray[i].ID = player1.playerCrafter.itemArray[9].ID; break; } } player1.playerCrafter = new CraftingInterface(10); } private void changeDialogueState() { if (currentDialogueNpc.ai.equals("LUMBERJACK")) { switch (TRIGGER_dialogueState) { case 0: switch (mousedOverDialogue) { case 1: TRIGGER_dialogueState = 1; break; case 2: exitDialogue(); break; case 3: break; } break; case 1: switch (mousedOverDialogue) { case 1: TRIGGER_dialogueState = 2; break; case 2: exitDialogue(); break; case 3: exitDialogue(); break; } break; case 2: switch (mousedOverDialogue) { case 1: boolean hasQuest = false; for (Quest q : player1.personalQuestLog) { if (q.questID == 0) { hasQuest = true; } } if (!hasQuest) { player1.personalQuestLog.add(new Quest(0, "Gathering Wood", "NPC wants you to gather 10 wood for him so he can build a new house", "Gather 10 Wood for NPC", new Item[]{new Item(1), new Item(1), new Item(1), new Item(1), new Item(1), new Item(1), new Item(1), new Item(1), new Item(1), new Item(1)}, new ArrayList<Integer>())); } exitDialogue(); break; case 2: exitDialogue(); break; case 3: exitDialogue(); break; } break; case 3: switch (mousedOverDialogue) { case 1: exitDialogue(); break; case 2: if (player1.playerInventory.hasItem(1, 10)) { player1.playerInventory.removeItem(1, 10); for (int i = 0; i < player1.personalQuestLog.size(); i++) { if (player1.personalQuestLog.get(i).questID == 0) { player1.personalQuestLog.remove(i); System.out.println("QUEST (id = 0) COMPLETE"); player1.personalQuestsCompleted.add(0); player1.gold += 3; TRIGGER_dialogueState = 4; } } } break; } break; case 4: switch (mousedOverDialogue) { case 1: exitDialogue(); break; case 2: exitDialogue(); break; } break; case 5: switch (mousedOverDialogue) { case 1: TRIGGER_dialogueState = 6; break; case 2: TRIGGER_dialogueState = 6; break; } break; case 6: switch (mousedOverDialogue) { case 1: TRIGGER_dialogueState = 7; break; case 2: exitDialogue(); break; case 3: exitDialogue(); break; } break; case 7: switch (mousedOverDialogue) { case 1: player1.personalQuestLog.add(new Quest(1, "Meet the castle", "Take the wood bundle to the castle doors", "Take the wood to the castle", new Item[1], new ArrayList<Integer>())); TRIGGER_dialogueState = 8; break; case 2: exitDialogue(); break; } break; case 8: switch (mousedOverDialogue) { case 1: exitDialogue(); break; } break; case 9: switch (mousedOverDialogue) { case 1: exitDialogue(); break; } break; } } else if (currentDialogueNpc.ai.equals("CASTLEGUARD")) { switch (TRIGGER_dialogueState) { case 0: switch (mousedOverDialogue) { case 1: exitDialogue(); break; } break; case 1: switch (mousedOverDialogue) { case 1: TRIGGER_dialogueState = 2; break; case 2: exitDialogue(); break; } break; case 2: switch (mousedOverDialogue) { case 1: for (int i = 0; i < player1.personalQuestLog.size(); i++) { if (player1.personalQuestLog.get(i).questID == 1) { player1.personalQuestLog.remove(i); System.out.println("QUEST (id = 1) COMPLETE"); player1.personalQuestsCompleted.add(1); player1.gold += 7; TRIGGER_dialogueState = 3; } } break; case 2: exitDialogue(); break; } break; case 3: switch (mousedOverDialogue) { case 1: exitDialogue(); break; } break; } } } private void exitDialogue() { stuckInDialogue = false; currentDialogueNpc = null; TRIGGER_dialogueState = 0; mousedOverDialogue = 0; npcDialogue = "npcdialogue"; playerResponse1 = "playerresponse1"; playerResponse2 = "playerresponse2"; playerResponse3 = "playerresponse3"; } private void onMouseClickInteractWithNpc(int x, int y) { for (Npc n : currentOverWorld.npcList) { if (n.ai.equals("LUMBERJACK") || n.ai.equals("CASTLEGUARD")) { if (((player1.xPos / 25) == (n.xPos / 25)) && (((player1.yPos / 25) == ((n.yPos / 25) - 1)) || ((player1.yPos / 25) == ((n.yPos / 25) + 1))) || ((player1.yPos / 25) == (n.yPos / 25)) && (((player1.xPos / 25) == ((n.xPos / 25) - 1)) || ((player1.xPos / 25) == ((n.xPos / 25) + 1)))) { if ((x / 25) == (n.xPos / 25) && (y / 25) == (n.yPos / 25)) { loadChopSound(); // Todo: Add an "interact with npc" soundclip. stuckInDialogue = true; currentDialogueNpc = n; } } } } } private void onMouseClickOpenDoor(int x, int y) { switch (currentOverWorld.tilemap[x / 25][y / 25].type) { case "woodfloordooreast": if (player1.yPos / 25 == y / 25) { if (player1.xPos / 25 == x / 25 + 1 || player1.xPos / 25 == x / 25 - 1) { currentOverWorld.tilemap[x / 25][y / 25].type = "openwoodfloordooreast"; } } tick(); break; case "woodfloordoorwest": if (player1.yPos / 25 == y / 25) { if (player1.xPos / 25 == x / 25 + 1 || player1.xPos / 25 == x / 25 - 1) { currentOverWorld.tilemap[x / 25][y / 25].type = "openwoodfloordoorwest"; } } tick(); break; case "woodfloordoornorth": if (player1.xPos / 25 == x / 25) { if (player1.yPos / 25 == y / 25 + 1 || player1.yPos / 25 == y / 25 - 1) { currentOverWorld.tilemap[x / 25][y / 25].type = "openwoodfloordoornorth"; } } tick(); break; case "woodfloordoorsouth": if (player1.xPos / 25 == x / 25) { if (player1.yPos / 25 == y / 25 + 1 || player1.yPos / 25 == y / 25 - 1) { currentOverWorld.tilemap[x / 25][y / 25].type = "openwoodfloordoorsouth"; } } tick(); break; case "openwoodfloordooreast": if (player1.yPos / 25 == y / 25) { if (player1.xPos / 25 == x / 25 + 1 || player1.xPos / 25 == x / 25 - 1) { currentOverWorld.tilemap[x / 25][y / 25].type = "woodfloordooreast"; } } tick(); break; case "openwoodfloordoorwest": if (player1.yPos / 25 == y / 25) { if (player1.xPos / 25 == x / 25 + 1 || player1.xPos / 25 == x / 25 - 1) { currentOverWorld.tilemap[x / 25][y / 25].type = "woodfloordoorwest"; } } tick(); break; case "openwoodfloordoornorth": if (player1.xPos / 25 == x / 25) { if (player1.yPos / 25 == y / 25 + 1 || player1.yPos / 25 == y / 25 - 1) { currentOverWorld.tilemap[x / 25][y / 25].type = "woodfloordoornorth"; } } tick(); break; case "openwoodfloordoorsouth": if (player1.xPos / 25 == x / 25) { if (player1.yPos / 25 == y / 25 + 1 || player1.yPos / 25 == y / 25 - 1) { currentOverWorld.tilemap[x / 25][y / 25].type = "woodfloordoorsouth"; } } tick(); break; } } private void onMouseClickEquipItems(int x, int y) { Item newItem = onMouseClickSelectItem(x, y); if (newItem != null) { // MAINHAND if ((newItem.ID == 9 || newItem.ID == 13 || newItem.ID == 20 || newItem.ID == 31 || newItem.ID == 32 || newItem.ID == 33 || newItem.ID == 38 || newItem.ID == 39 || newItem.ID == 40 || newItem.ID == 41 || newItem.ID == 46 )) { Item oldItem = player1.gearInterface.itemArray[5]; if (equipItem(newItem)) { for (int i = 0; i < player1.playerInventory.itemArray.length; i++) { if (player1.playerInventory.itemArray[i].ID == newItem.ID) { player1.playerInventory.itemArray[i].ID = oldItem.ID; break; } } } } // CHEST ARMOR if ((newItem.ID == 6 || newItem.ID == 16 || newItem.ID == 17 || newItem.ID == 23 || newItem.ID == 24 || newItem.ID == 29 || newItem.ID == 30 )) { Item oldItem = player1.gearInterface.itemArray[1]; if (equipItem(newItem)) { for (int i = 0; i < player1.playerInventory.itemArray.length; i++) { if (player1.playerInventory.itemArray[i].ID == newItem.ID) { player1.playerInventory.itemArray[i].ID = oldItem.ID; break; } } } } // LEG ARMOR if ((newItem.ID == 7 || newItem.ID == 14 || newItem.ID == 15 || newItem.ID == 21 || newItem.ID == 22 || newItem.ID == 27 || newItem.ID == 28 )) { Item oldItem = player1.gearInterface.itemArray[2]; if (equipItem(newItem)) { for (int i = 0; i < player1.playerInventory.itemArray.length; i++) { if (player1.playerInventory.itemArray[i].ID == newItem.ID) { player1.playerInventory.itemArray[i].ID = oldItem.ID; break; } } } } // OFFHAND if ((newItem.ID == 10 || newItem.ID == 11 || newItem.ID == 12 || newItem.ID == 18 || newItem.ID == 19 || newItem.ID == 25 || newItem.ID == 26 )) { Item oldItem = player1.gearInterface.itemArray[4]; if (equipItem(newItem)) { for (int i = 0; i < player1.playerInventory.itemArray.length; i++) { if (player1.playerInventory.itemArray[i].ID == newItem.ID) { player1.playerInventory.itemArray[i].ID = oldItem.ID; break; } } } } } } private boolean equipItem(Item item) { // MAIN HAND WEAPONS if (item.ID == 13) { player1.gearInterface.itemArray[5] = new Item(13); return true; } else if (item.ID == 9) { player1.gearInterface.itemArray[5] = new Item(9); return true; } else if (item.ID == 20) { player1.gearInterface.itemArray[5] = new Item(20); return true; } else if (item.ID == 31) { player1.gearInterface.itemArray[5] = new Item(31); return true; } else if (item.ID == 32) { player1.gearInterface.itemArray[5] = new Item(32); return true; } else if (item.ID == 33) { player1.gearInterface.itemArray[5] = new Item(33); return true; } else if (item.ID == 38) { player1.gearInterface.itemArray[5] = new Item(38); return true; } else if (item.ID == 39) { player1.gearInterface.itemArray[5] = new Item(39); return true; } else if (item.ID == 40) { player1.gearInterface.itemArray[5] = new Item(40); return true; } else if (item.ID == 41) { player1.gearInterface.itemArray[5] = new Item(41); return true; } else if (item.ID == 46) { player1.gearInterface.itemArray[5] = new Item(46); return true; } // CHEST ARMOR else if (item.ID == 6) { player1.gearInterface.itemArray[1] = new Item(6); return true; } else if (item.ID == 16) { player1.gearInterface.itemArray[1] = new Item(16); return true; } else if (item.ID == 17) { player1.gearInterface.itemArray[1] = new Item(17); return true; } else if (item.ID == 23) { player1.gearInterface.itemArray[1] = new Item(23); return true; } else if (item.ID == 24) { player1.gearInterface.itemArray[1] = new Item(24); return true; } else if (item.ID == 29) { player1.gearInterface.itemArray[1] = new Item(29); return true; } else if (item.ID == 30) { player1.gearInterface.itemArray[1] = new Item(30); return true; } // LEG ARMOR else if (item.ID == 7) { player1.gearInterface.itemArray[2] = new Item(7); return true; } else if (item.ID == 14) { player1.gearInterface.itemArray[2] = new Item(14); return true; } else if (item.ID == 15) { player1.gearInterface.itemArray[2] = new Item(15); return true; } else if (item.ID == 21) { player1.gearInterface.itemArray[2] = new Item(21); return true; } else if (item.ID == 22) { player1.gearInterface.itemArray[2] = new Item(22); return true; } else if (item.ID == 27) { player1.gearInterface.itemArray[2] = new Item(27); return true; } else if (item.ID == 28) { player1.gearInterface.itemArray[2] = new Item(28); return true; } // OFF HAND else if (item.ID == 10) { player1.gearInterface.itemArray[4] = new Item(10); return true; } else if (item.ID == 11) { player1.gearInterface.itemArray[4] = new Item(11); return true; } else if (item.ID == 12) { player1.gearInterface.itemArray[4] = new Item(12); return true; } else if (item.ID == 18) { player1.gearInterface.itemArray[4] = new Item(18); return true; } else if (item.ID == 19) { player1.gearInterface.itemArray[4] = new Item(19); return true; } else if (item.ID == 25) { player1.gearInterface.itemArray[4] = new Item(25); return true; } else if (item.ID == 26) { player1.gearInterface.itemArray[4] = new Item(26); return true; } return false; } private void onMouseClickAddAbility(int x, int y) { int abilityIDToAdd = 0; if (x > 26 && x < 56 && y > 386 && y < 416) { abilityIDToAdd = 1; } else if (x > 56 && x < 86 && y > 386 && y < 416) { abilityIDToAdd = 2; } else if (x > 86 && x < 116 && y > 386 && y < 416) { abilityIDToAdd = 3; } else if (x > 116 && x < 146 && y > 386 && y < 416) { abilityIDToAdd = 0; } else if (x > 146 && x < 176 && y > 386 && y < 416) { abilityIDToAdd = 0; } else if (x > 176 && x < 206 && y > 386 && y < 416) { abilityIDToAdd = 0; } else if (x > 206 && x < 236 && y > 386 && y < 416) { abilityIDToAdd = 0; } else if (x > 236 && x < 266 && y > 386 && y < 416) { abilityIDToAdd = 0; } if (abilities[0] == 0) { abilities[0] = abilityIDToAdd; } else if (abilities[1] == 0) { abilities[1] = abilityIDToAdd; } else if (abilities[2] == 0) { abilities[2] = abilityIDToAdd; } System.out.println(abilities[0] + ", " + abilities[1] + ", " + abilities[2]); } private void indexTiles() { BrushTileList.add("FURNACE_UNLIT"); BrushTileList.add("COOKING_POT"); BrushTileList.add("FURNACE_LIT"); BrushTileList.add("SAND"); BrushTileList.add("GRASS0"); BrushTileList.add("T0STONE0_1x2"); BrushTileList.add("T1STONE0_1x2"); BrushTileList.add("T2STONE0_1x2"); BrushTileList.add("T0STONE0"); BrushTileList.add("T1STONE0"); BrushTileList.add("T2STONE0"); BrushTileList.add("T3STONE0"); BrushTileList.add("T4STONE0"); BrushTileList.add("DIRT"); BrushTileList.add("PLANKWALL"); BrushTileList.add("RAKEDDIRT"); BrushTileList.add("WOODFLOOR"); BrushTileList.add("TREE"); BrushTileList.add("WATER"); BrushTileList.add("STONEPATHGRASS"); BrushTileList.add("WOODFLOORDOORNORTH"); BrushTileList.add("WOODFLOORDOOREAST"); BrushTileList.add("WOODFLOORDOORSOUTH"); BrushTileList.add("WOODFLOORDOORWEST"); BrushTileList.add("WOODENFENCEHORIZONTAL"); BrushTileList.add("WOODENFENCEVERTICAL"); BrushTileList.add("WOODENFENCENWCORNER"); BrushTileList.add("WOODENFENCENECORNER"); BrushTileList.add("WOODENFENCESECORNER"); BrushTileList.add("WOODENFENCESWCORNER"); tileBrushIndex = 0; } private void indexNpc() { brushNpcList.add("SHEEP"); brushNpcList.add("CHASER"); brushNpcList.add("LUMBERJACK"); brushNpcList.add("CASTLEGUARD"); npcBrushIndex = 0; } private void rotateTileBrush(Boolean up) { if (up) { if (tileBrushIndex == BrushTileList.size() - 1) { tileBrushIndex = 0; } else { tileBrushIndex++; } } else { if (tileBrushIndex == 0) { tileBrushIndex = BrushTileList.size() - 1; } else { tileBrushIndex } } tileBrush = BrushTileList.get(tileBrushIndex).toLowerCase(); } private void rotateNpcBrush(Boolean up) { if (up) { if (npcBrushIndex == brushNpcList.size() - 1) { npcBrushIndex = 0; } else { npcBrushIndex++; } } else { if (npcBrushIndex == 0) { npcBrushIndex = brushNpcList.size() - 1; } else { npcBrushIndex } } npcBrush = brushNpcList.get(npcBrushIndex).toLowerCase(); } private void putCurrentItemIntoCraftingInterface(int x, int y) { int craftingSlotIndex = -1; if (x > 34 && x < 34 + 30 && y > 149 && y < 149 + 30) { craftingSlotIndex = 0; } else if (x > 64 && x < 64 + 30 && y > 149 && y < 149 + 30) { craftingSlotIndex = 1; } else if (x > 94 && x < 94 + 30 && y > 149 && y < 149 + 30) { craftingSlotIndex = 2; } else if (x > 34 && x < 34 + 30 && y > 179 && y < 179 + 30) { craftingSlotIndex = 3; } else if (x > 64 && x < 64 + 30 && y > 179 && y < 179 + 30) { craftingSlotIndex = 4; } else if (x > 94 && x < 94 + 30 && y > 179 && y < 179 + 30) { craftingSlotIndex = 5; } else if (x > 34 && x < 34 + 30 && y > 209 && y < 209 + 30) { craftingSlotIndex = 6; } else if (x > 64 && x < 64 + 30 && y > 209 && y < 209 + 30) { craftingSlotIndex = 7; } else if (x > 94 && x < 94 + 30 && y > 209 && y < 209 + 30) { craftingSlotIndex = 8; } if (craftingSlotIndex != -1) { player1.playerCrafter.itemArray[craftingSlotIndex].ID = currentItem.ID; currentItem.ID = 0; currentItemIndex = 0; currentItemRow = 0; currentItemColumn = 0; } updateCrafterOutputSlot(); } private void updateCrafterOutputSlot() { // CRAFTING RECIPES if (player1.playerCrafter.itemArray[0].ID == 1 && // RECIPE FOR WOODEN WALL player1.playerCrafter.itemArray[1].ID == 1 && player1.playerCrafter.itemArray[2].ID == 1 && player1.playerCrafter.itemArray[3].ID == 0 && player1.playerCrafter.itemArray[4].ID == 0 && player1.playerCrafter.itemArray[5].ID == 0 && player1.playerCrafter.itemArray[6].ID == 0 && player1.playerCrafter.itemArray[7].ID == 0 && player1.playerCrafter.itemArray[8].ID == 0) { player1.playerCrafter.itemArray[9].ID = 4; } else if (player1.playerCrafter.itemArray[0].ID == 0 && // RECIPE FOR WOODEN WALL player1.playerCrafter.itemArray[1].ID == 2 && player1.playerCrafter.itemArray[2].ID == 2 && player1.playerCrafter.itemArray[3].ID == 0 && player1.playerCrafter.itemArray[4].ID == 1 && player1.playerCrafter.itemArray[5].ID == 2 && player1.playerCrafter.itemArray[6].ID == 0 && player1.playerCrafter.itemArray[7].ID == 1 && player1.playerCrafter.itemArray[8].ID == 0) { player1.playerCrafter.itemArray[9].ID = 32; } else if (player1.playerCrafter.itemArray[0].ID == 2 && // RECIPE FOR WOODEN WALL player1.playerCrafter.itemArray[1].ID == 2 && player1.playerCrafter.itemArray[2].ID == 2 && player1.playerCrafter.itemArray[3].ID == 0 && player1.playerCrafter.itemArray[4].ID == 1 && player1.playerCrafter.itemArray[5].ID == 0 && player1.playerCrafter.itemArray[6].ID == 0 && player1.playerCrafter.itemArray[7].ID == 1 && player1.playerCrafter.itemArray[8].ID == 0) { player1.playerCrafter.itemArray[9].ID = 33; } else { player1.playerCrafter.itemArray[9].ID = 0; } } private Item onMouseClickSelectItem(int x, int y) { currentItem = null; currentItemIndex = -1; currentItemColumn = -1; currentItemRow = -1; if (inRange(x, 587, 617, true)) { currentItemColumn = 1; if (inRange(y, 176, 206, true)) { currentItemRow = 1; currentItemIndex = 0; } else if (inRange(y, 207, 237, true)) { currentItemRow = 2; currentItemIndex = 6; } else if (inRange(y, 238, 268, true)) { currentItemRow = 3; currentItemIndex = 12; } else if (inRange(y, 269, 299, true)) { currentItemRow = 4; currentItemIndex = 18; } else if (inRange(y, 300, 330, true)) { currentItemRow = 5; currentItemIndex = 24; } else if (inRange(y, 331, 361, true)) { currentItemRow = 6; currentItemIndex = 30; } else if (inRange(y, 362, 392, true)) { currentItemRow = 7; currentItemIndex = 36; } else if (inRange(y, 393, 423, true)) { currentItemRow = 8; currentItemIndex = 42; } else if (inRange(y, 424, 454, true)) { currentItemRow = 9; currentItemIndex = 48; } else if (inRange(y, 455, 485, true)) { currentItemRow = 10; currentItemIndex = 54; } else if (inRange(y, 486, 516, true)) { currentItemRow = 11; currentItemIndex = 60; } } else if (inRange(x, 618, 648, true)) { currentItemColumn = 2; if (inRange(y, 176, 206, true)) { currentItemRow = 1; currentItemIndex = 1; } else if (inRange(y, 207, 237, true)) { currentItemRow = 2; currentItemIndex = 7; } else if (inRange(y, 238, 268, true)) { currentItemRow = 3; currentItemIndex = 13; } else if (inRange(y, 269, 299, true)) { currentItemRow = 4; currentItemIndex = 19; } else if (inRange(y, 300, 330, true)) { currentItemRow = 5; currentItemIndex = 25; } else if (inRange(y, 331, 361, true)) { currentItemRow = 6; currentItemIndex = 31; } else if (inRange(y, 362, 392, true)) { currentItemRow = 7; currentItemIndex = 37; } else if (inRange(y, 393, 423, true)) { currentItemRow = 8; currentItemIndex = 43; } else if (inRange(y, 424, 454, true)) { currentItemRow = 9; currentItemIndex = 49; } else if (inRange(y, 455, 485, true)) { currentItemRow = 10; currentItemIndex = 55; } else if (inRange(y, 486, 516, true)) { currentItemRow = 11; currentItemIndex = 61; } } else if (inRange(x, 649, 679, true)) { currentItemColumn = 3; if (inRange(y, 176, 206, true)) { currentItemRow = 1; currentItemIndex = 2; } else if (inRange(y, 207, 237, true)) { currentItemRow = 2; currentItemIndex = 8; } else if (inRange(y, 238, 268, true)) { currentItemRow = 3; currentItemIndex = 14; } else if (inRange(y, 269, 299, true)) { currentItemRow = 4; currentItemIndex = 20; } else if (inRange(y, 300, 330, true)) { currentItemRow = 5; currentItemIndex = 26; } else if (inRange(y, 331, 361, true)) { currentItemRow = 6; currentItemIndex = 32; } else if (inRange(y, 362, 392, true)) { currentItemRow = 7; currentItemIndex = 38; } else if (inRange(y, 393, 423, true)) { currentItemRow = 8; currentItemIndex = 44; } else if (inRange(y, 424, 454, true)) { currentItemRow = 9; currentItemIndex = 50; } else if (inRange(y, 455, 485, true)) { currentItemRow = 10; currentItemIndex = 56; } else if (inRange(y, 486, 516, true)) { currentItemRow = 11; currentItemIndex = 62; } } else if (inRange(x, 680, 710, true)) { currentItemColumn = 4; if (inRange(y, 176, 206, true)) { currentItemRow = 1; currentItemIndex = 3; } else if (inRange(y, 207, 237, true)) { currentItemRow = 2; currentItemIndex = 9; } else if (inRange(y, 238, 268, true)) { currentItemRow = 3; currentItemIndex = 15; } else if (inRange(y, 269, 299, true)) { currentItemRow = 4; currentItemIndex = 21; } else if (inRange(y, 300, 330, true)) { currentItemRow = 5; currentItemIndex = 27; } else if (inRange(y, 331, 361, true)) { currentItemRow = 6; currentItemIndex = 33; } else if (inRange(y, 362, 392, true)) { currentItemRow = 7; currentItemIndex = 39; } else if (inRange(y, 393, 423, true)) { currentItemRow = 8; currentItemIndex = 45; } else if (inRange(y, 424, 454, true)) { currentItemRow = 9; currentItemIndex = 51; } else if (inRange(y, 455, 485, true)) { currentItemRow = 10; currentItemIndex = 57; } else if (inRange(y, 486, 516, true)) { currentItemRow = 11; currentItemIndex = 63; } } else if (inRange(x, 711, 741, true)) { currentItemColumn = 5; if (inRange(y, 176, 206, true)) { currentItemRow = 1; currentItemIndex = 4; } else if (inRange(y, 207, 237, true)) { currentItemRow = 2; currentItemIndex = 10; } else if (inRange(y, 238, 268, true)) { currentItemRow = 3; currentItemIndex = 16; } else if (inRange(y, 269, 299, true)) { currentItemRow = 4; currentItemIndex = 22; } else if (inRange(y, 300, 330, true)) { currentItemRow = 5; currentItemIndex = 28; } else if (inRange(y, 331, 361, true)) { currentItemRow = 6; currentItemIndex = 34; } else if (inRange(y, 362, 392, true)) { currentItemRow = 7; currentItemIndex = 40; } else if (inRange(y, 393, 423, true)) { currentItemRow = 8; currentItemIndex = 46; } else if (inRange(y, 424, 454, true)) { currentItemRow = 9; currentItemIndex = 52; } else if (inRange(y, 455, 485, true)) { currentItemRow = 10; currentItemIndex = 58; } else if (inRange(y, 486, 516, true)) { currentItemRow = 11; currentItemIndex = 64; } } else if (inRange(x, 742, 772, true)) { currentItemColumn = 6; if (inRange(y, 176, 206, true)) { currentItemRow = 1; currentItemIndex = 5; } else if (inRange(y, 207, 237, true)) { currentItemRow = 2; currentItemIndex = 11; } else if (inRange(y, 238, 268, true)) { currentItemRow = 3; currentItemIndex = 17; } else if (inRange(y, 269, 299, true)) { currentItemRow = 4; currentItemIndex = 23; } else if (inRange(y, 300, 330, true)) { currentItemRow = 5; currentItemIndex = 29; } else if (inRange(y, 331, 361, true)) { currentItemRow = 6; currentItemIndex = 35; } else if (inRange(y, 362, 392, true)) { currentItemRow = 7; currentItemIndex = 41; } else if (inRange(y, 393, 423, true)) { currentItemRow = 8; currentItemIndex = 47; } else if (inRange(y, 424, 454, true)) { currentItemRow = 9; currentItemIndex = 53; } else if (inRange(y, 455, 485, true)) { currentItemRow = 10; currentItemIndex = 59; } else if (inRange(y, 486, 516, true)) { currentItemRow = 11; currentItemIndex = 65; } } if (x > 156 && x < 156 + 30 && y > 183 && y < 183 + 30) { return player1.playerCrafter.itemArray[9]; } if (currentItemIndex < 0) { return null; } return player1.playerInventory.itemArray[currentItemIndex]; } private Item onMouseMovedSelectHoverItem(int x, int y) { currentHoverItem = null; int currentHoverItemIndex = -1; int currentHoverItemRow = -1; if (inRange(x, 587, 617, true)) { if (inRange(y, 176, 206, true)) { currentHoverItemRow = 1; currentHoverItemIndex = 0; } else if (inRange(y, 207, 237, true)) { currentHoverItemRow = 2; currentHoverItemIndex = 6; } else if (inRange(y, 238, 268, true)) { currentHoverItemRow = 3; currentHoverItemIndex = 12; } else if (inRange(y, 269, 299, true)) { currentHoverItemRow = 4; currentHoverItemIndex = 18; } else if (inRange(y, 300, 330, true)) { currentHoverItemRow = 5; currentHoverItemIndex = 24; } else if (inRange(y, 331, 361, true)) { currentHoverItemRow = 6; currentHoverItemIndex = 30; } else if (inRange(y, 362, 392, true)) { currentHoverItemRow = 7; currentHoverItemIndex = 36; } else if (inRange(y, 393, 423, true)) { currentHoverItemRow = 8; currentHoverItemIndex = 42; } else if (inRange(y, 424, 454, true)) { currentHoverItemRow = 9; currentHoverItemIndex = 48; } else if (inRange(y, 455, 485, true)) { currentHoverItemRow = 10; currentHoverItemIndex = 54; } else if (inRange(y, 486, 516, true)) { currentHoverItemRow = 11; currentHoverItemIndex = 60; } } else if (inRange(x, 618, 648, true)) { if (inRange(y, 176, 206, true)) { currentHoverItemRow = 1; currentHoverItemIndex = 1; } else if (inRange(y, 207, 237, true)) { currentHoverItemRow = 2; currentHoverItemIndex = 7; } else if (inRange(y, 238, 268, true)) { currentHoverItemRow = 3; currentHoverItemIndex = 13; } else if (inRange(y, 269, 299, true)) { currentHoverItemRow = 4; currentHoverItemIndex = 19; } else if (inRange(y, 300, 330, true)) { currentHoverItemRow = 5; currentHoverItemIndex = 25; } else if (inRange(y, 331, 361, true)) { currentHoverItemRow = 6; currentHoverItemIndex = 31; } else if (inRange(y, 362, 392, true)) { currentHoverItemRow = 7; currentHoverItemIndex = 37; } else if (inRange(y, 393, 423, true)) { currentHoverItemRow = 8; currentHoverItemIndex = 43; } else if (inRange(y, 424, 454, true)) { currentHoverItemRow = 9; currentHoverItemIndex = 49; } else if (inRange(y, 455, 485, true)) { currentHoverItemRow = 10; currentHoverItemIndex = 55; } else if (inRange(y, 486, 516, true)) { currentHoverItemRow = 11; currentHoverItemIndex = 61; } } else if (inRange(x, 649, 679, true)) { if (inRange(y, 176, 206, true)) { currentHoverItemRow = 1; currentHoverItemIndex = 2; } else if (inRange(y, 207, 237, true)) { currentHoverItemRow = 2; currentHoverItemIndex = 8; } else if (inRange(y, 238, 268, true)) { currentHoverItemRow = 3; currentHoverItemIndex = 14; } else if (inRange(y, 269, 299, true)) { currentHoverItemRow = 4; currentHoverItemIndex = 20; } else if (inRange(y, 300, 330, true)) { currentHoverItemRow = 5; currentHoverItemIndex = 26; } else if (inRange(y, 331, 361, true)) { currentHoverItemRow = 6; currentHoverItemIndex = 32; } else if (inRange(y, 362, 392, true)) { currentHoverItemRow = 7; currentHoverItemIndex = 38; } else if (inRange(y, 393, 423, true)) { currentHoverItemRow = 8; currentHoverItemIndex = 44; } else if (inRange(y, 424, 454, true)) { currentHoverItemRow = 9; currentHoverItemIndex = 50; } else if (inRange(y, 455, 485, true)) { currentHoverItemRow = 10; currentHoverItemIndex = 56; } else if (inRange(y, 486, 516, true)) { currentHoverItemRow = 11; currentHoverItemIndex = 62; } } else if (inRange(x, 680, 710, true)) { if (inRange(y, 176, 206, true)) { currentHoverItemRow = 1; currentHoverItemIndex = 3; } else if (inRange(y, 207, 237, true)) { currentHoverItemRow = 2; currentHoverItemIndex = 9; } else if (inRange(y, 238, 268, true)) { currentHoverItemRow = 3; currentHoverItemIndex = 15; } else if (inRange(y, 269, 299, true)) { currentHoverItemRow = 4; currentHoverItemIndex = 21; } else if (inRange(y, 300, 330, true)) { currentHoverItemRow = 5; currentHoverItemIndex = 27; } else if (inRange(y, 331, 361, true)) { currentHoverItemRow = 6; currentHoverItemIndex = 33; } else if (inRange(y, 362, 392, true)) { currentHoverItemRow = 7; currentHoverItemIndex = 39; } else if (inRange(y, 393, 423, true)) { currentHoverItemRow = 8; currentHoverItemIndex = 45; } else if (inRange(y, 424, 454, true)) { currentHoverItemRow = 9; currentHoverItemIndex = 51; } else if (inRange(y, 455, 485, true)) { currentHoverItemRow = 10; currentHoverItemIndex = 57; } else if (inRange(y, 486, 516, true)) { currentHoverItemRow = 11; currentHoverItemIndex = 63; } } else if (inRange(x, 711, 741, true)) { if (inRange(y, 176, 206, true)) { currentHoverItemRow = 1; currentHoverItemIndex = 4; } else if (inRange(y, 207, 237, true)) { currentHoverItemRow = 2; currentHoverItemIndex = 10; } else if (inRange(y, 238, 268, true)) { currentHoverItemRow = 3; currentHoverItemIndex = 16; } else if (inRange(y, 269, 299, true)) { currentHoverItemRow = 4; currentHoverItemIndex = 22; } else if (inRange(y, 300, 330, true)) { currentHoverItemRow = 5; currentHoverItemIndex = 28; } else if (inRange(y, 331, 361, true)) { currentHoverItemRow = 6; currentHoverItemIndex = 34; } else if (inRange(y, 362, 392, true)) { currentHoverItemRow = 7; currentHoverItemIndex = 40; } else if (inRange(y, 393, 423, true)) { currentHoverItemRow = 8; currentHoverItemIndex = 46; } else if (inRange(y, 424, 454, true)) { currentHoverItemRow = 9; currentHoverItemIndex = 52; } else if (inRange(y, 455, 485, true)) { currentHoverItemRow = 10; currentHoverItemIndex = 58; } else if (inRange(y, 486, 516, true)) { currentHoverItemRow = 11; currentHoverItemIndex = 64; } } else if (inRange(x, 742, 772, true)) { if (inRange(y, 176, 206, true)) { currentHoverItemRow = 1; currentHoverItemIndex = 5; } else if (inRange(y, 207, 237, true)) { currentHoverItemRow = 2; currentHoverItemIndex = 11; } else if (inRange(y, 238, 268, true)) { currentHoverItemRow = 3; currentHoverItemIndex = 17; } else if (inRange(y, 269, 299, true)) { currentHoverItemRow = 4; currentHoverItemIndex = 23; } else if (inRange(y, 300, 330, true)) { currentHoverItemRow = 5; currentHoverItemIndex = 29; } else if (inRange(y, 331, 361, true)) { currentHoverItemRow = 6; currentHoverItemIndex = 35; } else if (inRange(y, 362, 392, true)) { currentHoverItemRow = 7; currentHoverItemIndex = 41; } else if (inRange(y, 393, 423, true)) { currentHoverItemRow = 8; currentHoverItemIndex = 47; } else if (inRange(y, 424, 454, true)) { currentHoverItemRow = 9; currentHoverItemIndex = 53; } else if (inRange(y, 455, 485, true)) { currentHoverItemRow = 10; currentHoverItemIndex = 59; } else if (inRange(y, 486, 516, true)) { currentHoverItemRow = 11; currentHoverItemIndex = 65; } } if (x > 156 && x < 156 + 30 && y > 183 && y < 183 + 30) { return player1.playerCrafter.itemArray[9]; } if (currentHoverItemIndex < 0) { return null; } return player1.playerInventory.itemArray[currentHoverItemIndex]; } private Tile onMouseClickSelectTile(int x, int y) { currentTileX = x / 25; currentTileY = y / 25; return currentOverWorld.tilemap[x / 25][y / 25]; } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } @Override public void mouseDragged(MouseEvent e) { } @Override public void mouseMoved(MouseEvent e) { mouseDragX = e.getX(); mouseDragY = e.getY(); currentHoverItem = onMouseMovedSelectHoverItem(mouseDragX, mouseDragY); } public static String printTileSet(Tile[][] tilemap) { String ans = ""; for (int i = 0; i < 32; i++) { ans += "\n"; for (int j = 0; j < 24; j++) { ans += " - " + tilemap[i][j].type + " - "; } } return ans; } public static String getUserInput() { Scanner stringIn = new Scanner(System.in); System.out.println("please enters string:"); while (stringIn.hasNext()) { if (stringIn.hasNextLine()) { return stringIn.nextLine(); } else { System.out.println("invalid input"); stringIn.next(); } } return null; } public static Integer getUserInputInt() { Scanner stringIn = new Scanner(System.in); System.out.println("please enters string:"); while (stringIn.hasNext()) { if (stringIn.hasNextInt()) { return stringIn.nextInt(); } else { System.out.println("invalid input"); stringIn.next(); } } return null; } public boolean inRange(int i, int lower, int upper, boolean inclusive) { if (inclusive) { return (i <= upper && i >= lower); } return (i < upper && i > lower); } }
package org.myrobotlab.service; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import java.io.IOException; import java.util.ArrayList; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.myrobotlab.fileLib.FileIO; import org.myrobotlab.fileLib.FileIO.FileComparisonException; import org.myrobotlab.framework.Message; import org.myrobotlab.framework.Service; import org.myrobotlab.framework.repo.Repo; import org.myrobotlab.logging.Level; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.logging.LoggingFactory; import org.myrobotlab.serial.VirtualSerialPort.VirtualNullModemCable; import org.slf4j.Logger; /** * @author GRPERRY * * FIXME - virtual serial should not need RXTXLib to function or to * .getPorts() ! FIXME - should be an easy way to report if JNI loaded * correctly */ public class SerialTest { public final static Logger log = LoggerFactory.getLogger(SerialTest.class); static VirtualNullModemCable cable = null; static Serial serial = null; static Serial uart = null; static TestCatcher catcher = null; static boolean cleanDepenencies = true; static boolean installDependencies = true; static boolean testHardware = false; /** * @throws java.lang.Exception */ @BeforeClass public static void setUpBeforeClass() throws Exception { LoggingFactory.getInstance().configure(); LoggingFactory.getInstance().setLevel(Level.INFO); log.info("setUpBeforeClass"); if (cleanDepenencies) { log.info("cleaning cache"); if (!Runtime.cleanCache()){ throw new IOException("could not clean cache"); } } if (installDependencies) { log.info("installing Serial"); Repo repo = new Repo("install"); repo.retrieveServiceType("org.myrobotlab.service.Serial"); if (repo.hasErrors()){ throw new IOException(repo.getErrors()); } } // FIXME TODO clean repo before installing !!!! serial = (Serial) Runtime.start("serial", "Serial"); uart = (Serial) Runtime.start("uart", "Serial"); cable = Serial.createNullModemCable("v0", "v1"); catcher = (TestCatcher) Runtime.start("catcher", "TestCatcher"); } /** * @throws java.lang.Exception */ @AfterClass public static void tearDownAfterClass() throws Exception { log.info("tearDownAfterClass"); // FIXME - check service and thread count // Runtime should still exist - but any // additional threads should not serial.releaseService(); uart.releaseService(); } /** * @throws java.lang.Exception */ @Before public void setUp() throws Exception { log.info("setUp"); } /** * @throws java.lang.Exception */ @After public void tearDown() throws Exception { //log.info("tearDown"); } /** * Test method for {@link org.myrobotlab.service.Serial#getDescription()}. */ @Test public final void testGetDescription() { // fail("Not yet implemented"); org.junit.Assert.assertNotNull("description is null", serial.getDescription()); } /** * Test method for {@link org.myrobotlab.service.Serial#test()}. * * @throws IOException * @throws InterruptedException * @throws FileComparisonException */ @Test public final void testTest() throws IOException, InterruptedException, FileComparisonException { // non destructive tests // TODO - test blocking / non blocking / time-out blocking / reading an // array (or don't bother?) or do with length? num bytes to block or // timeout // TODO - if I am connected to a different serial port // get that name - disconnect - and then reconnect when done // FIXME - very little functionality for a combined tx rx file // TODO - test sendFile & record // TODO - speed test // TODO use utility methods to help parse read data types // because we should not assume we know the details of ints longs etc // nor // the endianess // utility methods - ascii // FIXME - // test case write(-1) as display becomes -1 ! - file is // different than gui !?!?! boolean noWorky = true; if (noWorky) return; int timeout = 500;// 500 ms serial timeout // Runtime.start("gui", "GUIService"); // Runtime.start("webgui", "WebGUI"); serial.connect(cable.vp0.getName()); uart.connect(cable.vp1.getName()); // get serial handle and creates a uart & abl= null modem cable // verify the null modem cable is connected if (!serial.isConnected()) { throw new IOException(String.format("%s not connected", serial.getName())); } if (!uart.isConnected()) { throw new IOException(String.format("%s not connected", uart.getName())); } serial.stopRecording(); uart.stopRecording(); // start binary recording serial.record("test/Serial/serial.1"); uart.record("test/Serial/uart.1"); // test blocking on exact size serial.write("VER\r"); uart.write("000D\r"); // read back log.info(serial.readString(5)); // blocking read with timeout uart.write("HELLO"); String helo = serial.readString(5, timeout); assertEquals("HELLO", helo); log.info("array write"); serial.write(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 127, (byte) 128, (byte) 254, (byte) 255 }); // FIXME !!! - bug - we wrote a big array to serial - // then immediately cleared the uart buffer // has not reached uart (because there is some overhead in moving, // reading and formatting the incoming data) // then we start checking values in "test blocking" this by that // time the serial data above has hit the // uart // with a virtual null modem cable I could "cheat" and flush() could // look at the serial's tx buffer size // and block until its cleared - but this would not be typical of // "real" serial ports // but it could stabilize the test // in the real world we don't know when the sender to // our receiver is done - so we'll Service.sleep here Service.sleep(300); log.info("clear buffers"); serial.clear(); uart.clear(); assertEquals(0, serial.available()); log.info("testing blocking"); for (int i = 257; i > -2; --i) { serial.write(i); int readBack = uart.read(); log.info(String.format("written %d read back %d", i, readBack)); if (i < 256 && i > -1) { assertEquals(String.format("read back not the same as written for value %d %d !", i, readBack), readBack, i); } } // in the real world we don't know when the sender to // our receiver is done - so we'll Service.sleep here Service.sleep(300); log.info("clear buffers"); serial.clear(); uart.clear(); // cleared - nothing should be in the buffer assertNull(serial.readString(5, 100)); // test publish/subscribe nonblocking serial.addByteListener(catcher); uart.write(64); Message msg = catcher.getMsg(100); assertEquals("onByte", msg.method); assertEquals(1, msg.data.length); assertEquals(64, msg.data[0]); uart.clear(); serial.clear(); serial.write(new String("MRL ROCKS!")); // partial buffer filled String back = uart.readString(15, 100); assertEquals("MRL ROCKS!", back); // publish test uart.write(new String("MRL ROCKS!")); ArrayList<Message> msgs = catcher.getMsgs(100); FileIO.compareFiles("test/Serial/serial.1.rx.bin", "test/Serial/control/serial.1.rx.bin"); FileIO.compareFiles("test/Serial/serial.1.tx.bin", "test/Serial/control/serial.1.tx.bin"); FileIO.compareFiles("test/Serial/uart.1.rx.bin", "test/Serial/control/uart.1.rx.bin"); FileIO.compareFiles("test/Serial/uart.1.tx.bin", "test/Serial/control/uart.1.tx.bin"); serial.stopRecording(); uart.stopRecording(); // FIXME compare binary files // FIXME - finish up test & compare tx & rx files in multiple formats serial.setBinaryFileFormat(false); uart.setBinaryFileFormat(false); // default non-binary format is ascii decimal serial.record("test/Serial/serial.2"); // uart.record("test/Serial/uart.2"); serial.write(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, (byte) 255 }); // we have to pause here momentarily // so the data can be written and read from the virtual null modem // cable (on different threads) // before we close the file streams Service.sleep(30); // uart.stopRecording(); serial.stopRecording(); serial.setDisplayFormat(Serial.DISPLAY_HEX); serial.record("test/Serial/serial.3"); // uart.record("test/Serial/uart.3"); serial.write(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, (byte) 255 }); Service.sleep(30); serial.stopRecording(); // uart.stopRecording(); // parsing of files based on extension check // TODO flush & close tests ? // serial.disconnect(); // uart.disconnect(); } /** * Test method for {@link org.myrobotlab.service.Serial#stopService()}. */ @Test public final void testStopService() { // fail("Not yet implemented"); } /** * Test method for {@link org.myrobotlab.service.Serial#releaseService()}. */ @Test public final void testReleaseService() { // fail("Not yet implemented"); } /** * Test method for * {@link org.myrobotlab.service.Serial#Serial(java.lang.String)}. */ @Test public final void testSerial() { // fail("Not yet implemented"); } /** * Test method for {@link org.myrobotlab.service.Serial#setBufferSize(int)}. */ @Test public final void testSetBufferSize() { // fail("Not yet implemented"); } /** * Test method for * {@link org.myrobotlab.service.Serial#bytesToUnsignedInt(byte[], int, int)} * . */ @Test public final void testBytesToUnsignedInt() { // fail("Not yet implemented"); } /** * Test method for * {@link org.myrobotlab.service.Serial#bytesToLong(int[], int, int)}. */ @Test public final void testBytesToLong() { // fail("Not yet implemented"); } /** * Test method for * {@link org.myrobotlab.service.Serial#recordRX(java.lang.String)}. */ @Test public final void testRecordRX() { // fail("Not yet implemented"); } /** * Test method for * {@link org.myrobotlab.service.Serial#recordTX(java.lang.String)}. */ @Test public final void testRecordTX() { // fail("Not yet implemented"); } /** * Test method for * {@link org.myrobotlab.service.Serial#record(java.lang.String)}. */ @Test public final void testRecordString() { // fail("Not yet implemented"); } /** * Test method for {@link org.myrobotlab.service.Serial#record()}. */ @Test public final void testRecord() { // fail("Not yet implemented"); } /** * Test method for {@link org.myrobotlab.service.Serial#stopRecording()}. */ @Test public final void testStopRecording() { // fail("Not yet implemented"); } /** * Test method for {@link org.myrobotlab.service.Serial#isRecording()}. */ @Test public final void testIsRecording() { // fail("Not yet implemented"); } /** * Test method for {@link org.myrobotlab.service.Serial#getPortName()}. */ @Test public final void testGetPortName() { // fail("Not yet implemented"); } /** * Test method for {@link org.myrobotlab.service.Serial#format(int)}. */ @Test public final void testFormat() { // fail("Not yet implemented"); } /** * Test method for {@link org.myrobotlab.service.Serial#getExtention()}. */ @Test public final void testGetExtention() { // fail("Not yet implemented"); } /** * Test method for * {@link org.myrobotlab.service.Serial#serialEvent(org.myrobotlab.serial.SerialDeviceEvent)} * . */ @Test public final void testSerialEvent() { // fail("Not yet implemented"); } /** * Test method for {@link org.myrobotlab.service.Serial#getPortNames()}. */ @Test public final void testGetPortNames() { // fail("Not yet implemented"); ArrayList<String> ports = serial.getPortNames(); boolean v0Found = false; boolean v1Found = false; for (int i = 0; i < ports.size(); ++i) { if (ports.get(i).equals("v0")) { v0Found = true; } if (ports.get(i).equals("v1")) { v1Found = true; } } if (!v0Found || !v1Found) { fail(""); } } /** * Test method for * {@link org.myrobotlab.service.Serial#addByteListener(org.myrobotlab.service.interfaces.SerialDataListener)} * . */ @Test public final void testAddByteListener() { // fail("Not yet implemented"); } /** * Test method for * {@link org.myrobotlab.service.Serial#connect(java.lang.String, java.lang.Double, java.lang.Double, java.lang.Double, java.lang.Double)} * . */ @Test public final void testConnectStringDoubleDoubleDoubleDouble() { // fail("Not yet implemented"); } /** * Test method for * {@link org.myrobotlab.service.Serial#connect(java.lang.String, int, int, int, int)} * . */ @Test public final void testConnectStringIntIntIntInt() { // fail("Not yet implemented"); } /** * Test method for * {@link org.myrobotlab.service.Serial#connect(java.lang.String)}. */ @Test public final void testConnectString() { // fail("Not yet implemented"); } /** * Test method for * {@link org.myrobotlab.service.Serial#publishByte(java.lang.Integer)}. */ @Test public final void testPublishByte() { // fail("Not yet implemented"); } /** * Test method for * {@link org.myrobotlab.service.Serial#publishDisplay(java.lang.String)}. */ @Test public final void testPublishDisplay() { // fail("Not yet implemented"); } /** * Test method for {@link org.myrobotlab.service.Serial#read()}. */ @Test public final void testRead() { // fail("Not yet implemented"); } /** * Test method for {@link org.myrobotlab.service.Serial#read(byte[])}. */ @Test public final void testReadByteArray() { // fail("Not yet implemented"); } /** * Test method for {@link org.myrobotlab.service.Serial#read(int[])}. */ @Test public final void testReadIntArray() { // fail("Not yet implemented"); } /** * Test method for {@link org.myrobotlab.service.Serial#read(int[], int)}. */ @Test public final void testReadIntArrayInt() { // fail("Not yet implemented"); } /** * Test method for {@link org.myrobotlab.service.Serial#readString(int)}. */ @Test public final void testReadStringInt() { // fail("Not yet implemented"); } /** * Test method for * {@link org.myrobotlab.service.Serial#readString(int, int)}. */ @Test public final void testReadStringIntInt() { // fail("Not yet implemented"); } /** * Test method for * {@link org.myrobotlab.service.Serial#intArrayToByteArray(int[])}. */ @Test public final void testIntArrayToByteArray() { // fail("Not yet implemented"); } /** * Test method for {@link org.myrobotlab.service.Serial#isConnected()}. */ @Test public final void testIsConnected() { // fail("Not yet implemented"); } /** * Test method for * {@link org.myrobotlab.service.Serial#readToDelimiter(java.lang.String)}. */ @Test public final void testReadToDelimiter() { // fail("Not yet implemented"); } /** * Test method for * {@link org.myrobotlab.service.Serial#write(java.lang.String)}. */ @Test public final void testWriteString() { // fail("Not yet implemented"); } /** * Test method for {@link org.myrobotlab.service.Serial#write(byte[])}. */ @Test public final void testWriteByteArray() { // fail("Not yet implemented"); } /** * Test method for {@link org.myrobotlab.service.Serial#write(int)}. */ @Test public final void testWriteInt() { // fail("Not yet implemented"); } /** * Test method for * {@link org.myrobotlab.service.Serial#writeFile(java.lang.String)}. */ @Test public final void testWriteFile() { // fail("Not yet implemented"); } /** * Test method for {@link org.myrobotlab.service.Serial#disconnect()}. */ @Test public final void testDisconnect() { // fail("Not yet implemented"); } /** * Test method for {@link org.myrobotlab.service.Serial#clear()}. */ @Test public final void testClear() { // fail("Not yet implemented"); } /** * Test method for * {@link org.myrobotlab.service.Serial#createNullModemCable(java.lang.String, java.lang.String)} * . */ @Test public final void testCreateNullModemCable() { // fail("Not yet implemented"); } /** * Test method for {@link org.myrobotlab.service.Serial#createVirtualUART()} * . */ @Test public final void testCreateVirtualUART() { // fail("Not yet implemented"); } /** * Test method for {@link org.myrobotlab.service.Serial#isOpen()}. */ @Test public final void testIsOpen() { // fail("Not yet implemented"); } /** * Test method for {@link org.myrobotlab.service.Serial#refresh()}. */ @Test public final void testRefresh() { // fail("Not yet implemented"); } /** * Test method for * {@link org.myrobotlab.service.Serial#addRelay(java.lang.String, int)}. */ @Test public final void testAddRelay() { // fail("Not yet implemented"); } /** * Test method for * {@link org.myrobotlab.service.Serial#onByte(java.lang.Integer)}. */ @Test public final void testOnByte() { // fail("Not yet implemented"); } /** * Test method for * {@link org.myrobotlab.service.Serial#setBinaryFileFormat(boolean)}. */ @Test public final void testSetBinaryFileFormat() { // fail("Not yet implemented"); } /** * Test method for * {@link org.myrobotlab.service.Serial#parse(byte[], java.lang.String)}. */ @Test public final void testParse() { // fail("Not yet implemented"); } /** * Test method for * {@link org.myrobotlab.service.Serial#setDisplayFormat(java.lang.String)}. */ @Test public final void testSetDisplayFormat() { // fail("Not yet implemented"); } /** * Test method for {@link org.myrobotlab.service.Serial#getDisplayFormat()}. */ @Test public final void testGetDisplayFormat() { // fail("Not yet implemented"); } /** * Test method for {@link org.myrobotlab.service.Serial#available()}. */ @Test public final void testAvailable() { // fail("Not yet implemented"); } /** * Test method for * {@link org.myrobotlab.service.Serial#main(java.lang.String[])}. */ @Test public final void testMain() { // fail("Not yet implemented"); } }
import javax.imageio.ImageIO; import javax.sound.sampled.*; import javax.swing.*; import javax.swing.Timer; import java.awt.*; import java.awt.event.*; import java.awt.image.BufferedImage; import java.io.*; import java.util.*; public class GameEngine extends JPanel implements MouseListener, MouseMotionListener, ActionListener, KeyListener { private int movementSpeed = 25; private Vector<Integer> rnglist; private int gameSpeed = 1; private int worldSize = 20; // Defines Overworld dimensions private Overworld currentOverWorld = null; private Tile currentTile = null; private int currentTileX = 0; private int currentTileY = 0; private int tileBrushIndex = 0; private String tileBrush = "grass"; private int npcBrushIndex = 0; private String npcBrush = "SHEEP"; private Item currentItem = null; private int currentItemIndex = 0; private int currentItemRow = 0; private int currentItemColumn = 0; private Item currentHoverItem = null; private int actionTick = 0; // Ticker for player actions. private final Timer timer = new Timer(gameSpeed, this); // GAME CLOCK TIMER private Timer animationTimer0 = new Timer(1000, this); private int animation_frame = 0; private Player player1; private Npc currentNpc; // Selected Npc pointer FileOutputStream fileOut; FileInputStream fileIn; private boolean debugMenuVisible = false; private boolean inventoryMenuVisible = false; private boolean startMenuVisible = true; private boolean viewMenuVisible = false; private boolean mapVisible = false; private boolean worldExists = false; private boolean shiftPressed = false; private boolean controlPressed = false; private boolean altPressed = false; private Font font1_8 = new Font("Consola", Font.PLAIN, 8); private Font font2_16 = new Font("Consola", Font.BOLD, 16); private Font font3_24 = new Font("Consola", Font.BOLD, 24); private Font font4_22 = new Font("Arial",Font.BOLD,22); private Font font4_20 = new Font("Arial",Font.BOLD,20); private Overworld[][] overWorld = new Overworld[worldSize][worldSize]; double nextTime = (double) System.nanoTime() / 1000000000.0; Map<String, BufferedImage> bufferedImageMap; int rainVector = 1; private boolean raining; Point[] rainDrops; int numberOfRainDrops = 10; Deque<Point> bufferSplashAnimations = new LinkedList<>(); private ArrayList<String> BrushTileList = new ArrayList<>(); private ArrayList<String> brushNpcList = new ArrayList<>(); AudioInputStream audioInputStream; Clip movementSound; Clip rainSound; Clip woodsSound; Clip menuSound; private boolean rainSoundLoaded = false; private boolean woodsSoundLoaded = false; private boolean menuSoundLoaded = false; private boolean craftingMenuVisible = false; int mouseDragX = 0; int mouseDragY = 0; boolean engagedSuccessfully = false; // flag to determine real-time whether the key press triggers a successful harvest action private boolean TRIGGER_endOfCombat = false; private int storeXPos = 0; private int storeYPos = 0; private String storeOrientation = ""; private boolean attackStyleChooserVisible = false; int[] abilities = new int[3]; private boolean stuckInDialogue = false; private Npc currentDialogueNpc = null; String npcDialogue = "npcdialogue"; String playerResponse1 = "playerresponse1"; String playerResponse2 = "playerresponse2"; String playerResponse3 = "playerresponse3"; int TRIGGER_dialogueState = 0; int mousedOverDialogue = 0; Renderer renderer = null; public GameEngine() { addMouseListener(this); addMouseMotionListener(this); addKeyListener(this); // Adds keyboard listener. setFocusable(true); // Setting required for keyboard listener. run(); } private void startUp() { rnglist = rngSeeder(); // Loads pre-generated RNG numbers from file to a Vector. generatePlayer();// Player is created. for (int j = 0; j < 10; j++) { for (int i = 0; i < 64; i++) { if (player1.playerInventory.itemArray[i].ID == 0) { player1.playerInventory.itemArray[i].ID = 1; break; } } } // currentItem = player1.playerInventory.itemArray[0]; buildOverworld(); // adds worldSize x worldSize OverWorlds to the Overworld array. currentOverWorld = overWorld[0][0]; // Points currentOverWorld pointer to start map. dummyWorld(); // initializes currentOverWorld.tilemap list and fills it with an empty grass world. // currentTile = currentOverWorld.tilemap[0][0]; // points to the currently selected tile. loadSprites(); loadSpritesReworked(); indexTiles(); indexNpc(); loadMenuSound(); raining = true; generateRainPattern(); timer.start(); animationTimer0.start(); generateNpc(currentOverWorld.npcList.size() + 1, 5, 5, 10, Color.black, "LUMBERJACK"); generateNpc(currentOverWorld.npcList.size() + 1, 5, 8, 10, Color.black, "CASTLEGUARD"); generateNpc(currentOverWorld.npcList.size() + 1, 5, 11, 10, Color.black, "CHEF"); } private void loadSpritesReworked() { loadBufferedImage("LumberjackAxeE.png", "LUMBERJACK_AXE_EAST"); loadBufferedImage("LumberjackAxeW.png", "LUMBERJACK_AXE_WEST"); loadBufferedImage("EastChef.png", "EAST_CHEF"); loadBufferedImage("RaggedShirt.png", "RAGGEDSHIRT"); loadBufferedImage("EastLumberjack.png", "EAST_LUMBERJACK"); loadBufferedImage("EastCastleGuard.png", "EAST_CASTLEGUARD"); loadBufferedImage("GearWorksLogo.png", "GEARWORKS_LOGO"); loadBufferedImage("GearWorksLogoSmall.png", "GEARWORKS_LOGO_SMALL"); loadBufferedImage("GenericShieldBack.png", "GENERIC_SHIELD_BACK"); loadBufferedImage("BrownPlatebodyPlayerModelNorth.png", "BROWN_PLATEBODY_PLAYERMODEL_NORTH"); loadBufferedImage("BrownPlatebodyTrimmedPlayerModelNorth.png", "BROWN_PLATEBODY_TRIMMED_PLAYERMODEL_NORTH"); loadBufferedImage("BluePlatebodyPlayerModelNorth.png", "BLUE_PLATEBODY_PLAYERMODEL_NORTH"); loadBufferedImage("BluePlatebodyTrimmedPlayerModelNorth.png", "BLUE_PLATEBODY_TRIMMED_PLAYERMODEL_NORTH"); loadBufferedImage("GreenPlatebodyPlayerModelNorth.png", "GREEN_PLATEBODY_PLAYERMODEL_NORTH"); loadBufferedImage("GreenPlatebodyTrimmedPlayerModelNorth.png", "GREEN_PLATEBODY_TRIMMED_PLAYERMODEL_NORTH"); loadBufferedImage("ABILITY_MHAND_SLICE.png", "ABILITY_MHAND_SLICE"); loadBufferedImage("ABILITY_MHAND_STAB.png", "ABILITY_MHAND_STAB"); loadBufferedImage("ABILITY_OHAND_BLOCK.png", "ABILITY_OHAND_BLOCK"); loadBufferedImage("RedDaggerW.png", "RED_DAGGER_WEST"); loadBufferedImage("RedDaggerE.png", "RED_DAGGER_EAST"); loadBufferedImage("BlueDaggerE.png", "BLUE_DAGGER_EAST"); loadBufferedImage("GreenDaggerW.png", "GREEN_DAGGER_WEST"); loadBufferedImage("GreenDaggerE.png", "GREEN_DAGGER_EAST"); loadBufferedImage("JunkscrapLegguardsPlayerModelNorth.png", "JUNKSCRAP_LEGGUARDS_PLAYERMODEL_NORTH"); loadBufferedImage("JunkscrapLegguardsPlayerModelEast.png", "JUNKSCRAP_LEGGUARDS_PLAYERMODEL_EAST"); loadBufferedImage("JunkscrapLegguardsPlayerModelWest.png", "JUNKSCRAP_LEGGUARDS_PLAYERMODEL_WEST"); loadBufferedImage("JunkscrapLegguardsTrimmedPlayerModelEast.png", "JUNKSCRAP_LEGGUARDS_TRIMMED_PLAYERMODEL_EAST"); loadBufferedImage("JunkscrapLegguardsTrimmedPlayerModelNorth.png", "JUNKSCRAP_LEGGUARDS_TRIMMED_PLAYERMODEL_NORTH"); loadBufferedImage("JunkscrapLegguardsTrimmedPlayerModelWest.png", "JUNKSCRAP_LEGGUARDS_TRIMMED_PLAYERMODEL_WEST"); loadBufferedImage("BlueLegguardsPlayerModelEast.png", "BLUE_LEGGUARDS_PLAYERMODEL_EAST"); loadBufferedImage("BlueLegguardsPlayerModelNorth.png", "BLUE_LEGGUARDS_PLAYERMODEL_NORTH"); loadBufferedImage("BlueLegguardsPlayerModelWest.png", "BLUE_LEGGUARDS_PLAYERMODEL_WEST"); loadBufferedImage("BlueLegguardsTrimmedPlayerModelNorth.png", "BLUE_LEGGUARDS_TRIMMED_PLAYERMODEL_NORTH"); loadBufferedImage("BlueLegguardsTrimmedPlayerModelEast.png", "BLUE_LEGGUARDS_TRIMMED_PLAYERMODEL_EAST"); loadBufferedImage("BlueLegguardsTrimmedPlayerModelEast.png", "BLUE_LEGGUARDS_TRIMMED_PLAYERMODEL_WEST"); loadBufferedImage("GreenLegguardsPlayerModelEast.png", "GREEN_LEGGUARDS_PLAYERMODEL_EAST"); loadBufferedImage("GreenLegguardsPlayerModelNorth.png", "GREEN_LEGGUARDS_PLAYERMODEL_NORTH"); loadBufferedImage("GreenLegguardsPlayerModelWest.png", "GREEN_LEGGUARDS_PLAYERMODEL_WEST"); loadBufferedImage("GreenLegguardsTrimmedPlayerModelNorth.png", "GREEN_LEGGUARDS_TRIMMED_PLAYERMODEL_NORTH"); loadBufferedImage("GreenLegguardsTrimmedPlayerModelEast.png", "GREEN_LEGGUARDS_TRIMMED_PLAYERMODEL_EAST"); loadBufferedImage("GreenLegguardsTrimmedPlayerModelEast.png", "GREEN_LEGGUARDS_TRIMMED_PLAYERMODEL_WEST"); loadBufferedImage("RatskinPantsPlayerModelEast.png", "RATSKIN_PANTS_PLAYERMODEL_EAST"); loadBufferedImage("RatskinPantsPlayerModelNorth.png", "RATSKIN_PANTS_PLAYERMODEL_NORTH"); loadBufferedImage("RatskinPantsPlayerModelWest.png", "RATSKIN_PANTS_PLAYERMODEL_WEST"); loadBufferedImage("RaggedShirtPlayerModelSouth.png", "RAGGED_SHIRT_PLAYERMODEL_SOUTH"); loadBufferedImage("RaggedShirtPlayerModelEast.png", "RAGGED_SHIRT_PLAYERMODEL_EAST"); loadBufferedImage("RaggedShirtPlayerModelWest.png", "RAGGED_SHIRT_PLAYERMODEL_WEST"); loadBufferedImage("RaggedShirtPlayerModelNorth.png", "RAGGED_SHIRT_PLAYERMODEL_NORTH"); loadBufferedImage("BrownPlatebodyPlayerModelEast.png", "BROWN_PLATEBODY_PLAYERMODEL_EAST"); loadBufferedImage("BrownPlatebodyPlayerModelWest.png", "BROWN_PLATEBODY_PLAYERMODEL_WEST"); loadBufferedImage("BrownPlatebodyTrimmedPlayerModelEast.png", "BROWN_PLATEBODY_TRIMMED_PLAYERMODEL_EAST"); loadBufferedImage("BrownPlatebodyTrimmedPlayerModelWest.png", "BROWN_PLATEBODY_TRIMMED_PLAYERMODEL_WEST"); loadBufferedImage("bluePlatebodyPlayerModelEast.png", "BLUE_PLATEBODY_PLAYERMODEL_EAST"); loadBufferedImage("bluePlatebodyPlayerModelWest.png", "BLUE_PLATEBODY_PLAYERMODEL_WEST"); loadBufferedImage("bluePlatebodyPlayerTrimmedPlayerModelEast.png", "BLUE_PLATEBODY_TRIMMED_PLAYERMODEL_EAST"); loadBufferedImage("bluePlatebodyPlayerTrimmedPlayeModelWest.png", "BLUE_PLATEBODY_TRIMMED_PLAYERMODEL_WEST"); loadBufferedImage("greenPlatebodyPlayerModelEast.png", "GREEN_PLATEBODY_PLAYERMODEL_EAST"); loadBufferedImage("greenPlatebodyPlayerModelWest.png", "GREEN_PLATEBODY_PLAYERMODEL_WEST"); loadBufferedImage("GreenPlatebodyTrimmedPlayerModelEast.png", "GREEN_PLATEBODY_TRIMMED_PLAYERMODEL_EAST"); loadBufferedImage("GreenPlatebodyTrimmedPlayerModelWest.png", "GREEN_PLATEBODY_TRIMMED_PLAYERMODEL_WEST"); loadBufferedImage("BagIcon.png", "BAG_ICON"); loadBufferedImage("CraftingIcon.png", "CRAFTING_ICON"); loadBufferedImage("BACKGROUNDIMG_COMBAT_0.png", "BACKGROUNDIMG_COMBAT_0"); loadBufferedImage("GreenPlatebodyTrimmed.png", "GREEN_PLATEBODY_TRIMMED"); loadBufferedImage("GreenPlatebodyTrimmedPlayerModelSouth.png", "GREEN_PLATEBODY_TRIMMED_PLAYERMODEL_SOUTH"); loadBufferedImage("BrownPlatebody.png", "BROWN_PLATEBODY"); loadBufferedImage("BrownPlatebodyPlayerModelSouth.png", "BROWN_PLATEBODY_PLAYERMODEL_SOUTH"); loadBufferedImage("BluePlatebodyTrimmed.png", "BLUE_PLATEBODY_TRIMMED"); loadBufferedImage("BluePlatebodyTrimmedPlayerModelSouth.png", "BLUE_PLATEBODY_TRIMMED_PLAYERMODEL_SOUTH"); loadBufferedImage("BluePlatebody.png", "BLUE_PLATEBODY"); loadBufferedImage("BluePlatebodyPlayerModelSouth.png", "BLUE_PLATEBODY_PLAYERMODEL_SOUTH"); loadBufferedImage("BrownPlatebody.png", "BROWN_PLATEBODY"); loadBufferedImage("BrownPlatebodyPlayerModelSouth.png", "BROWN_PLATEBODY_PLAYERMODEL_SOUTH"); loadBufferedImage("GreenPlatebody.png", "GREEN_PLATEBODY"); loadBufferedImage("GreenPlatebodyPlayerModelSouth.png", "GREEN_PLATEBODY_PLAYERMODEL_SOUTH"); loadBufferedImage("BrownPlatebodyTrimmed.png", "BROWN_PLATEBODY_TRIMMED"); loadBufferedImage("BrownPlatebodyTrimmedPlayerModelSouth.png", "BROWN_PLATEBODY_TRIMMED_PLAYERMODEL_SOUTH"); loadBufferedImage("BlueLegguardsTrimmed.png", "BLUE_LEGGUARDS_TRIMMED"); loadBufferedImage("BlueLegguardsTrimmedPlayerModelSouth.png", "BLUE_LEGGUARDS_TRIMMED_PLAYERMODEL_SOUTH"); loadBufferedImage("BlueLegguards.png", "BLUE_LEGGUARDS"); loadBufferedImage("BlueLegguardsPlayerModelSouth.png", "BLUE_LEGGUARDS_PLAYERMODEL_SOUTH"); loadBufferedImage("GreenLegguards.png", "GREEN_LEGGUARDS"); loadBufferedImage("GreenLegguardsPlayerModelSouth.png", "GREEN_LEGGUARDS_PLAYERMODEL_SOUTH"); loadBufferedImage("GreenLegguardsTrimmed.png", "GREEN_LEGGUARDS_TRIMMED"); loadBufferedImage("GreenLegguardsTrimmedPlayerModelSouth.png", "GREEN_LEGGUARDS_TRIMMED_PLAYERMODEL_SOUTH"); loadBufferedImage("JunkscrapLegguards.png", "JUNKSCRAP_LEGGUARDS"); loadBufferedImage("JunkscrapLegguardsPlayerModelSouth.png", "JUNKSCRAP_LEGGUARDS_PLAYERMODEL_SOUTH"); loadBufferedImage("JunkscrapLegguardsTrimmed.png", "JUNKSCRAP_LEGGUARDS_TRIMMED"); loadBufferedImage("JunkscrapLegguardsTrimmedPlayerModelSouth.png", "JUNKSCRAP_LEGGUARDS_TRIMMED_PLAYERMODEL_SOUTH"); loadBufferedImage("RatskinPants.png", "Ratskin_Pants"); loadBufferedImage("RatskinPantsPlayerModelSouth.png", "RATSKIN_PANTS_PLAYERMODEL_SOUTH"); loadBufferedImage("GreenBucklerTrimmed.png", "GREEN_BUCKLER_TRIMMED"); loadBufferedImage("JunkscrapBuckler.png", "JUNKSCRAP_BUCKLER"); loadBufferedImage("JunkscrapBucklerTrimmed.png", "JUNKSCRAP_BUCKLER_TRIMMED"); } private void loadBufferedImage(String filePath, String syntaxName) { BufferedImage bi; try { bi = ImageIO.read((new File("Data/GFX/" + filePath))); bufferedImageMap.put(syntaxName, bi); } catch (IOException ignored) { } } private void reset() { player1 = null; cleanWorld(); generatePlayer(); } private void loadRainSound() { File rain = new File("Data/Sound/Rain.wav"); try { audioInputStream = AudioSystem.getAudioInputStream(rain); } catch (UnsupportedAudioFileException | IOException e) { e.printStackTrace(); } try { rainSound = AudioSystem.getClip(); rainSound.open(audioInputStream); rainSound.start(); rainSound.loop(999); rainSoundLoaded = true; } catch (LineUnavailableException | IOException e) { e.printStackTrace(); } } private void loadWoodsSound() { File woods = new File("Data/Sound/Woods.wav"); try { audioInputStream = AudioSystem.getAudioInputStream(woods); } catch (UnsupportedAudioFileException | IOException e) { e.printStackTrace(); } try { woodsSound = AudioSystem.getClip(); woodsSound.open(audioInputStream); woodsSound.start(); woodsSound.loop(999); woodsSoundLoaded = true; } catch (LineUnavailableException | IOException e) { e.printStackTrace(); } } private void loadMenuSound() { File menu1 = new File("Data/Sound/Menu1.wav"); try { audioInputStream = AudioSystem.getAudioInputStream(menu1); } catch (UnsupportedAudioFileException | IOException e) { e.printStackTrace(); } try { menuSound = AudioSystem.getClip(); menuSound.open(audioInputStream); menuSound.start(); menuSound.loop(999); menuSoundLoaded = true; } catch (LineUnavailableException | IOException e) { e.printStackTrace(); } } private void generateRainPattern() { rainDrops = new Point[numberOfRainDrops]; for (int i = 0; i < rainDrops.length; i++) { int x = (int) (Math.random() * (Main.WIDTH)); int y = (int) (Math.random() * (Main.HEIGHT)); rainDrops[i] = new Point(x, y); } } private void loadSprites() { bufferedImageMap = new HashMap<>(); BufferedImage greenBuckler; BufferedImage blueDagger; BufferedImage blueBuckler; BufferedImage blueBucklerTrimmed; BufferedImage woodenClubW; BufferedImage woodenClubE; BufferedImage woodenShield; BufferedImage northPlayer; BufferedImage eastPlayer; BufferedImage southPlayer; BufferedImage westPlayer; BufferedImage sand; BufferedImage woodenFenceNECorner; BufferedImage woodenFenceSWCorner; BufferedImage woodenFenceSECorner; BufferedImage woodenFenceNWCorner; BufferedImage ratSkinHood; BufferedImage ratSkinChest; BufferedImage ratSkinPants; BufferedImage WoodFloorDoorNorth; BufferedImage WoodFloorDoorEast; BufferedImage WoodFloorDoorSouth; BufferedImage WoodFloorDoorWest; BufferedImage stonePathGrass; BufferedImage northAdventurer; BufferedImage southAdventurer; BufferedImage eastAdventurer; BufferedImage westAdventurer; BufferedImage errorImg; BufferedImage northFrog; BufferedImage southFrog; BufferedImage eastFrog; BufferedImage westFrog; BufferedImage grass; BufferedImage dirt; BufferedImage water; BufferedImage rakedDirt; BufferedImage plankWall; BufferedImage woodFloor; BufferedImage tree; BufferedImage stone; BufferedImage inventoryLumber; BufferedImage northZombie; BufferedImage southZombie; BufferedImage eastZombie; BufferedImage westZombie; BufferedImage northSheep; BufferedImage southSheep; BufferedImage eastSheep; BufferedImage westSheep; BufferedImage upArrow; BufferedImage downArrow; BufferedImage woodenFenceHorizontal; BufferedImage woodenFenceVertical; try { blueDagger = ImageIO.read((new File("Data/GFX/BlueDaggerW.png"))); blueBucklerTrimmed = ImageIO.read((new File("Data/GFX/BlueBucklerTrimmed.png"))); greenBuckler = ImageIO.read((new File("Data/GFX/GreenBuckler.png"))); blueBuckler = ImageIO.read((new File("Data/GFX/BlueBuckler.png"))); woodenClubW = ImageIO.read((new File("Data/GFX/woodenClubW.png"))); woodenClubE = ImageIO.read((new File("Data/GFX/woodenClubE.png"))); woodenShield = ImageIO.read((new File("Data/GFX/WoodenShield.png"))); westPlayer = ImageIO.read((new File("Data/GFX/westPlayer.png"))); northPlayer = ImageIO.read((new File("Data/GFX/NorthPlayer.png"))); eastPlayer = ImageIO.read((new File("Data/GFX/EastPlayer.png"))); southPlayer = ImageIO.read((new File("Data/GFX/SouthPlayer.png"))); sand = ImageIO.read((new File("Data/GFX/Sand.png"))); woodenFenceNECorner = ImageIO.read(new File("Data/GFX/woodenFenceNECorner.png")); woodenFenceSWCorner = ImageIO.read(new File("Data/GFX/woodenFenceSWCorner.png")); woodenFenceSECorner = ImageIO.read(new File("Data/GFX/woodenFenceSECorner.png")); woodenFenceNWCorner = ImageIO.read(new File("Data/GFX/woodenFenceNWCorner.png")); woodenFenceHorizontal = ImageIO.read(new File("Data/GFX/woodenFenceHorizontal.png")); woodenFenceVertical = ImageIO.read(new File("Data/GFX/woodenFenceVertical.png")); ratSkinHood = ImageIO.read(new File("Data/GFX/ratSkinHood.png")); ratSkinChest = ImageIO.read(new File("Data/GFX/ratSkinChest.png")); ratSkinPants = ImageIO.read(new File("Data/GFX/ratSkinPants.png")); WoodFloorDoorNorth = ImageIO.read(new File("Data/GFX/WoodFloorDoorNorth.png")); WoodFloorDoorEast = ImageIO.read(new File("Data/GFX/WoodFloorDoorEast.png")); WoodFloorDoorSouth = ImageIO.read(new File("Data/GFX/WoodFloorDoorSouth.png")); WoodFloorDoorWest = ImageIO.read(new File("Data/GFX/WoodFloorDoorWest.png")); stonePathGrass = ImageIO.read(new File("Data/GFX/StonePathGrass.png")); upArrow = ImageIO.read(new File("Data/GFX/upArrow.png")); downArrow = ImageIO.read(new File("Data/GFX/downArrow.png")); northAdventurer = ImageIO.read(new File("Data/GFX/NorthAdventurer.png")); eastAdventurer = ImageIO.read(new File("Data/GFX/EastAdventurer.png")); southAdventurer = ImageIO.read(new File("Data/GFX/SouthAdventurer.png")); westAdventurer = ImageIO.read(new File("Data/GFX/WestAdventurer.png")); errorImg = ImageIO.read(new File("Data/GFX/ErrorImg.jpg")); northFrog = ImageIO.read(new File("Data/GFX/NorthFroggy.png")); southFrog = ImageIO.read(new File("Data/GFX/SouthFroggy.png")); eastFrog = ImageIO.read(new File("Data/GFX/EastFroggy.png")); // reads tree sprite westFrog = ImageIO.read(new File("Data/GFX/WestFroggy.png")); grass = ImageIO.read(new File("Data/GFX/Grass.png")); dirt = ImageIO.read(new File("Data/GFX/Dirt.png")); rakedDirt = ImageIO.read(new File("Data/GFX/RakedDirt.png")); woodFloor = ImageIO.read(new File("Data/GFX/WoodFloor.png")); plankWall = ImageIO.read(new File("Data/GFX/PlanksWall.png")); water = ImageIO.read(new File("Data/GFX/Water.png")); tree = ImageIO.read(new File("Data/GFX/Tree.png")); // reads tree sprite stone = ImageIO.read(new File("Data/GFX/Rock.gif")); // reads stone sprite. inventoryLumber = ImageIO.read(new File("Data/GFX/InventoryLumber.png")); // reads stone sprite. northSheep = ImageIO.read(new File("Data/GFX/NorthSheep.png")); southSheep = ImageIO.read(new File("Data/GFX/SouthSheep.png")); eastSheep = ImageIO.read(new File("Data/GFX/EastSheep.png")); westSheep = ImageIO.read(new File("Data/GFX/WestSheep.png")); northZombie = ImageIO.read(new File("Data/GFX/NorthZombie.png")); southZombie = ImageIO.read(new File("Data/GFX/SouthZombie.png")); eastZombie = ImageIO.read(new File("Data/GFX/EastZombie.png")); westZombie = ImageIO.read(new File("Data/GFX/WestZombie.png")); bufferedImageMap.put("GREEN_BUCKLER", greenBuckler); bufferedImageMap.put("BLUE_DAGGER_WEST", blueDagger); bufferedImageMap.put("BLUE_BUCKLER_TRIMMED", blueBucklerTrimmed); bufferedImageMap.put("WOODEN_CLUB_W", woodenClubW); bufferedImageMap.put("WOODEN_CLUB_E", woodenClubE); bufferedImageMap.put("BLUE_BUCKLER", blueBuckler); bufferedImageMap.put("WOODEN_SHIELD", woodenShield); bufferedImageMap.put("NORTH_PLAYER", northPlayer); bufferedImageMap.put("EAST_PLAYER", eastPlayer); bufferedImageMap.put("SOUTH_PLAYER", southPlayer); bufferedImageMap.put("WEST_PLAYER", westPlayer); bufferedImageMap.put("SAND", sand); bufferedImageMap.put("WOODENFENCENWCORNER", woodenFenceNWCorner); bufferedImageMap.put("WOODENFENCENECORNER", woodenFenceNECorner); bufferedImageMap.put("WOODENFENCESWCORNER", woodenFenceSWCorner); bufferedImageMap.put("WOODENFENCESECORNER", woodenFenceSECorner); bufferedImageMap.put("WOODENFENCEHORIZONTAL", woodenFenceHorizontal); bufferedImageMap.put("WOODENFENCEVERTICAL", woodenFenceVertical); bufferedImageMap.put("RATSKINCHEST", ratSkinChest); bufferedImageMap.put("RATSKINHOOD", ratSkinHood); bufferedImageMap.put("RATSKINPANTS", ratSkinPants); bufferedImageMap.put("WOODFLOORDOORNORTH", WoodFloorDoorNorth); bufferedImageMap.put("WOODFLOORDOOREAST", WoodFloorDoorEast); bufferedImageMap.put("WOODFLOORDOORSOUTH", WoodFloorDoorSouth); bufferedImageMap.put("WOODFLOORDOORWEST", WoodFloorDoorWest); bufferedImageMap.put("STONEPATHGRASS", stonePathGrass); bufferedImageMap.put("ARROW_UP", upArrow); bufferedImageMap.put("ARROW_DOWN", downArrow); bufferedImageMap.put("NORTH_ADVENTURER", northAdventurer); bufferedImageMap.put("SOUTH_ADVENTURER", southAdventurer); bufferedImageMap.put("EAST_ADVENTURER", eastAdventurer); bufferedImageMap.put("WEST_ADVENTURER", westAdventurer); bufferedImageMap.put("INVENTORY_LUMBER", inventoryLumber); bufferedImageMap.put("ERROR_IMG", errorImg); bufferedImageMap.put("NORTH_FROG", northFrog); bufferedImageMap.put("SOUTH_FROG", southFrog); bufferedImageMap.put("EAST_FROG", eastFrog); bufferedImageMap.put("WEST_FROG", westFrog); bufferedImageMap.put("GRASS", grass); bufferedImageMap.put("DIRT", dirt); bufferedImageMap.put("WOODFLOOR", woodFloor); bufferedImageMap.put("RAKEDDIRT", rakedDirt); bufferedImageMap.put("WATER", water); bufferedImageMap.put("PLANKWALL", plankWall); bufferedImageMap.put("TREE", tree); bufferedImageMap.put("STONE", stone); bufferedImageMap.put("NORTH_SHEEP", northSheep); bufferedImageMap.put("SOUTH_SHEEP", southSheep); bufferedImageMap.put("EAST_SHEEP", eastSheep); bufferedImageMap.put("WEST_SHEEP", westSheep); bufferedImageMap.put("NORTH_CHASER", northZombie); bufferedImageMap.put("SOUTH_CHASER", southZombie); bufferedImageMap.put("EAST_CHASER", eastZombie); bufferedImageMap.put("WEST_CHASER", westZombie); } catch (IOException ignored) { } } private boolean paint() { // convert the time to seconds double currTime = (double) System.nanoTime() / 1000000000.0; boolean paintScreen; if (currTime >= nextTime) { // assign the time for the next update double delta = 0.04; nextTime += delta; paintScreen = true; } else { int sleepTime = (int) (1000.0 * (nextTime - currTime)); // sanity check paintScreen = false; if (sleepTime > 0) { // sleep until the next update try { Thread.sleep(sleepTime); } catch (InterruptedException e) { // do nothing } } } return paintScreen; } private void run() { startUp(); } private Vector<Integer> rngSeeder() { FileReader file = null; try { file = new FileReader("Data/RNG.txt"); // creats a pointer to the the file Data/RNG.txt } catch (FileNotFoundException e) { e.printStackTrace(); } int rng; Vector<Integer> rnglist = new Vector<>(); // creates a Vector of type int to store RNG values. try { Scanner input = null; // creates a scanning stream pointing to file. if (file != null) { input = new Scanner(file); } if (input != null) { while (input.hasNext()) { // loops until file has no more text numbers. rng = input.nextInt(); // loads next integer in list. rnglist.add(rng); // adds the loaded integer to vector. } } if (input != null) { input.close(); // closes stream. } } catch (Exception e) { e.printStackTrace(); } return rnglist; // Returns the int list. } private int rotateRng() { int r = rnglist.firstElement(); rnglist.remove(0); rnglist.addElement(r); // Uses the rnglist vector as a circular buffer and rotates it. return r; //returns rotated integer. } private void dummyWorld() { for (int i = 0; i < 32; i++) { for (int j = 0; j < 24; j++) { currentOverWorld.tilemap[i][j] = new Tile(); // creates a default tile on every coordinate of the current Overworld. } } } private void generateWorldImproved() { for (int i = 0; i < 32; i++) { for (int j = 0; j < 24; j++) { int r = rotateRng(); // sets r to a new rng value. if (r > 99) { // Dirt spawn rate. currentOverWorld.tilemap[i][j].type = "dirt"; } r = rotateRng(); if (currentOverWorld.tilemap[i][j].type.equals("grass") && r > 96) { // tree spawn rate/condition. currentOverWorld.tilemap[i][j].type = "tree"; } else if ((currentOverWorld.tilemap[i][j].type.equals("dirt") && r > 96)) { // sand spawn rate/condition. currentOverWorld.tilemap[i][j].type = "sand"; } r = rotateRng(); if (r > 98) { currentOverWorld.tilemap[i][j].type = "stone"; } if (currentOverWorld.tilemap[i][j].type.equals("rakeddirt")) { // Makes all rakedDirt farmable currentOverWorld.tilemap[i][j].farmable = true; } } collisionMeshGenerator(); // generates a collision mesh for the current Overworld. } } private void collisionMeshGenerator() { int i; int j; for (i = 0; i < 32; i++) { // First, iterate through the entire tilemap of the current Overworld for (j = 0; j < 24; j++) { // and flag any non passable tiles as occupied. flag every passable tile as !occupied. currentOverWorld.tilemap[i][j].occupied = (currentOverWorld.tilemap[i][j].type.equals("tree")) || (currentOverWorld.tilemap[i][j].type.equals("stone")) || (currentOverWorld.tilemap[i][j].type.equals("water")) || (currentOverWorld.tilemap[i][j].type.equals("woodfloordoornorth")) || (currentOverWorld.tilemap[i][j].type.equals("woodfloordooreast")) || (currentOverWorld.tilemap[i][j].type.equals("woodfloordoorsouth")) || (currentOverWorld.tilemap[i][j].type.equals("woodfloordoorwest")) || (currentOverWorld.tilemap[i][j].type.equals("woodenfencevertical")) || (currentOverWorld.tilemap[i][j].type.equals("woodenfencehorizontal")) || (currentOverWorld.tilemap[i][j].type.equals("woodenfencenecorner")) || (currentOverWorld.tilemap[i][j].type.equals("woodenfencenwcorner")) || (currentOverWorld.tilemap[i][j].type.equals("woodenfencesecorner")) || (currentOverWorld.tilemap[i][j].type.equals("woodenfenceswcorner")) || (currentOverWorld.tilemap[i][j].type.equals("plankwall")); } currentOverWorld.tilemap[player1.xPos / 25][player1.yPos / 25].occupied = true; // flags current player position as occupied. for (Npc n : currentOverWorld.npcList) { // flags coordinate of every npc in the currentOverworld.npclist vector as occupied. currentOverWorld.tilemap[n.xPos / 25][n.yPos / 25].occupied = true; } } } private void naturalProcesses() { int i; int j; for (i = 0; i < 32; i++) { // First, iterate through the entire tilemap of the current Overworld for (j = 0; j < 24; j++) { if (currentOverWorld.tilemap[i][j].type.equals("dirt")) { currentOverWorld.tilemap[i][j].growth++; } if (currentOverWorld.tilemap[i][j].growth == 150) { if (currentOverWorld.tilemap[i][j].type.equals("dirt")) { currentOverWorld.tilemap[i][j].type = "grass"; currentOverWorld.tilemap[i][j].growth = 0; } } if (currentOverWorld.tilemap[i][j].type.equals("rakeddirt")) { currentOverWorld.tilemap[i][j].farmable = true; } } } } private void fillWorld() { int x; int y; for (x = 0; x < worldSize; x++) { // iterates through the entire overWorlds array. for (y = 0; y < worldSize; y++) { currentOverWorld = overWorld[x][y]; // moves currentOverWorlds pointer. dummyWorld(); // initializes current Overworld tilemap. generateWorldImproved(); // generates RNG world and serializes to file. if (currentOverWorld.idX < 10 && currentOverWorld.idY < 10) { System.out.println("World0" + currentOverWorld.idX + "0" + currentOverWorld.idY + " generated"); } else if (currentOverWorld.idX < 10) { System.out.println("World0" + currentOverWorld.idX + currentOverWorld.idY + " generated"); } else if (currentOverWorld.idY < 10) { System.out.println("World" + currentOverWorld.idX + "0" + currentOverWorld.idY + " generated"); } else { System.out.println("World" + currentOverWorld.idX + currentOverWorld.idY + " generated"); } populateWorld(); // initializes and populates currentOverWorld.npclist with RNG Npc's. saveWorld(); } } currentOverWorld = overWorld[0][0]; // resets currentOverWorld pointer. } private void cleanWorld() { int x; int y; for (x = 0; x < worldSize; x++) { // iterates through the entire overWorlds array. for (y = 0; y < worldSize; y++) { overWorld[x][y].npcList = null; overWorld[x][y].tilemap = null; System.out.println("World" + x + y + " cleaned"); } } buildOverworld(); currentOverWorld = overWorld[0][0]; dummyWorld(); } private void saveWorld() { try { if (currentOverWorld.idX < 10 && currentOverWorld.idY < 10) { fileOut = new FileOutputStream("Data/Maps/WORLD0" + currentOverWorld.idX + "0" + currentOverWorld.idY + ".ser"); } else if (currentOverWorld.idX < 10) { fileOut = new FileOutputStream("Data/Maps/WORLD0" + currentOverWorld.idX + currentOverWorld.idY + ".ser"); } else if (currentOverWorld.idY < 10) { fileOut = new FileOutputStream("Data/Maps/WORLD" + currentOverWorld.idX + "0" + currentOverWorld.idY + ".ser"); } else { fileOut = new FileOutputStream("Data/Maps/WORLD" + currentOverWorld.idX + currentOverWorld.idY + ".ser"); } ObjectOutputStream out = new ObjectOutputStream(fileOut); // creates output stream pointed to file. out.writeObject(overWorld[currentOverWorld.idX][currentOverWorld.idY]); // serialize currentOverWorld. out.close(); fileOut.close(); // closes stream and file pointers. } catch (IOException i) { i.printStackTrace(); } } public void saveCustomWorld(String name) { try { Writer writer = new BufferedWriter(new OutputStreamWriter( // First create a new textfile. new FileOutputStream("Data/CustomMaps/" + name + ".ser"), "utf-8")); writer.close(); } catch (IOException e) { e.printStackTrace(); } try { // Then serialize an Overworld object to it. FileOutputStream fileOut = new FileOutputStream("Data/CustomMaps/" + name + ".ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); // creates output stream pointed to file. out.writeObject(overWorld[currentOverWorld.idX][currentOverWorld.idY]); // serialize currentOverWorld. out.close(); fileOut.close(); // closes stream and file pointers. } catch (IOException i) { i.printStackTrace(); } } public void reloadOverWorld() { int x; int y; for (x = 0; x < worldSize; x++) { for (y = 0; y < worldSize; y++) { currentOverWorld = overWorld[x][y]; // moves currentOverWorlds pointer. dummyWorld(); readWorld(x, y); for (Npc n : currentOverWorld.npcList) { // Todo; this does nothing atm n = new Npc(n.ID, n.xPos, n.yPos, n.HP, Color.black, n.ai); // refreshes all loaded nps. with newly constructed versions. to avoid bugs related to out dated npcs. } } } currentOverWorld = overWorld[0][0]; } public void readWorld(int idX, int idY) { try { if (idX < 10 && idY < 10) { fileIn = new FileInputStream("Data/Maps/WORLD0" + idX + "0" + idY + ".ser"); } else if (currentOverWorld.idX < 10) { fileIn = new FileInputStream("Data/Maps/WORLD0" + idX + idY + ".ser"); } else if (currentOverWorld.idY < 10) { fileIn = new FileInputStream("Data/Maps/WORLD" + idX + "0" + idY + ".ser"); } else { fileIn = new FileInputStream("Data/Maps/WORLD" + idX + idY + ".ser"); } // point to file. ObjectInputStream in = new ObjectInputStream(fileIn); // open stream. overWorld[idX][idY] = (Overworld) in.readObject(); in.close(); fileIn.close(); if (idX < 10 && idY < 10) { System.out.println("World0" + idX + "0" + idY + " loaded"); } else if (currentOverWorld.idX < 10) { System.out.println("World0" + idX + idY + " loaded"); } else if (currentOverWorld.idY < 10) { System.out.println("World" + idX + "0" + idY + " loaded"); } else { System.out.println("World" + idX + idY + " loaded"); } } catch (IOException | ClassNotFoundException i) { i.printStackTrace(); } } public void readCustomWorld(String name) { try { FileInputStream fileIn = new FileInputStream("Data/CustomMaps/" + name + ".ser"); // point to file. ObjectInputStream in = new ObjectInputStream(fileIn); // open stream. overWorld[currentOverWorld.idX][currentOverWorld.idY] = (Overworld) in.readObject(); //read Overworld object from file and write to currentOverWorld pointer. in.close(); fileIn.close(); System.out.println("Data/CustomMaps/" + name + ".ser"); } catch (IOException | ClassNotFoundException i) { i.printStackTrace(); } } private void buildOverworld() { for (int i = 0; i < worldSize; i++) { for (int j = 0; j < worldSize; j++) { overWorld[i][j] = new Overworld(i, j); // iterates through Overworld array and intializes it. } } } private void generatePlayer() { player1 = new Player(0, 14, 9, 66, 100, Color.RED); System.out.println("Created new player1 - ID: " + player1.ID + " - X: " + player1.xPos + " - Y: " + player1.yPos + " Empty Inventory Slots: " + player1.playerInventory.itemArray.length); } private void generateNpc(int setID, int setxPos, int setyPos, float setHP, Color setColor, String setAi) { Npc n = new Npc(setID, setxPos, setyPos, setHP, setColor, setAi); System.out.println("Created new " + setAi + " - ID: " + n.ID + " - X: " + n.xPos + " - Y: " + n.yPos); currentOverWorld.npcList.addElement(n); // works just like generate player but adds generated Npc to currentOverWorld.npclist. collisionMeshGenerator(); // Perhaps unneeded code but might prove itself useful in the future } private void populateWorld() { int r; int counter; int pop = 4; // amount of npc's generated per Overworld. int x; // position. int y; // position Color color; // npc color. String type; // ai type. for (counter = 0; counter < pop; counter++) { // run as many times as population allows. r = rotateRng(); x = rotateRng() % 29 + 1; // generates RNG value between 1 and 30 y = rotateRng() % 21 + 1; // generates RNG value bet // ween 1 and 22. ( edge protection. ) if (r < 50) { // cloin flip between Sheep and Chaser npc. type = "SHEEP"; color = Color.yellow; } else { type = "CHASER"; color = Color.black; } generateNpc(counter, x, y, 50, color, type); // creates npc with RNG generated values as attributes. } } @Override public void paintComponent(Graphics g) { // paints and controls what is currently painted on screen. super.paintComponent(g); if (engagedSuccessfully) { paintCombatSequence(g); } if (mapVisible && !engagedSuccessfully) { paintTilesLayer0(g); paintTilesLayer1(g); paintQuickslotGUI(g); if (raining) { paintRain(g); // paintRain2(g); if (!bufferSplashAnimations.isEmpty()) { paintSplash(g); } } } if (debugMenuVisible && !engagedSuccessfully) { paintTileCoordinates(g); paintTileLines(g); paintDebugMenu(g); paintPalleteMenu(g); } if (stuckInDialogue) { paintDialogueScreen(g); } if (attackStyleChooserVisible) { paintAttackStyleChooser(g); paintChosenAbilities(g); } if (inventoryMenuVisible && !engagedSuccessfully) { paintInventory(g); paintPlayerGearInterface(g); } if (viewMenuVisible) { paintViewMenu(g); } if (craftingMenuVisible) { paintCraftingMenu(g); } if (currentTile != null) { paintCurrentlySelectedTileHighlights(g); } if (currentItem != null) { paintCurrentlySelectedItemHighlights(g); paintCurrentlySelectedItemOnMouse(g); } if (shiftPressed && currentHoverItem != null && inventoryMenuVisible) { // && 5 seconds rested on item paintInventoryItemTooltip(g); } if (startMenuVisible) { paintStartMenu(g); } else { g.drawImage(bufferedImageMap.get("GEARWORKS_LOGO_SMALL"), 15, 540, 28 * 2, 28 * 2, this); } } private void paintDialogueScreen(Graphics g) { Graphics2D g2d = (Graphics2D) g; updateDialogueState(); updateMouseOverState(); g2d.setColor(Color.black); g2d.fillRect(0,395,800, 600-395); g2d.setColor(Color.white); g2d.setStroke(new BasicStroke(5)); g2d.drawRoundRect(0,395,800,205,20,20); g2d.setStroke(new BasicStroke(1)); g2d.drawImage(bufferedImageMap.get("EAST_" + currentDialogueNpc.ai), 16, 419, 100, 180, this); g2d.setColor(Color.white); g2d.setFont(font4_22); g2d.drawString(npcDialogue, 116, 419); // g2d.drawString("H (placeholder)", 116, 446); g2d.setColor(Color.gray); g2d.setFont(font4_20); if (mousedOverDialogue == 1) { g2d.setColor(Color.yellow); } g2d.drawString(playerResponse1, 151, 464); // g2d.drawString("H (placeholder)", 151, 489); g2d.setColor(Color.gray); if (mousedOverDialogue == 2) { g2d.setColor(Color.yellow); } g2d.drawString(playerResponse2, 151, 515); // g2d.drawString("H (placeholder)", 151, 541); g2d.setColor(Color.gray); if (mousedOverDialogue == 3) { g2d.setColor(Color.yellow); } g2d.drawString(playerResponse3, 151, 567); // g2d.drawString("H (placeholder)", 151, 593); g2d.setColor(Color.red); g2d.setFont(font1_8); g2d.drawString("#Dialogue State = " + TRIGGER_dialogueState, 711, 408); g2d.drawString("#MousedOverDialogue = " + mousedOverDialogue, 698, 424); } private void updateMouseOverState() { if (mouseDragY > 393) { // if mouse is in dialogue window if (mouseDragY > 450 && mouseDragY < 494) { mousedOverDialogue = 1; } else if (mouseDragY > 494 && mouseDragY < 544) { mousedOverDialogue = 2; } else if (mouseDragY > 544) { mousedOverDialogue = 3; } } else { mousedOverDialogue = 0; } } private void updateDialogueState() { /* DIALOGUE STATE CHEAT-SHEET Dialogue State : Npc Type : Q- "Question" . A1- "Answer1" . A2- "Answer2" . A3- "Answer3". : 0 : LUMBERJACK : Q- "Hello traveller." . A1- "Hello" . A2- "Actually, never mind." . A3- null. : */ if (currentDialogueNpc.ai.equals("LUMBERJACK")) { switch (TRIGGER_dialogueState) { case 0: boolean hasQuest0 = false; boolean hasQuest1 = false; for (Quest q : player1.personalQuestLog) { if (q.questID == 0) { hasQuest0 = true; } if (q.questID == 1) { hasQuest1 = true; } } if (player1.personalQuestsCompleted.contains(0) && !hasQuest1) { // )f played already has completed the quest TRIGGER_dialogueState = 5; } else { if (hasQuest1) { TRIGGER_dialogueState = 9; } else if (hasQuest0) { TRIGGER_dialogueState = 3; } else { npcDialogue = currentDialogueNpc.dialogue[0]; playerResponse1 = "- " + currentDialogueNpc.dialogue[1]; playerResponse2 = "- " + currentDialogueNpc.dialogue[2]; playerResponse3 = "- "; } } break; case 1: npcDialogue = currentDialogueNpc.dialogue[3]; playerResponse1 = "- " + currentDialogueNpc.dialogue[4]; playerResponse2 = "- " + currentDialogueNpc.dialogue[5]; playerResponse3 = "- " + currentDialogueNpc.dialogue[2]; break; case 2: npcDialogue = currentDialogueNpc.dialogue[6]; playerResponse1 = "- " + currentDialogueNpc.dialogue[7]; playerResponse2 = "- " + currentDialogueNpc.dialogue[5]; playerResponse3 = "- " + currentDialogueNpc.dialogue[2]; break; case 3: npcDialogue = currentDialogueNpc.dialogue[11]; playerResponse1 = "- " + currentDialogueNpc.dialogue[2]; playerResponse2 = "- " + currentDialogueNpc.dialogue[7]; playerResponse3 = "- "; break; case 4: npcDialogue = currentDialogueNpc.dialogue[9]; playerResponse1 = "- " + currentDialogueNpc.dialogue[8]; playerResponse2 = "- " + currentDialogueNpc.dialogue[10]; playerResponse3 = "- "; break; case 5: npcDialogue = currentDialogueNpc.dialogue[20]; playerResponse1 = "- " + currentDialogueNpc.dialogue[1]; playerResponse2 = "- " + currentDialogueNpc.dialogue[2]; playerResponse3 = "- "; break; case 6: npcDialogue = currentDialogueNpc.dialogue[3]; playerResponse1 = "- " + currentDialogueNpc.dialogue[4]; playerResponse2 = "- " + currentDialogueNpc.dialogue[5]; playerResponse3 = "- " + currentDialogueNpc.dialogue[2]; break; case 7: npcDialogue = currentDialogueNpc.dialogue[18]; playerResponse1 = "- " + currentDialogueNpc.dialogue[7]; playerResponse2 = "- " + currentDialogueNpc.dialogue[5]; playerResponse3 = "- "; break; case 8: npcDialogue = currentDialogueNpc.dialogue[19]; playerResponse1 = "- " + currentDialogueNpc.dialogue[7]; playerResponse2 = "- "; playerResponse3 = "- "; break; case 9: npcDialogue = currentDialogueNpc.dialogue[21]; playerResponse1 = "- " + currentDialogueNpc.dialogue[7]; playerResponse2 = "- "; playerResponse3 = "- "; break; default: npcDialogue = "- "; playerResponse1 = "- "; playerResponse2 = "- "; playerResponse3 = "- "; } } else if (currentDialogueNpc.ai.equals("CASTLEGUARD")) { switch (TRIGGER_dialogueState) { case 0: boolean hasQuest1 = false; for (Quest q : player1.personalQuestLog) { if (q.questID == 1) { hasQuest1 = true; } } if (false) { // )f played already has completed the quest } else { if (hasQuest1) { TRIGGER_dialogueState = 1; } else { npcDialogue = currentDialogueNpc.dialogue[0]; playerResponse1 = "- " + currentDialogueNpc.dialogue[1]; playerResponse2 = "- "; playerResponse3 = "- "; } } break; case 1: npcDialogue = currentDialogueNpc.dialogue[2]; playerResponse1 = "- " + currentDialogueNpc.dialogue[3]; playerResponse2 = "- " + currentDialogueNpc.dialogue[4]; playerResponse3 = "- "; break; case 2: npcDialogue = currentDialogueNpc.dialogue[5]; playerResponse1 = "- " + currentDialogueNpc.dialogue[6]; playerResponse2 = "- " + currentDialogueNpc.dialogue[4]; playerResponse3 = "- "; break; case 3: npcDialogue = currentDialogueNpc.dialogue[0]; playerResponse1 = "- " + currentDialogueNpc.dialogue[1]; playerResponse2 = "- "; playerResponse3 = "- "; break; } } } private void paintRain2(Graphics g) { } private void paintInventoryItemTooltip(Graphics g) { Graphics2D g2d = (Graphics2D) g; int borderWidth = 120; int borderHeight = 60; if (mouseDragX > 677 && mouseDragY < 767) { g2d.setColor(Color.lightGray); g2d.fillRect(mouseDragX - borderWidth, mouseDragY - borderHeight, borderWidth, borderHeight); g2d.setStroke(new BasicStroke(3)); g2d.setColor(Color.black); g2d.drawRect(mouseDragX - borderWidth, mouseDragY - borderHeight, borderWidth, borderHeight); g2d.setFont(font2_16); g2d.drawString("ID: " +String.valueOf(currentHoverItem.ID),mouseDragX - borderWidth + 5,mouseDragY - borderHeight + 17); } else { // g2d.drawRect(mouseDragX, mouseDragY - borderHeight, borderWidth, borderHeight); g2d.setColor(Color.lightGray); g2d.fillRect(mouseDragX, mouseDragY - borderHeight, borderWidth, borderHeight); g2d.setStroke(new BasicStroke(3)); g2d.setColor(Color.black); g2d.drawRect(mouseDragX, mouseDragY - borderHeight, borderWidth, borderHeight); g2d.setFont(font2_16); g2d.drawString("ID: " + String.valueOf(currentHoverItem.ID), mouseDragX + 5, mouseDragY - borderHeight + 17); } } private void paintChosenAbilities(Graphics g) { for (int i = 0; i < 3; i++) { g.drawRect(24 + (30 * i), 440, 30, 30); } switch (abilities[0]) { case 1: g.drawImage(bufferedImageMap.get("ABILITY_MHAND_SLICE"), 24, 440, 30, 30, this); break; case 2: g.drawImage(bufferedImageMap.get("ABILITY_MHAND_STAB"), 24, 440, 30, 30, this); break; case 3: g.drawImage(bufferedImageMap.get("ABILITY_OHAND_BLOCK"), 24, 440, 30, 30, this); break; } switch (abilities[1]) { case 1: g.drawImage(bufferedImageMap.get("ABILITY_MHAND_SLICE"), 24 + 30, 440, 30, 30, this); break; case 2: g.drawImage(bufferedImageMap.get("ABILITY_MHAND_STAB"), 24 + 30, 440, 30, 30, this); break; case 3: g.drawImage(bufferedImageMap.get("ABILITY_OHAND_BLOCK"), 24 + 30, 440, 30, 30, this); break; } switch (abilities[2]) { case 1: g.drawImage(bufferedImageMap.get("ABILITY_MHAND_SLICE"), 24 + 60, 440, 30, 30, this); break; case 2: g.drawImage(bufferedImageMap.get("ABILITY_MHAND_STAB"), 24 + 60, 440, 30, 30, this); break; case 3: g.drawImage(bufferedImageMap.get("ABILITY_OHAND_BLOCK"), 24 + 60, 440, 30, 30, this); break; } } private void paintAttackStyleChooser(Graphics g) { g.setColor(Color.lightGray); g.fillRect(25, 356, 300, 120); g.setColor(Color.black); g.setFont(font2_16); g.drawString("Choose your skills", 25, 376); g.drawString("Active Skills", 25, 433); for (int i = 0; i < 8; i++) { g.drawRect(25 + (30 * i), 386, 30, 30); } g.drawImage(bufferedImageMap.get("ABILITY_MHAND_SLICE"), 30, 386, this); g.drawImage(bufferedImageMap.get("ABILITY_MHAND_STAB"), 60, 386, this); g.drawImage(bufferedImageMap.get("ABILITY_OHAND_BLOCK"), 90, 386, this); } private void paintQuickslotGUI(Graphics g) { if (mouseDragX > 730 && mouseDragX < 773 && mouseDragY > 26 && mouseDragY < 62) { g.drawImage(bufferedImageMap.get("BAG_ICON"), 730 - 10, 20 - 10, 60, 60, this); } else { g.drawImage(bufferedImageMap.get("BAG_ICON"), 730, 20, 40, 40, this); } if (mouseDragX > 678 && mouseDragX < 728 && mouseDragY > 26 && mouseDragY < 62) { g.drawImage(bufferedImageMap.get("CRAFTING_ICON"), 688 - 15, 20 - 17, 60, 60, this); } else { g.drawImage(bufferedImageMap.get("CRAFTING_ICON"), 678, 15, 40, 40, this); } if (mouseDragX > 626 && mouseDragX < 666 && mouseDragY > 26 && mouseDragY < 62) { g.drawImage(bufferedImageMap.get("RED_DAGGER_WEST"), 616, 20 - 17, 60, 60, this); } else { g.drawImage(bufferedImageMap.get("RED_DAGGER_WEST"), 628, 15, 40, 40, this); } } private void paintCombatSequence(Graphics g) { if (checkForEndOfTurnTrigger()) { return; } g.drawImage(bufferedImageMap.get("BACKGROUNDIMG_COMBAT_0"), 0, 0, this); player1.xPos = 340; player1.yPos = 100; player1.orientation = "SOUTH"; paintPlayer(g, 5); if (Objects.equals(currentNpc.ai, "SHEEP")) { if (animation_frame % 2 == 0) { g.drawImage(bufferedImageMap.get("NORTH_SHEEP"), 351, 311, 400, 400, this); } else { g.drawImage(bufferedImageMap.get("NORTH_SHEEP"), 351, 311 - 50, 400, 400, this); } } } private void paintPlayerGearInterface(Graphics g) { g.setColor(Color.white); g.fillRect(663, 512, 25, 25); // HELM LOCATION g.fillRect(663, 542, 25, 25); // CHEST LOCATION g.fillRect(663, 572, 25, 25); // PANTS LOCATION g.fillRect(693, 542, 25, 25); // OFFHAND LOCATION g.fillRect(633, 542, 25, 25); // MAINHAND LOCATION g.setColor(Color.black); g.drawRect(663, 512, 25, 25); g.drawRect(663, 542, 25, 25); g.drawRect(663, 572, 25, 25); g.drawRect(693, 542, 25, 25); g.drawRect(633, 542, 25, 25); g.setFont(font1_8); switch (player1.gearInterface.itemArray[0].ID) { // HELMET ZONE case 5: g.drawImage(bufferedImageMap.get("RATSKINHOOD"), 663, 512, 25, 25, this); break; case 0: break; default: g.drawString("ERROR", 663, 512); break; } switch (player1.gearInterface.itemArray[1].ID) { // CHEST ZONE case 6: g.drawImage(bufferedImageMap.get("RAGGEDSHIRT"), 661, 545, 30, 30, this); break; case 24: g.drawImage(bufferedImageMap.get("GREEN_PLATEBODY_TRIMMED"), 663, 542, 25, 25, this); break; case 23: g.drawImage(bufferedImageMap.get("GREEN_PLATEBODY"), 663, 542, 25, 25, this); break; case 29: g.drawImage(bufferedImageMap.get("BROWN_PLATEBODY"), 663, 542, 25, 25, this); break; case 30: g.drawImage(bufferedImageMap.get("BROWN_PLATEBODY_TRIMMED"), 663, 542, 25, 25, this); break; case 16: g.drawImage(bufferedImageMap.get("BLUE_PLATEBODY"), 663, 542, 25, 25, this); break; case 17: g.drawImage(bufferedImageMap.get("BLUE_PLATEBODY_TRIMMED"), 663, 542, 25, 25, this); break; case 0: break; default: g.drawString("ERROR", 663, 542); break; } switch (player1.gearInterface.itemArray[2].ID) { // LEG ZONE case 7: g.drawImage(bufferedImageMap.get("RATSKINPANTS"), 663, 572, 25, 25, this); break; case 14: g.drawImage(bufferedImageMap.get("BLUE_LEGGUARDS"), 663, 572, 25, 25, this); break; case 15: g.drawImage(bufferedImageMap.get("BLUE_LEGGUARDS_TRIMMED"), 663, 572, 25, 25, this); break; case 21: g.drawImage(bufferedImageMap.get("GREEN_LEGGUARDS"), 663, 572, 25, 25, this); break; case 22: g.drawImage(bufferedImageMap.get("GREEN_LEGGUARDS_TRIMMED"), 663, 572, 25, 25, this); break; case 27: g.drawImage(bufferedImageMap.get("JUNKSCRAP_LEGGUARDS"), 663, 572, 25, 25, this); break; case 28: g.drawImage(bufferedImageMap.get("JUNKSCRAP_LEGGUARDS_TRIMMED"), 663, 572, 25, 25, this); break; case 0: break; default: g.drawString("ERROR", 663, 572); break; } switch (player1.gearInterface.itemArray[3].ID) { // Todo: BOOT ZONE (NOT YET IMPLEMENTED) case 8: break; default: // g.drawString("ERROR",663,572); break; } switch (player1.gearInterface.itemArray[4].ID) { //OFFHAND ZONE case 10: g.drawImage(bufferedImageMap.get("WOODEN_SHIELD"), 694, 543, 25, 25, this); break; case 11: g.drawImage(bufferedImageMap.get("BLUE_BUCKLER"), 694, 543, 25, 25, this); break; case 12: g.drawImage(bufferedImageMap.get("BLUE_BUCKLER_TRIMMED"), 694, 543, 25, 25, this); break; case 18: g.drawImage(bufferedImageMap.get("GREEN_BUCKLER"), 694, 543, 25, 25, this); break; case 19: g.drawImage(bufferedImageMap.get("GREEN_BUCKLER_TRIMMED"), 694, 543, 25, 25, this); break; case 25: g.drawImage(bufferedImageMap.get("JUNKSCRAP_BUCKLER"), 694, 543, 25, 25, this); break; case 26: g.drawImage(bufferedImageMap.get("JUNKSCRAP_BUCKLER_TRIMMED"), 694, 543, 25, 25, this); break; case 0: break; default: g.drawString("ERROR", 693, 543); break; } switch (player1.gearInterface.itemArray[5].ID) { // MAINHAND ZONE case 9: g.drawImage(bufferedImageMap.get("WOODEN_CLUB_W"), 633, 543, 25, 25, this); break; case 13: g.drawImage(bufferedImageMap.get("BLUE_DAGGER_WEST"), 633, 543, 25, 25, this); break; case 31: g.drawImage(bufferedImageMap.get("RED_DAGGER_WEST"), 633, 543, 25, 25, this); break; case 20: g.drawImage(bufferedImageMap.get("GREEN_DAGGER_WEST"), 633, 543, 25, 25, this); break; case 32: g.drawImage(bufferedImageMap.get("LUMBERJACK_AXE_WEST"), 633, 543, 25, 25, this); break; case 0: break; default: g.drawString("ERROR", 633, 543); break; } } private void paintSplash(Graphics g) { Point p = bufferSplashAnimations.pollFirst(); /* for(int i = 0; i < 100; i++){ g.fillOval(p.x,p.y,i,i); } */ // System.out.println("Paintdrop Destroyed @" +p.x + ", " + p.y); } private void paintCurrentlySelectedItemOnMouse(Graphics g) { if (currentItem.ID == 1) { g.drawImage(bufferedImageMap.get("INVENTORY_LUMBER"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 2) { g.drawImage(bufferedImageMap.get("STONE"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 3) { g.drawImage(bufferedImageMap.get("SAND"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 4) { g.drawImage(bufferedImageMap.get("PLANKWALL"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 5) { g.drawImage(bufferedImageMap.get("RATSKINHOOD"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 6) { g.drawImage(bufferedImageMap.get("RATSKINCHEST"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 7) { g.drawImage(bufferedImageMap.get("RATSKINPANTS"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 8) { g.drawImage(bufferedImageMap.get("RATSKIN_BOOTS"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 9) { g.drawImage(bufferedImageMap.get("WOODEN_CLUB"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 10) { g.drawImage(bufferedImageMap.get("WOODEN_SHIELD"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 11) { g.drawImage(bufferedImageMap.get("BLUE_BUCKLER"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 12) { g.drawImage(bufferedImageMap.get("BLUE_BUCKLER_TRIMMED"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 13) { g.drawImage(bufferedImageMap.get("BLUE_DAGGER"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 14) { g.drawImage(bufferedImageMap.get("BLUE_LEGGUARDS"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 15) { g.drawImage(bufferedImageMap.get("BLUE_LEGGUARDS_TRIMMED"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 16) { g.drawImage(bufferedImageMap.get("BLUE_PLATEBODY"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 17) { g.drawImage(bufferedImageMap.get("BLUE_PLATEBODY_TRIMMED"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 18) { g.drawImage(bufferedImageMap.get("GREEN_BUCKLER"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 19) { g.drawImage(bufferedImageMap.get("GREEN_BUCKLER_TRIMMED"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 20) { g.drawImage(bufferedImageMap.get("GREEN_DAGGER"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 21) { g.drawImage(bufferedImageMap.get("GREEN_LEGGUARDS"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 22) { g.drawImage(bufferedImageMap.get("GREEN_LEGGUARDS_TRIMMED"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 23) { g.drawImage(bufferedImageMap.get("GREEN_PLATEBODY"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 24) { g.drawImage(bufferedImageMap.get("GREEN_PLATEBODY_TRIMMED"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 25) { g.drawImage(bufferedImageMap.get("JUNKSCRAP_BUCKLER"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 26) { g.drawImage(bufferedImageMap.get("JUNKSCRAP_BUCKLER_TRIMMED"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 27) { g.drawImage(bufferedImageMap.get("JUNKSCRAP_LEGGUARDS"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 28) { g.drawImage(bufferedImageMap.get("JUNKSCRAP_LEGGUARDS_TRIMMED"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 29) { g.drawImage(bufferedImageMap.get("BROWN_PLATEBODY"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 30) { g.drawImage(bufferedImageMap.get("BROWN_PLATEBODY_TRIMMED"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } if (currentItem.ID == 31) { g.drawImage(bufferedImageMap.get("RED_DAGGER"), mouseDragX - 10, mouseDragY - 14, 20, 20, this); } } private void paintPalleteMenu(Graphics g) { g.setColor(Color.lightGray); g.fillRect(62, 15, 250, 80); g.drawImage(bufferedImageMap.get("ARROW_UP"), 80, 20, 30, 30, this); g.drawImage(bufferedImageMap.get("ARROW_DOWN"), 80, 50, 30, 30, this); g.drawImage(bufferedImageMap.get("ARROW_UP"), 197, 20, 30, 30, this); g.drawImage(bufferedImageMap.get("ARROW_DOWN"), 197, 50, 30, 30, this); g.drawImage(bufferedImageMap.get(BrushTileList.get(tileBrushIndex)), 132, 44, 30, 30, this); g.drawImage(bufferedImageMap.get("EAST_" + brushNpcList.get(npcBrushIndex)), 250, 44, 30, 30, this); } private void paintCraftingMenu(Graphics g) { g.setColor(Color.lightGray); g.fillRect(25, 125, 200, 200); g.setColor(Color.white); g.fillRect(34, 149, 90, 90); g.fillRect(157, 183, 30, 30); g.setColor(Color.black); g.fillRect(151, 233, 59, 15); // "CRAFT BUTTON" g.fillRect(151,253,71,15); // "RETURN" BUTTON g.setFont(font2_16); g.drawString("Crafting", 34, 142); int counter = 0; int row = 0; for (int i = 0; i < player1.playerCrafter.itemArray.length - 1; i++) { if (counter == 3) { counter = 0; row++; } g.drawRect(34 + (counter * 30), 149 + (row * 30), 30, 30); if (player1.playerCrafter.itemArray[i].ID == 1) { g.drawImage(bufferedImageMap.get("INVENTORY_LUMBER"), 34 + (counter * 30), 149 + (row * 30), 25, 22, this); } else if (player1.playerCrafter.itemArray[i].ID == 2) { g.drawImage(bufferedImageMap.get("STONE"), 34 + (counter * 30), 149 + (row * 30), 25, 22, this); } counter++; } g.drawRect(157, 183, 30, 30); g.setColor(Color.white); g.setFont(font2_16); g.drawString("CRAFT", 153, 247); g.drawString("CANCEL", 153, 266); if (player1.playerCrafter.itemArray[9].ID == 4) { g.drawImage(bufferedImageMap.get("PLANKWALL"), 157, 183, 30, 30, this); } if (player1.playerCrafter.itemArray[9].ID == 32) { g.drawImage(bufferedImageMap.get("LUMBERJACK_AXE_WEST"), 157, 183, 30, 30, this); } } private void paintTilesLayer0(Graphics g) { // Tile Rendering System Npc n = new Npc(0, 0, 0, 0, Color.BLACK, ""); assert bufferedImageMap != null : "ERROR: bufferedImageMap is null"; for (int i = 0; i < 32; i++) { // foreach tile outer loop for (int j = 0; j < 24; j++) { // foreach tile inner loop String tileTypeToPaint = currentOverWorld.tilemap[i][j].type; // store tile type as string switch (tileTypeToPaint) { // Rendering unit for each tile type case "grass": g.setColor(Color.green); g.fillRect(i * 25, j * 25, 25, 25); g.drawImage(bufferedImageMap.get("GRASS"), i * 25, j * 25, 25, 25, this); // draws a grass on top of each "grass" ti break; case "woodfloor": g.drawImage(bufferedImageMap.get("WOODFLOOR"), i * 25, j * 25, 25, 25, this); // draws a grass on top of each "grass" ti break; case "water": g.setColor(Color.blue); g.drawImage(bufferedImageMap.get("WATER"), i * 25, j * 25, 25, 25, this); break; case "tree": g.setColor(Color.green); g.fillRect(i * 25, j * 25, 25, 25); g.drawImage(bufferedImageMap.get("GRASS"), i * 25, j * 25, 25, 25, this); // draws a grass g.drawImage(bufferedImageMap.get("TREE"), i * 25 - 19, j * 25 - 80, 65, 100, this); // draws a tree break; case "stone": g.setColor(Color.green); g.fillRect(i * 25, j * 25, 25, 25); g.drawImage(bufferedImageMap.get("GRASS"), i * 25, j * 25, 25, 25, this); // draws a grass g.drawImage(bufferedImageMap.get("STONE"), i * 25 - 5, j * 25 - 10, 40, 40, this); // draws a tree break; case "sand": g.setColor(Color.orange); g.drawImage(bufferedImageMap.get("SAND"), i * 25, j * 25, 25, 25, this); break; case "rakeddirt": g.setColor(new Color(100, 40, 19)); g.fillRect(i * 25, j * 25, 25, 25); g.drawImage(bufferedImageMap.get("RAKEDDIRT"), i * 25, j * 25, 25, 25, this); break; case "dirt": g.setColor(new Color(100, 80, 30)); g.fillRect(i * 25, j * 25, 25, 25); g.drawImage(bufferedImageMap.get("DIRT"), i * 25, j * 25, 25, 25, this); break; case "plankwall": g.drawImage(bufferedImageMap.get("GRASS"), i * 25, j * 25, 25, 25, this); // draws a grass g.drawImage(bufferedImageMap.get("PLANKWALL"), i * 25, j * 25, 25, 25, this); break; case "stonepathgrass": g.drawImage(bufferedImageMap.get("STONEPATHGRASS"), i * 25, j * 25, 25, 25, this); break; case "woodfloordooreast": g.drawImage(bufferedImageMap.get("WOODFLOORDOOREAST"), i * 25, j * 25, 25, 25, this); break; case "woodfloordoornorth": g.drawImage(bufferedImageMap.get("WOODFLOORDOORNORTH"), i * 25, j * 25, 25, 25, this); break; case "woodfloordoorsouth": g.drawImage(bufferedImageMap.get("WOODFLOORDOORSOUTH"), i * 25, j * 25, 25, 25, this); break; case "woodfloordoorwest": g.drawImage(bufferedImageMap.get("WOODFLOORDOORWEST"), i * 25, j * 25, 25, 25, this); break; case "openwoodfloordooreast": g.drawImage(bufferedImageMap.get("WOODFLOORDOORSOUTH"), i * 25, j * 25, 25, 25, this); break; case "openwoodfloordoornorth": g.drawImage(bufferedImageMap.get("WOODFLOORDOOREAST"), i * 25, j * 25, 25, 25, this); break; case "openwoodfloordoorsouth": g.drawImage(bufferedImageMap.get("WOODFLOORDOORWEST"), i * 25, j * 25, 25, 25, this); break; case "openwoodfloordoorwest": g.drawImage(bufferedImageMap.get("WOODFLOORDOORNORTH"), i * 25, j * 25, 25, 25, this); break; case "woodenfencehorizontal": g.drawImage(bufferedImageMap.get("GRASS"), i * 25, j * 25, 25, 25, this); // draws a grass break; case "woodenfencevertical": g.drawImage(bufferedImageMap.get("GRASS"), i * 25, j * 25, 25, 25, this); // draws a grass break; case "woodenfencenwcorner": g.drawImage(bufferedImageMap.get("GRASS"), i * 25, j * 25, 25, 25, this); // draws a grass break; case "woodenfencenecorner": g.drawImage(bufferedImageMap.get("GRASS"), i * 25, j * 25, 25, 25, this); // draws a grass break; case "woodenfencesecorner": g.drawImage(bufferedImageMap.get("GRASS"), i * 25, j * 25, 25, 25, this); // draws a grass break; case "woodenfenceswcorner": g.drawImage(bufferedImageMap.get("GRASS"), i * 25, j * 25, 25, 25, this); // draws a grass break; default: g.setColor(Color.red); g.drawString("ERR", i * 25, j * 25 + 25); break; } } } } private void paintTilesLayer1(Graphics g) { assert bufferedImageMap != null : "ERROR: bufferedImageMap is null"; for (int j = 0; j < 24; j++) { // foreach tile outer loop for (int i = 31; i > 0; i--) { // foreach tile inner loop String tileTypeToPaint = currentOverWorld.tilemap[i][j].type; // store tile type as string switch (tileTypeToPaint) { // Rendering unit for each tile type case "tree": g.drawImage(bufferedImageMap.get("TREE"), i * 25 - 19, j * 25 - 80, 65, 100, this); // draws a tree break; case "stone": g.drawImage(bufferedImageMap.get("STONE"), i * 25 - 5, j * 25 - 10, 40, 40, this); // draws a tree break; case "woodenfencehorizontal": g.drawImage(bufferedImageMap.get("WOODENFENCEHORIZONTAL"), i * 25, j * 25, 25, 25, this); break; case "woodenfencevertical": g.drawImage(bufferedImageMap.get("WOODENFENCEVERTICAL"), i * 25, j * 25, 25, 25, this); break; case "woodenfencenwcorner": g.drawImage(bufferedImageMap.get("WOODENFENCENWCORNER"), i * 25, j * 25, 25, 25, this); break; case "woodenfenceswcorner": g.drawImage(bufferedImageMap.get("WOODENFENCESWCORNER"), i * 25, j * 25, 25, 25, this); break; case "woodenfencenecorner": g.drawImage(bufferedImageMap.get("WOODENFENCENECORNER"), i * 25, j * 25, 25, 25, this); break; case "woodenfencesecorner": g.drawImage(bufferedImageMap.get("WOODENFENCESECORNER"), i * 25, j * 25, 25, 25, this); break; } if (player1.xPos / 25 == i && player1.yPos / 25 == j) { paintPlayer(g, 1); } for (Npc n : currentOverWorld.npcList) { if (j == n.yPos / 25 && i == n.xPos / 25) { paintNpcs(g, n); } } } } } private void paintRain(Graphics g) { Graphics2D g2d = (Graphics2D) g; g2d.setColor(Color.red); g2d.setStroke(new BasicStroke(2)); g.setColor(Color.blue); for (Point p : rainDrops) { g2d.drawLine(p.x, p.y, p.x + 10, p.y + 10); } moveRain(); g2d.setStroke(new BasicStroke(1)); } private void moveRain() { for (int i = 0; i < rainDrops.length; i++) { int gravity = (rotateRng() % (12)); rainDrops[i].x += gravity; rainDrops[i].y += gravity; } for (int i = 0; i < rainDrops.length; i++) { int wind = (rotateRng() % (6)); rainDrops[i].x += wind * rainVector; } destroyRandomRaindrops(); replaceOutOfScreenRain(); } private void destroyRandomRaindrops() { int rng = (int) (Math.random() * (5000)); if (rng > 4990) { rainVector = -rainVector; } if (rng > 2500) { int rainDropIndexToDestroy = (int) (Math.random() * (rainDrops.length)); // bufferSplashAnimations.offerFirst(new Point(rainDrops[rainDropIndexToDestroy].x, rainDrops[rainDropIndexToDestroy].y)); rainDrops[rainDropIndexToDestroy].x = (int) (Math.random() * (Main.WIDTH)); rainDrops[rainDropIndexToDestroy].y = (int) (Math.random() * (Main.WIDTH)); } } private void replaceOutOfScreenRain() { for (int i = 0; i < rainDrops.length; i++) { if (rainDrops[i].x > Main.WIDTH || rainDrops[i].y > Main.HEIGHT) { rainDrops[i].x = (int) (Math.random() * (Main.WIDTH)); rainDrops[i].y = (int) (Math.random() * (Main.HEIGHT)); } } } private void paintCurrentlySelectedItemHighlights(Graphics g) { Graphics2D g2d = (Graphics2D) g; g2d.setColor(Color.red); g2d.setStroke(new BasicStroke(2)); if (inventoryMenuVisible && currentItem != null && currentItem.equals(player1.playerCrafter.itemArray[9])) { g2d.drawRect(156, 183, 30, 30); } else if (inventoryMenuVisible && currentItem != null) { g2d.drawRect(587 + ((currentItemColumn - 1) * 30), 176 + ((currentItemRow - 1) * 30), 30, 30); } g2d.setStroke(new BasicStroke(1)); } private void paintCurrentlySelectedTileHighlights(Graphics g) { Graphics2D g2d = (Graphics2D) g; g2d.setColor(Color.yellow); g2d.setStroke(new BasicStroke(2)); g2d.drawRect(currentTileX * 25, currentTileY * 25, 25, 25); g2d.setStroke(new BasicStroke(1)); } private void paintInventory(Graphics g) { g.setColor(Color.lightGray); g.fillRect(575, 149, 200, 600); g.setFont(font3_24); g.setColor(Color.black); g.drawString("Inventory", 585, 167); g.setColor(Color.white); g.fillRect(588, 176, 180, 329); g.setColor(Color.black); int counter = 0; int row = 0; for (int i = 0; i < player1.playerInventory.itemArray.length; i++) { if (counter == 6) { counter = 0; row++; } if (player1.playerInventory.itemArray[i].ID == 1) { g.drawImage(bufferedImageMap.get("INVENTORY_LUMBER"), 593 + (counter * 30) - 5, 183 + (row * 30) - 5, 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 2) { g.drawImage(bufferedImageMap.get("STONE"), 593 + (counter * 30) - 5, 183 + (row * 30) - 5, 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 3) { g.drawImage(bufferedImageMap.get("SAND"), 593 + (counter * 30) - 5, 183 + (row * 30) - 5, 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 4) { g.drawImage(bufferedImageMap.get("PLANKWALL"), 593 + (counter * 30), 183 + (row * 30), 20, 20, this); } else if (player1.playerInventory.itemArray[i].ID == 5) { g.drawImage(bufferedImageMap.get("RATSKINHOOD"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 6) { g.drawImage(bufferedImageMap.get("RAGGEDSHIRT"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 7) { g.drawImage(bufferedImageMap.get("RATSKINPANTS"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 8) { g.drawImage(bufferedImageMap.get("ERROR_IMG"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); //todo: NOT YET IMPLEMENTED // g.drawImage(bufferedImageMap.get("RATSKIN_BOOTS"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 9) { g.drawImage(bufferedImageMap.get("WOODEN_CLUB_W"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 10) { g.drawImage(bufferedImageMap.get("WOODEN_SHIELD"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 11) { g.drawImage(bufferedImageMap.get("BLUE_BUCKLER"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 12) { g.drawImage(bufferedImageMap.get("BLUE_BUCKLER_TRIMMED"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 13) { g.drawImage(bufferedImageMap.get("BLUE_DAGGER_EAST"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 14) { g.drawImage(bufferedImageMap.get("BLUE_LEGGUARDS"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 15) { g.drawImage(bufferedImageMap.get("BLUE_LEGGUARDS_TRIMMED"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 16) { g.drawImage(bufferedImageMap.get("BLUE_PLATEBODY"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 17) { g.drawImage(bufferedImageMap.get("BLUE_PLATEBODY_TRIMMED"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 18) { g.drawImage(bufferedImageMap.get("GREEN_BUCKLER"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 19) { g.drawImage(bufferedImageMap.get("GREEN_BUCKLER_TRIMMED"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 20) { g.drawImage(bufferedImageMap.get("GREEN_DAGGER_EAST"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 21) { g.drawImage(bufferedImageMap.get("GREEN_LEGGUARDS"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 22) { g.drawImage(bufferedImageMap.get("GREEN_LEGGUARDS_TRIMMED"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 23) { g.drawImage(bufferedImageMap.get("GREEN_PLATEBODY"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 24) { g.drawImage(bufferedImageMap.get("GREEN_PLATEBODY_TRIMMED"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 25) { g.drawImage(bufferedImageMap.get("JUNKSCRAP_BUCKLER"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 26) { g.drawImage(bufferedImageMap.get("JUNKSCRAP_BUCKLER_TRIMMED"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 27) { g.drawImage(bufferedImageMap.get("JUNKSCRAP_LEGGUARDS"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 28) { g.drawImage(bufferedImageMap.get("JUNKSCRAP_LEGGUARDS_TRIMMED"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 29) { g.drawImage(bufferedImageMap.get("BROWN_PLATEBODY"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 30) { g.drawImage(bufferedImageMap.get("BROWN_PLATEBODY_TRIMMED"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 31) { g.drawImage(bufferedImageMap.get("RED_DAGGER_EAST"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } else if (player1.playerInventory.itemArray[i].ID == 32) { g.drawImage(bufferedImageMap.get("LUMBERJACK_AXE_EAST"), 593 + (counter * 30), 183 + (row * 30), 25, 25, this); } g.setColor(Color.black); g.drawRect(587 + (counter * 30), 176 + (row * 30), 30, 30); counter++; } paintGold(g); } private void paintGold(Graphics g) { g.setColor(Color.black); g.drawString("Gold: " + player1.gold, 690, 528); } private void paintOrientationArrow(Graphics g) { g.setColor(Color.black); switch (player1.orientation) { case "EAST": g.drawLine(player1.xPos + 10, player1.yPos + 10, player1.xPos + 20, player1.yPos + 10); break; case "WEST": g.drawLine(player1.xPos + 10, player1.yPos + 10, player1.xPos, player1.yPos + 10); break; case "NORTH": g.drawLine(player1.xPos + 10, player1.yPos + 10, player1.xPos + 10, player1.yPos); break; case "SOUTH": g.drawLine(player1.xPos + 10, player1.yPos + 10, player1.xPos + 10, player1.yPos + 20); break; } } private void paintDebugMenu(Graphics g) { g.setColor(Color.gray); g.fillRect(24, 450, 300, 124); g.setColor(Color.black); g.setFont(font2_16); g.drawString("player1 TrueCoords: (" + player1.xPos + ", " + player1.yPos + ")", 37, 465); g.drawString("player1 TileCoords: (" + (player1.xPos / 25) + ", " + (player1.yPos / 25) + ")", 37, 490); int player1_TileCoordinated_xPos = (player1.xPos / 25); int player1_TileCoordinated_yPos = (player1.yPos / 25); g.drawString("player1 standing on tile: " + currentOverWorld.tilemap[player1_TileCoordinated_xPos][player1_TileCoordinated_yPos].type, 37, 515); g.drawString("Farmable? " + (currentOverWorld.tilemap[player1_TileCoordinated_xPos][player1_TileCoordinated_yPos].farmable ? "yes" : "no"), 88, 532); g.drawString("action ticker: (" + actionTick + ")", 39, 556); } private void paintStartMenu(Graphics g) { g.setColor(Color.gray); g.fillRect(24, 1, 750, 600); g.setColor(Color.black); g.setFont(font2_16); g.drawString("0 : Generate world ( overwrites all saves in Maps folder.) / close menu", 87, 88); g.drawString("1 : Load map from files", 87, 122); g.drawString("9 : Load Map ( test function )", 87, 157); if (worldExists) { g.drawString("World ready", 87, 220); } else { g.drawString("No world spawned", 87, 220); } g.drawImage(bufferedImageMap.get("GEARWORKS_LOGO"), 0, 275, Main.WIDTH, 325, this); } private void paintViewMenu(Graphics g) { g.setColor(Color.gray); g.fillRect(363, 452, 300, 100); g.setColor(Color.black); g.setFont(font2_16); if (currentTile != null) { g.drawString(currentTile.type, 373, 468); if (currentTile.farmable) { g.drawString("Farmable", 373, 488); } if (currentTile.occupied) { g.drawString("Obstacle", 373, 508); } } } private void paintNpcs(Graphics g, Npc n) { if (n.ai.equals("SHEEP")) { int xOffset = 0; int yOffset = 0; if (n.orientation.equals("NORTH")) { xOffset = 4; yOffset = 6; } else if (n.orientation.equals("SOUTH")) { xOffset = 5; yOffset = 6; } else if (n.orientation.equals("WEST")) { xOffset = 6; yOffset = 5; } else if (n.orientation.equals("EAST")) { xOffset = 4; yOffset = 3; } g.drawImage(bufferedImageMap.get(n.orientation + "_" + n.ai), n.xPos - xOffset, n.yPos - yOffset, 30, 30, this); } else if (n.ai.equals("CHASER")) { int xOffset = 0; int yOffset = 0; if (n.orientation.equals("NORTH")) { xOffset = 4; yOffset = 20; } else if (n.orientation.equals("SOUTH")) { xOffset = 5; yOffset = 20; } else if (n.orientation.equals("WEST")) { xOffset = 6; yOffset = 19; } else if (n.orientation.equals("EAST")) { xOffset = 4; yOffset = 19; } g.drawImage(bufferedImageMap.get(n.orientation + "_" + n.ai), n.xPos - xOffset, n.yPos - yOffset, 30, 45, this); } else if (n.ai.equals("LUMBERJACK")) { int xOffset = 0; int yOffset = 0; switch (n.orientation) { case "NORTH": xOffset = 0; yOffset = 0; break; case "SOUTH": xOffset = 0; yOffset = 0; break; case "WEST": xOffset = 0; yOffset = 0; break; case "EAST": xOffset = 0; yOffset = +15; break; } g.drawImage(bufferedImageMap.get(n.orientation + "_" + n.ai), n.xPos - xOffset, n.yPos - yOffset, 23, 40, this); } else if (n.ai.equals("CASTLEGUARD")) { int xOffset = 0; int yOffset = 0; switch (n.orientation) { case "NORTH": xOffset = 0; yOffset = 0; break; case "SOUTH": xOffset = 0; yOffset = 0; break; case "WEST": xOffset = 0; yOffset = 0; break; case "EAST": xOffset = 0; yOffset = +15; break; } g.drawImage(bufferedImageMap.get(n.orientation + "_" + n.ai), n.xPos - xOffset, n.yPos - yOffset, 23, 40, this); } else if (n.ai.equals("CHEF")) { int xOffset = 0; int yOffset = 0; switch (n.orientation) { case "NORTH": xOffset = 0; yOffset = 0; break; case "SOUTH": xOffset = 0; yOffset = 0; break; case "WEST": xOffset = 0; yOffset = 0; break; case "EAST": xOffset = 0; yOffset = 25; break; } g.drawImage(bufferedImageMap.get(n.orientation + "_" + n.ai), n.xPos - xOffset, n.yPos - yOffset, this); } } private void paintPlayer(Graphics g, int magnitude) { assert bufferedImageMap != null : "ERROR: bufferedImageMap is null"; // paintOrientationArrow(g); switch (player1.orientation) { // DRAWS A NAKED PLAYER CHARACTER case "NORTH": paintShield(g, magnitude); paintWeapon(g, magnitude); g.drawImage(bufferedImageMap.get("NORTH_PLAYER"), player1.xPos - 4, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); paintArmor(g, magnitude); paintLegs(g, magnitude); break; case "SOUTH": g.drawImage(bufferedImageMap.get("SOUTH_PLAYER"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); paintArmor(g, magnitude); paintLegs(g, magnitude); paintShield(g, magnitude); paintWeapon(g, magnitude); break; case "EAST": paintShield(g, magnitude); g.drawImage(bufferedImageMap.get("EAST_PLAYER"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); paintArmor(g, magnitude); paintLegs(g, magnitude); paintWeapon(g, magnitude); break; case "WEST": paintWeapon(g, magnitude); g.drawImage(bufferedImageMap.get("WEST_PLAYER"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); paintArmor(g, magnitude); paintLegs(g, magnitude); paintShield(g, magnitude); break; default: g.setColor(player1.pallete); g.fillOval(player1.xPos, player1.yPos, 20, 20); break; } } private void paintLegs(Graphics g, int magnitude) { if (magnitude == 1) { switch (player1.orientation) { // SOUTH-FACING RENDERING UNIT case "SOUTH": { switch (player1.gearInterface.itemArray[2].ID) { // SOUTH-FACING PANTS RENDERING UNIT case 7: g.drawImage(bufferedImageMap.get("RATSKIN_PANTS_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; case 14: g.drawImage(bufferedImageMap.get("BLUE_LEGGUARDS_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; case 21: g.drawImage(bufferedImageMap.get("GREEN_LEGGUARDS_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; case 22: g.drawImage(bufferedImageMap.get("GREEN_LEGGUARDS_TRIMMED_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; case 27: g.drawImage(bufferedImageMap.get("JUNKSCRAP_LEGGUARDS_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 19, this); break; case 28: g.drawImage(bufferedImageMap.get("JUNKSCRAP_LEGGUARDS_TRIMMED_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 19, this); break; } break; } case "EAST": { switch (player1.gearInterface.itemArray[2].ID) { // EAST-FACING ARMOR RENDERING UNIT case 7: g.drawImage(bufferedImageMap.get("RATSKIN_PANTS_PLAYERMODEL_EAST"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; case 14: g.drawImage(bufferedImageMap.get("BLUE_LEGGUARDS_PLAYERMODEL_EAST"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; case 21: g.drawImage(bufferedImageMap.get("GREEN_LEGGUARDS_PLAYERMODEL_EAST"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; case 22: g.drawImage(bufferedImageMap.get("GREEN_LEGGUARDS_TRIMMED_PLAYERMODEL_EAST"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; case 27: g.drawImage(bufferedImageMap.get("JUNKSCRAP_LEGGUARDS_PLAYERMODEL_EAST"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; case 28: g.drawImage(bufferedImageMap.get("JUNKSCRAP_LEGGUARDS_TRIMMED_PLAYERMODEL_EAST"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; } break; } case "NORTH": { switch (player1.gearInterface.itemArray[2].ID) { // EAST-FACING ARMOR RENDERING UNIT case 7: g.drawImage(bufferedImageMap.get("RATSKIN_PANTS_PLAYERMODEL_NORTH"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; case 14: g.drawImage(bufferedImageMap.get("BLUE_LEGGUARDS_PLAYERMODEL_NORTH"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; case 21: g.drawImage(bufferedImageMap.get("GREEN_LEGGUARDS_PLAYERMODEL_NORTH"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; case 22: g.drawImage(bufferedImageMap.get("GREEN_LEGGUARDS_TRIMMED_PLAYERMODEL_NORTH"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; case 27: g.drawImage(bufferedImageMap.get("JUNKSCRAP_LEGGUARDS_PLAYERMODEL_NORTH"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; case 28: g.drawImage(bufferedImageMap.get("JUNKSCRAP_LEGGUARDS_TRIMMED_PLAYERMODEL_NORTH"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; } break; } case "WEST": { switch (player1.gearInterface.itemArray[2].ID) { // EAST-FACING ARMOR RENDERING UNIT case 7: g.drawImage(bufferedImageMap.get("RATSKIN_PANTS_PLAYERMODEL_WEST"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; case 14: g.drawImage(bufferedImageMap.get("BLUE_LEGGUARDS_PLAYERMODEL_WEST"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; case 21: g.drawImage(bufferedImageMap.get("GREEN_LEGGUARDS_PLAYERMODEL_WEST"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; case 22: g.drawImage(bufferedImageMap.get("GREEN_LEGGUARDS_TRIMMED_PLAYERMODEL_WEST"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; case 27: g.drawImage(bufferedImageMap.get("JUNKSCRAP_LEGGUARDS_PLAYERMODEL_WEST"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; case 28: g.drawImage(bufferedImageMap.get("JUNKSCRAP_LEGGUARDS_TRIMMED_PLAYERMODEL_WEST"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; } } break; } } if (magnitude == 5) { switch (player1.orientation) { // SOUTH-FACING RENDERING UNIT case "SOUTH": { switch (player1.gearInterface.itemArray[2].ID) { // SOUTH-FACING PANTS RENDERING UNIT case 7: g.drawImage(bufferedImageMap.get("RATSKIN_PANTS_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 19, 25 * magnitude, 40 * magnitude, this); break; case 14: g.drawImage(bufferedImageMap.get("BLUE_LEGGUARDS_PLAYERMODEL_SOUTH"), player1.xPos - 4, player1.yPos - 12, 25 * magnitude, 40 * magnitude, this); break; case 21: g.drawImage(bufferedImageMap.get("GREEN_LEGGUARDS_PLAYERMODEL_SOUTH"), player1.xPos - 4, player1.yPos - 12, 25 * magnitude, 40 * magnitude, this); break; case 22: g.drawImage(bufferedImageMap.get("GREEN_LEGGUARDS_TRIMMED_PLAYERMODEL_SOUTH"), player1.xPos - 4, player1.yPos - 12, 25 * magnitude, 40 * magnitude, this); break; case 27: // *jt Todo: ASSET IS MISSING A (MODEL/FILE) // g.drawImage(bufferedImageMap.get("JUNKSCRAP_LEGGUARDS_PLAYERMODEL_SOUTH"), player1.xPos - 5, player1.yPos - 20, this); break; case 28: // *jt Todo: ASSET IS MISSING A (MODEL/FILE) // g.drawImage(bufferedImageMap.get("JUNKSCRAP_LEGGUARDS_TRIMMED_PLAYERMODEL_SOUTH"), player1.xPos -5, player1.yPos -20, this); break; } break; } case "EAST": { switch (player1.gearInterface.itemArray[2].ID) { // EAST-FACING ARMOR RENDERING UNIT case 10: break; } break; } case "NORTH": { switch (player1.gearInterface.itemArray[2].ID) { // EAST-FACING ARMOR RENDERING UNIT case 10: break; } break; } case "WEST": { switch (player1.gearInterface.itemArray[2].ID) { // EAST-FACING ARMOR RENDERING UNIT case 10: break; } } break; } } } private void paintArmor(Graphics g, int magnitude) { if (magnitude == 1) { switch (player1.orientation) { // SOUTH-FACING RENDERING UNIT case "SOUTH": { switch (player1.gearInterface.itemArray[1].ID) { // SOUTH-FACING ARMOR RENDERING UNIT case 6: g.drawImage(bufferedImageMap.get("RAGGED_SHIRT_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 24: g.drawImage(bufferedImageMap.get("GREEN_PLATEBODY_TRIMMED_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 17: g.drawImage(bufferedImageMap.get("BLUE_PLATEBODY_TRIMMED_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 30: g.drawImage(bufferedImageMap.get("BROWN_PLATEBODY_TRIMMED_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 23: g.drawImage(bufferedImageMap.get("GREEN_PLATEBODY_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 16: g.drawImage(bufferedImageMap.get("BLUE_PLATEBODY_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 29: g.drawImage(bufferedImageMap.get("BROWN_PLATEBODY_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; } break; } case "EAST": { switch (player1.gearInterface.itemArray[1].ID) { // EAST-FACING ARMOR RENDERING UNIT case 6: g.drawImage(bufferedImageMap.get("RAGGED_SHIRT_PLAYERMODEL_EAST"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 24: g.drawImage(bufferedImageMap.get("GREEN_PLATEBODY_TRIMMED_PLAYERMODEL_EAST"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 17: g.drawImage(bufferedImageMap.get("BLUE_PLATEBODY_TRIMMED_PLAYERMODEL_EAST"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 30: g.drawImage(bufferedImageMap.get("BROWN_PLATEBODY_TRIMMED_PLAYERMODEL_EAST"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 23: g.drawImage(bufferedImageMap.get("GREEN_PLATEBODY_PLAYERMODEL_EAST"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 16: g.drawImage(bufferedImageMap.get("BLUE_PLATEBODY_PLAYERMODEL_EAST"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 29: g.drawImage(bufferedImageMap.get("BROWN_PLATEBODY_PLAYERMODEL_EAST"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; } break; } case "NORTH": { switch (player1.gearInterface.itemArray[1].ID) { // NORTH-FACING ARMOR RENDERING UNIT case 6: g.drawImage(bufferedImageMap.get("RAGGED_SHIRT_PLAYERMODEL_NORTH"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 24: g.drawImage(bufferedImageMap.get("GREEN_PLATEBODY_TRIMMED_PLAYERMODEL_NORTH"), player1.xPos - 4, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 17: g.drawImage(bufferedImageMap.get("BLUE_PLATEBODY_TRIMMED_PLAYERMODEL_NORTH"), player1.xPos - 4, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 30: g.drawImage(bufferedImageMap.get("BROWN_PLATEBODY_TRIMMED_PLAYERMODEL_NORTH"), player1.xPos - 4, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 23: g.drawImage(bufferedImageMap.get("GREEN_PLATEBODY_PLAYERMODEL_NORTH"), player1.xPos - 4, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 16: g.drawImage(bufferedImageMap.get("BLUE_PLATEBODY_PLAYERMODEL_NORTH"), player1.xPos - 4, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 29: g.drawImage(bufferedImageMap.get("BROWN_PLATEBODY_PLAYERMODEL_NORTH"), player1.xPos - 4, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; } break; } case "WEST": { switch (player1.gearInterface.itemArray[1].ID) { // WEST-FACING ARMOR RENDERING UNIT case 6: g.drawImage(bufferedImageMap.get("RAGGED_SHIRT_PLAYERMODEL_WEST"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 24: g.drawImage(bufferedImageMap.get("GREEN_PLATEBODY_TRIMMED_PLAYERMODEL_WEST"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 17: g.drawImage(bufferedImageMap.get("BLUE_PLATEBODY_TRIMMED_PLAYERMODEL_WEST"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 30: g.drawImage(bufferedImageMap.get("BROWN_PLATEBODY_TRIMMED_PLAYERMODEL_WEST"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 23: g.drawImage(bufferedImageMap.get("GREEN_PLATEBODY_PLAYERMODEL_WEST"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 16: g.drawImage(bufferedImageMap.get("BLUE_PLATEBODY_PLAYERMODEL_WEST"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 29: g.drawImage(bufferedImageMap.get("BROWN_PLATEBODY_PLAYERMODEL_WEST"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; } } break; } } if (magnitude == 5) { switch (player1.orientation) { // SOUTH-FACING RENDERING UNIT case "SOUTH": { switch (player1.gearInterface.itemArray[1].ID) { // SOUTH-FACING SHIELD RENDERING UNIT case 6: g.drawImage(bufferedImageMap.get("RAGGED_SHIRT_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 24: g.drawImage(bufferedImageMap.get("GREEN_PLATEBODY_TRIMMED_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 17: g.drawImage(bufferedImageMap.get("BLUE_PLATEBODY_TRIMMED_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 30: g.drawImage(bufferedImageMap.get("BROWN_PLATEBODY_TRIMMED_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 23: g.drawImage(bufferedImageMap.get("GREEN_PLATEBODY_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 16: g.drawImage(bufferedImageMap.get("BLUE_PLATEBODY_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; case 29: g.drawImage(bufferedImageMap.get("BROWN_PLATEBODY_PLAYERMODEL_SOUTH"), player1.xPos - 3, player1.yPos - 20, 25 * magnitude, 40 * magnitude, this); break; } break; } } } } private void paintWeapon(Graphics g, int magnitude) { if (magnitude == 1) { switch (player1.orientation) { // SOUTH-FACING RENDERING UNIT case "SOUTH": { switch (player1.gearInterface.itemArray[5].ID) { // SOUTH-FACING WEAPON RENDERING UNIT case 9: g.drawImage(bufferedImageMap.get("WOODEN_CLUB_W"), player1.xPos - 15, player1.yPos - 13, 25 * magnitude, 25 * magnitude, this); break; case 13: g.drawImage(bufferedImageMap.get("BLUE_DAGGER_WEST"), player1.xPos - 15, player1.yPos - 13, 25 * magnitude, 25 * magnitude, this); break; case 20: g.drawImage(bufferedImageMap.get("GREEN_DAGGER_WEST"), player1.xPos - 15, player1.yPos - 13, 25 * magnitude, 25 * magnitude, this); break; case 31: g.drawImage(bufferedImageMap.get("RED_DAGGER_WEST"), player1.xPos - 15, player1.yPos - 13, 25 * magnitude, 25 * magnitude, this); break; case 32: g.drawImage(bufferedImageMap.get("LUMBERJACK_AXE_WEST"), player1.xPos - 15, player1.yPos - 13, 25 * magnitude, 25 * magnitude, this); break; } break; } case "EAST": { switch (player1.gearInterface.itemArray[5].ID) { // EAST-FACING WEAPON RENDERING UNIT case 9: g.drawImage(bufferedImageMap.get("WOODEN_CLUB_E"), player1.xPos + 5, player1.yPos - 15, 25 * magnitude, 25 * magnitude, this); break; case 13: g.drawImage(bufferedImageMap.get("BLUE_DAGGER_EAST"), player1.xPos + 5, player1.yPos - 15, 25 * magnitude, 25 * magnitude, this); break; case 20: g.drawImage(bufferedImageMap.get("GREEN_DAGGER_EAST"), player1.xPos + 5, player1.yPos - 15, 25 * magnitude, 25 * magnitude, this); break; case 31: g.drawImage(bufferedImageMap.get("RED_DAGGER_EAST"), player1.xPos + 5, player1.yPos - 15, 25 * magnitude, 25 * magnitude, this); break; case 32: g.drawImage(bufferedImageMap.get("LUMBERJACK_AXE_EAST"), player1.xPos + 5, player1.yPos - 15, 25 * magnitude, 25 * magnitude, this); break; } break; } case "NORTH": { switch (player1.gearInterface.itemArray[5].ID) { // NORTH-FACING WEAPON RENDERING UNIT case 9: g.drawImage(bufferedImageMap.get("WOODEN_CLUB_W"), player1.xPos - 17, player1.yPos - 12, 25 * magnitude, 25 * magnitude, this); break; case 13: g.drawImage(bufferedImageMap.get("BLUE_DAGGER_WEST"), player1.xPos - 17, player1.yPos - 12, 25 * magnitude, 25 * magnitude, this); break; case 20: g.drawImage(bufferedImageMap.get("GREEN_DAGGER_WEST"), player1.xPos - 17, player1.yPos - 12, 25 * magnitude, 25 * magnitude, this); break; case 31: g.drawImage(bufferedImageMap.get("RED_DAGGER_WEST"), player1.xPos - 17, player1.yPos - 12, 25 * magnitude, 25 * magnitude, this); break; case 32: g.drawImage(bufferedImageMap.get("LUMBERJACK_AXE_WEST"), player1.xPos - 17, player1.yPos - 12, 25 * magnitude, 25 * magnitude, this); break; } break; } case "WEST": { switch (player1.gearInterface.itemArray[5].ID) { // EAST-FACING WEAPON RENDERING UNIT case 9: g.drawImage(bufferedImageMap.get("WOODEN_CLUB_W"), player1.xPos - 14, player1.yPos - 12, 25 * magnitude, 25 * magnitude, this); break; case 13: g.drawImage(bufferedImageMap.get("BLUE_DAGGER_WEST"), player1.xPos - 14, player1.yPos - 12, 25 * magnitude, 25 * magnitude, this); break; case 20: g.drawImage(bufferedImageMap.get("GREEN_DAGGER_WEST"), player1.xPos - 14, player1.yPos - 12, 25 * magnitude, 25 * magnitude, this); break; case 31: g.drawImage(bufferedImageMap.get("RED_DAGGER_WEST"), player1.xPos - 14, player1.yPos - 12, 25 * magnitude, 25 * magnitude, this); break; case 32: g.drawImage(bufferedImageMap.get("LUMBERJACK_AXE_WEST"), player1.xPos - 14, player1.yPos - 12, 25 * magnitude, 25 * magnitude, this); break; } } break; } } if (magnitude == 5) { switch (player1.orientation) { // SOUTH-FACING RENDERING UNIT case "SOUTH": { switch (player1.gearInterface.itemArray[5].ID) { // SOUTH-FACING WEAPON RENDERING UNIT case 9: g.drawImage(bufferedImageMap.get("WOODEN_CLUB_W"), player1.xPos - 70, player1.yPos - 5, 25 * magnitude, 25 * magnitude, this); break; case 13: g.drawImage(bufferedImageMap.get("BLUE_DAGGER_WEST"), player1.xPos - 70, player1.yPos - 5, 25 * magnitude, 25 * magnitude, this); break; case 20: g.drawImage(bufferedImageMap.get("GREEN_DAGGER_WEST"), player1.xPos - 70, player1.yPos - 5, 25 * magnitude, 25 * magnitude, this); break; case 31: g.drawImage(bufferedImageMap.get("RED_DAGGER_WEST"), player1.xPos - 70, player1.yPos - 5, 25 * magnitude, 25 * magnitude, this); break; case 32: g.drawImage(bufferedImageMap.get("LUMBERJACK_AXE_WEST"), player1.xPos - 70, player1.yPos - 5, 25 * magnitude, 25 * magnitude, this); break; } } break; } } } private void paintShield(Graphics g, int magnitude) { if (magnitude == 1) { switch (player1.orientation) { // SOUTH-FACING RENDERING UNIT case "SOUTH": { switch (player1.gearInterface.itemArray[4].ID) { // SOUTH-FACING SHIELD RENDERING UNIT case 10: g.drawImage(bufferedImageMap.get("WOODEN_SHIELD"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 11: g.drawImage(bufferedImageMap.get("BLUE_BUCKLER"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 12: g.drawImage(bufferedImageMap.get("BLUE_BUCKLER_TRIMMED"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 18: g.drawImage(bufferedImageMap.get("GREEN_BUCKLER"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 19: g.drawImage(bufferedImageMap.get("GREEN_BUCKLER_TRIMMED"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 25: g.drawImage(bufferedImageMap.get("JUNKSCRAP_BUCKLER"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 26: g.drawImage(bufferedImageMap.get("JUNKSCRAP_BUCKLER_TRIMMED"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; } } break; case "EAST": { if (player1.gearInterface.itemArray[4].ID != 0) { g.drawImage(bufferedImageMap.get("GENERIC_SHIELD_BACK"), player1.xPos - 1, player1.yPos - 12, 25 * magnitude, 25 * magnitude, this); } /* switch (player1.gearInterface.itemArray[4].ID) { // EAST-FACING SHIELD RENDERING UNIT case 10: g.drawImage(bufferedImageMap.get("WOODEN_SHIELD"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 11: g.drawImage(bufferedImageMap.get("BLUE_BUCKLER"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 12: g.drawImage(bufferedImageMap.get("BLUE_BUCKLER_TRIMMED"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 18: g.drawImage(bufferedImageMap.get("GREEN_BUCKLER"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 19: g.drawImage(bufferedImageMap.get("GREEN_BUCKLER_TRIMMED"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 25: g.drawImage(bufferedImageMap.get("JUNKSCRAP_BUCKLER"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 26: g.drawImage(bufferedImageMap.get("JUNKSCRAP_BUCKLER_TRIMMED"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; } */ } break; case "NORTH": { if (player1.gearInterface.itemArray[4].ID != 0) { g.drawImage(bufferedImageMap.get("GENERIC_SHIELD_BACK"), player1.xPos + 1, player1.yPos - 10, 25 * magnitude, 25 * magnitude, this); } /* switch (player1.gearInterface.itemArray[4].ID) { // EAST-FACING SHIELD RENDERING UNIT case 10: g.drawImage(bufferedImageMap.get("WOODEN_SHIELD"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 11: g.drawImage(bufferedImageMap.get("BLUE_BUCKLER"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 12: g.drawImage(bufferedImageMap.get("BLUE_BUCKLER_TRIMMED"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 18: g.drawImage(bufferedImageMap.get("GREEN_BUCKLER"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 19: g.drawImage(bufferedImageMap.get("GREEN_BUCKLER_TRIMMED"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 25: g.drawImage(bufferedImageMap.get("JUNKSCRAP_BUCKLER"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 26: g.drawImage(bufferedImageMap.get("JUNKSCRAP_BUCKLER_TRIMMED"), player1.xPos + 5, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; } */ } break; case "WEST": { switch (player1.gearInterface.itemArray[4].ID) { // EAST-FACING SHIELD RENDERING UNIT case 10: g.drawImage(bufferedImageMap.get("WOODEN_SHIELD"), player1.xPos - 2, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 11: g.drawImage(bufferedImageMap.get("BLUE_BUCKLER"), player1.xPos - 2, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 12: g.drawImage(bufferedImageMap.get("BLUE_BUCKLER_TRIMMED"), player1.xPos - 2, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 18: g.drawImage(bufferedImageMap.get("GREEN_BUCKLER"), player1.xPos - 2, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 19: g.drawImage(bufferedImageMap.get("GREEN_BUCKLER_TRIMMED"), player1.xPos - 2, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 25: g.drawImage(bufferedImageMap.get("JUNKSCRAP_BUCKLER"), player1.xPos - 2, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; case 26: g.drawImage(bufferedImageMap.get("JUNKSCRAP_BUCKLER_TRIMMED"), player1.xPos - 2, player1.yPos - 8, 25 * magnitude, 25 * magnitude, this); break; } } break; } } if (magnitude == 5) { switch (player1.orientation) { // SOUTH-FACING RENDERING UNIT case "SOUTH": { switch (player1.gearInterface.itemArray[4].ID) { // SOUTH-FACING SHIELD RENDERING UNIT case 10: g.drawImage(bufferedImageMap.get("WOODEN_SHIELD"), player1.xPos + 30, player1.yPos + 35, 25 * magnitude, 25 * magnitude, this); break; case 11: g.drawImage(bufferedImageMap.get("BLUE_BUCKLER"), player1.xPos + 30, player1.yPos + 35, 25 * magnitude, 25 * magnitude, this); break; case 12: g.drawImage(bufferedImageMap.get("BLUE_BUCKLER_TRIMMED"), player1.xPos + 30, player1.yPos + 35, 25 * magnitude, 25 * magnitude, this); break; case 18: g.drawImage(bufferedImageMap.get("GREEN_BUCKLER"), player1.xPos + 30, player1.yPos + 35, 25 * magnitude, 25 * magnitude, this); break; case 19: g.drawImage(bufferedImageMap.get("GREEN_BUCKLER_TRIMMED"), player1.xPos + 30, player1.yPos + 35, 25 * magnitude, 25 * magnitude, this); break; case 25: g.drawImage(bufferedImageMap.get("JUNKSCRAP_BUCKLER"), player1.xPos + 30, player1.yPos + 35, 25 * magnitude, 25 * magnitude, this); break; case 26: g.drawImage(bufferedImageMap.get("JUNKSCRAP_BUCKLER_TRIMMED"), player1.xPos + 30, player1.yPos + 35, 25 * magnitude, 25 * magnitude, this); break; } break; } } } } private void paintTileCoordinates(Graphics g) { g.setFont(font1_8); g.setColor(Color.black); for (int i = 0; i < 32; i++) { for (int j = 0; j < 24; j++) { g.drawString("" + i + ", " + j, i * 25 + 2, j * 25 + 13); } } } private void paintTileLines(Graphics g) { int counter = 0; int row = 0; for (int i = 0; i < 768; i++) { if (counter == 32) { row++; counter = 0; } g.setColor(Color.black); g.drawRect(counter * 25, row * 25, 25, 25); counter++; } } private void npcBehaviour() { int r; for (Npc n : currentOverWorld.npcList) { // iterater through current Overworld npc list. int counter; switch (n.ai) { // reads ai type from each Npc. case "SHEEP": // Sheep ai. moves every 5 actions. random walks through passable tiles. wont leave edge of map. counter = (actionTick % 5); if (counter == 0) { r = rotateRng(); if (r <= 25) { if (n.yPos / 25 != 22) { if (!currentOverWorld.tilemap[n.xPos / 25][n.yPos / 25 + 1].occupied) { n.yPos += movementSpeed; n.orientation = "SOUTH"; } } } else if (r > 25 && r < 50) { if (n.yPos / 25 != 1) { if (!currentOverWorld.tilemap[n.xPos / 25][n.yPos / 25 - 1].occupied) { n.yPos -= movementSpeed; n.orientation = "NORTH"; } } } else if (r > 50 && r < 75) { if (n.xPos / 25 != 31) { if (!currentOverWorld.tilemap[n.xPos / 25 + 1][n.yPos / 25].occupied) { n.xPos += movementSpeed; n.orientation = "EAST"; } } } else if (r >= 75) { if (n.xPos / 25 != 1) { if (!currentOverWorld.tilemap[n.xPos / 25 - 1][n.yPos / 25].occupied) { n.xPos -= movementSpeed; n.orientation = "WEST"; } } } } r = rotateRng(); if (r > 98 && currentOverWorld.tilemap[n.xPos / 25][n.yPos / 25].type.equals("grass")) { currentOverWorld.tilemap[n.xPos / 25][n.yPos / 25].type = "dirt"; currentOverWorld.tilemap[n.xPos / 25][n.yPos / 25].growth = 0; } break; case "CHASER": // Chaser ai. moves every 4 actions. compares own position to player's and attempt to equalize y and x coordinates. Won't leave map. counter = (actionTick % 4); if (counter == 0) { if (player1.yPos / 25 < n.yPos / 25) { if (n.yPos / 25 != 1) { if (!currentOverWorld.tilemap[n.xPos / 25][n.yPos / 25 - 1].occupied) { n.yPos -= movementSpeed; n.orientation = "NORTH"; } else if (n.yPos / 25 - 1 == player1.yPos / 25 && n.xPos / 25 == player1.xPos / 25) { n.orientation = "NORTH"; System.out.println("the chaser hits you for 10 damage"); player1.HP = player1.HP - 10; } else { n.orientation = "NORTH"; } } } else if (player1.yPos / 25 > n.yPos / 25) { if (n.yPos / 25 != 22) { if (!currentOverWorld.tilemap[n.xPos / 25][n.yPos / 25 + 1].occupied) { n.yPos += movementSpeed; n.orientation = "SOUTH"; } else if (n.yPos / 25 + 1 == player1.yPos / 25 && n.xPos / 25 == player1.xPos / 25) { n.orientation = "SOUTH"; System.out.println("the chaser hits you for 10 damage"); player1.HP = player1.HP - 10; } else { n.orientation = "SOUTH"; } } } if (player1.xPos / 25 < n.xPos / 25) { if (n.xPos / 25 != 1) { if (!currentOverWorld.tilemap[n.xPos / 25 - 1][n.yPos / 25].occupied) { n.xPos -= movementSpeed; n.orientation = "WEST"; } else if (n.xPos / 25 - 1 == player1.xPos / 25 && n.yPos / 25 == player1.yPos / 25) { n.orientation = "WEST"; System.out.println("the chaser hits you for 10 damage"); player1.HP = player1.HP - 10; } else { n.orientation = "WEST"; } } } else if (player1.xPos / 25 > n.xPos / 25) { if (n.xPos / 25 != 30) { if (!currentOverWorld.tilemap[n.xPos / 25 + 1][n.yPos / 25].occupied) { n.xPos += movementSpeed; n.orientation = "EAST"; } else if (n.xPos / 25 + 1 == player1.xPos / 25 && n.yPos / 25 == player1.yPos / 25) { n.orientation = "EAST"; System.out.println("the chaser hits you for 10 damage"); player1.HP = player1.HP - 10; } else { n.orientation = "EAST"; } } } } break; } collisionMeshGenerator(); // Re-generates collision mesh after each Npc takes action. } } private void mapChange(int direction) { // controls the change of map as player reaches map edge. if (direction == 0) { // 0=up. 1=right 2=down 3=left if (currentOverWorld.idY == worldSize - 1) // checks for top edge of Overworld. { if (!overWorld[currentOverWorld.idX][0].tilemap[player1.xPos / 25][22].occupied && !overWorld[currentOverWorld.idX][0].tilemap[player1.xPos / 25][23].occupied) { currentOverWorld.tilemap[player1.xPos / 25][player1.yPos / 25].occupied = false; currentOverWorld = overWorld[currentOverWorld.idX][0]; // load bottom edge of Overworld. ( world is currently round. ) player1.yPos = 22 * 25; // sets player y coordinate to bottom edge of tilemap } } else { if (!overWorld[currentOverWorld.idX][currentOverWorld.idY + 1].tilemap[player1.xPos / 25][22].occupied && !overWorld[currentOverWorld.idX][currentOverWorld.idY + 1].tilemap[player1.xPos / 25][23].occupied) { currentOverWorld.tilemap[player1.xPos / 25][player1.yPos / 25].occupied = false; player1.yPos = 22 * 25; currentOverWorld = overWorld[currentOverWorld.idX][currentOverWorld.idY + 1]; // Otherwise loads next Overworld up. } } } else if (direction == 1) { if (currentOverWorld.idX == worldSize - 1) // same concept for every direction. { if (!overWorld[0][currentOverWorld.idY].tilemap[1][player1.yPos / 25].occupied && !overWorld[0][currentOverWorld.idY].tilemap[0][player1.yPos / 25].occupied) { currentOverWorld.tilemap[player1.xPos / 25][player1.yPos / 25].occupied = false; currentOverWorld = overWorld[0][currentOverWorld.idY]; player1.xPos = 1 * 25; } } else { if (!overWorld[currentOverWorld.idX + 1][currentOverWorld.idY].tilemap[1][player1.yPos / 25].occupied && !overWorld[currentOverWorld.idX + 1][currentOverWorld.idY].tilemap[0][player1.yPos / 25].occupied) { currentOverWorld.tilemap[player1.xPos / 25][player1.yPos / 25].occupied = false; player1.xPos = 1 * 25; currentOverWorld = overWorld[currentOverWorld.idX + 1][currentOverWorld.idY]; } } } else if (direction == 2) { if (currentOverWorld.idY == 0) { if (!overWorld[currentOverWorld.idX][worldSize - 1].tilemap[player1.xPos / 25][1].occupied && !overWorld[currentOverWorld.idX][worldSize - 1].tilemap[player1.xPos / 25][0].occupied) { currentOverWorld.tilemap[player1.xPos / 25][player1.yPos / 25].occupied = false; player1.yPos = 1 * 25; currentOverWorld = overWorld[currentOverWorld.idX][worldSize - 1]; } } else { if (!overWorld[currentOverWorld.idX][currentOverWorld.idY - 1].tilemap[player1.xPos / 25][1].occupied && !overWorld[currentOverWorld.idX][currentOverWorld.idY - 1].tilemap[player1.xPos / 25][0].occupied) { currentOverWorld.tilemap[player1.xPos / 25][player1.yPos / 25].occupied = false; player1.yPos = 1 * 25; currentOverWorld = overWorld[currentOverWorld.idX][currentOverWorld.idY - 1]; } } } else if (direction == 3) { if (currentOverWorld.idX == 0) { if (!overWorld[worldSize - 1][currentOverWorld.idY].tilemap[30][player1.yPos / 25].occupied && !overWorld[worldSize - 1][currentOverWorld.idY].tilemap[31][player1.yPos / 25].occupied) { currentOverWorld.tilemap[player1.xPos / 25][player1.yPos / 25].occupied = false; currentOverWorld = overWorld[worldSize - 1][currentOverWorld.idY]; player1.xPos = 30 * 25; } } else { if (!overWorld[currentOverWorld.idX - 1][currentOverWorld.idY].tilemap[30][player1.yPos / 25].occupied && !overWorld[currentOverWorld.idX - 1][currentOverWorld.idY].tilemap[31][player1.yPos / 25].occupied) { currentOverWorld.tilemap[player1.xPos / 25][player1.yPos / 25].occupied = false; player1.xPos = 30 * 25; currentOverWorld = overWorld[currentOverWorld.idX - 1][currentOverWorld.idY]; } } } if (currentOverWorld.idX < 10 && currentOverWorld.idY < 10) { System.out.println("Overworld0" + currentOverWorld.idX + "0" + currentOverWorld.idY + " loaded"); } else if (currentOverWorld.idX < 10) { System.out.println("Overworld0" + currentOverWorld.idX + +currentOverWorld.idY + " loaded"); } else if (currentOverWorld.idY < 10) { System.out.println("Overworld" + currentOverWorld.idX + "0" + currentOverWorld.idY + " loaded"); } else { System.out.println("Overworld" + currentOverWorld.idX + +currentOverWorld.idY + " loaded"); } } private void tick() { actionTick++; // ticks action counter and runs any subroutines that should run for each tick. npcBehaviour(); naturalProcesses(); collisionMeshGenerator(); if (player1.HP < 0) { System.out.println("GAME OVER,!!!!!"); startMenuVisible = true; mapVisible = false; inventoryMenuVisible = false; debugMenuVisible = false; craftingMenuVisible = false; reset(); worldExists = false; } } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == timer && paint()) { this.repaint(); } if (engagedSuccessfully && e.getSource() == animationTimer0) { animation_frame++; if (animation_frame == 100) { animation_frame = 0; } } } private boolean checkForEndOfTurnTrigger() { if (TRIGGER_endOfCombat) { player1.xPos = storeXPos; player1.yPos = storeYPos; player1.orientation = storeOrientation; TRIGGER_endOfCombat = false; engagedSuccessfully = false; return true; } return false; } @Override public void keyTyped(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { switch (e.getKeyCode()) { // Keyboard switch -> e.getKeyCode() returns a virtual keyboard int value /* MOVEMENT AND ORIENTATION */ case KeyEvent.VK_H: break; case KeyEvent.VK_Q: if (player1.personalQuestLog.isEmpty()) { System.out.println("You have no quests"); } for (Quest q : player1.personalQuestLog) { System.out.println(q); } break; case KeyEvent.VK_CONTROL: controlPressed = true; break; case KeyEvent.VK_SHIFT: shiftPressed = true; break; case KeyEvent.VK_ALT: altPressed = true; break; case KeyEvent.VK_0: currentTile = null; if (worldExists) { if (startMenuVisible) { startMenuVisible = false; // this is how the menu hides other windows. if (!rainSoundLoaded && !woodsSoundLoaded) { loadRainSound(); loadWoodsSound(); } mapVisible = true; break; } else { startMenuVisible = true; mapVisible = false; inventoryMenuVisible = false; debugMenuVisible = false; craftingMenuVisible = false; break; } } else if (startMenuVisible) { fillWorld(); worldExists = true; startMenuVisible = false; // this is how the menu hides other windows. mapVisible = true; if (!rainSoundLoaded && !woodsSoundLoaded) { loadRainSound(); loadWoodsSound(); } break; } else { startMenuVisible = true; mapVisible = false; inventoryMenuVisible = false; debugMenuVisible = false; craftingMenuVisible = false; break; } case KeyEvent.VK_9: readWorld(1, 1); // loads world11. System.out.println(currentOverWorld.idX + currentOverWorld.idY); break; case KeyEvent.VK_C: craftingMenuVisible = !craftingMenuVisible; break; case KeyEvent.VK_UP: // User presses the up key if (!stuckInDialogue) { loadMovementSound(); if (mapVisible && !engagedSuccessfully) { player1.orientation = "NORTH"; // set the player1 orientation state to "NORTH" if (!currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25) - 1].occupied) { if (player1.yPos / 25 != 1) { player1.yPos -= movementSpeed; //update ypos currentOverWorld.tilemap[player1.xPos / 25][player1.yPos / 25].occupied = true; // set's player position to occupied. // ( needed for npc actions that might occur before a new collision mesh is generated) } else { mapChange(0); // edge detection and map scrolling. } } } } break; case KeyEvent.VK_DOWN: // Tries to move down if (!stuckInDialogue) { loadMovementSound(); if (mapVisible && !engagedSuccessfully) { player1.orientation = "SOUTH"; if (!currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25) + 1].occupied) { if (player1.yPos / 25 != 22) { player1.yPos += movementSpeed; //update ypos currentOverWorld.tilemap[player1.xPos / 25][player1.yPos / 25].occupied = true; } else { mapChange(2); // edge detection. } } } } break; case KeyEvent.VK_LEFT: // Tries to move left if (!stuckInDialogue) { loadMovementSound(); if (mapVisible && !engagedSuccessfully) { player1.orientation = "WEST"; if (!currentOverWorld.tilemap[player1.xPos / 25 - 1][(player1.yPos / 25)].occupied) { if (player1.xPos / 25 != 1) { player1.xPos -= movementSpeed; //update ypos currentOverWorld.tilemap[player1.xPos / 25][player1.yPos / 25].occupied = true; } else { mapChange(3); // edge detection. } } } } break; case KeyEvent.VK_RIGHT: // Tries to move right if (!stuckInDialogue) { loadMovementSound(); if (mapVisible && !engagedSuccessfully) { player1.orientation = "EAST"; if (!currentOverWorld.tilemap[player1.xPos / 25 + 1][(player1.yPos / 25)].occupied) { if (player1.xPos / 25 != 30) { player1.xPos += movementSpeed; //update ypos currentOverWorld.tilemap[player1.xPos / 25][player1.yPos / 25].occupied = true; } else { mapChange(1); } } } } break; case KeyEvent.VK_M: if (menuSoundLoaded && rainSoundLoaded && woodsSoundLoaded) { menuSound.stop(); rainSound.stop(); woodsSound.stop(); menuSoundLoaded = false; rainSoundLoaded = false; woodsSoundLoaded = false; } else { loadMenuSound(); loadWoodsSound(); loadRainSound(); } break; /* DEBUG MENU/INDICATORS OPEN/CLOSE Open all debug menus and indicators */ case KeyEvent.VK_X: // keyboard press X -> Shows debug menu if (!startMenuVisible) { debugMenuVisible = !debugMenuVisible; // reverse the debug menu boolean state System.out.println(printTileSet(currentOverWorld.tilemap)); } break; /* Player Actions */ /* Harvesting: Requirements -> 1. Player's inventory is not full 2. Player's orientation faces a harvestable tile/entity. 3. The tile harvested by the player is harvestable. Outcomes -> 1. (IFF Successful) The player receives an item to his inventory on his next free slot. -> "receives an item" means the ID state of the player's item inventory array changes from 0 ("empty") to another ID related to the harvested tile. 2. (IFF Successful) The tile harvested by the player can be modified (eg: if cut tree -> tile becomes grass) 3. (IFF Failure) The tile the player attempted to harvest remains unchanged. */ case KeyEvent.VK_1: // keyboard press 1 -> attempt to harvest block currentItem = null; if (!startMenuVisible) { System.out.println("1- Block Harvesting"); if (!player1.playerInventory.isFull()) { // Allows harvesting process to happen only if the inventory isnt full. boolean harvestedSuccessfully = false; // flag to determine real-time whether the key press triggers a successful harvest action String harvestedItem = ""; if (player1.gearInterface.itemArray[5].ID == 32 && player1.orientation.equals("EAST") && currentOverWorld.tilemap[player1.xPos / 25 + 1][(player1.yPos / 25)].type.equals("tree")) { currentOverWorld.tilemap[player1.xPos / 25 + 1][(player1.yPos / 25)].type = "grass"; harvestedItem = "lumber"; harvestedSuccessfully = true; } if (player1.orientation.equals("EAST") && currentOverWorld.tilemap[player1.xPos / 25 + 1][(player1.yPos / 25)].type.equals("stone")) { currentOverWorld.tilemap[player1.xPos / 25 + 1][(player1.yPos / 25)].type = "dirt"; harvestedItem = "cobblestone"; currentOverWorld.tilemap[player1.xPos / 25 + 1][(player1.yPos / 25)].farmable = true; harvestedSuccessfully = true; } if (player1.gearInterface.itemArray[5].ID == 32 && player1.orientation.equals("WEST") && currentOverWorld.tilemap[player1.xPos / 25 - 1][(player1.yPos / 25)].type.equals("tree")) { currentOverWorld.tilemap[player1.xPos / 25 - 1][(player1.yPos / 25)].type = "grass"; harvestedItem = "lumber"; harvestedSuccessfully = true; } if (player1.orientation.equals("WEST") && currentOverWorld.tilemap[player1.xPos / 25 - 1][(player1.yPos / 25)].type.equals("stone")) { currentOverWorld.tilemap[player1.xPos / 25 - 1][(player1.yPos / 25)].type = "dirt"; harvestedItem = "cobblestone"; currentOverWorld.tilemap[player1.xPos / 25 - 1][(player1.yPos / 25)].farmable = true; harvestedSuccessfully = true; } if (player1.gearInterface.itemArray[5].ID == 32 && player1.orientation.equals("NORTH") && currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 - 1)].type.equals("tree")) { currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 - 1)].type = "grass"; harvestedSuccessfully = true; harvestedItem = "lumber"; } if (player1.orientation.equals("NORTH") && currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 - 1)].type.equals("stone")) { currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 - 1)].type = "dirt"; currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 - 1)].farmable = true; harvestedSuccessfully = true; harvestedItem = "cobblestone"; } if (player1.gearInterface.itemArray[5].ID == 32 && player1.orientation.equals("SOUTH") && currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 + 1)].type.equals("tree")) { currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 + 1)].type = "grass"; harvestedItem = "lumber"; harvestedSuccessfully = true; } if (player1.orientation.equals("SOUTH") && currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 + 1)].type.equals("stone")) { currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 + 1)].type = "dirt"; harvestedItem = "cobblestone"; currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 + 1)].farmable = true; harvestedSuccessfully = true; } if (harvestedSuccessfully) { // Iff the tile is flagged to be successfully harvested, find an empty slot and fill it with a given item. for (int i = 0; i < 64; i++) { if (player1.playerInventory.itemArray[i].ID == 0) { if (harvestedItem.equals("lumber")) { loadChopSound(); player1.playerInventory.itemArray[i].ID = 1; break; } if (harvestedItem.equals("cobblestone")) { player1.playerInventory.itemArray[i].ID = 2; break; } } } tick(); } } break; } else if (startMenuVisible){ reloadOverWorld(); worldExists = true; } /* ITEM PLACEMENT */ case KeyEvent.VK_2: if (currentItem != null && currentItem.ID == 2) { if (player1.orientation.equals("NORTH") && !currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 - 1)].occupied) { currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 - 1)].type = "stone"; player1.playerInventory.itemArray[currentItemIndex].ID = 0; tick(); } else if (player1.orientation.equals("EAST") && !currentOverWorld.tilemap[player1.xPos / 25 + 1][(player1.yPos / 25)].occupied) { currentOverWorld.tilemap[player1.xPos / 25 + 1][(player1.yPos / 25)].type = "stone"; player1.playerInventory.itemArray[currentItemIndex].ID = 0; tick(); } if (player1.orientation.equals("SOUTH") && !currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 + 1)].occupied) { currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 + 1)].type = "stone"; player1.playerInventory.itemArray[currentItemIndex].ID = 0; tick(); } else if (player1.orientation.equals("WEST") && !currentOverWorld.tilemap[player1.xPos / 25 - 1][(player1.yPos / 25)].occupied) { currentOverWorld.tilemap[player1.xPos / 25 - 1][(player1.yPos / 25)].type = "stone"; player1.playerInventory.itemArray[currentItemIndex].ID = 0; tick(); } } else if (currentItem != null && currentItem.ID == 4) { if (player1.orientation.equals("NORTH") && !currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 - 1)].occupied) { currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 - 1)].type = "plankwall"; player1.playerInventory.itemArray[currentItemIndex].ID = 0; tick(); } else if (player1.orientation.equals("EAST") && !currentOverWorld.tilemap[player1.xPos / 25 + 1][(player1.yPos / 25)].occupied) { currentOverWorld.tilemap[player1.xPos / 25 + 1][(player1.yPos / 25)].type = "plankwall"; player1.playerInventory.itemArray[currentItemIndex].ID = 0; tick(); } if (player1.orientation.equals("SOUTH") && !currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 + 1)].occupied) { currentOverWorld.tilemap[player1.xPos / 25][(player1.yPos / 25 + 1)].type = "plankwall"; player1.playerInventory.itemArray[currentItemIndex].ID = 0; tick(); } else if (player1.orientation.equals("WEST") && !currentOverWorld.tilemap[player1.xPos / 25 - 1][(player1.yPos / 25)].occupied) { currentOverWorld.tilemap[player1.xPos / 25 - 1][(player1.yPos / 25)].type = "plankwall"; player1.playerInventory.itemArray[currentItemIndex].ID = 0; tick(); } } break; case KeyEvent.VK_R: raining = !raining; break; case KeyEvent.VK_K: rainVector = -rainVector; break; case KeyEvent.VK_F: System.out.println("F- fighting"); if (player1.orientation.equals("EAST")) { for (Npc n : currentOverWorld.npcList) { if (player1.xPos / 25 + 1 == n.xPos / 25 && player1.yPos / 25 == n.yPos / 25) { currentNpc = n; engagedSuccessfully = true; storeOrientation = player1.orientation; storeXPos = player1.xPos; // STORES WHERE THE COMBAT WAS INITIATED IN ORDER TO RETURN THE PLAYER TO THAT COORDINATE storeYPos = player1.yPos; // STORES WHERE THE COMBAT WAS INITIATED IN ORDER TO RETURN THE PLAYER TO THAT COORDINATE } } } if (player1.orientation.equals("WEST")) { for (Npc n : currentOverWorld.npcList) { if (player1.xPos / 25 - 1 == n.xPos / 25 && player1.yPos / 25 == n.yPos / 25) { currentNpc = n; engagedSuccessfully = true; storeOrientation = player1.orientation; storeXPos = player1.xPos; // STORES WHERE THE COMBAT WAS INITIATED IN ORDER TO RETURN THE PLAYER TO THAT COORDINATE storeYPos = player1.yPos; // STORES WHERE THE COMBAT WAS INITIATED IN ORDER TO RETURN THE PLAYER TO THAT COORDINATE } } } if (player1.orientation.equals("NORTH")) { for (Npc n : currentOverWorld.npcList) { if (player1.yPos / 25 - 1 == n.yPos / 25 && player1.xPos / 25 == n.xPos / 25) { currentNpc = n; engagedSuccessfully = true; storeOrientation = player1.orientation; storeXPos = player1.xPos; // STORES WHERE THE COMBAT WAS INITIATED IN ORDER TO RETURN THE PLAYER TO THAT COORDINATE storeYPos = player1.yPos; // STORES WHERE THE COMBAT WAS INITIATED IN ORDER TO RETURN THE PLAYER TO THAT COORDINATE } } } if (player1.orientation.equals("SOUTH")) { for (Npc n : currentOverWorld.npcList) { if (player1.yPos / 25 + 1 == n.yPos / 25 && player1.xPos / 25 == n.xPos / 25) { currentNpc = n; engagedSuccessfully = true; storeOrientation = player1.orientation; storeXPos = player1.xPos; // STORES WHERE THE COMBAT WAS INITIATED IN ORDER TO RETURN THE PLAYER TO THAT COORDINATE storeYPos = player1.yPos; // STORES WHERE THE COMBAT WAS INITIATED IN ORDER TO RETURN THE PLAYER TO THAT COORDINATE } } } System.out.println(engagedSuccessfully); if (engagedSuccessfully) { System.out.println("engaged"); currentNpc.HP -= 20; if (currentNpc.HP < 0) { TRIGGER_endOfCombat = true; currentNpc.HP = 100F; } break; } case KeyEvent.VK_I: currentTile = null; if (!startMenuVisible) { inventoryMenuVisible = !inventoryMenuVisible; System.out.println(player1.playerInventory); System.out.println("Inventory is full: " + player1.playerInventory.isFull()); break; } case KeyEvent.VK_V: if (!startMenuVisible) { viewMenuVisible = !viewMenuVisible; break; } case KeyEvent.VK_L: currentOverWorld.npcList = new Vector<>(); // overwrites current Overworld npclist with an empty one. break; case KeyEvent.VK_W: tick(); break; case KeyEvent.VK_3: String nameR; nameR = getUserInput(); readCustomWorld(nameR); break; case KeyEvent.VK_4: if (currentOverWorld.idX < 10 && currentOverWorld.idY < 10) { saveCustomWorld("WORLD0" + currentOverWorld.idX + "0" + currentOverWorld.idY); } else if (currentOverWorld.idX < 10) { saveCustomWorld("WORLD0" + currentOverWorld.idX + currentOverWorld.idY); } else if (currentOverWorld.idY < 10) { saveCustomWorld("WORLD" + currentOverWorld.idX + "0" + currentOverWorld.idY); } else { saveCustomWorld("WORLD" + currentOverWorld.idX + currentOverWorld.idY); } System.out.println(currentOverWorld.idX + " " + currentOverWorld.idY); break; case KeyEvent.VK_5: reloadOverWorld(); break; case KeyEvent.VK_6: currentOverWorld.npcList = new Vector<>(); dummyWorld(); break; case KeyEvent.VK_ESCAPE: currentItem = null; currentTile = null; currentTileX = 0; currentTileY = 0; break; case KeyEvent.VK_A: System.out.println("WELCOME TO THE DEBUG CONSOLE"); String inputString = JOptionPane.showInputDialog("Please input a command \n set id [mhand/ohand/chest/legs/head] [itemID] \n weather rain toggle \n weather rain setVector [x] \n add inv [itemId] "); if (inputString != null && inputString.length() > 7) { /* SET ID ARMOR */ if (inputString.substring(0, 7).equals("add inv")) { if (inputString.length() == 9) { for (int i = 0; i < 64; i++) { if (player1.playerInventory.itemArray[i].ID == 0) { player1.playerInventory.itemArray[i].ID = Integer.valueOf(inputString.substring(8, 9)); break; } } } else if (inputString.length() == 10) { for (int i = 0; i < 64; i++) { if (player1.playerInventory.itemArray[i].ID == 0) { player1.playerInventory.itemArray[i].ID = Integer.valueOf(inputString.substring(8, 10)); break; } } } } else if (inputString.substring(0, 12).equals("set id chest")) { if (inputString.length() < 15) { // case for if the user inputs a number less than 2 digits player1.gearInterface.itemArray[1].ID = Integer.valueOf(inputString.substring(13, 14)); } else if (inputString.length() < 16) { // case for if the user inputs a number less than 3 digits player1.gearInterface.itemArray[1].ID = Integer.valueOf(inputString.substring(13, 15)); } /* SET ID LEGS */ } else if (inputString.substring(0, 11).equals("set id legs")) { if (inputString.length() < 14) { // case for if the user inputs a number less than 2 digits player1.gearInterface.itemArray[2].ID = Integer.valueOf(inputString.substring(12, 13)); } else if (inputString.length() < 15) { // case for if the user inputs a number less than 3 digits player1.gearInterface.itemArray[2].ID = Integer.valueOf(inputString.substring(12, 14)); } /* SET ID OFFHAND */ } else if (inputString.substring(0, 12).equals("set id ohand")) { System.out.println(player1.gearInterface.itemArray[4].ID); if (inputString.length() < 15) { // case for if the user inputs a number less than 2 digits player1.gearInterface.itemArray[4].ID = Integer.valueOf(inputString.substring(13, 14)); } else if (inputString.length() < 16) { // case for if the user inputs a number less than 3 digits player1.gearInterface.itemArray[4].ID = Integer.valueOf(inputString.substring(13, 15)); } } /* SET ID MAINHAND */ else if (inputString.substring(0, 12).equals("set id mhand")) { System.out.println("EDIT MHAND"); System.out.println(player1.gearInterface.itemArray[5].ID); if (inputString.length() < 15) { // case for if the user inputs a number less than 2 digits player1.gearInterface.itemArray[5].ID = Integer.valueOf(inputString.substring(13, 14)); } else if (inputString.length() < 16) { // case for if the user inputs a number less than 3 digits player1.gearInterface.itemArray[5].ID = Integer.valueOf(inputString.substring(13, 15)); } System.out.println(player1.gearInterface.itemArray[4].ID); /* WEATHER RAIN TOGGLE */ } else if (Objects.equals(inputString, "weather rain toggle")) { raining = !raining; /* WEATHER RAIN SET VECTOR */ } else if (inputString.length() > 22 && inputString.substring(0, 22).equals("weather rain setVector")) { if (inputString.length() < 25) { rainVector = Integer.valueOf(inputString.substring(23, 24)); } else if (inputString.length() < 26) { rainVector = Integer.valueOf(inputString.substring(23, 25)); } } } } if (!stuckInDialogue && (e.getKeyCode() == KeyEvent.VK_UP || e.getKeyCode() == KeyEvent.VK_DOWN || e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_RIGHT)) { if (mapVisible) { tick(); } } } private void loadMovementSound() { File Step1 = new File("Data/Sound/Step1.wav"); File Step2 = new File("Data/Sound/Step2.wav"); File Step3 = new File("Data/Sound/Step3.wav"); File Step4 = new File("Data/Sound/Step4.wav"); int stepCounter = rotateRng() % 3; try { if (stepCounter == 0) { audioInputStream = AudioSystem.getAudioInputStream(Step1); } else if (stepCounter == 1) { audioInputStream = AudioSystem.getAudioInputStream(Step2); } else if (stepCounter == 2) { audioInputStream = AudioSystem.getAudioInputStream(Step3); } } catch (UnsupportedAudioFileException | IOException e) { e.printStackTrace(); } try { movementSound = AudioSystem.getClip(); movementSound.open(audioInputStream); movementSound.start(); } catch (LineUnavailableException | IOException e) { e.printStackTrace(); } } private void loadChopSound() { File woodChoop = new File("Data/Sound/WoodChop.wav"); try { audioInputStream = AudioSystem.getAudioInputStream(woodChoop); } catch (UnsupportedAudioFileException | IOException e) { e.printStackTrace(); } try { Clip woodsSound = AudioSystem.getClip(); woodsSound.open(audioInputStream); woodsSound.start(); } catch (LineUnavailableException | IOException e) { e.printStackTrace(); } } @Override public void keyReleased(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_SHIFT: shiftPressed = false; break; case KeyEvent.VK_CONTROL: controlPressed = false; break; case KeyEvent.VK_ALT: altPressed = false; break; } } @Override public void mouseClicked(MouseEvent e) { requestFocusInWindow(); int x = e.getX(); int y = e.getY(); System.out.println("==CLICK=="); System.out.println(x + ", " + y); System.out.println("" + (x / 25) + ", " + (y / 25)); System.out.println("========="); if (e.getButton() == MouseEvent.BUTTON3) { // ON LEFT MOUSE CLICK if (inventoryMenuVisible) { onMouseClickEquipItems(x, y); } currentItem = null; currentItemIndex = 0; currentItemColumn = 0; currentItemRow = 0; } else if (e.getButton() == MouseEvent.BUTTON1) { // ON RIGHT MOUSE CLICK if (craftingMenuVisible) { putCurrentItemIntoCraftingInterface(x, y); } if (inventoryMenuVisible) { currentItem = onMouseClickSelectItem(x, y); } if (debugMenuVisible && x > 81 && x < 107 && y > 23 && y < 50) { rotateTileBrush(true); } if (debugMenuVisible && x > 81 && x < 107 && y > 55 && y < 81) { rotateTileBrush(false); } if (debugMenuVisible && x > 196 && x < 228 && y > 23 && y < 50) { rotateNpcBrush(true); } if (debugMenuVisible && x > 196 && x < 228 && y > 55 && y < 81) { rotateNpcBrush(false); } if (shiftPressed && controlPressed) { currentTileX = x / 25; currentTileY = y / 25; currentOverWorld.tilemap[currentTileX][currentTileY].type = tileBrush; } if (shiftPressed && altPressed) { currentTileX = x / 25; currentTileY = y / 25; generateNpc(currentOverWorld.npcList.size() + 1, currentTileX, currentTileY, 50, Color.black, npcBrush.toUpperCase()); } if (inventoryMenuVisible && x > 151 && x < 151 +59 && y > 233 && y < 233 + 15) { // Todo: adjust range of clicking to craft INTERACTS WITH BUTTON -> g.fillRect(151, 233, 59, 15); // "CRAFT BUTTON" craftItem(); } if (inventoryMenuVisible && x > 151 && x < 151 + 71 && y > 253 && y < 253 + 15) { // Todo: adjust range of clicking to return INTERACTS WITH BUTTON -> g.fillRect(151,253,71,15); // "RETURN" BUTTON returnAllItemsFromCraftingInterface(); } } if (!inventoryMenuVisible && !debugMenuVisible && !startMenuVisible) { currentTile = onMouseClickSelectTile(x, y); onMouseClickOpenDoor(x, y); } onMouseClickInteractWithNpc(x, y); if (attackStyleChooserVisible) { onMouseClickAddAbility(x, y); } if (stuckInDialogue && mousedOverDialogue != 0) { changeDialogueState(); } /* QUICKSLOT GUI INTERFACE */ if (x > 730 && x < 773 && y > 26 && y < 62) { inventoryMenuVisible = !inventoryMenuVisible; } else if (x > 678 && x < 728 && y > 26 && y < 62) { craftingMenuVisible = !craftingMenuVisible; } else if (x > 626 && x < 666 && y > 26 && y < 62) { attackStyleChooserVisible = !attackStyleChooserVisible; } } private void returnAllItemsFromCraftingInterface() { for(int i = 0 ; i < player1.playerCrafter.itemArray.length-1; i++){ player1.playerInventory.addItem(player1.playerCrafter.itemArray[i].ID); } player1.playerCrafter = new CraftingInterface(10); } private void craftItem() { for (int i = 0; i < 64; i++) { if (player1.playerInventory.itemArray[i].ID == 0) { player1.playerInventory.itemArray[i].ID = player1.playerCrafter.itemArray[9].ID; break; } } player1.playerCrafter = new CraftingInterface(10); } private void changeDialogueState() { if (currentDialogueNpc.ai.equals("LUMBERJACK")) { switch (TRIGGER_dialogueState) { case 0: switch (mousedOverDialogue) { case 1: TRIGGER_dialogueState = 1; break; case 2: exitDialogue(); break; case 3: break; } break; case 1: switch (mousedOverDialogue) { case 1: TRIGGER_dialogueState = 2; break; case 2: exitDialogue(); break; case 3: exitDialogue(); break; } break; case 2: switch (mousedOverDialogue) { case 1: boolean hasQuest = false; for (Quest q : player1.personalQuestLog) { if (q.questID == 0) { hasQuest = true; } } if (!hasQuest) { player1.personalQuestLog.add(new Quest(0, "Gathering Wood", "NPC wants you to gather 10 wood for him so he can build a new house", "Gather 10 Wood for NPC", new Item[]{new Item(1), new Item(1), new Item(1), new Item(1), new Item(1), new Item(1), new Item(1), new Item(1), new Item(1), new Item(1)}, new ArrayList<Integer>())); } exitDialogue(); break; case 2: exitDialogue(); break; case 3: exitDialogue(); break; } break; case 3: switch (mousedOverDialogue) { case 1: exitDialogue(); break; case 2: if (player1.playerInventory.hasItem(1, 10)) { player1.playerInventory.removeItem(1, 10); for (int i = 0; i < player1.personalQuestLog.size(); i++) { if (player1.personalQuestLog.get(i).questID == 0) { player1.personalQuestLog.remove(i); System.out.println("QUEST (id = 0) COMPLETE"); player1.personalQuestsCompleted.add(0); player1.gold += 3; TRIGGER_dialogueState = 4; } } } break; } break; case 4: switch (mousedOverDialogue) { case 1: exitDialogue(); break; case 2: exitDialogue(); break; } break; case 5: switch (mousedOverDialogue) { case 1: TRIGGER_dialogueState = 6; break; case 2: TRIGGER_dialogueState = 6; break; } break; case 6: switch (mousedOverDialogue) { case 1: TRIGGER_dialogueState = 7; break; case 2: exitDialogue(); break; case 3: exitDialogue(); break; } break; case 7: switch (mousedOverDialogue) { case 1: player1.personalQuestLog.add(new Quest(1, "Meet the castle", "Take the wood bundle to the castle doors", "Take the wood to the castle", new Item[1], new ArrayList<Integer>())); TRIGGER_dialogueState = 8; break; case 2: exitDialogue(); break; } break; case 8: switch (mousedOverDialogue) { case 1: exitDialogue(); break; } break; case 9: switch (mousedOverDialogue) { case 1: exitDialogue(); break; } break; } } else if (currentDialogueNpc.ai.equals("CASTLEGUARD")) { switch (TRIGGER_dialogueState) { case 0: switch (mousedOverDialogue) { case 1: exitDialogue(); break; } break; case 1: switch (mousedOverDialogue) { case 1: TRIGGER_dialogueState = 2; break; case 2: exitDialogue(); break; } break; case 2: switch (mousedOverDialogue) { case 1: for (int i = 0; i < player1.personalQuestLog.size(); i++) { if (player1.personalQuestLog.get(i).questID == 1) { player1.personalQuestLog.remove(i); System.out.println("QUEST (id = 1) COMPLETE"); player1.personalQuestsCompleted.add(1); player1.gold += 7; TRIGGER_dialogueState = 3; } } break; case 2: exitDialogue(); break; } break; case 3: switch (mousedOverDialogue) { case 1: exitDialogue(); break; } break; } } } private void exitDialogue() { stuckInDialogue = false; currentDialogueNpc = null; TRIGGER_dialogueState = 0; mousedOverDialogue = 0; npcDialogue = "npcdialogue"; playerResponse1 = "playerresponse1"; playerResponse2 = "playerresponse2"; playerResponse3 = "playerresponse3"; } private void onMouseClickInteractWithNpc(int x, int y) { for (Npc n : currentOverWorld.npcList) { if (n.ai.equals("LUMBERJACK") || n.ai.equals("CASTLEGUARD")) { if (((player1.xPos / 25) == (n.xPos / 25)) && (((player1.yPos / 25) == ((n.yPos / 25) - 1)) || ((player1.yPos / 25) == ((n.yPos / 25) + 1))) || ((player1.yPos / 25) == (n.yPos / 25)) && (((player1.xPos / 25) == ((n.xPos / 25) - 1)) || ((player1.xPos / 25) == ((n.xPos / 25) + 1)))) { if ((x / 25) == (n.xPos / 25) && (y / 25) == (n.yPos / 25)) { loadChopSound(); // Todo: Add an "interact with npc" soundclip. stuckInDialogue = true; currentDialogueNpc = n; } } } } } private void onMouseClickOpenDoor(int x, int y) { switch (currentOverWorld.tilemap[x / 25][y / 25].type) { case "woodfloordooreast": if (player1.yPos / 25 == y / 25) { if (player1.xPos / 25 == x / 25 + 1 || player1.xPos / 25 == x / 25 - 1) { currentOverWorld.tilemap[x / 25][y / 25].type = "openwoodfloordooreast"; } } tick(); break; case "woodfloordoorwest": if (player1.yPos / 25 == y / 25) { if (player1.xPos / 25 == x / 25 + 1 || player1.xPos / 25 == x / 25 - 1) { currentOverWorld.tilemap[x / 25][y / 25].type = "openwoodfloordoorwest"; } } tick(); break; case "woodfloordoornorth": if (player1.xPos / 25 == x / 25) { if (player1.yPos / 25 == y / 25 + 1 || player1.yPos / 25 == y / 25 - 1) { currentOverWorld.tilemap[x / 25][y / 25].type = "openwoodfloordoornorth"; } } tick(); break; case "woodfloordoorsouth": if (player1.xPos / 25 == x / 25) { if (player1.yPos / 25 == y / 25 + 1 || player1.yPos / 25 == y / 25 - 1) { currentOverWorld.tilemap[x / 25][y / 25].type = "openwoodfloordoorsouth"; } } tick(); break; case "openwoodfloordooreast": if (player1.yPos / 25 == y / 25) { if (player1.xPos / 25 == x / 25 + 1 || player1.xPos / 25 == x / 25 - 1) { currentOverWorld.tilemap[x / 25][y / 25].type = "woodfloordooreast"; } } tick(); break; case "openwoodfloordoorwest": if (player1.yPos / 25 == y / 25) { if (player1.xPos / 25 == x / 25 + 1 || player1.xPos / 25 == x / 25 - 1) { currentOverWorld.tilemap[x / 25][y / 25].type = "woodfloordoorwest"; } } tick(); break; case "openwoodfloordoornorth": if (player1.xPos / 25 == x / 25) { if (player1.yPos / 25 == y / 25 + 1 || player1.yPos / 25 == y / 25 - 1) { currentOverWorld.tilemap[x / 25][y / 25].type = "woodfloordoornorth"; } } tick(); break; case "openwoodfloordoorsouth": if (player1.xPos / 25 == x / 25) { if (player1.yPos / 25 == y / 25 + 1 || player1.yPos / 25 == y / 25 - 1) { currentOverWorld.tilemap[x / 25][y / 25].type = "woodfloordoorsouth"; } } tick(); break; } } private void onMouseClickEquipItems(int x, int y) { Item newItem = onMouseClickSelectItem(x, y); if (newItem != null) { // MAINHAND if ((newItem.ID == 9 || newItem.ID == 13 || newItem.ID == 20 || newItem.ID == 31 || newItem.ID == 32)) { Item oldItem = player1.gearInterface.itemArray[5]; if (equipItem(newItem)) { for (int i = 0; i < player1.playerInventory.itemArray.length; i++) { if (player1.playerInventory.itemArray[i].ID == newItem.ID) { player1.playerInventory.itemArray[i].ID = oldItem.ID; break; } } } } // CHEST ARMOR if ((newItem.ID == 6 || newItem.ID == 16 || newItem.ID == 17 || newItem.ID == 23 || newItem.ID == 24 || newItem.ID == 29 || newItem.ID == 30 )) { Item oldItem = player1.gearInterface.itemArray[1]; if (equipItem(newItem)) { for (int i = 0; i < player1.playerInventory.itemArray.length; i++) { if (player1.playerInventory.itemArray[i].ID == newItem.ID) { player1.playerInventory.itemArray[i].ID = oldItem.ID; break; } } } } // LEG ARMOR if ((newItem.ID == 7 || newItem.ID == 14 || newItem.ID == 15 || newItem.ID == 21 || newItem.ID == 22 || newItem.ID == 27 || newItem.ID == 28 )) { Item oldItem = player1.gearInterface.itemArray[2]; if (equipItem(newItem)) { for (int i = 0; i < player1.playerInventory.itemArray.length; i++) { if (player1.playerInventory.itemArray[i].ID == newItem.ID) { player1.playerInventory.itemArray[i].ID = oldItem.ID; break; } } } } // OFFHAND if ((newItem.ID == 10 || newItem.ID == 11 || newItem.ID == 12 || newItem.ID == 18 || newItem.ID == 19 || newItem.ID == 25 || newItem.ID == 26 )) { Item oldItem = player1.gearInterface.itemArray[4]; if (equipItem(newItem)) { for (int i = 0; i < player1.playerInventory.itemArray.length; i++) { if (player1.playerInventory.itemArray[i].ID == newItem.ID) { player1.playerInventory.itemArray[i].ID = oldItem.ID; break; } } } } } } private boolean equipItem(Item item) { // MAIN HAND WEAPONS if (item.ID == 13) { player1.gearInterface.itemArray[5] = new Item(13); return true; } else if (item.ID == 9) { player1.gearInterface.itemArray[5] = new Item(9); return true; } else if (item.ID == 20) { player1.gearInterface.itemArray[5] = new Item(20); return true; } else if (item.ID == 31) { player1.gearInterface.itemArray[5] = new Item(31); return true; } else if (item.ID == 32) { player1.gearInterface.itemArray[5] = new Item(32); return true; } // CHEST ARMOR else if (item.ID == 6) { player1.gearInterface.itemArray[1] = new Item(6); return true; } else if (item.ID == 16) { player1.gearInterface.itemArray[1] = new Item(16); return true; } else if (item.ID == 17) { player1.gearInterface.itemArray[1] = new Item(17); return true; } else if (item.ID == 23) { player1.gearInterface.itemArray[1] = new Item(23); return true; } else if (item.ID == 24) { player1.gearInterface.itemArray[1] = new Item(24); return true; } else if (item.ID == 29) { player1.gearInterface.itemArray[1] = new Item(29); return true; } else if (item.ID == 30) { player1.gearInterface.itemArray[1] = new Item(30); return true; } // LEG ARMOR else if (item.ID == 7) { player1.gearInterface.itemArray[2] = new Item(7); return true; } else if (item.ID == 14) { player1.gearInterface.itemArray[2] = new Item(14); return true; } else if (item.ID == 15) { player1.gearInterface.itemArray[2] = new Item(15); return true; } else if (item.ID == 21) { player1.gearInterface.itemArray[2] = new Item(21); return true; } else if (item.ID == 22) { player1.gearInterface.itemArray[2] = new Item(22); return true; } else if (item.ID == 27) { player1.gearInterface.itemArray[2] = new Item(27); return true; } else if (item.ID == 28) { player1.gearInterface.itemArray[2] = new Item(28); return true; } // OFF HAND else if (item.ID == 10) { player1.gearInterface.itemArray[4] = new Item(10); return true; } else if (item.ID == 11) { player1.gearInterface.itemArray[4] = new Item(11); return true; } else if (item.ID == 12) { player1.gearInterface.itemArray[4] = new Item(12); return true; } else if (item.ID == 18) { player1.gearInterface.itemArray[4] = new Item(18); return true; } else if (item.ID == 19) { player1.gearInterface.itemArray[4] = new Item(19); return true; } else if (item.ID == 25) { player1.gearInterface.itemArray[4] = new Item(25); return true; } else if (item.ID == 26) { player1.gearInterface.itemArray[4] = new Item(26); return true; } return false; } private void onMouseClickAddAbility(int x, int y) { int abilityIDToAdd = 0; if (x > 26 && x < 56 && y > 386 && y < 416) { abilityIDToAdd = 1; } else if (x > 56 && x < 86 && y > 386 && y < 416) { abilityIDToAdd = 2; } else if (x > 86 && x < 116 && y > 386 && y < 416) { abilityIDToAdd = 3; } else if (x > 116 && x < 146 && y > 386 && y < 416) { abilityIDToAdd = 0; } else if (x > 146 && x < 176 && y > 386 && y < 416) { abilityIDToAdd = 0; } else if (x > 176 && x < 206 && y > 386 && y < 416) { abilityIDToAdd = 0; } else if (x > 206 && x < 236 && y > 386 && y < 416) { abilityIDToAdd = 0; } else if (x > 236 && x < 266 && y > 386 && y < 416) { abilityIDToAdd = 0; } if (abilities[0] == 0) { abilities[0] = abilityIDToAdd; } else if (abilities[1] == 0) { abilities[1] = abilityIDToAdd; } else if (abilities[2] == 0) { abilities[2] = abilityIDToAdd; } System.out.println(abilities[0] + ", " + abilities[1] + ", " + abilities[2]); } private void indexTiles() { BrushTileList.add("SAND"); BrushTileList.add("GRASS"); BrushTileList.add("STONE"); BrushTileList.add("DIRT"); BrushTileList.add("PLANKWALL"); BrushTileList.add("RAKEDDIRT"); BrushTileList.add("WOODFLOOR"); BrushTileList.add("TREE"); BrushTileList.add("WATER"); BrushTileList.add("STONEPATHGRASS"); BrushTileList.add("WOODFLOORDOORNORTH"); BrushTileList.add("WOODFLOORDOOREAST"); BrushTileList.add("WOODFLOORDOORSOUTH"); BrushTileList.add("WOODFLOORDOORWEST"); BrushTileList.add("WOODENFENCEHORIZONTAL"); BrushTileList.add("WOODENFENCEVERTICAL"); BrushTileList.add("WOODENFENCENWCORNER"); BrushTileList.add("WOODENFENCENECORNER"); BrushTileList.add("WOODENFENCESECORNER"); BrushTileList.add("WOODENFENCESWCORNER"); tileBrushIndex = 0; } private void indexNpc() { brushNpcList.add("SHEEP"); brushNpcList.add("CHASER"); brushNpcList.add("LUMBERJACK"); brushNpcList.add("CASTLEGUARD"); npcBrushIndex = 0; } private void rotateTileBrush(Boolean up) { if (up) { if (tileBrushIndex == BrushTileList.size() - 1) { tileBrushIndex = 0; } else { tileBrushIndex++; } } else { if (tileBrushIndex == 0) { tileBrushIndex = BrushTileList.size() - 1; } else { tileBrushIndex } } tileBrush = BrushTileList.get(tileBrushIndex).toLowerCase(); } private void rotateNpcBrush(Boolean up) { if (up) { if (npcBrushIndex == brushNpcList.size() - 1) { npcBrushIndex = 0; } else { npcBrushIndex++; } } else { if (npcBrushIndex == 0) { npcBrushIndex = brushNpcList.size() - 1; } else { npcBrushIndex } } npcBrush = brushNpcList.get(npcBrushIndex).toLowerCase(); } private void putCurrentItemIntoCraftingInterface(int x, int y) { int craftingSlotIndex = -1; if (x > 34 && x < 34 + 30 && y > 149 && y < 149 + 30) { craftingSlotIndex = 0; } else if (x > 64 && x < 64 + 30 && y > 149 && y < 149 + 30) { craftingSlotIndex = 1; } else if (x > 94 && x < 94 + 30 && y > 149 && y < 149 + 30) { craftingSlotIndex = 2; } else if (x > 34 && x < 34 + 30 && y > 179 && y < 179 + 30) { craftingSlotIndex = 3; } else if (x > 64 && x < 64 + 30 && y > 179 && y < 179 + 30) { craftingSlotIndex = 4; } else if (x > 94 && x < 94 + 30 && y > 179 && y < 179 + 30) { craftingSlotIndex = 5; } else if (x > 34 && x < 34 + 30 && y > 209 && y < 209 + 30) { craftingSlotIndex = 6; } else if (x > 64 && x < 64 + 30 && y > 209 && y < 209 + 30) { craftingSlotIndex = 7; } else if (x > 94 && x < 94 + 30 && y > 209 && y < 209 + 30) { craftingSlotIndex = 8; } if (craftingSlotIndex != -1) { player1.playerCrafter.itemArray[craftingSlotIndex].ID = currentItem.ID; currentItem.ID = 0; currentItemIndex = 0; currentItemRow = 0; currentItemColumn = 0; } updateCrafterOutputSlot(); } private void updateCrafterOutputSlot() { // CRAFTING RECIPES if (player1.playerCrafter.itemArray[0].ID == 1 && // RECIPE FOR WOODEN WALL player1.playerCrafter.itemArray[1].ID == 1 && player1.playerCrafter.itemArray[2].ID == 1 && player1.playerCrafter.itemArray[3].ID == 0 && player1.playerCrafter.itemArray[4].ID == 0 && player1.playerCrafter.itemArray[5].ID == 0 && player1.playerCrafter.itemArray[6].ID == 0 && player1.playerCrafter.itemArray[7].ID == 0 && player1.playerCrafter.itemArray[8].ID == 0 ) { player1.playerCrafter.itemArray[9].ID = 4 ; } if (player1.playerCrafter.itemArray[0].ID == 0 && // RECIPE FOR WOODEN WALL player1.playerCrafter.itemArray[1].ID == 2 && player1.playerCrafter.itemArray[2].ID == 2 && player1.playerCrafter.itemArray[3].ID == 0 && player1.playerCrafter.itemArray[4].ID == 1 && player1.playerCrafter.itemArray[5].ID == 2 && player1.playerCrafter.itemArray[6].ID == 0 && player1.playerCrafter.itemArray[7].ID == 1 && player1.playerCrafter.itemArray[8].ID == 0 ) { player1.playerCrafter.itemArray[9].ID = 32 ; } else { player1.playerCrafter.itemArray[9].ID = 0; } } private Item onMouseClickSelectItem(int x, int y) { currentItem = null; currentItemIndex = -1; currentItemColumn = -1; currentItemRow = -1; if (inRange(x, 587, 617, true)) { currentItemColumn = 1; if (inRange(y, 176, 206, true)) { currentItemRow = 1; currentItemIndex = 0; } else if (inRange(y, 207, 237, true)) { currentItemRow = 2; currentItemIndex = 6; } else if (inRange(y, 238, 268, true)) { currentItemRow = 3; currentItemIndex = 12; } else if (inRange(y, 269, 299, true)) { currentItemRow = 4; currentItemIndex = 18; } else if (inRange(y, 300, 330, true)) { currentItemRow = 5; currentItemIndex = 24; } else if (inRange(y, 331, 361, true)) { currentItemRow = 6; currentItemIndex = 30; } else if (inRange(y, 362, 392, true)) { currentItemRow = 7; currentItemIndex = 36; } else if (inRange(y, 393, 423, true)) { currentItemRow = 8; currentItemIndex = 42; } else if (inRange(y, 424, 454, true)) { currentItemRow = 9; currentItemIndex = 48; } else if (inRange(y, 455, 485, true)) { currentItemRow = 10; currentItemIndex = 54; } else if (inRange(y, 486, 516, true)) { currentItemRow = 11; currentItemIndex = 60; } } else if (inRange(x, 618, 648, true)) { currentItemColumn = 2; if (inRange(y, 176, 206, true)) { currentItemRow = 1; currentItemIndex = 1; } else if (inRange(y, 207, 237, true)) { currentItemRow = 2; currentItemIndex = 7; } else if (inRange(y, 238, 268, true)) { currentItemRow = 3; currentItemIndex = 13; } else if (inRange(y, 269, 299, true)) { currentItemRow = 4; currentItemIndex = 19; } else if (inRange(y, 300, 330, true)) { currentItemRow = 5; currentItemIndex = 25; } else if (inRange(y, 331, 361, true)) { currentItemRow = 6; currentItemIndex = 31; } else if (inRange(y, 362, 392, true)) { currentItemRow = 7; currentItemIndex = 37; } else if (inRange(y, 393, 423, true)) { currentItemRow = 8; currentItemIndex = 43; } else if (inRange(y, 424, 454, true)) { currentItemRow = 9; currentItemIndex = 49; } else if (inRange(y, 455, 485, true)) { currentItemRow = 10; currentItemIndex = 55; } else if (inRange(y, 486, 516, true)) { currentItemRow = 11; currentItemIndex = 61; } } else if (inRange(x, 649, 679, true)) { currentItemColumn = 3; if (inRange(y, 176, 206, true)) { currentItemRow = 1; currentItemIndex = 2; } else if (inRange(y, 207, 237, true)) { currentItemRow = 2; currentItemIndex = 8; } else if (inRange(y, 238, 268, true)) { currentItemRow = 3; currentItemIndex = 14; } else if (inRange(y, 269, 299, true)) { currentItemRow = 4; currentItemIndex = 20; } else if (inRange(y, 300, 330, true)) { currentItemRow = 5; currentItemIndex = 26; } else if (inRange(y, 331, 361, true)) { currentItemRow = 6; currentItemIndex = 32; } else if (inRange(y, 362, 392, true)) { currentItemRow = 7; currentItemIndex = 38; } else if (inRange(y, 393, 423, true)) { currentItemRow = 8; currentItemIndex = 44; } else if (inRange(y, 424, 454, true)) { currentItemRow = 9; currentItemIndex = 50; } else if (inRange(y, 455, 485, true)) { currentItemRow = 10; currentItemIndex = 56; } else if (inRange(y, 486, 516, true)) { currentItemRow = 11; currentItemIndex = 62; } } else if (inRange(x, 680, 710, true)) { currentItemColumn = 4; if (inRange(y, 176, 206, true)) { currentItemRow = 1; currentItemIndex = 3; } else if (inRange(y, 207, 237, true)) { currentItemRow = 2; currentItemIndex = 9; } else if (inRange(y, 238, 268, true)) { currentItemRow = 3; currentItemIndex = 15; } else if (inRange(y, 269, 299, true)) { currentItemRow = 4; currentItemIndex = 21; } else if (inRange(y, 300, 330, true)) { currentItemRow = 5; currentItemIndex = 27; } else if (inRange(y, 331, 361, true)) { currentItemRow = 6; currentItemIndex = 33; } else if (inRange(y, 362, 392, true)) { currentItemRow = 7; currentItemIndex = 39; } else if (inRange(y, 393, 423, true)) { currentItemRow = 8; currentItemIndex = 45; } else if (inRange(y, 424, 454, true)) { currentItemRow = 9; currentItemIndex = 51; } else if (inRange(y, 455, 485, true)) { currentItemRow = 10; currentItemIndex = 57; } else if (inRange(y, 486, 516, true)) { currentItemRow = 11; currentItemIndex = 63; } } else if (inRange(x, 711, 741, true)) { currentItemColumn = 5; if (inRange(y, 176, 206, true)) { currentItemRow = 1; currentItemIndex = 4; } else if (inRange(y, 207, 237, true)) { currentItemRow = 2; currentItemIndex = 10; } else if (inRange(y, 238, 268, true)) { currentItemRow = 3; currentItemIndex = 16; } else if (inRange(y, 269, 299, true)) { currentItemRow = 4; currentItemIndex = 22; } else if (inRange(y, 300, 330, true)) { currentItemRow = 5; currentItemIndex = 28; } else if (inRange(y, 331, 361, true)) { currentItemRow = 6; currentItemIndex = 34; } else if (inRange(y, 362, 392, true)) { currentItemRow = 7; currentItemIndex = 40; } else if (inRange(y, 393, 423, true)) { currentItemRow = 8; currentItemIndex = 46; } else if (inRange(y, 424, 454, true)) { currentItemRow = 9; currentItemIndex = 52; } else if (inRange(y, 455, 485, true)) { currentItemRow = 10; currentItemIndex = 58; } else if (inRange(y, 486, 516, true)) { currentItemRow = 11; currentItemIndex = 64; } } else if (inRange(x, 742, 772, true)) { currentItemColumn = 6; if (inRange(y, 176, 206, true)) { currentItemRow = 1; currentItemIndex = 5; } else if (inRange(y, 207, 237, true)) { currentItemRow = 2; currentItemIndex = 11; } else if (inRange(y, 238, 268, true)) { currentItemRow = 3; currentItemIndex = 17; } else if (inRange(y, 269, 299, true)) { currentItemRow = 4; currentItemIndex = 23; } else if (inRange(y, 300, 330, true)) { currentItemRow = 5; currentItemIndex = 29; } else if (inRange(y, 331, 361, true)) { currentItemRow = 6; currentItemIndex = 35; } else if (inRange(y, 362, 392, true)) { currentItemRow = 7; currentItemIndex = 41; } else if (inRange(y, 393, 423, true)) { currentItemRow = 8; currentItemIndex = 47; } else if (inRange(y, 424, 454, true)) { currentItemRow = 9; currentItemIndex = 53; } else if (inRange(y, 455, 485, true)) { currentItemRow = 10; currentItemIndex = 59; } else if (inRange(y, 486, 516, true)) { currentItemRow = 11; currentItemIndex = 65; } } if (x > 156 && x < 156 + 30 && y > 183 && y < 183 + 30) { return player1.playerCrafter.itemArray[9]; } if (currentItemIndex < 0) { return null; } return player1.playerInventory.itemArray[currentItemIndex]; } private Item onMouseMovedSelectHoverItem(int x, int y) { currentHoverItem = null; int currentHoverItemIndex = -1; int currentHoverItemRow = -1; if (inRange(x, 587, 617, true)) { if (inRange(y, 176, 206, true)) { currentHoverItemRow = 1; currentHoverItemIndex = 0; } else if (inRange(y, 207, 237, true)) { currentHoverItemRow = 2; currentHoverItemIndex = 6; } else if (inRange(y, 238, 268, true)) { currentHoverItemRow = 3; currentHoverItemIndex = 12; } else if (inRange(y, 269, 299, true)) { currentHoverItemRow = 4; currentHoverItemIndex = 18; } else if (inRange(y, 300, 330, true)) { currentHoverItemRow = 5; currentHoverItemIndex = 24; } else if (inRange(y, 331, 361, true)) { currentHoverItemRow = 6; currentHoverItemIndex = 30; } else if (inRange(y, 362, 392, true)) { currentHoverItemRow = 7; currentHoverItemIndex = 36; } else if (inRange(y, 393, 423, true)) { currentHoverItemRow = 8; currentHoverItemIndex = 42; } else if (inRange(y, 424, 454, true)) { currentHoverItemRow = 9; currentHoverItemIndex = 48; } else if (inRange(y, 455, 485, true)) { currentHoverItemRow = 10; currentHoverItemIndex = 54; } else if (inRange(y, 486, 516, true)) { currentHoverItemRow = 11; currentHoverItemIndex = 60; } } else if (inRange(x, 618, 648, true)) { if (inRange(y, 176, 206, true)) { currentHoverItemRow = 1; currentHoverItemIndex = 1; } else if (inRange(y, 207, 237, true)) { currentHoverItemRow = 2; currentHoverItemIndex = 7; } else if (inRange(y, 238, 268, true)) { currentHoverItemRow = 3; currentHoverItemIndex = 13; } else if (inRange(y, 269, 299, true)) { currentHoverItemRow = 4; currentHoverItemIndex = 19; } else if (inRange(y, 300, 330, true)) { currentHoverItemRow = 5; currentHoverItemIndex = 25; } else if (inRange(y, 331, 361, true)) { currentHoverItemRow = 6; currentHoverItemIndex = 31; } else if (inRange(y, 362, 392, true)) { currentHoverItemRow = 7; currentHoverItemIndex = 37; } else if (inRange(y, 393, 423, true)) { currentHoverItemRow = 8; currentHoverItemIndex = 43; } else if (inRange(y, 424, 454, true)) { currentHoverItemRow = 9; currentHoverItemIndex = 49; } else if (inRange(y, 455, 485, true)) { currentHoverItemRow = 10; currentHoverItemIndex = 55; } else if (inRange(y, 486, 516, true)) { currentHoverItemRow = 11; currentHoverItemIndex = 61; } } else if (inRange(x, 649, 679, true)) { if (inRange(y, 176, 206, true)) { currentHoverItemRow = 1; currentHoverItemIndex = 2; } else if (inRange(y, 207, 237, true)) { currentHoverItemRow = 2; currentHoverItemIndex = 8; } else if (inRange(y, 238, 268, true)) { currentHoverItemRow = 3; currentHoverItemIndex = 14; } else if (inRange(y, 269, 299, true)) { currentHoverItemRow = 4; currentHoverItemIndex = 20; } else if (inRange(y, 300, 330, true)) { currentHoverItemRow = 5; currentHoverItemIndex = 26; } else if (inRange(y, 331, 361, true)) { currentHoverItemRow = 6; currentHoverItemIndex = 32; } else if (inRange(y, 362, 392, true)) { currentHoverItemRow = 7; currentHoverItemIndex = 38; } else if (inRange(y, 393, 423, true)) { currentHoverItemRow = 8; currentHoverItemIndex = 44; } else if (inRange(y, 424, 454, true)) { currentHoverItemRow = 9; currentHoverItemIndex = 50; } else if (inRange(y, 455, 485, true)) { currentHoverItemRow = 10; currentHoverItemIndex = 56; } else if (inRange(y, 486, 516, true)) { currentHoverItemRow = 11; currentHoverItemIndex = 62; } } else if (inRange(x, 680, 710, true)) { if (inRange(y, 176, 206, true)) { currentHoverItemRow = 1; currentHoverItemIndex = 3; } else if (inRange(y, 207, 237, true)) { currentHoverItemRow = 2; currentHoverItemIndex = 9; } else if (inRange(y, 238, 268, true)) { currentHoverItemRow = 3; currentHoverItemIndex = 15; } else if (inRange(y, 269, 299, true)) { currentHoverItemRow = 4; currentHoverItemIndex = 21; } else if (inRange(y, 300, 330, true)) { currentHoverItemRow = 5; currentHoverItemIndex = 27; } else if (inRange(y, 331, 361, true)) { currentHoverItemRow = 6; currentHoverItemIndex = 33; } else if (inRange(y, 362, 392, true)) { currentHoverItemRow = 7; currentHoverItemIndex = 39; } else if (inRange(y, 393, 423, true)) { currentHoverItemRow = 8; currentHoverItemIndex = 45; } else if (inRange(y, 424, 454, true)) { currentHoverItemRow = 9; currentHoverItemIndex = 51; } else if (inRange(y, 455, 485, true)) { currentHoverItemRow = 10; currentHoverItemIndex = 57; } else if (inRange(y, 486, 516, true)) { currentHoverItemRow = 11; currentHoverItemIndex = 63; } } else if (inRange(x, 711, 741, true)) { if (inRange(y, 176, 206, true)) { currentHoverItemRow = 1; currentHoverItemIndex = 4; } else if (inRange(y, 207, 237, true)) { currentHoverItemRow = 2; currentHoverItemIndex = 10; } else if (inRange(y, 238, 268, true)) { currentHoverItemRow = 3; currentHoverItemIndex = 16; } else if (inRange(y, 269, 299, true)) { currentHoverItemRow = 4; currentHoverItemIndex = 22; } else if (inRange(y, 300, 330, true)) { currentHoverItemRow = 5; currentHoverItemIndex = 28; } else if (inRange(y, 331, 361, true)) { currentHoverItemRow = 6; currentHoverItemIndex = 34; } else if (inRange(y, 362, 392, true)) { currentHoverItemRow = 7; currentHoverItemIndex = 40; } else if (inRange(y, 393, 423, true)) { currentHoverItemRow = 8; currentHoverItemIndex = 46; } else if (inRange(y, 424, 454, true)) { currentHoverItemRow = 9; currentHoverItemIndex = 52; } else if (inRange(y, 455, 485, true)) { currentHoverItemRow = 10; currentHoverItemIndex = 58; } else if (inRange(y, 486, 516, true)) { currentHoverItemRow = 11; currentHoverItemIndex = 64; } } else if (inRange(x, 742, 772, true)) { if (inRange(y, 176, 206, true)) { currentHoverItemRow = 1; currentHoverItemIndex = 5; } else if (inRange(y, 207, 237, true)) { currentHoverItemRow = 2; currentHoverItemIndex = 11; } else if (inRange(y, 238, 268, true)) { currentHoverItemRow = 3; currentHoverItemIndex = 17; } else if (inRange(y, 269, 299, true)) { currentHoverItemRow = 4; currentHoverItemIndex = 23; } else if (inRange(y, 300, 330, true)) { currentHoverItemRow = 5; currentHoverItemIndex = 29; } else if (inRange(y, 331, 361, true)) { currentHoverItemRow = 6; currentHoverItemIndex = 35; } else if (inRange(y, 362, 392, true)) { currentHoverItemRow = 7; currentHoverItemIndex = 41; } else if (inRange(y, 393, 423, true)) { currentHoverItemRow = 8; currentHoverItemIndex = 47; } else if (inRange(y, 424, 454, true)) { currentHoverItemRow = 9; currentHoverItemIndex = 53; } else if (inRange(y, 455, 485, true)) { currentHoverItemRow = 10; currentHoverItemIndex = 59; } else if (inRange(y, 486, 516, true)) { currentHoverItemRow = 11; currentHoverItemIndex = 65; } } if (x > 156 && x < 156 + 30 && y > 183 && y < 183 + 30) { return player1.playerCrafter.itemArray[9]; } if (currentHoverItemIndex < 0) { return null; } return player1.playerInventory.itemArray[currentHoverItemIndex]; } private Tile onMouseClickSelectTile(int x, int y) { currentTileX = x / 25; currentTileY = y / 25; return currentOverWorld.tilemap[x / 25][y / 25]; } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } @Override public void mouseDragged(MouseEvent e) { } @Override public void mouseMoved(MouseEvent e) { mouseDragX = e.getX(); mouseDragY = e.getY(); currentHoverItem = onMouseMovedSelectHoverItem(mouseDragX, mouseDragY); } public static String printTileSet(Tile[][] tilemap) { String ans = ""; for (int i = 0; i < 32; i++) { ans += "\n"; for (int j = 0; j < 24; j++) { ans += " - " + tilemap[i][j].type + " - "; } } return ans; } public static String getUserInput() { Scanner stringIn = new Scanner(System.in); System.out.println("please enters string:"); while (stringIn.hasNext()) { if (stringIn.hasNextLine()) { return stringIn.nextLine(); } else { System.out.println("invalid input"); stringIn.next(); } } return null; } public static Integer getUserInputInt() { Scanner stringIn = new Scanner(System.in); System.out.println("please enters string:"); while (stringIn.hasNext()) { if (stringIn.hasNextInt()) { return stringIn.nextInt(); } else { System.out.println("invalid input"); stringIn.next(); } } return null; } public boolean inRange(int i, int lower, int upper, boolean inclusive) { if (inclusive) { return (i <= upper && i >= lower); } return (i < upper && i > lower); } }
import static java.lang.reflect.Modifier.*; import static org.junit.Assert.*; import org.junit.Test; public class SuperTest { @Test public void isNotPublic() { int modifiers = Super.class.getModifiers(); boolean isPublic = isPublic(modifiers); assertFalse("Super is public (modifiers: " + modifiers + ").", isPublic); } }
package cn.luo.yuan.maze.dlc; import cn.luo.yuan.maze.model.Element; import cn.luo.yuan.maze.model.Hero; import cn.luo.yuan.maze.model.Monster; import cn.luo.yuan.maze.model.NPCLevelRecord; import cn.luo.yuan.maze.model.Race; import cn.luo.yuan.maze.model.dlc.DLC; import cn.luo.yuan.maze.model.dlc.GoodsDLC; import cn.luo.yuan.maze.model.dlc.MonsterDLC; import cn.luo.yuan.maze.model.dlc.NPCDLC; import cn.luo.yuan.maze.model.dlc.SkillDLC; import cn.luo.yuan.maze.model.goods.types.EmptyAccessory; import cn.luo.yuan.maze.model.names.FirstName; import cn.luo.yuan.maze.model.names.SecondName; import cn.luo.yuan.maze.model.skill.Skill; import cn.luo.yuan.maze.model.skill.race.Alayer; import cn.luo.yuan.maze.model.skill.race.Chaos; import cn.luo.yuan.maze.model.skill.race.Decide; import cn.luo.yuan.maze.model.skill.race.Exorcism; import cn.luo.yuan.maze.model.skill.race.Masimm; import cn.luo.yuan.maze.model.skill.race.Painkiller; import cn.luo.yuan.maze.serialize.ObjectTable; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.UUID; public class BuildDLC { public static File root = new File("dlc"); public static void main(String... args) throws IOException { ObjectTable<DLC> dlcTable = new ObjectTable<DLC>(DLC.class, new File("dlc")); /*buildAngel(dlcTable); buildJiuwei(dlcTable); buildEmprtyAccessory(dlcTable); buildSkillDlc(new Alayer(), dlcTable); buildSkillDlc(new Chaos(), dlcTable); buildSkillDlc(new Decide(), dlcTable); buildSkillDlc(new Exorcism(), dlcTable); buildSkillDlc(new Masimm(), dlcTable); buildSkillDlc(new Painkiller(), dlcTable);*/ //buildEveoo(dlcTable); buildNPC(dlcTable); } public static void buildNPC(ObjectTable<DLC> dlcObjectTable) throws IOException{ /*chuyin(dlcObjectTable); yuanshuxion(dlcObjectTable);*/ leierdan(dlcObjectTable); yuanxiaomei(dlcObjectTable); } public static void yuanxiaomei(ObjectTable<DLC> dlcObjectTable) throws IOException { Hero hero = new Hero(); hero.setMaxHp(500000); hero.setHp(hero.getMaxHp()); hero.setAtk(700000); hero.setDef(4000000); hero.setRace(Race.Elyosr.ordinal()); hero.setElement(Element.FIRE); hero.setName(""); hero.setId(hero.getName()); NPCLevelRecord record = new NPCLevelRecord(hero); record.setSex(1); record.setLevel(500); record.setHead("Succubus.png"); NPCDLC npcdlc = new NPCDLC(); npcdlc.setDebrisCost(25); npcdlc.setDesc("……"); npcdlc.setNpc(record); npcdlc.setTitle(hero.getName()); dlcObjectTable.save(npcdlc); } public static void leierdan(ObjectTable<DLC> dlcObjectTable) throws IOException { Hero hero = new Hero(); hero.setMaxHp(7000000); hero.setHp(hero.getMaxHp()); hero.setAtk(9000000); hero.setDef(7000000); hero.setRace(Race.Orger.ordinal()); hero.setElement(Element.FIRE); hero.setName(""); hero.setId(hero.getName()); NPCLevelRecord record = new NPCLevelRecord(hero); record.setSex(0); record.setLevel(1000); record.setHead("General_m.png"); NPCDLC npcdlc = new NPCDLC(); npcdlc.setDebrisCost(5); npcdlc.setDesc(""); npcdlc.setNpc(record); npcdlc.setTitle(hero.getName()); dlcObjectTable.save(npcdlc); } public static void chuyin(ObjectTable<DLC> dlcObjectTable) throws IOException { Hero hero = new Hero(); hero.setMaxHp(1200000); hero.setHp(hero.getMaxHp()); hero.setAtk(1050000); hero.setDef(180000); hero.setRace(Race.Wizardsr.ordinal()); hero.setElement(Element.FIRE); hero.setName(""); hero.setId(hero.getName()); NPCLevelRecord record = new NPCLevelRecord(hero); record.setSex(1); record.setLevel(300); record.setHead("chuyin"); NPCDLC npcdlc = new NPCDLC(); npcdlc.setDebrisCost(15); npcdlc.setDesc("100W"); npcdlc.setNpc(record); npcdlc.setTitle(hero.getName()); dlcObjectTable.save(npcdlc); } public static void yuanshuxion(ObjectTable<DLC> dlcObjectTable) throws IOException { Hero hero = new Hero(); hero.setMaxHp(4000); hero.setHp(hero.getMaxHp()); hero.setAtk(3000); hero.setDef(5000); hero.setRace(Race.Ghosr.ordinal()); hero.setElement(Element.FIRE); hero.setName(""); hero.setId(hero.getName()); NPCLevelRecord record = new NPCLevelRecord(hero); record.setSex(0); record.setLevel(100); record.setHead("Actor2_1.png"); NPCDLC npcdlc = new NPCDLC(); npcdlc.setDebrisCost(5); npcdlc.setDesc("……<br><br><br>"); npcdlc.setNpc(record); npcdlc.setTitle(hero.getName()); dlcObjectTable.save(npcdlc); } public static void buildEmprtyAccessory(ObjectTable<DLC> dlcTable) throws IOException { GoodsDLC dlc = new GoodsDLC(); EmptyAccessory ea = new EmptyAccessory(); ea.setCount(1); dlc.setGoods(ea); dlc.setDebrisCost(500); dlc.setId(ea.getName()); dlc.setDesc(ea.getDesc()); dlc.setTitle(ea.getName()); System.out.println(dlcTable.save(dlc)); } private static byte[] readImage(String path) throws IOException { FileInputStream fis = new FileInputStream(path); ArrayList<Byte> buffer = new ArrayList<>(); Integer i = fis.read(); while (i >= 0) { buffer.add(i.byteValue()); i = fis.read(); } byte[] bytes = new byte[buffer.size()]; for (int j = 0; j < buffer.size(); j++) { bytes[j] = buffer.get(j); } return bytes; } public static void buildJiuwei(ObjectTable<DLC> table) throws IOException { MonsterDLC dlc = new MonsterDLC(); dlc.setTitle(""); dlc.setDebrisCost(50); dlc.setDesc("<br><br>DLC"); Monster monster = new Monster(); monster.setIndex(96); monster.setHp(185); monster.setMaxHp(185); monster.setFirstName(FirstName.frailty); monster.setSecondName(SecondName.face); monster.setAtk(199); monster.setDef(125); monster.setEggRate(0); monster.setPetRate(5); monster.setSilent(90); monster.setHitRate(10); monster.setSex(1); monster.setRank(5); monster.setRace(Race.Eviler); monster.setType(""); monster.setDesc(""); dlc.getMonsters().add(monster); dlc.getImage().add(readImage("E:\\NeverEnd\\assets\\monster\\jiuwei_yzq.png")); monster = new Monster(); monster.setIndex(81); monster.setHp(89); monster.setMaxHp(89); monster.setFirstName(FirstName.frailty); monster.setSecondName(SecondName.face); monster.setAtk(199); monster.setDef(225); monster.setEggRate(1); monster.setPetRate(15); monster.setSilent(70); monster.setHitRate(10); monster.setNext(96); monster.setSex(1); monster.setRace(Race.Wizardsr); monster.setRank(3); monster.setType(""); monster.setDesc(" dlc.getMonsters().add(monster); dlc.getImage().add(readImage("E:\\NeverEnd\\assets\\monster\\jiuwei_kynei.png")); monster = new Monster(); monster.setIndex(41); monster.setHp(100); monster.setMaxHp(100); monster.setFirstName(FirstName.frailty); monster.setSecondName(SecondName.face); monster.setAtk(130); monster.setDef(199); monster.setEggRate(19); monster.setPetRate(25); monster.setSilent(7); monster.setHitRate(10); monster.setNext(81); monster.setSex(1); monster.setRank(2); monster.setRace(Race.Wizardsr); monster.setType(""); monster.setDesc(" dlc.getMonsters().add(monster); dlc.getImage().add(readImage("E:\\NeverEnd\\assets\\monster\\jiuweihu_red.png")); System.out.println(table.save(dlc)); } public static void buildAngel(ObjectTable<DLC> table) throws IOException { MonsterDLC dlc = new MonsterDLC(); dlc.setTitle(""); dlc.setDebrisCost(100); dlc.setDesc("DLC"); Monster monster = new Monster(); monster.setIndex(68); monster.setHp(76); monster.setMaxHp(76); monster.setAtk(219); monster.setDef(123); monster.setEggRate(40); monster.setPetRate(15); monster.setSilent(16); monster.setHitRate(10); monster.setSex(-1); monster.setRank(2); monster.setNext(69); monster.setRace(Race.Elyosr); monster.setType(""); monster.setDesc(""); dlc.getMonsters().add(monster); dlc.getImage().add(readImage("E:\\NeverEnd\\assets\\monster\\angle_0.png")); monster = new Monster(); monster.setIndex(71); monster.setHp(51); monster.setMaxHp(51); monster.setAtk(105); monster.setDef(255); monster.setEggRate(19); monster.setPetRate(22); monster.setSilent(37); monster.setHitRate(28); monster.setSex(-1); monster.setRank(3); monster.setRace(Race.Eviler); monster.setType(""); monster.setDesc(""); dlc.getMonsters().add(monster); dlc.getImage().add(readImage("E:\\NeverEnd\\assets\\monster\\angle_miao.png")); monster = new Monster(); monster.setIndex(92); monster.setHp(240); monster.setMaxHp(240); monster.setAtk(68); monster.setDef(237); monster.setEggRate(9); monster.setPetRate(22); monster.setSilent(37); monster.setHitRate(18); monster.setSex(1); monster.setRank(4); monster.setRace(Race.Elyosr); monster.setType(""); monster.setDesc("β"); dlc.getMonsters().add(monster); dlc.getImage().add(readImage("E:\\NeverEnd\\assets\\monster\\nimufu.png")); monster = new Monster(); monster.setIndex(69); monster.setHp(86); monster.setMaxHp(86); monster.setAtk(175); monster.setDef(253); monster.setEggRate(21); monster.setPetRate(13); monster.setSilent(12); monster.setHitRate(10); monster.setSex(-1); monster.setRace(Race.Orger); monster.setRank(3); monster.setType(""); monster.setDesc(""); dlc.getMonsters().add(monster); dlc.getImage().add(readImage("E:\\NeverEnd\\assets\\monster\\angle_1.png")); monster = new Monster(); monster.setIndex(70); monster.setHp(41); monster.setMaxHp(41); monster.setFirstName(FirstName.frailty); monster.setSecondName(SecondName.face); monster.setAtk(105); monster.setDef(210); monster.setEggRate(9); monster.setPetRate(12); monster.setSilent(27); monster.setHitRate(18); monster.setSex(-1); monster.setRank(4); monster.setRace(Race.Elyosr); monster.setType(""); monster.setDesc(""); dlc.getMonsters().add(monster); dlc.getImage().add(readImage("E:\\NeverEnd\\assets\\monster\\Angel.png")); monster = new Monster(); monster.setIndex(93); monster.setHp(255); monster.setMaxHp(255); monster.setAtk(255); monster.setDef(37); monster.setEggRate(0); monster.setPetRate(22); monster.setSilent(37); monster.setHitRate(18); monster.setSex(1); monster.setRank(4); monster.setRace(Race.Elyosr); monster.setType(""); monster.setDesc("α"); dlc.getMonsters().add(monster); dlc.getImage().add(readImage("E:\\NeverEnd\\assets\\monster\\yikaluos.png")); monster = new Monster(); monster.setIndex(95); monster.setHp(125); monster.setMaxHp(125); monster.setAtk(255); monster.setDef(99); monster.setEggRate(0); monster.setPetRate(20); monster.setSilent(47); monster.setHitRate(38); monster.setSex(1); monster.setRank(5); monster.setRace(Race.Nonsr); monster.setType("CHISE"); monster.setDesc("\"\""); dlc.getMonsters().add(monster); dlc.getImage().add(readImage("E:\\NeverEnd\\assets\\monster\\chisi.png")); System.out.println(table.save(dlc)); } public static void buildSkillDlc(Skill skill, ObjectTable<DLC> table) throws IOException { SkillDLC dlc = new SkillDLC(); dlc.setSkill(skill); dlc.setDebrisCost(20); System.out.println(table.save(dlc)); } private static void buildEveoo(ObjectTable<DLC> table) throws IOException { MonsterDLC dlc = new MonsterDLC(); Monster monster = null; monster = new Monster(); monster.setIndex(102); monster.setAtk(228); monster.setMaxHp(40); monster.setHp(monster.getMaxHp()); monster.setDef(170); monster.setPetRate(0); monster.setEggRate(50); monster.setSilent(39); monster.setHitRate(18); monster.setSex(-1); monster.setRank(3); monster.setRace(Race.Ghosr); monster.setType(""); monster.setDesc(""); dlc.getMonsters().add(monster); dlc.getImage().add(readImage("pics/evee/evo_gui.png")); monster = new Monster(); monster.setIndex(129); monster.setAtk(228); monster.setMaxHp(40); monster.setHp(monster.getMaxHp()); monster.setDef(170); monster.setPetRate(0); monster.setEggRate(50); monster.setSilent(39); monster.setHitRate(90); monster.setSex(-1); monster.setRank(3); monster.setRace(Race.Ghosr); monster.setType(""); monster.setDesc(""); dlc.getMonsters().add(monster); dlc.getImage().add(readImage("pics/evee/evo_gui_1.png")); monster = new Monster(); monster.setIndex(119); monster.setAtk(208); monster.setMaxHp(140); monster.setHp(monster.getMaxHp()); monster.setDef(90); monster.setPetRate(0); monster.setEggRate(50); monster.setSilent(29); monster.setHitRate(90); monster.setSex(-1); monster.setRank(3); monster.setRace(Race.Eviler); monster.setType(""); monster.setDesc(""); dlc.getMonsters().add(monster); dlc.getImage().add(readImage("pics/evee/evo_bin.png")); monster = new Monster(); monster.setIndex(106); monster.setAtk(128); monster.setMaxHp(140); monster.setHp(monster.getMaxHp()); monster.setDef(170); monster.setPetRate(0); monster.setEggRate(50); monster.setSilent(29); monster.setHitRate(10); monster.setSex(-1); monster.setRank(3); monster.setRace(Race.Orger); monster.setType(""); monster.setDesc(""); dlc.getMonsters().add(monster); dlc.getImage().add(readImage("pics/evee/evo_an.png")); monster = new Monster(); monster.setIndex(118); monster.setAtk(128); monster.setMaxHp(100); monster.setHp(monster.getMaxHp()); monster.setDef(100); monster.setPetRate(0); monster.setEggRate(50); monster.setSilent(39); monster.setHitRate(10); monster.setSex(-1); monster.setRank(3); monster.setRace(Race.Orger); monster.setType(""); monster.setDesc(""); dlc.getMonsters().add(monster); dlc.getImage().add(readImage("pics/evee/evo_cao.png")); monster = new Monster(); monster.setIndex(125); monster.setAtk(208); monster.setMaxHp(140); monster.setHp(monster.getMaxHp()); monster.setDef(50); monster.setPetRate(0); monster.setEggRate(50); monster.setSilent(49); monster.setHitRate(10); monster.setSex(-1); monster.setRank(3); monster.setRace(Race.Wizardsr); monster.setType(""); monster.setDesc(""); dlc.getMonsters().add(monster); dlc.getImage().add(readImage("pics/evee/evo_cao_1.png")); monster = new Monster(); monster.setIndex(124); monster.setAtk(128); monster.setMaxHp(140); monster.setHp(monster.getMaxHp()); monster.setDef(170); monster.setPetRate(0); monster.setEggRate(50); monster.setSilent(49); monster.setHitRate(10); monster.setSex(-1); monster.setRank(3); monster.setRace(Race.Elyosr); monster.setType(""); monster.setDesc(""); dlc.getMonsters().add(monster); dlc.getImage().add(readImage("pics/evee/evo_cao_2.png")); monster = new Monster(); monster.setIndex(109); monster.setAtk(128); monster.setMaxHp(140); monster.setHp(monster.getMaxHp()); monster.setDef(170); monster.setPetRate(0); monster.setEggRate(50); monster.setSilent(49); monster.setHitRate(10); monster.setSex(-1); monster.setRank(3); monster.setRace(Race.Wizardsr); monster.setType(""); monster.setDesc("!"); dlc.getMonsters().add(monster); dlc.getImage().add(readImage("pics/evee/evo_chao.png")); monster = new Monster(); monster.setIndex(110); monster.setAtk(28); monster.setMaxHp(40); monster.setHp(monster.getMaxHp()); monster.setDef(250); monster.setPetRate(0); monster.setEggRate(50); monster.setSilent(49); monster.setHitRate(10); monster.setSex(-1); monster.setRank(3); monster.setRace(Race.Eviler); monster.setType(""); monster.setDesc(""); dlc.getMonsters().add(monster); dlc.getImage().add(readImage("pics/evee/evo_cong.png")); monster = new Monster(); monster.setIndex(111); monster.setAtk(28); monster.setMaxHp(40); monster.setHp(monster.getMaxHp()); monster.setDef(250); monster.setPetRate(0); monster.setEggRate(50); monster.setSilent(49); monster.setHitRate(10); monster.setSex(-1); monster.setRank(3); monster.setRace(Race.Eviler); monster.setType(""); monster.setDesc(""); dlc.getMonsters().add(monster); dlc.getImage().add(readImage("pics/evee/evo_cong_1.png")); monster = new Monster(); monster.setIndex(117); monster.setAtk(228); monster.setMaxHp(132); monster.setHp(monster.getMaxHp()); monster.setDef(55); monster.setPetRate(0); monster.setEggRate(50); monster.setSilent(49); monster.setHitRate(10); monster.setSex(-1); monster.setRank(3); monster.setRace(Race.Elyosr); monster.setType(""); monster.setDesc(""); dlc.getMonsters().add(monster); dlc.getImage().add(readImage("pics/evee/evo_dian.png")); dlc.setTitle("I"); dlc.setDesc("12"); dlc.setDebrisCost(200); System.out.println(table.save(dlc)); } }
/* * $Id: MockUrlCacher.java,v 1.28 2005-08-02 22:54:06 troberts Exp $ */ package org.lockss.test; import java.io.*; import java.util.*; import org.lockss.util.*; import org.lockss.util.urlconn.*; import org.lockss.daemon.*; import org.lockss.plugin.*; import org.lockss.crawler.PermissionMap; /** * This is a mock version of <code>UrlCacher</code> used for testing */ public class MockUrlCacher implements UrlCacher { private static Logger logger = Logger.getLogger("MockUrlCacher"); private MockArchivalUnit au = null; private MockCachedUrlSet cus = null; private MockCachedUrl cu; private String url; private InputStream cachedIS; private InputStream uncachedIS; private CIProperties cachedProp; private CIProperties uncachedProp; private boolean shouldBeCached = false; private IOException cachingException = null; private RuntimeException cachingRuntimException = null; private int numTimesToThrow = 1; private int timesThrown = 0; // private boolean forceRefetch = false; private BitSet fetchFlags = new BitSet(); private PermissionMapSource permissionMapSource; public MockUrlCacher(String url, MockArchivalUnit au){ this.url = url; this.au = au; this.cus = (MockCachedUrlSet)au.getAuCachedUrlSet(); } public String getUrl() { return url; } public CachedUrlSet getCachedUrlSet() { return cus; } public void setCachedUrlSet(MockCachedUrlSet cus) { this.cus = cus; } public boolean shouldBeCached(){ return shouldBeCached; } public void setShouldBeCached(boolean shouldBeCached){ this.shouldBeCached = shouldBeCached; } public CachedUrl getCachedUrl() { return cu; } public void setCachedUrl(MockCachedUrl cu) { this.cu = cu; } public void setConnectionPool(LockssUrlConnectionPool connectionPool) { } public void setProxy(String proxyHost, int proxyPort) { } // public void setForceRefetch(boolean force) { // this.forceRefetch = force; public void setFetchFlags(BitSet fetchFlags) { this.fetchFlags = fetchFlags; } public BitSet getFetchFlags() { return this.fetchFlags; } public void setRequestProperty(String key, String value) { } public void setRedirectScheme(RedirectScheme scheme) { } public void setupCachedUrl(String contents) throws IOException { MockCachedUrl cu = new MockCachedUrl(url); cu.setProperties(getUncachedProperties()); if (contents != null) { cu.setContent(contents); } setCachedUrl(cu); } // Read interface - used by the proxy. public InputStream openForReading(){ return cachedIS; } public CIProperties getProperties(){ return cachedProp; } // Write interface - used by the crawler. public void storeContent(InputStream input, CIProperties headers) throws IOException{ cachedIS = input; cachedProp = headers; if (cus != null) { if (fetchFlags.get(UrlCacher.REFETCH_FLAG)) { // if (forceRefetch) { cus.addForceCachedUrl(url); } else { cus.addCachedUrl(url); } } } public void setCachingException(IOException e, int numTimesToThrow) { this.cachingException = e; this.numTimesToThrow = numTimesToThrow; } public void setCachingException(RuntimeException e, int numTimesToThrow) { this.cachingRuntimException = e; } private void throwExceptionIfSet() throws IOException { logger.debug3("Deciding whether to throw an exception"); if (cachingException != null && timesThrown < numTimesToThrow) { timesThrown++; throw cachingException; } else { logger.debug3("No cachingException set"); } if (cachingRuntimException != null) { // Get a stack trace from here, not from the test case where the // exception was created cachingRuntimException.fillInStackTrace(); timesThrown++; throw cachingRuntimException; } else { logger.debug3("No cachingRuntimeException set"); } } public int cache() throws IOException { int resultCode; if(cus == null) System.out.println("Warning cache() called with null cus"); if (cus != null) { cus.signalCacheAttempt(url); } throwExceptionIfSet(); if (cus != null) { if (fetchFlags.get(UrlCacher.REFETCH_FLAG)) { // if (forceRefetch) { cus.addForceCachedUrl(url); } else { cus.addCachedUrl(url); } } //XXX messy //content already there, so we should be doing a not modified response // if (!forceRefetch && cu.hasContent()) { if (cu.hasContent()) { return CACHE_RESULT_NOT_MODIFIED; } //otherwise, mark that there is content and send a fetched response if (cu != null) { cu.setExists(true); } return CACHE_RESULT_FETCHED; } public InputStream getUncachedInputStream() throws IOException { throwExceptionIfSet(); return uncachedIS; } public CIProperties getUncachedProperties() throws IOException { throwExceptionIfSet(); return uncachedProp; } //mock specific acessors public void setCachedInputStream(InputStream is){ cachedIS = is; } public void setUncachedInputStream(InputStream is){ uncachedIS = is; } public void setCachedProperties(CIProperties prop){ cachedProp = prop; } public void setUncachedProperties(CIProperties prop){ uncachedProp = prop; } public String toString() { StringBuffer sb = new StringBuffer(url.length()+17); sb.append("[MockUrlCacher: "); sb.append(url); sb.append("]"); return sb.toString(); } public void setPermissionMapSource(PermissionMapSource pmSource) { this.permissionMapSource = pmSource; } public PermissionMapSource getPermissionMapSource() { return permissionMapSource; } }
import java.util.*; /** * Given a collection of intervals, merge all overlapping intervals. * * For example, * Given [1,3],[2,6],[8,10],[15,18], * return [1,6],[8,10],[15,18]. * * Tags: Array, Sort */ class MergeIntervals { public static void main(String[] args) { } /** * Sort and merge, O(nlogn) * Sort the intervals according to their start value * Go through the intervals and update last interval * If last interval in result overlap with current interval * Remove last interval and add new interval with updated end value * Which is the bigger of last.end and i.end */ public List<Interval> merge(List<Interval> intervals) { List<Interval> res = new ArrayList<Interval>(); if (intervals == null || intervals.size() == 0) return res; Collections.sort(intervals, new MyComparator()); for (Interval i : intervals) { if (res.isEmpty()) res.add(i); // first interval else { Interval last = res.get(res.size() - 1); // get last interval if (last.end >= i.start) { // overlap res.remove(last); res.add(new Interval(last.start, Math.max(last.end, i.end))); // extend end } else res.add(i); //no overlap } } return res; } /** * Comparator for interval * Sort according to start date */ class MyComparator implements Comparator<Interval> { @Override public int compare(Interval i1, Interval i2) { return i1.start - i2.start; } } public class Interval { int start; int end; Interval() { start = 0; end = 0; } Interval(int s, int e) { start = s; end = e; } } }
/* NTUA ECE AI robots * * Given two robots and a plane with destinations and obstacles * implement A* to get the two robots to pass through the destinations * and meet at the last one */ import java.util.*; import java.io.*; import java.io.FileNotFoundException; class Point implements Comparable<Point> { public int c, r; int min(int a, int b) { return a < b ? a : b; } int max(int a, int b) { return a > b ? a : b; } // Constructors Point(int a, int b) { r = a; c = b; } Point() { c = r = 0; } // Returns the distance between this and p public int dist(Point p) { return Math.abs(this.r-p.r) + Math.abs(this.c-p.c); } @Override public int compareTo(Point a) { int i; if((i=this.r-a.r)!=0) return i; else return this.c - a.c; } @Override public boolean equals(Object other) { if(this == other) return true; if(other == null || (this.getClass() != other.getClass())) { return false; } Point guest = (Point) other; return (this.r == guest.r) && (this.c == guest.c); } } class Interest implements Comparable<Interest> { public Point pos; // Where it is public int dist; // Distance so far public int heur; // Heuristic distance to be travelled public Interest father; // Previous step @Override public int compareTo(Interest a) { double i; if((i=this.heur-a.heur)!=0) return (int) i; else if((i=this.dist-a.dist)!=0) return (int) i; else if((i=this.pos.r-a.pos.r)!=0) return (int) i; else return this.pos.c-a.pos.c; } @Override public boolean equals(Object other) { if(this == other) return true; if(other == null || (this.getClass() != other.getClass())) { return false; } Interest guest = (Interest) other; return (this.pos.equals(guest.pos)) && (this.dist == guest.dist) && (this.heur == guest.heur); } /* Constructors */ Interest(Point p, int d, int h, Interest f) { pos = p; dist = d; heur = h; father = f; } Interest() { pos = new Point(); dist = 0; heur = 0; father = null; } // Returns a list of all the possible points we can go public ArrayList<Interest> next(char[][] board, int N, int M, Point finish) { ArrayList<Interest> ret = new ArrayList<Interest>(); // Down if(pos.r+1 < N && board[this.pos.r+1][this.pos.c] != 'X') { Point n = new Point(pos.r+1, pos.c); ret.add(new Interest(n, dist+1, dist+1+n.dist(finish), this)); } // Right if(pos.c+1 < M && board[this.pos.r][this.pos.c+1] != 'X') { Point n = new Point(pos.r, pos.c+1); ret.add(new Interest(n, dist+1, dist+1+n.dist(finish), this)); } if(pos.r > 0 && board[this.pos.r-1][this.pos.c] != 'X') { Point n = new Point(pos.r-1, pos.c); ret.add(new Interest(n, dist+1, dist+1+n.dist(finish), this)); } // Left if(pos.c > 0 && board[this.pos.r][this.pos.c-1] != 'X') { Point n = new Point(pos.r, pos.c-1); ret.add(new Interest(n, dist+1, dist+1+n.dist(finish), this)); } return ret; } } /* Main class */ public class Robots { static int min(int a, int b) { return a < b ? a : b; } static int max(int a, int b) { return a > b ? a : b; } static int M, N; static char[][] board; // Given a starting and ending point, returns the last Interest of the path // Usually it would be used in conjuction to backtrace public static Interest Astar(Point start, Point fin, Point[] player, int size, int prev) throws Exception{ PriorityQueue<Interest> queue = new PriorityQueue<Interest>(); TreeSet<Point> closed = new TreeSet<Point>(); Interest start_i = new Interest(start, 0, start.dist(fin), null); queue.add(start_i); int size_t = size; String Name; if(player == null) Name = new String("Player 1 "); else Name = new String("Player 2 "); while(!queue.isEmpty()) { Interest curr = queue.poll(); // Get next element System.out.println(Name + "considering new posisition at<" + curr.pos.r +"," + curr.pos.c +"> at step " + (curr.dist+prev)); if(curr.pos.equals(fin)) // Base case return curr; if(closed.contains(curr.pos)) // No rechecks continue; closed.add(curr.pos); ArrayList<Interest> next_moves= curr.next(board,N,M,fin); for(Interest next : next_moves) { int pos_print = next.dist + prev; if(closed.contains(next.pos)) continue; if(player != null) { if(next.dist >= size || !player[(next.dist)].equals(next.pos)) queue.add(next); else { System.out.println("** Conflict ** , thinking about stall or another move"); queue.add(new Interest(next.pos, next.dist+1, next.heur+1, next.father)); } } else queue.add(next); } } System.out.println(closed.size()); System.out.println(fin.c + " " + fin.r); System.out.println("You guys really fucked it up"); throw new Exception(); // return null; } public static ArrayList<Point> backtrace(Interest a) { ArrayList<Point> val = new ArrayList<Point>(); Interest temp=a; while(temp!=null) { if(temp.father != null && temp.dist - temp.father.dist > 1) val.add(temp.father.pos); val.add(temp.pos); temp=temp.father; } Collections.reverse(val); return val; } static void print_route(ArrayList<Point> player1, ArrayList<Point> player2) { try { int s = max(player1.size(), player2.size()); int i; System.out.println("Printing final path"); for(i=0;i<s;i++) { Point pl1, pl2; if(i < player1.size()) pl1 = player1.get(i); else pl1 = player1.get(player1.size() - 1); if(i < player2.size()) pl2 = player2.get(i); else pl2 = player2.get(player2.size() - 1); System.out.println("Player 1 going at posisition <" + pl1.r + "," + pl1.c + "> at step " + i ); System.out.println("Player 2 going at posisition <" + pl2.r + "," + pl2.c + "> at step " + i ); } } catch(Exception e) { e.printStackTrace(); System.out.println("Exception has been raised"); } } public static void main(String[] args) { /* Input */ try { Scanner in = new Scanner(System.in); // Read dimensions M = in.nextInt(); N = in.nextInt(); int r, c; // Get starting points c = in.nextInt(); r = in.nextInt(); Point first = new Point(r, c); c = in.nextInt(); r = in.nextInt(); Point second = new Point(r, c); // Get meeting point c = in.nextInt(); r = in.nextInt(); Point last = new Point(r, c); // Get intermediate points int meet_points = in.nextInt(); Point[] meet = new Point[meet_points + 1]; int i, j; for(i = 0; i < meet_points; i++) { c = in.nextInt(); r = in.nextInt(); meet[i] = new Point(c,r); } meet[meet_points] = last; // Get board board = new char[N][M]; for(i = 0; i < N; i++) { board[i] = in.next().toCharArray(); } for(i = 0; i < meet_points + 1; i++) { if(board[meet[i].r][meet[i].c] == 'X') { System.out.println(meet[i].r + " " + meet[i].c); throw new IOException(); } } ArrayList<Point> player1 = backtrace(Astar(first, meet[0], null,0,0)); for(i = 1; i < meet_points + 1; i++) { player1.addAll(backtrace(Astar(meet[i-1], meet[i], null,0,player1.size()))); } ArrayList<Point> player2 = backtrace(Astar(second, meet[0],player1.toArray( new Point[player1.size()] ),player1.size(),0)); for(i = 1; i < meet_points + 1; i++) { ArrayList<Point> temp =(new ArrayList<Point> (player1.subList(player2.size(), player1.size()-1))); player2.addAll(backtrace(Astar(meet[i-1], meet[i], (temp.toArray(new Point[temp.size()])),temp.size(),player2.size()))); } if(player1.size() > player2.size()) { player1.remove(player1.size()-1); } else { player2.remove(player2.size()-1); } print_route(player1, player2); } // If file is not valid catch(Exception e) { e.printStackTrace(); System.out.println("Exception is raised"); } } }
package controller; import java.io.File; import java.util.List; import javafx.application.Application; import javafx.stage.Stage; public class MainController extends Application { private UserInterface userInterface; public static void main(String[] args) throws Exception { Parser.parserXml("gridInput.xml"); launch(args); } @Override public void start(Stage s) throws Exception { // create our UI userInterface = new UserInterface(s, this); } public void initializeSimulationWithData(File XMLData) { try { @SuppressWarnings("unchecked") List<TestCell> cellList = Parser.parserXml(XMLData .getAbsolutePath()); initializeSimulationObjects(cellList); } catch (Exception e) { System.out.println("Error processing file, make sure it's XML."); } } private void initializeSimulationObjects(List<TestCell> cellList){ for (TestCell c : cellList){ try { //create a patch object at the x and y location //create a cell object String classPathAndName = "simulationObjects."+c.cellType; Class<?> cellClass = Class.forName(classPathAndName); System.out.println(cellClass); Object cell = cellClass.newInstance(); //assign the cell to the patch //add the patch to grid manager } catch (ClassNotFoundException e) { System.out.println("One or more cell classes from your XML file could not be found."); } catch (InstantiationException e) { System.out.println("One or more paramaters could not be applied to the simulation."); } catch (IllegalAccessException e) { System.out.println("Couldn't create a class from the XML file: illegal access."); } } } public void startSimulation() { // TODO Auto-generated method stub } public void stopSimulation() { // TODO Auto-generated method stub } public void stepSimulation() { // TODO Auto-generated method stub } }
// Sample JFrame stuff import javax.swing.JFrame; import javax.swing.JButton; import javax.swing.JOptionPane; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class Sample extends JFrame { private final JButton b = new JButton(); public Sample() { super(); this.setTitle("HellISISopp"); this.getContentPane().setLayout(null); this.setBounds(100, 100, 180, 140); this.add(makeButton()); this.setVisible(true); this.setDefaultCloseOperation(EXIT_ON_CLOSE); } private JButton makeButton() { b.setText("Click me!"); b.setBounds(40, 40, 100, 30); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(b, "Hello World!"); } }); return b; } public static void main(String[] args) { new Sample(); } }
package perl.aaron.TruthTrees; import java.awt.Color; import java.awt.FontMetrics; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import perl.aaron.TruthTrees.logic.AtomicStatement; import perl.aaron.TruthTrees.logic.Decomposable; import perl.aaron.TruthTrees.logic.Statement; import perl.aaron.TruthTrees.logic.Negation; /** * A class that represents a single line in a branch, used for storing and verifying decompositions * @author Aaron * */ public class BranchLine { protected Branch parent; protected Statement statement; // protected Set<Set<BranchLine>> decomposition; protected Set<Branch> selectedBranches; // holds the parent of the split that decomposes this line protected Set<BranchLine> selectedLines; protected BranchLine decomposedFrom; protected boolean isPremise; public static final Color SELECTED_COLOR = new Color(0.3f,0.9f,0.9f); public static final Color DEFAULT_COLOR = Color.LIGHT_GRAY; public static final Color EDIT_COLOR = Color.GREEN; public BranchLine(Branch branch) { parent = branch; statement = null; // decomposition = new LinkedHashSet<Set<BranchLine>>(); selectedBranches = new LinkedHashSet<Branch>(); selectedLines = new LinkedHashSet<BranchLine>(); isPremise = false; } public String toString() { if (statement != null) return statement.toString(); return ""; } public void setIsPremise(boolean isPremise) { this.isPremise = isPremise; } public boolean isPremise() { return isPremise; } public void setStatement(Statement statement) { this.statement = statement; } public Statement getStatement() { return statement; } public int getWidth(FontMetrics f) { return f.stringWidth(toString()); } public Set<BranchLine> getSelectedLines() { return selectedLines; } public Set<Branch> getSelectedBranches() { return selectedBranches; } public void setDecomposedFrom(BranchLine decomposedFrom) { this.decomposedFrom = decomposedFrom; } public BranchLine getDecomposedFrom() { return decomposedFrom; } public Branch getParent() { return parent; } public String verifyDecomposition() { // Check if the statement is decomposable and it is not the negation of an atomic statement if (statement == null) return null; if (decomposedFrom == null && !isPremise) { if (!verifyIsBranchOn()) { // also check if the statement is not branching on any statement + negation of that statement return "Unexpected statement \"" + statement.toString() + "\" in tree"; } else { return null; } } if (statement instanceof Decomposable && !(statement instanceof Negation && (((Negation)statement).getNegand() instanceof AtomicStatement))) { if (selectedBranches.size() > 0) // branching decomposition (disjunction) { Set<BranchLine> usedLines = new LinkedHashSet<BranchLine>(); for (Branch curRootBranch : selectedBranches) { List<List<Statement>> curTotalSet = new ArrayList<List<Statement>>(); for (Branch curBranch : curRootBranch.getBranches()) { List<Statement> curBranchSet = new ArrayList<Statement>(); for (BranchLine curLine : selectedLines) { if (curLine.getParent() == curBranch) { curBranchSet.add(curLine.getStatement()); usedLines.add(curLine); } } curTotalSet.add(curBranchSet); } if (selectedLines.size() > 0 && !((Decomposable)statement).verifyDecomposition(curTotalSet, parent.getConstants(), parent.getConstantsBefore(selectedLines.iterator().next()))) return "Invalid decomposition of statement \"" + statement.toString() + "\""; } if (!usedLines.equals(selectedLines)) // extra lines that were unused return "Too many statements decomposed from \"" + statement.toString() + "\""; if (!BranchLine.satisfiesAllBranches(parent, selectedBranches)) return "Statement \"" + statement.toString() + "\" not decomposed in every child branch"; } else // non-branching decomposition (conjunction) { // A map of leaf branches to a list of statements in that branch and up that are selected Map<Branch, List<Statement>> branchMap = new LinkedHashMap<Branch, List<Statement>>(); Set<Branch> selectedBranches = new LinkedHashSet<Branch>(); // Add all branches that contain selected lines for (BranchLine curLine : selectedLines) { selectedBranches.add(curLine.getParent()); } for (BranchLine curLine : selectedLines) { List<Statement> curList = null; // Check if this branch is in the map and add the statement to it if (branchMap.containsKey(curLine.getParent())) curList = branchMap.get(curLine.getParent()); else // Check for child branches and add this line to all of those { boolean foundChildren = false; for (Branch curBranch : selectedBranches) { if (curBranch != curLine.getParent() && curBranch.isChildOf(curLine.getParent())) { System.out.println("Found child of " + curLine.getStatement()); foundChildren = true; if (branchMap.containsKey(curBranch)) { branchMap.get(curBranch).add(curLine.getStatement()); } else { List<Statement> newList = new ArrayList<Statement>(); newList.add(curLine.getStatement()); branchMap.put(curBranch, newList); } } } if (!foundChildren) { curList = new ArrayList<Statement>(); branchMap.put(curLine.getParent(), curList); } } if (curList != null) curList.add(curLine.getStatement()); } for (Branch curBranch : branchMap.keySet()) { List<List<Statement>> currentDecomp = new ArrayList<List<Statement>>(); currentDecomp.add(branchMap.get(curBranch)); if (!((Decomposable) statement).verifyDecomposition(currentDecomp, curBranch.getConstants(), curBranch.getConstantsBefore(selectedLines.iterator().next()))) { return "Invalid decomposition of statement \"" + statement.toString() + "\""; } } if (branchMap.size() == 0) { List<List<Statement>> currentDecomp = Collections.emptyList(); Set<String> constants = Collections.emptySet(); if (!((Decomposable) statement).verifyDecomposition(currentDecomp,constants,constants)) return "Statement \"" + statement.toString() + "\" has not been decomposed!"; else return null; } if(!BranchLine.satisfiesAllBranches(parent, branchMap.keySet())) { return "Statement \"" + statement.toString() + "\" not decomposed in every child branch"; } } } return null; } /** * Verifies if this statement is part of a statement and its negation branching (branch on any P and ~P, for example) * @return true if this is a valid BranchOn, false otherwise */ private boolean verifyIsBranchOn() { // if the direct root has more or less than 2 branches, or if this BranchLine is not the first BranchLine in this branch, // then will return false if (parent.getRoot() == null || parent.getRoot().getBranches().size() != 2 || !parent.getStatement(0).equals(statement)) { return false; } else { // compare to the first BranchLine in the sister branch to see if they are each other's negations Iterator<Branch> branchItr = parent.getRoot().getBranches().iterator(); while (branchItr.hasNext()) { Branch temp = branchItr.next(); if (!temp.getStatement(0).equals(statement)) { // then it is the other branch in this set of two branches if ((temp.getStatement(0) instanceof Negation && ((Negation)temp.getStatement(0)).getNegand().equals(statement)) || (statement instanceof Negation && ((Negation)statement).getNegand().equals(temp.getStatement(0))) ) { return true; } else { return false; } } } return false; } } public static boolean satisfiesAllBranches(Branch root, Set<Branch> descendents) { if (descendents.contains(root) || root.isClosed()) return true; else { if (root.getBranches().size() > 0) { for (Branch curBranch : root.getBranches()) { if (!satisfiesAllBranches(curBranch, descendents)) return false; } return true; } else return false; } } }
import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.Map; public class CommandGet extends Command { public CommandGet(String path, boolean http1, Map<String, String> info) { super(path, http1, info, null); } @Override public String getResponse() { String response = ""; // HTTP 1.1 or 1.0, and must close after this request? if (http1) { response = "HTTP/1.1 "; if (info.containsKey("connection") && info.get("connection").equalsIgnoreCase("close")) this.mustClose = true; } else { response = "HTTP/1.0 "; this.mustClose = true; } // REST OF THE RESPONSE String currentDate = getCurrentDate(); if (isBadRequest()) { // Bad Request // STATUS response += "400 Bad Request\r\n"; // DATE response += "Date: " + currentDate + "\r\n"; } else { try { File file = new File("www"+this.path); String contentType = Files.probeContentType(file.toPath()); long nbBytes = getNbBytes(readFile(file.getPath(), StandardCharsets.UTF_8)); String fileContent = readFile(file.getPath(), StandardCharsets.UTF_8); // STATUS response += "200 OK\r\n"; // DATE response += "Date: " + currentDate + "\r\n"; // CONTENT-TYPE response += "Content-Type: " + contentType +"\r\n"; // CONTENT-LENGTH response += "Content-Length: " + nbBytes +"\r\n"; // CONTENT response += "\r\n"; response += fileContent; } catch (IOException e) { // Not Found response += "404 Not Found\r\n"; // DATE response += "Date: " + currentDate + "\r\n"; } } return response; } @Override public boolean mustClose() { return true; } }
package Tuple; import java.util.ArrayList; import java.util.List; /** * Tuple<E> contains two objects of type E. * @param <E> */ public class Tuple<E> { public E x, y; public Tuple(){ x = null; y = null; } /** * Stores two objects obj1 and obj2 in that order. The objects are * referenced by x and y respectively. * @param obj1 * 1st Object * @param obj2 * 2nd Object of Same Type */ public Tuple(E obj1, E obj2){ x = obj1; y = obj2; } @SuppressWarnings("unchecked") public boolean equals(Object other){ try{ Tuple<E> castedOther = (Tuple<E>) other; return castedOther.x.equals(x) && castedOther.y.equals(y); }catch(Exception e){ return false; } } /** * Reverses the order of the tuple. Transforms Tuple(a, b) to Tuple(b, a). */ public void reverse(){ E temp = x; x = y; y = temp; } @Override public String toString(){ return "(" + x.toString() + ", " + y.toString() + ")"; } /** * Returns a shallow clone of the tuple. Object references are simply * copied. * @return new Tuple<E>(x, y) */ public Tuple<E> clone(){ return new Tuple<E>(x, y); } /** * Returns list containing the toStrings of x and y. * @return List */ public List<String> toListString(){ List<String> ret = new ArrayList<String>(); ret.add(x.toString()); ret.add(y.toString()); return ret; } /** * Returns a list containing x and y. * @return List */ public List<E> toList(){ List<E> ret = new ArrayList<E>(); ret.add(x); ret.add(y); return ret; } @Override public int hashCode() { return x.toString().hashCode() + y.toString().hashCode(); } /** * Sorts (if possible) the tuple. */ @SuppressWarnings("unchecked") public void sort(){ try{ if(((Comparable<E>) x).compareTo(y) > 0){ reverse(); } }catch(Exception e){ //do nothing } } }
package server; import java.net.*; import java.io.*; import message.*; public class CommunicationAnalyzer implements Runnable { private Socket socket = null; private RemoteReferenceModule rrm = null; private DispatchingModule dispatcher = null; public CommunicationAnalyzer(Socket socket, RemoteReferenceModule rrm, DispatchingModule dispatcher) { this.socket = socket; this.rrm = rrm; this.dispatcher = dispatcher; } public void run() { try { ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream()); ObjectInputStream in = new ObjectInputStream( socket.getInputStream()); Object object = null; RequestMessage requestMessage = null; boolean trueBoolean = true; while (trueBoolean) { try { object = in.readObject(); requestMessage = (RequestMessage) object; } catch (ClassNotFoundException e) { e.printStackTrace(); } ReplyMessage replyMessage = dispatcher.dispatchCall(requestMessage, rrm.retrieve(requestMessage.to)); if (replyMessage == null) continue; out.writeObject(replyMessage); } socket.close(); } catch (IOException e) { e.printStackTrace(); } } /*private RequestMessage deserializeRequestMessage(BufferedReader in) { RequestMessage message = null; try { ObjectInputStream objIn = new ObjectInputStream(in); e = (Employee) objIn.readObject(); objIn.close(); } catch(IOException i) { i.printStackTrace(); return null; } catch(ClassNotFoundException c) { System.out.println("Employee class not found"); c.printStackTrace(); return null; } }*/ }
import java.util.*; import javax.swing.JOptionPane; public class Controller { UserGui guiObj; Sort sortObj; Search searchObj; static FileHandler fileHandlerObj; CommandFetch fetchObj = new CommandFetch(this); static Table testTable; public static String aTable = ""; // String userCommand; public Controller(UserGui _gui){ guiObj = _gui; sortObj = new Sort(); searchObj = new Search(); fileHandlerObj = new FileHandler(); ArrayList<Field> newField = new ArrayList<Field>(); newField.add(new Field(Field.KEY.PRIMARY, Field.TYPE.INTEGER,"ID")); newField.add(new Field(Field.TYPE.VARCHAR,"Name")); testTable = new Table(newField,"testTable"); String names[] = {"Alan Lee","Matt","Ronnie","Joy","Park"}; for (int i=0;i<names.length;i++){ Record newRecord = new Record(testTable); // create record : specify table to check added data type try{ newRecord.addValue(new Value(testTable.getField("Name"),names[i])); }catch(TableException e){ System.out.println(e.getMessage()); } try{ newRecord.addValue(new Value(testTable.getField("ID"),i)); }catch(TableException e){ System.out.println(e.getMessage()); } if(!testTable.addRow(newRecord)){ System.out.println("Failed to add row"); } } System.out.println(sortObj.orderBy(testTable, "ID", true).toString()); } public Table getCommand(String _input){ //Deliver this input string to command fetch System.out.println(_input); //test fetchObj.loader(_input); //Matt: something like this? return fileHandlerObj.getFile(aTable + ".txt"); } // THESE METHODS FOR CREATING TABLES public static void createTable(String tName, ArrayList<String> colNames, ArrayList<String> dataTypes) { ArrayList<Field> theFields = new ArrayList<Field>(); try { for (int i = 0; i < colNames.size(); i++) { Field.TYPE theType = getDataType(dataTypes.get(i)); Field.KEY theKey = getKey(colNames.get(i)); if (theKey == Field.KEY.FOREIGN) { if (theType != Field.TYPE.INTEGER) { throw new DataFormatException("ERROR: Foreign Keys must be an integer"); } String refTable = JOptionPane.showInputDialog(null, "Please enter the reference table for the field " + colNames.get(i), "Foreign Key", JOptionPane.INFORMATION_MESSAGE); Field aField = new Field(theKey, theType, colNames.get(i)); if (fileHandlerObj.getFile(refTable + ".txt") == null) { throw new CriticalExistanceFailure("ERROR: Referenced Table [" + refTable + "] doesn't exist"); } aField.setForeignKey(refTable); theFields.add(aField); } else { theFields.add(new Field(theKey, theType, colNames.get(i))); } aTable = tName; } Table newTable = new Table(theFields, tName); //I need to add this new table some sort of DB object? fileHandlerObj.setFile(tName + ".txt", newTable); //DEBUG MESSAGE System.out.println(newTable.toString()); } catch(DataFormatException | CriticalExistanceFailure z) { JOptionPane.showMessageDialog(null, z.getMessage(), "whoops", JOptionPane.ERROR_MESSAGE); } } //this interprets the data type public static Field.TYPE getDataType(String a) { Field.TYPE temp = Field.TYPE.NULL; if (a.equalsIgnoreCase("STRING")) { temp = Field.TYPE.VARCHAR; } else { if (a.equalsIgnoreCase("INT")) { temp = Field.TYPE.INTEGER; } else { if (a.equalsIgnoreCase("DOUBLE")) { temp = Field.TYPE.DOUBLE; } else { if (a.equalsIgnoreCase("DATE")) { temp = Field.TYPE.DATE; } } } } return temp; } //this interprets the key public static Field.KEY getKey(String a) { Field.KEY temp; if (a.charAt(0) == 'P' && a.charAt(1) == 'K') { temp = Field.KEY.PRIMARY; } else { if (a.charAt(0) == 'F' && a.charAt(1) == 'K') { temp = Field.KEY.FOREIGN; } else { temp = Field.KEY.NORMAL; } } return temp; } // THIS METHOD FOR INSERTING INTO TABLES (adding records?) public static void insertTable(String tName, ArrayList<String> fields, ArrayList<String> values) { try { Table activeTable = fileHandlerObj.getFile(tName + ".txt"); if (activeTable == null) { throw new CriticalExistanceFailure("ERROR: Referenced Table [" + tName + "] doesn't exist"); } Record newRecord = new Record(activeTable); for (int i = 0; i < fields.size(); i++) { for (int f = 0; f < activeTable.alRecord.size(); f++) { int h = 0; if ((int)(activeTable.alRecord.get(f).getAlValue().get(h).data) == Integer.parseInt(values.get(0))) { throw new DataFormatException("ERROR: An entry with the primary key [" + values.get(0) + "] already exists in the table [" + tName + "]!"); } } if (activeTable.alField.get(i).fName.equalsIgnoreCase(fields.get(i)) == false) { throw new CriticalExistanceFailure("ERROR: The field [" + fields.get(i) + "] does not exist in table [" + tName + "]!"); } try{ newRecord.addValue(new Value(activeTable.getField(fields.get(i)), values.get(i))); }catch(TableException e){ JOptionPane.showMessageDialog(null, e.getMessage(), "whoops", JOptionPane.ERROR_MESSAGE); } } activeTable.addRow(newRecord); //DEBUG MESSAGE System.out.println(activeTable.toString()); //This method will then have to save the additions to the table fileHandlerObj.setFile(tName + ".txt", activeTable); aTable = tName; } catch(CriticalExistanceFailure | DataFormatException z) { JOptionPane.showMessageDialog(null, z.getMessage(), "whoops", JOptionPane.ERROR_MESSAGE); } } //THESE METHODS FOR DELETING THINGS public static void deleteAllRows(String tName) { try { Table activeTable = fileHandlerObj.getFile(tName + ".txt"); if (activeTable == null) { throw new CriticalExistanceFailure("ERROR: Referenced Table [" + tName + "] doesn't exist"); } activeTable.alRecord.clear(); //TABLE SAVE GOES HERE fileHandlerObj.setFile(tName + ".txt", activeTable); aTable = tName; } catch(CriticalExistanceFailure z) { JOptionPane.showMessageDialog(null, z.getMessage(), "whoops", JOptionPane.ERROR_MESSAGE); } } public static void deleteTable(String tName) { try { if (fileHandlerObj.getFile(tName + ".txt") == null) { throw new CriticalExistanceFailure("ERROR: Referenced Table [" + tName + "] doesn't exist"); } //PLEASE DOUBLE CHECK WITH PARK TO SEE IF THIS WILL WORK fileHandlerObj.deleteFile(tName); aTable = tName; } catch(CriticalExistanceFailure z) { JOptionPane.showMessageDialog(null, z.getMessage(), "whoops", JOptionPane.ERROR_MESSAGE); } } public static void deleteRow(String tName, int pKey) { try { Table activeTable = fileHandlerObj.getFile(tName + ".txt"); if (activeTable == null) { throw new CriticalExistanceFailure("ERROR: Referenced Table [" + tName + "] doesn't exist"); } boolean found = false; for (int i = 0; i < activeTable.alRecord.size(); i++) { for (int z = 0; z < activeTable.alField.size(); z++) { if (activeTable.alRecord.get(i).getAlValue().get(z).compareTo(String.valueOf(pKey)) == 0 && activeTable.alField.get(z).fKey == Field.KEY.PRIMARY) { activeTable.alRecord.remove(i); found = true; break; } } if (found) break; } if (!found) { throw new CriticalExistanceFailure("ERROR: Entry No." + pKey + " in [" + tName + "] doesn't exist"); } //and then a table save/display update goes here fileHandlerObj.setFile(tName + ".txt", activeTable); aTable = tName; } catch(CriticalExistanceFailure z) { JOptionPane.showMessageDialog(null, z.getMessage(), "whoops", JOptionPane.ERROR_MESSAGE); } } //THIS METHOD FOR UPDATING FIELDS IN TABLES public static void updateField(String tName, int pKey, String field, String value) { try { Table activeTable = fileHandlerObj.getFile(tName + ".txt"); //Table activeTable = testTable; if (activeTable == null) { throw new CriticalExistanceFailure("ERROR: Referenced Table [" + tName + "] doesn't exist"); } //DEBUG MESSAGE System.out.println("BEFORE: " + testTable.toString()); //find the correct index using the PK int row = 0; boolean found = false; boolean found2 = false; for (int i = 0; i < activeTable.alRecord.size(); i++) { for (int z = 0; z < activeTable.alField.size(); z++) { if (String.valueOf(activeTable.alRecord.get(i).getAlValue().get(z).data).compareTo(String.valueOf(pKey)) == 0 && activeTable.alField.get(z).fKey == Field.KEY.PRIMARY) { row = i; found = true; //DEBUG MESSAGE System.out.println("THE ROW IS " + i); break; } } if (found) break; } if (!found) { throw new CriticalExistanceFailure("ERROR: Entry No." + pKey + " in [" + tName + "] does not exist"); } for (int i = 0; i < activeTable.alField.size(); i++) { if (activeTable.alRecord.get(row).getAlValue().get(i).field.compareTo(field) == 0) { //DEBUG MESSAGE System.out.println("TEST"); found2 = true; activeTable.alRecord.get(row).getAlValue().get(i).data = value; aTable = tName; } } if (!found2) { throw new CriticalExistanceFailure("ERROR: Field [" + field + "] does not exist"); } //DEBUG MESSAGE System.out.println("AFTER: " + activeTable.toString()); //TABLE SAVE GOES HERE fileHandlerObj.setFile(tName + ".txt", activeTable); } catch(CriticalExistanceFailure z) { JOptionPane.showMessageDialog(null, z.getMessage(), "whoops", JOptionPane.ERROR_MESSAGE); } } public void doSelect(CommandSet command){ System.out.println("SE:"+command.tableName); Table tTable = fileHandlerObj.getFile(command.tableName+".txt"); String whereC = command.whereC; String orderC = command.orderC; boolean orderDir = command.orderDir; Table resultTbl = tTable.clone(); System.out.println("tTable:"+tTable); System.out.println("rTable:"+resultTbl); resultTbl = selectField(command.colNames,resultTbl); System.out.println("WHERE:"+whereC); if(!whereC.equalsIgnoreCase("")){ System.out.println("Start Search=================="); try{ resultTbl = searchObj.doSearch(tTable, whereC); System.out.println("1st"+resultTbl.toString()); //resultTbl = selectField(command.colNames,resultTbl); }catch(SearchException ex){ System.out.println(ex.getMessage()); } } System.out.println("ORDERBY:"+orderC); if(!orderC.equalsIgnoreCase("")){ try{ resultTbl = sortObj.orderBy(resultTbl, orderC, orderDir); System.out.println("After orderBy ================"); System.out.println(resultTbl.toString()); }catch(Exception ex){ System.out.println(ex.getMessage()); } } resultTbl = selectField(command.colNames,resultTbl); System.out.println("Final Table ===========================" ); System.out.println(resultTbl); aTable = resultTbl.tableName; guiObj.updateContents(resultTbl); /* CommandSet selectC = new CommandSet(); selectC.fullCommand = command; selectC.tableName = tableName; selectC.joinTableName = joinTableName; selectC.colNames = colNames; selectC.whereC = fetchWhere(command); selectC.orderC = fetchField(command); selectC.orderDir = fetchDir(command);*/ } public Table selectField(ArrayList<String> _colNames, Table _targetTable){ Table resultTbl = _targetTable.clone(); resultTbl.alRecord = new ArrayList<Record>(); ArrayList<Field> alNewField = new ArrayList<Field>(); ArrayList<Integer> alIndex = new ArrayList<Integer>(); if(_colNames.get(0).equals("*")){ return _targetTable; } for (int i=0;i<_colNames.size();i++){ String colName = _colNames.get(i); int idx = _targetTable.getFieldIdx(colName); if(idx >= 0){ try{ alNewField.add(_targetTable.getField(idx)); alIndex.add(idx); //accumulate valied index numbers }catch(Exception e){ System.out.println(e.getMessage()); } } // System.out.println("Index AL:"+alIndex); } resultTbl.alField = alNewField; ArrayList<Record> alRecordR = new ArrayList<Record>(); for (int i=0;i<_targetTable.alRecord.size();i++){ Record sampleR = _targetTable.alRecord.get(i); //get n-th row record object Record returnR = new Record(resultTbl); //create New Record to be generated as a result record for (int j=0;j<alIndex.size();j++){ int index = alIndex.get(j); returnR.addValue(sampleR.getValue(index)); } resultTbl.addRow(returnR); } return resultTbl; } } //CONTROLLER-SIDE ERROR HANDLING GOES IN THIS SECTION //This exception for data not matching the datatype class DataFormatException extends Exception { public DataFormatException(String message) { super(message); } } //this exception if a table or field does not exist class CriticalExistanceFailure extends Exception { public CriticalExistanceFailure(String message) { super(message); } }
package dta_solver; import generalLWRNetwork.Cell; import generalLWRNetwork.Junction; import generalNetwork.state.CellInfo; import generalNetwork.state.JunctionInfo; import generalNetwork.state.State; import generalNetwork.state.internalSplitRatios.IntertemporalSplitRatios; import generalNetwork.state.internalSplitRatios.JunctionSplitRatios; import cern.colt.matrix.tdouble.DoubleMatrix1D; import cern.colt.matrix.tdouble.DoubleFactory1D; import cern.colt.matrix.tdouble.algo.DenseDoubleAlgebra; import cern.colt.matrix.tdouble.impl.DenseDoubleMatrix1D; import cern.colt.matrix.tdouble.impl.SparseCCDoubleMatrix2D; import dataStructures.Numerical; public class SOPC_Optimizer extends SO_Optimizer { public SOPC_Optimizer(int maxIter, Simulator simu) { super(maxIter, simu); simulator.initializSplitRatios(); } /** * @brief Computes the derivative dJ/dU * @details * The condition \beta >= 0 is already put in the solver (in * AdjointJVM/org.wsj/Optimizers.scala) do there is only one barrier * in J */ @Override public DoubleMatrix1D djdu(State state, double[] control) { return DoubleFactory1D.dense.make(T * temporal_control_block_size); } /** * @details This function imposes that the control is physical (every split * ratio is positive) */ @Override public double objective(double[] control) { /* Inforces control[i] >= 0, \forall i */ for (int i = 0; i < control.length; i++) if (control[i] < 0) assert false : "Negative control " + control[i]; // return Double.MAX_VALUE; return objective(forwardSimulate(control), control); } /** * @brief Computes the objective function: * \sum_(i,c,k) \rho(i,c,k) * - \sum_{origin o} epsilon2 * ln(\sum \rho(o,c,k) - 1) * @details * The condition \beta >= 0 is already put in the solver (in * AdjointJVM/org.wsj/Optimizers.scala) do there is only one barrier * in J */ public double objective(State state, double[] control) { double objective = 0; /* * To compute the sum of the densities ON the network, we add the density of * all the cells and then remove the density of the sinks */ for (int k = 0; k < T; k++) { for (int cell_id = 0; cell_id < cells.length; cell_id++) objective += state.profiles[k].getCell(cell_id).total_density; for (int d = 0; d < destinations.length; d++) objective -= state.profiles[k].getCell(destinations[d].getUniqueId()).total_density; } return objective; } /* Returns the position of rho(i, c)(k) */ private int rho(int k, int i, int c) { return k * x_block_size + (C + 1) * i + c; } private int f_in(int k, int i, int c) { return k * x_block_size + f_in_position + (C + 1) * i + c; } private int f_out(int k, int i, int c) { return k * x_block_size + f_out_position + (C + 1) * i + c; } public DoubleMatrix1D lambdaByAdjointMethod(State state, double[] control) { DoubleMatrix1D lambda = new DenseDoubleMatrix1D(T * x_block_size); double delta_t = simulator.time_discretization.getDelta_t(); IntertemporalSplitRatios internal_SR = simulator.lwr_network.getInternal_split_ratios(); for (int k = T - 1; k >= 0; k if (k < T - 1) { /* We first solve f_in */ for (int cell_id = 0; cell_id < cells.length; cell_id++) { for (int c = 0; c < (C + 1); c++) { if (!cells[cell_id].isBuffer() && !cells[cell_id].isSink()) { double value = delta_t / cells[cell_id].getLength() * lambda.get(rho(k + 1, cell_id, c)); assert Numerical.validNumber(value); lambda.set(f_in(k, cell_id, c), value); } } } } /* We solve f_out */ for (int junction_id = 0; junction_id < junctions.length; junction_id++) { Junction junction = junctions[junction_id]; Cell[] in_links = junction.getPrev(); Cell[] out_links = junction.getNext(); JunctionSplitRatios junction_SR = internal_SR.get(k, junction_id); for (int c = 0; c < (C + 1); c++) { for (int in_link = 0; in_link < in_links.length; in_link++) { int in_link_id = in_links[in_link].getUniqueId(); double value = 0; for (int out_link = 0; out_link < out_links.length; out_link++) { int out_link_id = out_links[out_link].getUniqueId(); double beta; /* For the Nx1 junctions the split ratios are always 1 */ if (junction.isMergingJunction()) { assert junction_SR == null; beta = 1; /* For other junctions, it is registered except if it is 0 */ } else { assert junction_SR != null; Double beta_res = junction_SR.get(in_link_id, out_link_id, c); if (beta_res == null) continue; beta = beta_res.doubleValue(); } value += beta * lambda.get(f_in(k, out_link_id, c)); } if (k < T - 1) value -= delta_t / cells[in_link_id].getLength() * lambda.get(rho(k + 1, in_link_id, c)); assert Numerical.validNumber(value); lambda.set(f_out(k, in_link_id, c), value); } } } /* We solve the aggregate split ratios */ /* We solve the partial densities */ for (int cell_id = 0; cell_id < cells.length; cell_id++) { /* The increase of the density of a sink has no influence */ if (cells[cell_id].isSink()) continue; for (int c = 0; c < (C + 1); c++) { double value = cells[cell_id].getLength(); if (k < T - 1) value += lambda.get(rho(k + 1, cell_id, c)); lambda.set(rho(k, cell_id, c), value); } } if (k == T - 1) continue; for (int j_id = 0; j_id < junctions.length; j_id++) { Junction junction = junctions[j_id]; JunctionInfo junction_info = state.get(k).getJunction(j_id); Cell[] in_links = junction.getPrev(); Cell[] out_links = junction.getNext(); int nb_prev = in_links.length; int nb_next = out_links.length; // 1xN junctions if (nb_prev == 1) { if (junction_info.is_demand_limited()) { int limiting_demand_id = in_links[0].getUniqueId(); double total_density = state.get(k).getCell(limiting_demand_id).total_density; for (int c = 0; c < (C + 1); c++) { double value = lambda.get(rho(k, limiting_demand_id, c)) + in_links[0].getDerivativeDemand(total_density, delta_t) * lambda.get(f_out(k, limiting_demand_id, c)); assert Numerical.validNumber(value); lambda.set(rho(k, limiting_demand_id, c), value); } } else if (junction_info.is_supply_limited()) { int limiting_outgoing_link_id = junction_info.getLimiting_supply(); Cell limiting_outgoing_link = cells[limiting_outgoing_link_id]; // 1xN junctions if (nb_prev == 1) { int in_cell_id = in_links[0].getUniqueId(); CellInfo in_cell = state.get(k).getCell(in_cell_id); double total_density = in_cell.total_density; assert total_density != 0; double value = 0; Double aggr_beta = junction_info.getAggregateSR(in_cell_id, limiting_outgoing_link_id); assert (aggr_beta != 0 && aggr_beta != null); /* We compute the upstream effect */ for (int c = 0; c < (C + 1); c++) { Double partial_density = in_cell.partial_densities.get(c); if (partial_density == null) continue; value += partial_density / total_density / aggr_beta * lambda.get(f_out(k, in_cell_id, c)); } double limiting_density = state .get(k) .getCell(limiting_outgoing_link).total_density; double backspeed = limiting_outgoing_link .getDerivativeSupply(limiting_density); value = backspeed * value; for (int c = 0; c < (C + 1); c++) { lambda.set(rho(k, limiting_outgoing_link_id, c), lambda.get(rho(k, limiting_outgoing_link_id, c)) + value); } /* We compute the downstream effect */ double supply = junction_info.getFlowOut(in_cell_id) * aggr_beta; double rho_aggrSR = total_density * aggr_beta; /* Update of rho(k, in_cell_id, c) */ for (int c = 0; c < (C + 1); c++) { for (int c2 = 0; c2 < (C + 1); c2++) { Double partial_density = in_cell.partial_densities.get(c2); double tmp_value = 0; if (partial_density == null) partial_density = 0.0; JunctionSplitRatios JSR = internal_SR.get(k, j_id); double SR; if (JSR == null) { SR = 1; } else { Double res = JSR.get(in_cell_id, limiting_outgoing_link_id, c); if (res == null) SR = 0; else SR = res.doubleValue(); } if (c2 == c) { tmp_value = (total_density * aggr_beta) - partial_density * SR; } else { tmp_value = -partial_density * SR; } tmp_value *= supply / (total_density * aggr_beta) / (total_density * aggr_beta); assert Numerical.validNumber(tmp_value); lambda.set(rho(k, in_cell_id, c), lambda.get(rho(k, in_cell_id, c)) + tmp_value * lambda.get(f_out(k, in_cell_id, c2))); } } } else { System.out.println("Case not handled yet"); System.exit(1); } } else { System.out .println("[Critical]The junction " + j_id + " at time step " + k + " is neither demand nor supply limited. Adjoint descent not defined !"); // System.exit(1); } } else { System.out.println("Case not handled yet"); System.exit(1); } } } return lambda; } public double[] gradientByAdjointMethod(State state, double[] control) { DoubleMatrix1D lambda = lambdaByAdjointMethod(state, control); DenseDoubleAlgebra dAlg = new DenseDoubleAlgebra(); SparseCCDoubleMatrix2D dhduT = dhdu(state, control).getTranspose(); DoubleMatrix1D gradient = dAlg.mult(dhduT, lambda); return gradient.toArray(); } /** * @brief We project the gradient given by the adjoint */ public void gradient(double[] gradient_f, double[] control) { State state = forwardSimulate(control); double[] g2 = gradientByAdjointMethod(state, control); projectGradient(gradient_f, g2); } public void projectGradient(double[] gradient_f, double[] init_gradient) { for (int k = 0; k < T; k++) { int index = 0; for (int o = 0; o < O; o++) { double average = 0; int nb_commodities = sources[o].getCompliant_commodities().size(); if (nb_commodities == 0) { System.out .println("[Warning] In Computation of the gradient by finite diff. 0 commodities"); continue; } for (int c = 0; c < nb_commodities; c++) { average += init_gradient[k * C + index + c]; } average /= nb_commodities; for (int c = 0; c < nb_commodities; c++) gradient_f[k * C + index + c] = init_gradient[k * C + index + c] - average; index += nb_commodities; } } } }
import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /* * A simple HTTP Client application * * Computer Networks, KU Leuven. * * Arne De Brabandere * Ward Schodts */ class HTTPClient { /** * Log file: log.txt */ public static LogFile logFile = new LogFile("log.txt"); public static void main(String[] args) throws Exception { // if the arguments are invalid, then print the description of how to specify the program arguments if (! validArguments(args)) { printHelp(); } else { // add command string to log file logFile.addLine("\n" + "Command:" + "\n\n" + args[0] + " " + args[1] + " " + args[2] + " " + args[3]); // get arguments String command = args[0]; String uriString = args[1]; String portString = args[2]; String version = args[3]; // get URI object from uriString URI uri = getURI(uriString); // get port int int port = Integer.parseInt(portString); executeCommand(command, uri, port, version); // add separator to log file logFile.addLine(" } } /** * Print the description of how to specify the program arguments. */ public static void printHelp() { // TODO System.out.println("The argument that you entered were wrong:"); System.out.println("HEAD url(starting with or without http) port(usuallly 80) httpversion(1.0 or 1.1)"); System.out.println("GET url port httpversion"); System.out.println("PUT url port httpversion"); System.out.println("POST url port httpversion"); } /** * Get URI object from given URI string * @param uriString String value of the given URI */ private static URI getURI(String uriString) throws Exception { if (! uriString.startsWith("http: uriString = "http://" + uriString; } return new URI(uriString); } /** * Execute the command. * @param command command string * @param uri URI object * @param port port number * @param version http version (1.0 or 1.1) */ private static void executeCommand(String command, URI uri, int port, String version) throws Exception { String path = uri.getPath(); // path to file String host = uri.getHost(); // Connect to the host. Socket clientSocket = null; try { clientSocket = new Socket(host, port); } catch (IOException e) { System.out.println("Unable to connect to " + host + ":" + port); } // Create outputstream (convenient data writer) to this host. DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream()); // Create an inputstream (convenient data reader) to this host BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); // Parse command. try { switch (command) { case "HEAD": head(inFromServer, outToServer, path, host, version); break; case "GET": get(inFromServer, outToServer, path, host, version); break; /*case "PUT": put(inFromServer, outToServer, path, host, version); break;*/ case "POST": post(inFromServer, outToServer, path, host, version); break; } } catch (Exception e) { e.printStackTrace(); } // Close the socket. clientSocket.close(); } private static void head(BufferedReader inFromServer, DataOutputStream outToServer, String path, String host, String version) throws Exception { // Send HTTP command to server. if(version.equals(1.0)) { outToServer.writeBytes("HEAD " + path + " HTTP/" + version + "\r\n\r\n"); } else { outToServer.writeBytes("HEAD " + path + " HTTP/" + version + "\r\n" + "HOST: " + host + "\r\n\r\n"); } logFile.addLine("\n" + "Response:" + "\n"); // Read text from the server String response = ""; while ((response = inFromServer.readLine()) != null) { // print response to screen System.out.println(response); // write response to log file logFile.addLine(response); } } private static void get(BufferedReader inFromServer, DataOutputStream outToServer, String path, String host, String version) throws Exception { // Send HTTP command to server. if(version.equals(1.0)) { outToServer.writeBytes("GET " + path + " HTTP/" + version + "\r\n\r\n"); } else { outToServer.writeBytes("GET " + path + " HTTP/" + version + "\r\n" + "HOST: " + host + "\r\n\r\n"); } logFile.addLine("\n" + "Response:" + "\n"); // Read text from the server String response = ""; String outputString = ""; while ((response = inFromServer.readLine()) != null) { // print response to screen System.out.println(response); // write response to log file logFile.addLine(response); // add line to output in outputString outputString += response; } // Find URI's of embedded objects String pattern = "src=\"(.*?)\""; Pattern r = Pattern.compile(pattern); Matcher m = r.matcher(outputString); while (m.find( )) { System.out.println("Found embedded object: " + m.group(1)); } } /** * Check if the arguments are valid. */ public static boolean validArguments(String[] arguments) { if (arguments.length != 4) return false; if (! arguments[0].equals("HEAD") && ! arguments[0].equals("GET") && ! arguments[0].equals("PUT") && ! arguments[0].equals("POST")) return false; if (! isInteger(arguments[2])) return false; if (! arguments[3].equals("1.0") && ! arguments[3].equals("1.1")) return false; return true; } /** * Check if a string is an integer. */ private static boolean isInteger(String s) { try { Integer.parseInt(s); } catch(NumberFormatException e) { return false; } return true; } ///////////////////////////////////////////////////POST//////////////////////////////////////////////////////////// private static void post(BufferedReader inFromServer, DataOutputStream outToServer, String path, String host, String version) throws Exception { // Send HTTP command to server. if(version.equals(1.0)) { outToServer.writeBytes("HEAD " + path + " HTTP/" + version + "\r\n\r\n"); } else { outToServer.writeBytes("HEAD " + path + " HTTP/" + version + "\r\n" + "HOST: " + host + "\r\n\r\n"); } logFile.addLine("\n" + "Response:" + "\n"); // Read text from the server String response = ""; while ((response = inFromServer.readLine()) != null) { // print response to screen System.out.println(response); // write response to log file logFile.addLine(response); } } }
public class HelloWorld { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("Hello World!"); } }
package org.reactfx.value; import java.time.Duration; import java.util.NoSuchElementException; import java.util.Objects; import java.util.Optional; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import javafx.animation.Interpolatable; import javafx.beans.InvalidationListener; import javafx.beans.property.Property; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.scene.Node; import javafx.scene.Scene; import javafx.stage.Window; import org.reactfx.Change; import org.reactfx.EventStream; import org.reactfx.EventStreamBase; import org.reactfx.EventStreams; import org.reactfx.Observable; import org.reactfx.Subscription; import org.reactfx.collection.LiveList; import org.reactfx.util.HexaFunction; import org.reactfx.util.Interpolator; import org.reactfx.util.PentaFunction; import org.reactfx.util.TetraFunction; import org.reactfx.util.TriFunction; import org.reactfx.util.WrapperBase; /** * Adds more operations to {@link ObservableValue}. * * <p>Canonical observer of {@code Val<T>} is an <em>invalidation observer</em> * of type {@code Consumer<? super T>}, which accepts the _invalidated_ value. * This is different from {@linkplain InvalidationListener}, which does not * accept the invalidated value. */ public interface Val<T> extends ObservableValue<T>, Observable<Consumer<? super T>> { default void addInvalidationObserver(Consumer<? super T> observer) { addObserver(observer); } default void removeInvalidationObserver(Consumer<? super T> observer) { removeObserver(observer); } default Subscription observeInvalidations( Consumer<? super T> oldValueObserver) { return observe(oldValueObserver); } default Subscription pin() { return observeInvalidations(oldVal -> {}); } @Override default void addListener(InvalidationListener listener) { addInvalidationObserver(new InvalidationListenerWrapper<>(this, listener)); } @Override default void removeListener(InvalidationListener listener) { removeInvalidationObserver(new InvalidationListenerWrapper<>(this, listener)); } @Override default void addListener(ChangeListener<? super T> listener) { addInvalidationObserver(new ChangeListenerWrapper<>(this, listener)); } @Override default void removeListener(ChangeListener<? super T> listener) { removeInvalidationObserver(new ChangeListenerWrapper<>(this, listener)); } /** * Adds a change listener and returns a Subscription that can be * used to remove that listener. */ default Subscription observeChanges(ChangeListener<? super T> listener) { return observeInvalidations(new ChangeListenerWrapper<>(this, listener)); } /** * Returns a stream of invalidated values, which emits the invalidated value * (i.e. the old value) on each invalidation of this observable value. */ default EventStream<T> invalidations() { return new EventStreamBase<T>() { @Override protected Subscription observeInputs() { return observeInvalidations(this::emit); } }; } /** * Returns a stream of changed values, which emits the changed value * (i.e. the old and the new value) on each change of this observable value. */ default EventStream<Change<T>> changes() { return EventStreams.changesOf(this); } /** * Returns a stream of values of this {@linkplain Val}. The returned stream * emits the current value of this {@linkplain Val} for each new subscriber * and then the new value whenever the value changes. */ default EventStream<T> values() { return EventStreams.valuesOf(this); } /** * Returns a stream of non-null values of this {@linkplain Val}. The returned stream * emits the current value of this {@linkplain Val} if it is not null for each new subscriber * and then the new value if it is not null whenever the value changes. */ default EventStream<T> nonNullValues() { return EventStreams.nonNullValuesOf(this); } /** * Checks whether this {@linkplain Val} holds a (non-null) value. * @return {@code true} if this {@linkplain Val} holds a (non-null) value, * {@code false} otherwise. */ default boolean isPresent() { return getValue() != null; } /** * Inverse of {@link #isPresent()}. */ default boolean isEmpty() { return getValue() == null; } /** * Invokes the given function if this {@linkplain Val} holds a (non-null) * value. * @param f function to invoke on the value currently held by this * {@linkplain Val}. */ default void ifPresent(Consumer<? super T> f) { T val = getValue(); if(val != null) { f.accept(val); } } /** * Returns the value currently held by this {@linkplain Val}. * @throws NoSuchElementException if there is no value present. */ default T getOrThrow() { T res = getValue(); if(res != null) { return res; } else { throw new NoSuchElementException(); } } /** * Returns the value currently held by this {@linkplain Val}. If this * {@linkplain Val} is empty, {@code defaultValue} is returned instead. * @param defaultValue value to return if there is no value present in * this {@linkplain Val}. */ default T getOrElse(T defaultValue) { T res = getValue(); if(res != null) { return res; } else { return defaultValue; } } /** * Like {@link #getOrElse(Object)}, except the default value is computed * by {@code defaultSupplier} only when necessary. * @param defaultSupplier computation to produce default value, if this * {@linkplain Val} is empty. */ default T getOrSupply(Supplier<? extends T> defaultSupplier) { T res = getValue(); if(res != null) { return res; } else { return defaultSupplier.get(); } } /** * Returns an {@code Optional} describing the value currently held by this * {@linkplain Val}, or and empty {@code Optional} if this {@linkplain Val} * is empty. */ default Optional<T> getOpt() { return Optional.ofNullable(getValue()); } /** * Returns a new {@linkplain Val} that holds the value held by this * {@linkplain Val}, or {@code other} when this {@linkplain Val} is empty. */ default Val<T> orElseConst(T other) { return orElseConst(this, other); } /** * Returns a new {@linkplain Val} that holds the value held by this * {@linkplain Val}, or the value held by {@code other} when this * {@linkplain Val} is empty. */ default Val<T> orElse(ObservableValue<T> other) { return orElse(this, other); } /** * Returns a new {@linkplain Val} that holds the same value * as this {@linkplain Val} when the value satisfies the predicate * and is empty when this {@linkplain Val} is empty or its value * does not satisfy the given predicate. */ default Val<T> filter(Predicate<? super T> p) { return filter(this, p); } /** * Returns a new {@linkplain Val} that holds a mapping of the value held by * this {@linkplain Val}, and is empty when this {@linkplain Val} is empty. * @param f function to map the value held by this {@linkplain Val}. */ default <U> Val<U> map(Function<? super T, ? extends U> f) { return map(this, f); } /** * Like {@link #map(Function)}, but also allows dynamically changing * map function. */ default <U> Val<U> mapDynamic( ObservableValue<? extends Function<? super T, ? extends U>> f) { return mapDynamic(this, f); } /** * Returns a new {@linkplain Val} that, when this {@linkplain Val} holds * value {@code x}, holds the value held by {@code f(x)}, and is empty * when this {@linkplain Val} is empty. */ default <U> Val<U> flatMap( Function<? super T, ? extends ObservableValue<U>> f) { return flatMap(this, f); } /** * Similar to {@link #flatMap(Function)}, except the returned Val is also * a Var. This means you can call {@code setValue()} and {@code bind()} * methods on the returned value, which delegate to the currently selected * Property. * * <p>As the value of this {@linkplain Val} changes, so does the selected * Property. When the Var returned from this method is bound, as the * selected Property changes, the previously selected Property is unbound * and the newly selected Property is bound. * * <p>Note that if the currently selected Property is {@code null}, then * calling {@code getValue()} on the returned value will return {@code null} * regardless of any prior call to {@code setValue()} or {@code bind()}. */ default <U> Var<U> selectVar( Function<? super T, ? extends Property<U>> f) { return selectVar(this, f); } default <U> Var<U> selectVar( Function<? super T, ? extends Property<U>> f, U resetToOnUnbind) { return selectVar(this, f, resetToOnUnbind); } /** * Returns a new {@linkplain Val} that only observes this {@linkplain Val} * when {@code condition} is {@code true}. More precisely, the returned * {@linkplain Val} observes {@code condition} whenever it itself has at * least one observer and observes {@code this} {@linkplain Val} whenever * it itself has at least one observer <em>and</em> the value of * {@code condition} is {@code true}. When {@code condition} is * {@code true}, the returned {@linkplain Val} has the same value as this * {@linkplain Val}. When {@code condition} is {@code false}, the returned * {@linkplain Val} has the value that was held by this {@linkplain Val} at * the time when {@code condition} changed to {@code false}. */ default Val<T> conditionOn(ObservableValue<Boolean> condition) { return conditionOn(this, condition); } /** * Equivalent to {@link #conditionOn(ObservableValue)} where the condition * is that {@code node} is <em>showing</em>: it is part of a scene graph * ({@link Node#sceneProperty()} is not {@code null}), its scene is part of * a window ({@link Scene#windowProperty()} is not {@code null}) and the * window is showing ({@link Window#showingProperty()} is {@code true}). */ default Val<T> conditionOnShowing(Node node) { return conditionOnShowing(this, node); } default SuspendableVal<T> suspendable() { return suspendable(this); } /** * Returns a new {@linkplain Val} that gradually transitions to the value * of this {@linkplain Val} every time this {@linkplain Val} changes. * * <p>When the returned {@linkplain Val} has no observer, there is no * gradual transition taking place. This means that there is no animation * running in the background that would consume system resources. This also * means that in that case {@link #getValue()} always returns the target * value (i.e. the current value of this {@linkplain Val}), instead of any * intermediate interpolated value. * * @param duration function that calculates the desired duration of the * transition for two boundary values. * @param interpolator calculates the interpolated value between two * boundary values, given a fraction. */ default Val<T> animate( BiFunction<? super T, ? super T, Duration> duration, Interpolator<T> interpolator) { return animate(this, duration, interpolator); } /** * Returns a new {@linkplain Val} that gradually transitions to the value * of this {@linkplain Val} every time this {@linkplain Val} changes. * * <p>When the returned {@linkplain Val} has no observer, there is no * gradual transition taking place. This means that there is no animation * running in the background that would consume system resources. This also * means that in that case {@link #getValue()} always returns the target * value (i.e. the current value of this {@linkplain Val}), instead of any * intermediate interpolated value. * * @param duration the desired duration of the transition * @param interpolator calculates the interpolated value between two * boundary values, given a fraction. */ default Val<T> animate( Duration duration, Interpolator<T> interpolator) { return animate(this, duration, interpolator); } /** * Let's this {@linkplain Val} be viewed as a {@linkplain Var}, with the * given {@code setValue} function serving the purpose of * {@link Var#setValue(Object)}. * @see Var#fromVal(ObservableValue, Consumer) */ default Var<T> asVar(Consumer<T> setValue) { return new VarFromVal<>(this, setValue); } /** * Returns a {@linkplain LiveList} view of this {@linkplain Val}. The * returned list will have size 1 when this {@linkplain Val} is present * (i.e. not {@code null}) and size 0 otherwise. */ default LiveList<T> asList() { return LiveList.wrapVal(this); } /** * Returns a {@linkplain Val} wrapper around {@linkplain ObservableValue}. * If the argument is already a {@code Val<T>}, no wrapping occurs and the * argument is returned as is. * Note that one rarely needs to use this method, because most of the time * one can use the appropriate static method directly to get the desired * result. For example, instead of * * <pre> * {@code * Val.wrap(obs).orElse(other) * } * </pre> * * one can write * * <pre> * {@code * Val.orElse(obs, other) * } * </pre> * * However, an explicit wrapper is necessary if access to * {@link #observeInvalidations(Consumer)}, or {@link #invalidations()} * is needed, since there is no direct static method equivalent for them. */ static <T> Val<T> wrap(ObservableValue<T> obs) { return obs instanceof Val ? (Val<T>) obs : new ValWrapper<>(obs); } /** * Adds the given invalidation {@code listener} to the {@code obs} and returns a {@link Subscription} whose * {@link Subscription#unsubscribe() unsubscribe()} will remove the listener and prevent memory leaks. */ static <T> Subscription observeChanges( ObservableValue<? extends T> obs, ChangeListener<? super T> listener) { if(obs instanceof Val) { return ((Val<? extends T>) obs).observeChanges(listener); } else { obs.addListener(listener); return () -> obs.removeListener(listener); } } /** * Adds the given change {@code listener} to the {@code obs} and returns a {@link Subscription} whose * {@link Subscription#unsubscribe() unsubscribe()} will remove the listener and prevent memory leaks. */ static Subscription observeInvalidations( ObservableValue<?> obs, InvalidationListener listener) { obs.addListener(listener); return () -> obs.removeListener(listener); } /** * Returns a {@link Val} whose value is either the value of {@code src} when it is null, or the {@code other} * value when {@code src}'s value is null. */ static <T> Val<T> orElseConst(ObservableValue<? extends T> src, T other) { return new OrElseConst<>(src, other); } /** * Returns a {@link Val} whose value is either the value of {@code src} when it is non-null, and the value * of {@code other} when {@code src}'s value is null. */ static <T> Val<T> orElse( ObservableValue<? extends T> src, ObservableValue<? extends T> other) { return new OrElse<>(src, other); } /** * Returns a {@link Val} whose value is either null when the value stored in {@code src} does not pass the * {@link Predicate#test(Object) predicate's test} or the value stored in {@code src} when it does. */ static <T> Val<T> filter( ObservableValue<T> src, Predicate<? super T> p) { return map(src, t -> p.test(t) ? t : null); } /** * Returns a {@link Val} whose value is the result of applying the given mapping function, {@code f}, to * {@code src}'s value wheneve it changes. */ static <T, U> Val<U> map( ObservableValue<T> src, Function<? super T, ? extends U> f) { return new MappedVal<>(src, f); } /** * Returns a {@link Val} whose value is the result of applying the current mapping function stored in {@code f} * to {@code src}'s value whenever it changes. */ static <T, U> Val<U> mapDynamic( ObservableValue<T> src, ObservableValue<? extends Function<? super T, ? extends U>> f) { return combine( src, f, (t, fn) -> t == null || fn == null ? null : fn.apply(t)); } /** * Returns a {@link Val} whose value is equal to that stored in the returned {@link ObservableValue} after applying * the function, {@code f}, to {@code src}'s value every time it changes. */ static <T, U> Val<U> flatMap( ObservableValue<T> src, Function<? super T, ? extends ObservableValue<U>> f) { return new FlatMappedVal<>(src, f); } static <T, U> Var<U> selectVar( ObservableValue<T> src, Function<? super T, ? extends Property<U>> f) { return new FlatMappedVar<>(src, f); } static <T, U> Var<U> selectVar( ObservableValue<T> src, Function<? super T, ? extends Property<U>> f, U resetToOnUnbind) { return new FlatMappedVar<>(src, f, resetToOnUnbind); } /** * Returns a {@link Val} whose value is the value of {@code obs} while {@code condition}'s value is true; when * that becomes false, this {@code Val}'s value will be the currently stored value of {@code obs} and * not update its value, even when {@code obs}' value changes, until {@code condition} becomes true again. */ static <T> Val<T> conditionOn( ObservableValue<T> obs, ObservableValue<Boolean> condition) { return flatMap(condition, con -> con ? obs : constant(obs.getValue())); } /** * Same as {@link #conditionOn(ObservableValue, ObservableValue)} but uses {@link #showingProperty(Node)} as * its {@code condition} using the given {@code node}. */ static <T> Val<T> conditionOnShowing(ObservableValue<T> obs, Node node) { return conditionOn(obs, showingProperty(node)); } /** * Returns a {@link Val} whose value is the value of {@code obs} while unsuspended; once suspended, the * {@code Val} will ignore any updates until unsuspended again, which will cause this {@code Val} to recompute * its value to the latest stored in {@code obs}. */ static <T> SuspendableVal<T> suspendable(ObservableValue<T> obs) { if(obs instanceof SuspendableVal) { return (SuspendableVal<T>) obs; } else { Val<T> val = obs instanceof Val ? (Val<T>) obs : new ValWrapper<>(obs); return new SuspendableValWrapper<>(val); } } /** * Creates a new {@linkplain Val} that gradually transitions to the value * of the given {@linkplain ObservableValue} {@code obs} every time * {@code obs} changes. * * <p>When the returned {@linkplain Val} has no observer, there is no * gradual transition taking place. This means that there is no animation * running in the background that would consume system resources. This also * means that in that case {@link #getValue()} always returns the target * value (i.e. the current value of {@code obs}), instead of any intermediate * interpolated value. * * @param obs observable value to animate * @param duration function that calculates the desired duration of the * transition for two boundary values. * @param interpolator calculates the interpolated value between two * boundary values, given a fraction. */ static <T> Val<T> animate( ObservableValue<T> obs, BiFunction<? super T, ? super T, Duration> duration, Interpolator<T> interpolator) { return new AnimatedVal<>(obs, duration, interpolator); } /** * Creates a new {@linkplain Val} that gradually transitions to the value * of the given {@linkplain ObservableValue} {@code obs} every time * {@code obs} changes. * * <p>When the returned {@linkplain Val} has no observer, there is no * gradual transition taking place. This means that there is no animation * running in the background that would consume system resources. This also * means that in that case {@link #getValue()} always returns the target * value (i.e. the current value of {@code obs}), instead of any intermediate * interpolated value. * * @param obs observable value to animate * @param duration the desired duration of the transition * @param interpolator calculates the interpolated value between two * boundary values, given a fraction. */ static <T> Val<T> animate( ObservableValue<T> obs, Duration duration, Interpolator<T> interpolator) { return animate(obs, (a, b) -> duration, interpolator); } /** * Like {@link #animate(ObservableValue, BiFunction, Interpolator)}, but * uses the interpolation defined by the {@linkplain Interpolatable} type * {@code T}. */ static <T extends Interpolatable<T>> Val<T> animate( ObservableValue<T> obs, BiFunction<? super T, ? super T, Duration> duration) { return animate(obs, duration, Interpolator.get()); } /** * Like {@link #animate(ObservableValue, Duration, Interpolator)}, but * uses the interpolation defined by the {@linkplain Interpolatable} type * {@code T}. */ static <T extends Interpolatable<T>> Val<T> animate( ObservableValue<T> obs, Duration duration) { return animate(obs, duration, Interpolator.get()); } /** * Returns a {@link Val} whose value is recalculated using the given function, {@code f}, whenever any of the * given observable values (dependencies) change by passing the currently stored value of each dependency * into {@code f} and storing the returned result into the {@code Val}. */ static <A, B, R> Val<R> combine( ObservableValue<A> src1, ObservableValue<B> src2, BiFunction<? super A, ? super B, ? extends R> f) { return create( () -> { if(src1.getValue() != null && src2.getValue() != null) { return f.apply(src1.getValue(), src2.getValue()); } else { return null; } }, src1, src2); } /** * Returns a {@link Val} whose value is recalculated using the given function, {@code f}, whenever any of the * given observable values (dependencies) change by passing the currently stored value of each dependency * into {@code f} and storing the returned result into the {@code Val}. */ static <A, B, C, R> Val<R> combine( ObservableValue<A> src1, ObservableValue<B> src2, ObservableValue<C> src3, TriFunction<? super A, ? super B, ? super C, ? extends R> f) { return create( () -> { if(src1.getValue() != null && src2.getValue() != null && src3.getValue() != null) { return f.apply( src1.getValue(), src2.getValue(), src3.getValue()); } else { return null; } }, src1, src2, src3); } /** * Returns a {@link Val} whose value is recalculated using the given function, {@code f}, whenever any of the * given observable values (dependencies) change by passing the currently stored value of each dependency * into {@code f} and storing the returned result into the {@code Val}. */ static <A, B, C, D, R> Val<R> combine( ObservableValue<A> src1, ObservableValue<B> src2, ObservableValue<C> src3, ObservableValue<D> src4, TetraFunction<? super A, ? super B, ? super C, ? super D, ? extends R> f) { return create( () -> { if(src1.getValue() != null && src2.getValue() != null && src3.getValue() != null && src4.getValue() != null) { return f.apply( src1.getValue(), src2.getValue(), src3.getValue(), src4.getValue()); } else { return null; } }, src1, src2, src3, src4); } /** * Returns a {@link Val} whose value is recalculated using the given function, {@code f}, whenever any of the * given observable values (dependencies) change by passing the currently stored value of each dependency * into {@code f} and storing the returned result into the {@code Val}. */ static <A, B, C, D, E, R> Val<R> combine( ObservableValue<A> src1, ObservableValue<B> src2, ObservableValue<C> src3, ObservableValue<D> src4, ObservableValue<E> src5, PentaFunction<? super A, ? super B, ? super C, ? super D, ? super E, ? extends R> f) { return create( () -> { if(src1.getValue() != null && src2.getValue() != null && src3.getValue() != null && src4.getValue() != null && src5.getValue() != null) { return f.apply( src1.getValue(), src2.getValue(), src3.getValue(), src4.getValue(), src5.getValue()); } else { return null; } }, src1, src2, src3, src4, src5); } /** * Returns a {@link Val} whose value is recalculated using the given function, {@code f}, whenever any of the * given observable values (dependencies) change by passing the currently stored value of each dependency * into {@code f} and storing the returned result into the {@code Val}. */ static <A, B, C, D, E, F, R> Val<R> combine( ObservableValue<A> src1, ObservableValue<B> src2, ObservableValue<C> src3, ObservableValue<D> src4, ObservableValue<E> src5, ObservableValue<F> src6, HexaFunction<? super A, ? super B, ? super C, ? super D, ? super E, ? super F, ? extends R> f) { return create( () -> { if(src1.getValue() != null && src2.getValue() != null && src3.getValue() != null && src4.getValue() != null && src5.getValue() != null && src6.getValue() != null) { return f.apply( src1.getValue(), src2.getValue(), src3.getValue(), src4.getValue(), src5.getValue(), src6.getValue()); } else { return null; } }, src1, src2, src3, src4, src5, src6); } /** * Returns a {@link Val} whose value is recalculated using the given {@link Supplier}, {@code computeValue}, * whenever any of the given observable values (dependencies) change. */ static <T> Val<T> create( Supplier<? extends T> computeValue, javafx.beans.Observable... dependencies) { return new ValBase<T>() { @Override protected Subscription connect() { InvalidationListener listener = obs -> invalidate(); for(javafx.beans.Observable dep: dependencies) { dep.addListener(listener); } return () -> { for(javafx.beans.Observable dep: dependencies) { dep.removeListener(listener); } }; } @Override protected T computeValue() { return computeValue.get(); } }; } /** * Returns a {@link Val} whose value is recalculated using the given {@link Supplier}, {@code computeValue}, * whenever any of the given {@link EventStream}s emit a value. */ static <T> Val<T> create( Supplier<? extends T> computeValue, EventStream<?> invalidations) { return new ValBase<T>() { @Override protected Subscription connect() { return invalidations.subscribe(x -> invalidate()); } @Override protected T computeValue() { return computeValue.get(); } }; } /** * Returns a constant {@linkplain Val} that holds the given value. * The value never changes and no notifications are ever produced. */ static <T> Val<T> constant(T value) { return new ConstVal<>(value); } /** * Returns a {@linkplain Val} whose value is {@code true} when {@code node} * is <em>showing</em>: it is part of a scene graph * ({@link Node#sceneProperty()} is not {@code null}), its scene is part of * a window ({@link Scene#windowProperty()} is not {@code null}) and the * window is showing ({@link Window#showingProperty()} is {@code true}). */ static Val<Boolean> showingProperty(Node node) { return Val .flatMap(node.sceneProperty(), Scene::windowProperty) .flatMap(Window::showingProperty) .orElseConst(false); } } class InvalidationListenerWrapper<T> extends WrapperBase<InvalidationListener> implements Consumer<T> { private final ObservableValue<T> obs; public InvalidationListenerWrapper( ObservableValue<T> obs, InvalidationListener listener) { super(listener); this.obs = obs; } @Override public void accept(T oldValue) { getWrappedValue().invalidated(obs); } } class ChangeListenerWrapper<T> extends WrapperBase<ChangeListener<? super T>> implements Consumer<T> { private final ObservableValue<T> obs; public ChangeListenerWrapper( ObservableValue<T> obs, ChangeListener<? super T> listener) { super(listener); this.obs = obs; } @Override public void accept(T oldValue) { T newValue = obs.getValue(); if(!Objects.equals(oldValue, newValue)) { getWrappedValue().changed(obs, oldValue, newValue); } } }
package convwatch; import java.io.File; import java.io.FileFilter; import java.util.ArrayList; /** * Helper for directory access * * @author Lars.Langhans@sun.com */ public class DirectoryHelper { ArrayList m_aFileList = new ArrayList(); boolean m_bRecursiveIsAllowed = true; void setRecursiveIsAllowed(boolean _bValue) { m_bRecursiveIsAllowed = _bValue; } /** * Traverse over a given directory, and filter with a given FileFilter * object and gives back the deep directory as a Object[] list, which * contain a String object for every directory entry. * * <B>Example</B> * List directory /bin, filter out all files which ends with '.prn' * * FileFilter aFileFilter = new FileFilter() * { * public boolean accept( File pathname ) * { * if (pathname.getName().endsWith(".prn")) * { * return false; * } * return true; * } * }; * * Object[] aList = DirectoryHelper.traverse("/bin", aFileFilter); * for (int i=0;i<aList.length;i++) * { * String aEntry = (String)aList[i]; * System.out.println(aEntry); * } * */ public static Object[] traverse( String _sDirectory, FileFilter _aFileFilter, boolean _bRecursiveIsAllowed ) { DirectoryHelper a = new DirectoryHelper(); a.setRecursiveIsAllowed(_bRecursiveIsAllowed); a.traverse_impl(_sDirectory, _aFileFilter); return a.m_aFileList.toArray(); } public static Object[] traverse( String _sDirectory, boolean _bRecursiveIsAllowed ) { DirectoryHelper a = new DirectoryHelper(); a.setRecursiveIsAllowed(_bRecursiveIsAllowed); a.traverse_impl(_sDirectory, null); return a.m_aFileList.toArray(); } void traverse_impl( String afileDirectory, FileFilter _aFileFilter ) { File fileDirectory = new File(afileDirectory); // Testing, if the file is a directory, and if so, it throws an exception if ( !fileDirectory.isDirectory() ) { throw new IllegalArgumentException( "not a directory: " + fileDirectory.getName() ); } // Getting all files and directories in the current directory File[] aDirEntries; if (_aFileFilter != null) { aDirEntries = fileDirectory.listFiles(_aFileFilter); } else { aDirEntries = fileDirectory.listFiles(); } // Iterating for each file and directory for ( int i = 0; i < aDirEntries.length; ++i ) { if ( aDirEntries[ i ].isDirectory() ) { if (m_bRecursiveIsAllowed == true) { // Recursive call for the new directory traverse_impl( aDirEntries[ i ].getAbsolutePath(), _aFileFilter ); } } else { // adding file to List try { // Composing the URL by replacing all backslashs // String stringUrl = "file:///" + aFileEntries[ i ].getAbsolutePath().replace( '\\', '/' ); String aStr = aDirEntries[ i ].getAbsolutePath(); m_aFileList.add(aStr); } catch( Exception exception ) { exception.printStackTrace(); break; } } } } // tests // public static void main(String[] args) // String sDirectory = "/misc/convwatch/gfxcmp/data/doc-pool/demo"; // Object[] aDirectoryList = DirectoryHelper.traverse( sDirectory, false ); // for (int i=0;i<aDirectoryList.length;i++) // String sEntry = (String)aDirectoryList[i]; // System.out.println(sEntry); }
package mod._fwk; import java.io.PrintWriter; import lib.Status; import lib.StatusException; import lib.TestCase; import lib.TestEnvironment; import lib.TestParameters; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.uno.XInterface; import com.sun.star.util.URL; import util.utils; /** * Test for object that implements the following interfaces : * <ul> * <li><code>com::sun::star::frame::XDispatch</code></li> * <li><code>com::sun::star::frame::XNotifyingDispatch</code></li> * </ul><p> * @see com.sun.star.frame.XDispatch * @see com.sun.star.frame.XNotifyingDispatch * @see ifc.frame._XDispatch * @see ifc.frame._XNotifyingDispatch */ public class SoundHandler extends TestCase { /** * Creating a Testenvironment for the interfaces to be tested. */ public TestEnvironment createTestEnvironment( TestParameters Param, PrintWriter log ) throws StatusException { XInterface oObj = null; try { oObj = (XInterface)((XMultiServiceFactory)Param.getMSF()).createInstance( "com.sun.star.frame.ContentHandler"); } catch(com.sun.star.uno.Exception e) { e.printStackTrace(log); throw new StatusException( Status.failed("Couldn't create instance")); } TestEnvironment tEnv = new TestEnvironment( oObj ); URL dispURL = utils.parseURL((XMultiServiceFactory)Param.getMSF(), utils.getFullTestURL("ok.wav")); System.out.println("DISPATCHURL: "+ dispURL.Complete); tEnv.addObjRelation("XDispatch.URL", dispURL); return tEnv; } // finish method getTestEnvironment }
import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringWriter; import java.net.BindException; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Scanner; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; /** * The main server program. * @author Kevin * */ public class Server { public static final int INCREMENT = 1; //payload tags in Slack POST public static final String PAYLOAD_START = "token="; public static final String CMD_TAG = "command="; public static final String TEXT_TAG = "text="; public static final String CHANNEL_NAME_TAG = "channel_name="; public static final String CHANNEL_ID_TAG = "channel_id="; public static final String USER_NAME_TAG = "user_name="; public static final String USER_ID_TAG = "user_id="; //custom commands. public static final String TIP_CMD = "/tip"; public static final String CHECK_CMD = "/check"; public static final String REGISTER_CMD = "/register"; private static ServerSocket listenSock; //loggers private static volatile Logger log; private static volatile Logger errorLog; private static final String LOG_FOLDER = "logs"; private static final String ERROR_LOG_FOLDER = LOG_FOLDER; private static final String LOG_FILENAME = "log"; private static final String ERROR_LOG_FILENAME = "errorLog"; //threads private static Thread acceptThread; private static Thread maintanenceThread; //see Maintenence Thread for maintentence interval private static boolean running = true; //server running or not private static boolean silent = false; //silent mode prevents server from posting to slack //private static Date startDate = new Date(System.currentTimeMillis()); private static Server instance; public static Server getInstance(){ if (instance == null){ instance = new Server(); } return instance; } private Server(){} /** * Starts the server, binds all resources. If an instance has already is or has been * running, then nothing happens. */ public void startServer(){ //run only if the current thread is not created. Single instance if (acceptThread == null){ println("Getting configuration settings..."); println("Retriving user database..."); println("Found " + UserDB.getUserCount() + " users in database."); UserMapping.getCount(); //Initialize the mapping //if there's no users in the database, warn user to add some if (UserDB.getUserCount() == 0){ println("Warning! Server has no users registered in database."); } //create the system log println("Creating system logs..."); log = new Logger(LOG_FOLDER, LOG_FILENAME); errorLog = new Logger(ERROR_LOG_FOLDER, ERROR_LOG_FILENAME); println("Log started in file: " + log.getFileName()); println("Starting server on port " + Config.getPort() + "..."); System.out.println("\n====================================================="); //create the listen socket try { listenSock = new ServerSocket(Config.getPort()); } catch (BindException e){ System.err.println(e.getMessage()); System.err.println("Cannot setup server! Quitting..."); System.exit(-1); } catch (UnknownHostException e) { e.printStackTrace(); System.err.println("Cannot setup server! Quitting..."); System.exit(-1); } catch (IOException e) { e.printStackTrace(); System.err.println("Cannot setup server! Quitting..."); System.exit(-1); } //create the handling thread and run it. acceptThread = new Thread(new SocketAccepter()); acceptThread.start(); //startTime = new Date(System.currentTimeMillis()); //server actually starts running here. maintanenceThread = new Thread(new MaintenanceThread()); maintanenceThread.start(); } //move this thread into command line service println("Server now running. Enter commands to maintain."); commandLine(); } /** * Server commandline that runs commands to manage the * server. */ private static void commandLine(){ Scanner in = new Scanner(System.in); String nextInput; while (running == true){ nextInput = in.nextLine(); String[] commandArgs = nextInput.split(" ", 2); String command = commandArgs[0].trim(); String args = (commandArgs.length == 2)? commandArgs[1] : ""; if (command.equals("/stop")){ //stop server command println("Saving all information and stopping server..."); saveAllFiles(); running = false; } else if(command.equals("/save")){ //save all current information immediately println("Saving all logs and user information..."); saveAllFiles(); println("All files have been saved."); } else if(command.equals("/message")){ //sends a message onto slack given the channel and message respectively String[] split = args.split(" ", 2); //must be exactly two args. if(split.length == 2){ println("Sending message..."); messageSlack(split[1], split[0]); } else{ println("To use /message, enter channel name then the message to send."); } } else if (command.equals("/silent")){ //toggle silent mode if (silent == false){ //turn silent on silent = true; printRecord("Slient mode is ON, no messages will be posted to Slack."); } else if (silent == true){ //turn silent of silent = false; printRecord("Slient mode is OFF, messages will be posted to Slack."); } } else{ println("Invalid command."); } } //shutdown server. in.close(); System.exit(0); } /** * Posts a message on slack on the specified channel * @param message * @param channel */ private static void messageSlack(String textPost, String channel){ //System.out.println(textPost); //convert all new lines into proper characters textPost = textPost.replaceAll("\n", "`\\\\n`"); if(silent == false){ String message; //construct the JSON message if (channel != null){ message = "payload={\"text\":\"`" + textPost + "`\", \"channel\":\"#" + channel + "\", \"username\": \"" + Config.getBotName() + "\"}"; } else{ message = "payload={\"text\":\"`" + textPost + "`\", \"username\": \"" + Config.getBotName() + "\"}"; } //System.out.println(message); try { CloseableHttpClient slackServer = HttpClients.createDefault(); HttpPost slackMessage = new HttpPost(Config.getSlackWebHook()); slackMessage.setHeader("User-Agent", "Slack Points Server"); slackMessage.setHeader("content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); slackMessage.setEntity(new StringEntity(message)); HttpResponse response = slackServer.execute(slackMessage); //print reply from slack server if any. ByteArrayOutputStream baos = new ByteArrayOutputStream(); response.getEntity().writeTo(baos); println("<Slack Server>: " + (new String(baos.toByteArray()))); slackServer.close(); } catch (UnknownHostException e){ printException(e); } catch (IOException e) { printException(e); } } } //The request handler /** * The request handler created when a new request is being made. * @author Kevin * */ private final class RequestHandler implements Runnable{ Socket client; public RequestHandler(Socket client){ this.client = client; } @Override public void run() { try { BufferedReader buff = new BufferedReader(new InputStreamReader(client.getInputStream(), "UTF-8")); //find the command field of the POST request //gather all lines String complete = ""; String nextLine = buff.readLine(); while (nextLine != null){ complete = complete + nextLine; nextLine = buff.readLine(); } if (complete.indexOf("token=") >= 0){ //proper request. String payload = complete.substring(complete.indexOf("token=")); //convert payload into proper text //with complete request, find the command sent String channelName = getTagArg(payload, CHANNEL_NAME_TAG); //String channelID = getTagArg(payload, CHANNEL_ID_TAG); String userID = getTagArg(payload, USER_ID_TAG); String userName = getTagArg(payload, USER_NAME_TAG); String command = getTagArg(payload, CMD_TAG).replaceAll("%2F", "/"); //replace "%2f" with forward slash String[] args = getTextArgs(payload); //arguements of the command //print command out String fullCommand = command; for (int i =0; i < args.length; i++){ fullCommand = fullCommand + " " + args[i]; } printRecord("<SLACK_CMD> " + userName + " issued command: \t"+fullCommand ); if (command.equals(TIP_CMD)){ //increment command sent, increment points //increment only if there is a user that exists. if (args.length == 1){ String targetID = UserMapping.getID(args[0]); if (targetID != null){ if (UserDB.hasUser(targetID)){ if (targetID.equals(userID) == false){ //not self, do tipping UserDB.increment(targetID, INCREMENT); String confirmMessage = args[0] + " gained " + INCREMENT + Config.getCurrencyName(); log.writeLine(confirmMessage); messageSlack(confirmMessage, channelName); } else{ //error, cannot tip self. messageSlack("You cannot tip yourself " + userName + "!", channelName); } } } else{ //no mapping found, return error messageSlack("I do not recognize who " + args[0] + " is! Did that user get an account with the bank of Slack? Get that user to enter the command /register to sign up. If you already have an account, but changed your name recently please enter the command /register ASAP.", channelName); } } } else if (command.equals(CHECK_CMD)){ //check command sent, return current points. if ((args.length == 1) && (args[0].equals("") == false)){ //get the id of the user String targetID = UserMapping.getID(args[0]); if(targetID != null){ if (UserDB.hasUser(targetID)){ //user exists, return their count. User check = UserDB.getUser(targetID); String humanName = UserMapping.getName(targetID); messageSlack(humanName + " has " + check.getPts() + Config.getCurrencyName() + ".", channelName); } } else{ //no such user exists, report back messageSlack("No such user named " + userName + " exists. Have they registered yet?", channelName); } } else if ((args.length == 1) && (args[0].equals("") == true)){ //get the id of the user String targetID = UserMapping.getID(userName); if(targetID != null){ if (UserDB.hasUser(targetID)){ //user exists, return their count. User check = UserDB.getUser(targetID); String humanName = UserMapping.getName(targetID); messageSlack(humanName + " has " + check.getPts() + Config.getCurrencyName() + ".", channelName); } } else{ //no such user exists, report back messageSlack("I cannot find your record " + userName + ". Have you registered yet?", channelName); } } } else if (command.equals(REGISTER_CMD)){ //register command sent, update id of new user. if (UserMapping.registerPair(userName, userID)){ UserMapping.saveAll(); log.writeLine("Added " + userName + " as new ID: " + userID); //create new user in database UserDB.registerUser(userID); UserDB.saveAll(); messageSlack("Welcome "+ userName + "! You have " + UserDB.getUser(userID).getPts() + Config.getCurrencyName() + ". Earn more by getting tips from friends.", channelName); } else{ String oldName = UserMapping.getName(userID); if (UserMapping.updateName(oldName, userName)){ //successful name update. UserMapping.saveAll(); log.writeLine("Updated " + oldName + " -> " + userName); messageSlack("Gotcha! I'll remember you as " + userName + " from now on.", channelName); } } } else{ //invalid command messageSlack("Sorry I don't understand that command. :frown:", channelName); } } } catch (IOException e) { printException(e); } catch(Exception e){ printException(e); } //always close the client try { client.close(); } catch (IOException e) { printException(e); } } } /** * Gets the command argument of the Slack slash command of the * specified tag in the request. * Returned string is pre-trimmed. * @param postRequest The request to parse * @param tag The tag to extract the value of * @return Empty string if tag is not found, Value of the tag otherwise. */ private static String getTagArg(String payload, String tag){ int index = payload.indexOf(tag); if (index >= 0){ String arg = payload.substring(index + tag.length(),payload.indexOf("&", index)); return arg.trim(); } return ""; } /** * Gets all the arguments seperated by spaces (the '+' symbol). * Returns a String array of each argument in the order they are found in. * * If there are no arguments, an empty array is returned. * If the string does not contain the " * @param payload * @return */ private static String[] getTextArgs(String payload){ int index = payload.indexOf(TEXT_TAG); if (index >=0){ String raw = payload.substring(index + TEXT_TAG.length()); return raw.split("\\+"); } return (new String[0]); } /** * The socket accepting thread that accepts all connections and attempts * to service them. * @author Kevin * */ private final class SocketAccepter implements Runnable{ @Override public void run() { while( running == true ){ try { Socket client = listenSock.accept(); //got a connection println("Recieved connection from: " + client.getInetAddress().toString() + ":" + client.getPort()); //handle request in new thread Thread clientHandler = new Thread(new RequestHandler(client)); clientHandler.start(); } catch (IOException e) { printException(e); } } try { listenSock.close(); } catch (IOException e) { printException(e); } } } private final class MaintenanceThread implements Runnable{ private static final int MAINTENANCE_TIME = 300000; //every 5 minutes, run maintenance thread. //the time to reset the logs. Write new log at about 12:05 am. (aka 0:05) private static final int HOUR_WINDOW = 0; private static final int MINUTE_WINDOW_MIN = 5; private static final int MINUTE_WINDOW_MAX = 11; public MaintenanceThread(){ } @Override public void run() { while (running == true){ try { Thread.sleep(MAINTENANCE_TIME); //if new day, swap out logs Calendar today = Calendar.getInstance(); if ((today.get(Calendar.HOUR_OF_DAY) == HOUR_WINDOW) && (today.get(Calendar.MINUTE) >= MINUTE_WINDOW_MIN) && (today.get(Calendar.MINUTE) <= MINUTE_WINDOW_MAX)){ printRecord("--> Maintenance thread now saving new log for the day."); //save old logs log.saveLog(); errorLog.saveLog(); //swtich to new ones. log = new Logger(LOG_FOLDER, LOG_FILENAME); errorLog = new Logger(ERROR_LOG_FOLDER, ERROR_LOG_FILENAME); //save both logs log.saveLog(); errorLog.saveLog(); } //maintain server here saveAllFiles(); printRecord("--> Maintenance Thread saved all information"); } catch (InterruptedException e) { printException(e); } } } } /** * Saves all critical files. */ private static void saveAllFiles(){ log.saveLog(); errorLog.saveLog(); UserDB.saveAll(); UserMapping.saveAll(); } //Reporting methods and console print private static SimpleDateFormat consoleDate = new SimpleDateFormat("HH:mm:ss"); private static String timeStamp(){ return "[" + (consoleDate.format(new Date(System.currentTimeMillis()))) + "]: "; } /** * Prints out an exception when it occurs. Only the stack * trace is printed to the error log. But an occurance is shown * in both the console and the log. * * @param e */ public static void printException(Exception e){ String message = timeStamp() + "Exception occurred. " + UnknownHostException.class.getName() + ": " + e.getMessage(); printRecord(message + " --Please see error log for stack trace //Convert stack trace into string and print to error log StringWriter error = new StringWriter(); e.printStackTrace(new PrintWriter(error)); String stackTrace = error.toString(); errorLog.writeLine(message + "\n" + stackTrace); messageSlack("Whoops! I ran into an exception. See my log.", null); } /** * Prints a line in the server and in the log. Time stamped */ public static void printRecord(String message){ System.out.println(timeStamp() + message); log.writeLine(message); } /** * Prints a line in the server. Time stamped */ public static void println(String message){ System.out.println(timeStamp() + message); } /* public static void main(String[] args){ //Server.messageSlack("New \nLine", null); String derp = "f%2ff"; String convert = derp.replaceAll("%2f", "/"); System.out.println(convert); Calendar d = Calendar.getInstance(); d.add(Calendar.HOUR_OF_DAY, 6); d.add(Calendar.MINUTE, -15); if ((d.get(Calendar.HOUR_OF_DAY) == 0) && (d.get(Calendar.MINUTE) >= 5) && (d.get(Calendar.MINUTE) <= 10)){ System.out.println(d.get(Calendar.HOUR_OF_DAY)); } } */ }
import java.util.ArrayList; public class Server { private String name; private Table tableList []; private static ArrayList<Table> tables = new ArrayList<>(); public Server() { } public Server(String name, int [] tableArray) { this.name = name; tableList = new Table [tableArray.length]; String tableString; for(int i = 0; i < tableArray.length; i++) { tableString = "T" + tableArray[i]; Table t = new Table(tableString); tableList[i] = t; tables.add(t); } } public void setName(String name) { this.name = name; } public String getName() { return this.name; } public String getServerStatus() { String output = ""; for(int i = 0; i < tableList.length; i++) { output += "\t" + tableList[i].getLabel() + "(" + tableList[i].getStatus() + ")"; } return output; } public String getTableLabel(String label) { String tableLabel = "Table not Found"; for(int i = 0; i < tableList.length; i++) { if(label.equals(tableList[i].getLabel())) tableLabel = label; } return tableLabel; } public char getTableStatus(String label) { char tableStatus = '0'; for(int i = 0; i < tables.size(); i++) { if(label.equals(tables.get(i).getLabel())) tableStatus = tables.get(i).getStatus(); } return tableStatus; } public void setTabelStatus(char status, String label) { for(int i = 0; i < tables.size(); i++) { if(label.equals(tables.get(i).getLabel())) tables.get(i).setStatus(status); } } }
//package mygame; //import com.jme3.app.SimpleApplication; //import com.jme3.material.Material; //import com.jme3.math.ColorRGBA; //import com.jme3.math.Vector3f; //import com.jme3.renderer.RenderManager; //import com.jme3.scene.Geometry; //import com.jme3.scene.shape.Box; /** * test * @author Devin Bost */ //public class Main extends SimpleApplication { // This extends the Application class. The Application class represents a generic real-time 3D rendering jME3 application // public static void main(String[] args) { // Main app = new Main(); // app.start(); // @Override // public void simpleInitApp() { // Box b = new Box(1, 1, 1); // Geometry geom = new Geometry("Box", b); // Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); // mat.setColor("Color", ColorRGBA.Red); // geom.setMaterial(mat); // rootNode.attachChild(geom); // @Override // public void simpleUpdate(float tpf) { // //TODO: add update code // @Override // public void simpleRender(RenderManager rm) { // //TODO: add render code /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package mygame; /** * * @author devinbost */ import com.jme3.animation.AnimChannel; import com.jme3.animation.AnimControl; import com.jme3.animation.AnimEventListener; import com.jme3.animation.LoopMode; import com.jme3.app.SimpleApplication; import com.jme3.asset.TextureKey; import com.jme3.asset.plugins.ZipLocator; import com.jme3.bounding.BoundingBox; import com.jme3.bullet.BulletAppState; import com.jme3.bullet.collision.shapes.BoxCollisionShape; import com.jme3.bullet.collision.shapes.CapsuleCollisionShape; import com.jme3.bullet.collision.shapes.CollisionShape; import com.jme3.bullet.collision.shapes.CompoundCollisionShape; import com.jme3.bullet.control.BetterCharacterControl; import com.jme3.bullet.control.CharacterControl; import com.jme3.bullet.control.RigidBodyControl; import com.jme3.bullet.control.VehicleControl; import com.jme3.bullet.objects.VehicleWheel; import com.jme3.bullet.util.CollisionShapeFactory; import com.jme3.collision.CollisionResult; import com.jme3.collision.CollisionResults; import com.jme3.font.BitmapText; import com.jme3.light.DirectionalLight; import com.jme3.material.Material; import com.jme3.math.ColorRGBA; import com.jme3.math.Vector3f; import com.jme3.scene.Geometry; import com.jme3.scene.shape.Box; import com.jme3.scene.Node; import com.jme3.scene.Spatial; import com.jme3.input.KeyInput; import com.jme3.input.MouseInput; import com.jme3.input.controls.ActionListener; import com.jme3.input.controls.AnalogListener; import com.jme3.input.controls.KeyTrigger; import com.jme3.input.controls.MouseButtonTrigger; import com.jme3.light.AmbientLight; import com.jme3.math.FastMath; import com.jme3.math.Matrix3f; import com.jme3.math.Quaternion; import com.jme3.math.Ray; import com.jme3.math.Vector2f; import com.jme3.niftygui.NiftyJmeDisplay; import com.jme3.renderer.queue.RenderQueue.ShadowMode; import com.jme3.scene.debug.SkeletonDebugger; import com.jme3.scene.shape.Cylinder; import com.jme3.scene.shape.Sphere; import com.jme3.scene.shape.Sphere.TextureMode; import com.jme3.shadow.BasicShadowRenderer; import com.jme3.texture.Texture; import com.jme3.texture.Texture.WrapMode; import de.lessvoid.nifty.Nifty; import de.lessvoid.nifty.screen.Screen; /** Sample 1 - how to get started with the most simple JME 3 application. * Display a blue 3D cube and view from all sides by * moving the mouse and pressing the WASD keys. */ public class Main extends SimpleApplication implements AnimEventListener , ActionListener { // Make this class implement the ActionListener interface to customize the navigational inputs later. public Node player; public Node cannon; private Node carNode; public Spatial ninja; private AnimChannel channel; private AnimControl control; private AnimChannel animationChannel; private AnimChannel attackChannel; private AnimControl animationControl; private Node shootables; private Node inventory; Boolean isRunning=true; private Geometry mark; private BulletAppState bulletAppState; private RigidBodyControl landscape; private BetterCharacterControl playerControl; private Spatial gameLevel; // track directional input, so we can walk left-forward etc private boolean left = false, right = false, up = false, down = false; private Vector3f walkDirection = new Vector3f(0,0,0); // stop private float airTime = 0; private Vector3f oldPosition; // this may be deprecated. public Nifty _nifty; public Screen _screen; private Node explosionEffectWrapper = new Node("explosionFX"); private ExplosionEffect explosion; private boolean triggerExplosion1 = false; private VehicleControl vehicle; private final float accelerationForce = 1000.0f; private final float brakeForce = 100.0f; private float steeringValue = 0; private float accelerationValue = 0; private Vector3f jumpForce = new Vector3f(0, 3000, 0); private VehicleWheel fr, fl, br, bl; private Node node_fr, node_fl, node_br, node_bl; private float wheelRadius; /** Prepare Materials */ Material wall_mat; Material stone_mat; Material floor_mat; /** Prepare geometries and physical nodes for bricks and cannon balls. */ private RigidBodyControl brick_phy; private static final Box box; private RigidBodyControl ball_phy; private static final Sphere sphere; private RigidBodyControl floor_phy; private static final Box floor; /** dimensions used for bricks and wall */ private static final float brickLength = 0.48f; private static final float brickWidth = 0.24f; private static final float brickHeight = 0.12f; public static void main(String[] args){ System.out.println("Main.main(String[] args) is being called here."); Main app = new Main(); app.start(); // start the game } static { /** Initialize the cannon ball geometry */ sphere = new Sphere(32, 32, 0.4f, true, false); sphere.setTextureMode(TextureMode.Projected); /** Initialize the brick geometry */ box = new Box(brickLength, brickHeight, brickWidth); box.scaleTextureCoordinates(new Vector2f(1f, .5f)); /** Initialize the floor geometry */ floor = new Box(10f, 0.1f, 5f); floor.scaleTextureCoordinates(new Vector2f(3, 6)); } @Override public void simpleInitApp() { System.out.println("Main.simpleInitApp() is being called here."); NiftyJmeDisplay niftyDisplay = new NiftyJmeDisplay(assetManager, inputManager, audioRenderer, guiViewPort); /** Create a new NiftyGUI object */ Nifty nifty = niftyDisplay.getNifty(); // How do I set the screen here? /** Read your XML and initialize your custom ScreenController */ MainScreenController screenController = new MainScreenController(this); stateManager.attach(screenController); // [...] boilerplate init nifty omitted nifty.fromXml("Interface/startGameScreen.xml", "startGameScreen", screenController); nifty.addXml("Interface/hudScreen.xml"); //nifty.fromXml("Interface/hudScreen.xml", "hudScreen", screenController); // attach the Nifty display to the gui view port as a processor guiViewPort.addProcessor(niftyDisplay); this._nifty = nifty; System.out.println("In the Main.simpleInitApp() method, nifty is: " + nifty.toString()); // Q: How do I determine if "startGame" is the correct string to pass the above method? // A: I think this (second parameter) is the ID of the screen in the given file. // nifty.fromXml("Interface/startGameScreen.xml", "startGame"); // Once I have a screencontroller, we will use the commented version // nifty.fromXml("Interface/helloworld.xml", "start", new MySettingsScreenController(data)); flyCam.setDragToRotate(true); // This may cause complications without additional on/off logic. // if we have additional screens to load, just call them like this: // nifty.fromXml("Interface/startGameScreen.xml", "startGame"); // We need to call LoadGameFromScreen() next!! If it won't be called from a screen, // then it needs to be called here instead! // Need to disable mouse cursor when ready to start actual game: mouseInput.setCursorVisible(false); LoadGameFromScreen(); if (settings.getRenderer().startsWith("LWJGL")) { BasicShadowRenderer bsr = new BasicShadowRenderer(assetManager, 512); bsr.setDirection(new Vector3f(-0.5f, -0.3f, -0.3f).normalizeLocal()); viewPort.addProcessor(bsr); } } public void LoadGameFromScreen(){ System.out.println("The Main.LoadGameFromScreen() method is getting called here."); bulletAppState = new BulletAppState(); // add the BulletAppState object to enable integration with jBullet's physical forces and collisions. stateManager.attach(bulletAppState); // If you ever get confusing physics behaviour, remember to have a look at the collision shapes. Add the following line after the bulletAppState initialization to make the shapes visible: bulletAppState.getPhysicsSpace().enableDebug(assetManager); guiNode.detachAllChildren(); // be sure to reset guiNode BEFORE we load the crossHairs initCrossHairs(); // a "+" in the middle of the screen to help aiming initMark(); // a red sphere to mark the hit shootables = new Node("Shootables"); rootNode.attachChild(shootables); inventory = new Node("Inventory"); guiNode.attachChild(inventory); shootables.attachChild(makeCube("a Dragon", -2f, 0f, 1f)); shootables.attachChild(makeCube("a tin can", 1f, -2f, 0f)); shootables.attachChild(makeCube("the Sheriff", 0f, 1f, -12f)); shootables.attachChild(makeCube("the Deputy", 10f, 0f, -4f)); flyCam.setMoveSpeed(50); // make the camera move at a managable speed // Create a blue box at coordinates (1, -1, 1) Geometry blueBox = ConstructBox(ColorRGBA.Blue); rootNode.attachChild(blueBox); // make the cube appear in the scene Geometry redBox = ConstructBox(ColorRGBA.Red); // Create a pivot node at (0,0,0) and attach it to the root node. Node pivot = new Node("pivot"); rootNode.attachChild(pivot); pivot.attachChild(blueBox); // Attach the two boxes to the pivot node. (And transitively to the root node.) pivot.attachChild(redBox); pivot.rotate(.4f, .4f, 0f);// rotate the pivot node: Note that both boxes have rotated. Spatial wall = ConstructWall();// Create a wall with a simple texture from test_data //rootNode.attachChild(wall); shootables.attachChild(wall); BitmapText helloText = ConstructGuiText();// Display a line of text with a default font guiNode.attachChild(helloText); // Load a model from test_data (OgreXML + material + texture) this.ConstructNinja(); rootNode.attachChild(ninja); initKeys(); // load my custom keybinding // You must add light to make the model visible DirectionalLight sun = new DirectionalLight(); sun.setDirection(new Vector3f(-0.1f, -0.7f, 1.0f)); rootNode.addLight(sun); Spatial elephant = assetManager.loadModel("Models/Elephant/Elephant.mesh.xml"); rootNode.attachChild(elephant); this.ConstructLevel(); //rootNode.attachChild(gameLevel); DirectionalLight dl = new DirectionalLight(); dl.setDirection(new Vector3f(-0.1f, -1f, -1).normalizeLocal()); rootNode.addLight(dl); this.ConstructCharacter(); this.ConstructCannon(); this.explosion = new ExplosionEffect(explosionEffectWrapper, this.getAssetManager()); renderManager.preloadScene(explosionEffectWrapper); rootNode.attachChild(explosionEffectWrapper); explosionEffectWrapper.setLocalTranslation(new Vector3f(0,10,10)); // Set position of explosionEffectWrapper to position explosion. // We want to position the explosion at the tip of the cannon. this.ConstructPhysicalCannon(); initMaterials(); initWall(); initFloor(); } // private void setUpLight() { // // We add light so we see the scene // AmbientLight al = new AmbientLight(); // al.setColor(ColorRGBA.White.mult(1.3f)); // rootNode.addLight(al); // DirectionalLight dl = new DirectionalLight(); // dl.setColor(ColorRGBA.White); // dl.setDirection(new Vector3f(2.8f, -2.8f, -2.8f).normalizeLocal()); // rootNode.addLight(dl); // private SkeletonDebugger ConstructSkeleton(){ // SkeletonDebugger skeletonDebug = // new SkeletonDebugger("skeleton", control.getSkeleton()); // Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); // mat.setColor("Color", ColorRGBA.Green); // mat.getAdditionalRenderState().setDepthTest(false); // skeletonDebug.setMaterial(mat); // return skeletonDebug; private void ConstructPhysicalCannon(){ // CompoundCollisionShape compoundShape = new CompoundCollisionShape(); // BoxCollisionShape box = new BoxCollisionShape(new Vector3f(1.2f, 0.5f, 2.4f)); // compoundShape.addChildShape(box, new Vector3f(0, 1, 0)); // Best Practice: We attach the BoxCollisionShape (the vehicle body) to the CompoundCollisionShape at a Vector of (0,1,0): This shifts the effective center of mass of the BoxCollisionShape downwards to 0,-1,0 and makes a moving vehicle more stable! // Spatial cannonPhysicalSpatial = assetManager.loadModel("Models/Cannon/cannon_body_01.j3o"); // Node cannonPhysicalNode = (Node)cannonPhysicalSpatial; // vehicle = new VehicleControl(compoundShape, 400); // 400 is the mass that we set. This is heavy. // cannonPhysicalNode.addControl(vehicle); // float stiffness = 60.0f;//200=f1 car // float compValue = .3f; //(should be lower than damp) // float dampValue = .4f; // vehicle.setSuspensionCompression(compValue * 2.0f * FastMath.sqrt(stiffness)); // vehicle.setSuspensionDamping(dampValue * 2.0f * FastMath.sqrt(stiffness)); // vehicle.setSuspensionStiffness(stiffness); // vehicle.setMaxSuspensionForce(10000.0f); float stiffness = 120.0f;//200=f1 car float compValue = 0.2f; //(lower than damp!) float dampValue = 0.3f; final float mass = 400; //Load model and get chassis Geometry carNode = (Node)assetManager.loadModel("Models/Ferrari/Car.scene"); carNode.setShadowMode(ShadowMode.Cast); Geometry chasis = findGeom(carNode, "Car"); BoundingBox boundingBox = (BoundingBox) chasis.getModelBound(); //Create a hull collision shape for the chassis CollisionShape carHull = CollisionShapeFactory.createDynamicMeshShape(chasis); //Create a vehicle control vehicle = new VehicleControl(carHull, mass); carNode.addControl(vehicle); //Setting default values for wheels vehicle.setSuspensionCompression(compValue * 2.0f * FastMath.sqrt(stiffness)); vehicle.setSuspensionDamping(dampValue * 2.0f * FastMath.sqrt(stiffness)); vehicle.setSuspensionStiffness(stiffness); vehicle.setMaxSuspensionForce(10000); //Create four wheels and add them at their locations Vector3f wheelDirection = new Vector3f(0, -1, 0); Vector3f wheelAxle = new Vector3f(-1, 0, 0); // Is this how the wheels rotate? Geometry wheel_fr = findGeom(carNode, "WheelFrontRight"); wheel_fr.center(); boundingBox = (BoundingBox) wheel_fr.getModelBound(); wheelRadius = boundingBox.getYExtent(); float back_wheel_h = (wheelRadius * 1.7f) - 1f; float front_wheel_h = (wheelRadius * 1.9f) - 1f; vehicle.addWheel(wheel_fr.getParent(), boundingBox.getCenter().add(0, -front_wheel_h, 0), wheelDirection, wheelAxle, 0.2f, wheelRadius, true); Geometry wheel_fl = findGeom(carNode, "WheelFrontLeft"); wheel_fl.center(); boundingBox = (BoundingBox) wheel_fl.getModelBound(); vehicle.addWheel(wheel_fl.getParent(), boundingBox.getCenter().add(0, -front_wheel_h, 0), wheelDirection, wheelAxle, 0.2f, wheelRadius, true); Geometry wheel_br = findGeom(carNode, "WheelBackRight"); wheel_br.center(); boundingBox = (BoundingBox) wheel_br.getModelBound(); vehicle.addWheel(wheel_br.getParent(), boundingBox.getCenter().add(0, -back_wheel_h, 0), wheelDirection, wheelAxle, 0.2f, wheelRadius, false); Geometry wheel_bl = findGeom(carNode, "WheelBackLeft"); wheel_bl.center(); boundingBox = (BoundingBox) wheel_bl.getModelBound(); vehicle.addWheel(wheel_bl.getParent(), boundingBox.getCenter().add(0, -back_wheel_h, 0), wheelDirection, wheelAxle, 0.2f, wheelRadius, false); vehicle.getWheel(2).setFrictionSlip(4); vehicle.getWheel(3).setFrictionSlip(4); rootNode.attachChild(carNode); bulletAppState.getPhysicsSpace().add(vehicle); //Vector3f wheelAxle = new Vector3f(0, 0, -1); // How do I have the wheels rotate without the body rotating? // How do I separate the body from the wheels? // float radius = 0.5f; // float restLength = 0.3f; // float yOff = 0.0f; // float xOff = 0.0f; // float zOff = 0.0f; // Material mat = new Material(getAssetManager(), "Common/MatDefs/Misc/Unshaded.j3md"); // mat.getAdditionalRenderState().setWireframe(true); // mat.setColor("Color", ColorRGBA.Red); // float radius = 0.5f; // float restLength = 0.3f; // float yOff = 0.5f; // float xOff = 1f; // float zOff = 2f; // // We create a Cylinder mesh shape that we use to create the four visible wheel geometries. // Cylinder wheelMesh = new Cylinder(16, 16, radius, radius * 0.6f, true); // Node node1 = new Node("wheel 1 node"); // Geometry wheels1 = new Geometry("wheel 1", wheelMesh); // node1.attachChild(wheels1); // wheels1.rotate(0, FastMath.HALF_PI, 0); // wheels1.setMaterial(mat); // vehicle.addWheel(node1, new Vector3f(-xOff, yOff, zOff), // wheelDirection, wheelAxle, restLength, radius, true); // Node node2 = new Node("wheel 2 node"); // Geometry wheels2 = new Geometry("wheel 2", wheelMesh); // node2.attachChild(wheels2); // wheels2.rotate(0, FastMath.HALF_PI, 0); // wheels2.setMaterial(mat); // vehicle.addWheel(node2, new Vector3f(xOff, yOff, zOff), // wheelDirection, wheelAxle, restLength, radius, true); // Node node3 = new Node("wheel 3 node"); // Geometry wheels3 = new Geometry("wheel 3", wheelMesh); // node3.attachChild(wheels3); // wheels3.rotate(0, FastMath.HALF_PI, 0); // wheels3.setMaterial(mat); // vehicle.addWheel(node3, new Vector3f(-xOff, yOff, -zOff), // wheelDirection, wheelAxle, restLength, radius, false); // Node node4 = new Node("wheel 4 node"); // Geometry wheels4 = new Geometry("wheel 4", wheelMesh); // node4.attachChild(wheels4); // wheels4.rotate(0, FastMath.HALF_PI, 0); // wheels4.setMaterial(mat); // vehicle.addWheel(node4, new Vector3f(xOff, yOff, -zOff), // wheelDirection, wheelAxle, restLength, radius, false); //// Spatial cannonLeftWheel = assetManager.loadModel("Models/Cannon/cannon_wheel_01_left.j3o"); //// Node cannonLeftWheelNode = (Node)cannonLeftWheel; //// Spatial cannonRightWheel = assetManager.loadModel("Models/Cannon/cannon_wheel_01_right.j3o"); //// Node cannonRightWheelNode = (Node)cannonRightWheel; //// vehicle.addWheel(cannonLeftWheelNode, new Vector3f(-xOff, yOff, zOff), //// wheelDirection, wheelAxle, restLength, radius, true); //// vehicle.addWheel(cannonRightWheelNode, new Vector3f(-xOff, yOff, zOff), //// wheelDirection, wheelAxle, restLength, radius, true); //// // Do I need little wheels in the back? ////// vehicle.addWheel(cannonLeftRearWheelNode, new Vector3f(-xOff, yOff, zOff), ////// wheelDirection, wheelAxle, restLength, radius, false); ////// vehicle.addWheel(cannonRightRearWheelNode, new Vector3f(-xOff, yOff, zOff), ////// wheelDirection, wheelAxle, restLength, radius, false); ////// vehicle.addWheel(cannonLeftWheelNode, new Vector3f(-xOff, yOff, -0.5f), ////// wheelDirection, wheelAxle, restLength, radius, false); ////// vehicle.addWheel(cannonRightWheelNode, new Vector3f(-xOff, yOff, -0.5f), ////// wheelDirection, wheelAxle, restLength, radius, false); //// cannonPhysicalNode.attachChild(cannonLeftWheelNode); //// cannonPhysicalNode.attachChild(cannonRightWheelNode); //rootNode.attachChild(cannonPhysicalNode); // rootNode.attachChild(carNode); // bulletAppState.getPhysicsSpace().add(vehicle); // Geometry chasis = findGeom(cannonPhysicalNode, "Barrel"); //???? // BoundingBox boundingBox = (BoundingBox) chasis.getModelBound(); // //Create a hull collision shape for the chassis // CollisionShape carHull = CollisionShapeFactory.createDynamicMeshShape(chasis); // Geometry wheel_fr = findGeom(carNode, "WheelFrontRight"); // wheel_fr.center(); // box = (BoundingBox) wheel_fr.getModelBound(); // wheelRadius = box.getYExtent(); // float back_wheel_h = (wheelRadius * 1.7f) - 1f; // float front_wheel_h = (wheelRadius * 1.9f) - 1f; // player.addWheel(wheel_fr.getParent(), box.getCenter().add(0, -front_wheel_h, 0), // wheelDirection, wheelAxle, 0.2f, wheelRadius, true); // Geometry wheel_fl = findGeom(carNode, "WheelFrontLeft"); // wheel_fl.center(); // box = (BoundingBox) wheel_fl.getModelBound(); // player.addWheel(wheel_fl.getParent(), box.getCenter().add(0, -front_wheel_h, 0), // wheelDirection, wheelAxle, 0.2f, wheelRadius, true); // Geometry wheel_br = findGeom(carNode, "WheelBackRight"); // wheel_br.center(); // box = (BoundingBox) wheel_br.getModelBound(); // player.addWheel(wheel_br.getParent(), box.getCenter().add(0, -back_wheel_h, 0), // wheelDirection, wheelAxle, 0.2f, wheelRadius, false); // Geometry wheel_bl = findGeom(carNode, "WheelBackLeft"); // wheel_bl.center(); // box = (BoundingBox) wheel_bl.getModelBound(); // player.addWheel(wheel_bl.getParent(), box.getCenter().add(0, -back_wheel_h, 0), // wheelDirection, wheelAxle, 0.2f, wheelRadius, false); // player.getWheel(2).setFrictionSlip(4); // player.getWheel(3).setFrictionSlip(4); // rootNode.attachChild(carNode); // getPhysicsSpace().add(player); } private Geometry findGeom(Spatial spatial, String name) { if (spatial instanceof Node) { Node node = (Node) spatial; for (int i = 0; i < node.getQuantity(); i++) { System.out.println("findGeom is returning: " + node.getChild(i).getName() + " for node.getChild(" + i + ")"); Spatial child = node.getChild(i); Geometry result = findGeom(child, name); if (result != null) { return result; } } } else if (spatial instanceof Geometry) { if (spatial.getName().startsWith(name)) { return (Geometry) spatial; } } return null; } private void ConstructCannon(){ System.out.println("Constructing cannon."); Spatial cannonSpatial = assetManager.loadModel("Models/Cannon/cannon_01.j3o"); cannon = (Node)cannonSpatial; Node cannonNode = new Node(); cannonNode.attachChild(cannon); cannon.move(5f,-3.5f,8f); cannon.setLocalScale(5f); DirectionalLight dl = new DirectionalLight(); dl.setDirection(new Vector3f(-0.1f, -1f, -1).normalizeLocal()); cannon.addLight(dl); rootNode.attachChild(cannon); } private void ConstructCharacter(){ Spatial playerSpatial = assetManager.loadModel("Models/Oto/Oto.mesh.xml"); player = (Node)playerSpatial; Node playerNode = new Node(); playerNode.attachChild(player); player.move(0,3.5f,0); player.setLocalScale(0.5f); //rootNode.attachChild(player); /* Load the animation controls, listen to animation events, * create an animation channel, and bring the model in its default position. */ //// control = player.getControl(AnimControl.class); //// control.addListener(this); //// channel = control.createChannel(); //// channel.setAnim("stand"); // CapsuleCollisionShape capsuleShape = new CapsuleCollisionShape(1.5f, 6f, 1); // CharacterControl playerControl = new CharacterControl(capsuleShape, 0.01f); playerControl = new BetterCharacterControl(1.5f, 6f, 1f); // player.addControl(playerControl); playerNode.addControl(playerControl); // playerControl.setJumpSpeed(10f); playerControl.setJumpForce(new Vector3f(0,5f,0)); // playerControl.setFallSpeed(20f); // playerControl.setGravity(1f); playerControl.setGravity(new Vector3f(0,1f,0)); playerControl.warp(new Vector3f(0,10,10)); // We need to register all solid objects to the PhysicsSpace! bulletAppState.getPhysicsSpace().add(playerControl); bulletAppState.getPhysicsSpace().addAll(playerNode); rootNode.attachChild(playerNode); // SkeletonDebugger skeletonDebug = ConstructSkeleton(); // player.attachChild(skeletonDebug); animationControl = player.getControl(AnimControl.class); animationControl.addListener(this); animationChannel = animationControl.createChannel(); attackChannel = animationControl.createChannel(); attackChannel.addBone(animationControl.getSkeleton().getBone("uparm.right")); attackChannel.addBone(animationControl.getSkeleton().getBone("arm.right")); attackChannel.addBone(animationControl.getSkeleton().getBone("hand.right")); } private void ConstructLevel(){ assetManager.registerLocator("town.zip", ZipLocator.class); gameLevel = assetManager.loadModel("main.scene"); // be sure to give new names to new scenes gameLevel.setLocalTranslation(0, -5.2f, 0); // move the level down by 5.2 units gameLevel.setLocalScale(2f); // Wrap the scene in a rigidbody collision object. CollisionShape sceneShape = CollisionShapeFactory.createMeshShape((Node) gameLevel); landscape = new RigidBodyControl(sceneShape, 0); gameLevel.addControl(landscape); bulletAppState.getPhysicsSpace().addAll(gameLevel); // Now attach it. shootables.attachChild(gameLevel); // should we add the shootables to the bulletAppState? } private void ConstructNinja(){ ninja = assetManager.loadModel("Models/Ninja/Ninja.mesh.xml"); ninja.scale(0.05f, 0.05f, 0.05f); ninja.rotate(0.0f, -3.0f, 0.0f); ninja.setLocalTranslation(0.0f, -5.0f, -2.0f); } private BitmapText ConstructGuiText(){ guiFont = assetManager.loadFont("Interface/Fonts/Default.fnt"); BitmapText helloText = new BitmapText(guiFont, false); helloText.setSize(guiFont.getCharSet().getRenderedSize()); helloText.setText("Hello World"); helloText.setLocalTranslation(300, helloText.getLineHeight(), 0); return helloText; } private Geometry ConstructBox(ColorRGBA color){ Box box1 = new Box(1, 1, 1); // create cube shape Geometry blueBox = new Geometry("Box", box1); // create cube geometry from the shape blueBox.setLocalTranslation(new Vector3f(1, -1, 4)); Material blueBoxMaterial = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); // create a simple material blueBoxMaterial.setColor("Color", color.Blue); // set color of material to blue blueBox.setMaterial(blueBoxMaterial); // set the cube's material return blueBox; } private Spatial ConstructWall(){ // Create a wall with a simple texture from test_data Box superBox = new Box(2.5f, 2.5f, 4.0f); Spatial wall = new Geometry("Box", superBox); Material mat_brick = new Material( assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); mat_brick.setTexture("ColorMap", assetManager.loadTexture("Textures/Terrain/BrickWall/BrickWall.jpg")); wall.setMaterial(mat_brick); wall.setLocalTranslation(2.0f, -2.5f, 0.0f); return wall; } @Override public void simpleUpdate(float tpf){ // "tpf" stands for "time per frame" // How do I pause the game? Vector3f camDir = cam.getDirection().clone().multLocal(7.25f); // multLocal controls rate of movement multiplier. Vector3f camLeft = cam.getLeft().clone().multLocal(7.25f); camDir.y = 0; camLeft.y = 0; walkDirection.set(0, 0, 0); if (left) walkDirection.addLocal(camLeft); if (right) walkDirection.addLocal(camLeft.negate()); if (up) walkDirection.addLocal(camDir); if (down) walkDirection.addLocal(camDir.negate()); if (!playerControl.isOnGround()) { airTime = airTime + tpf; } else { airTime = 0; } if (walkDirection.length() == 0) { if (!"stand".equals(animationChannel.getAnimationName())) { animationChannel.setAnim("stand", 1f); } } else { playerControl.setViewDirection(walkDirection); if (airTime > .3f) { if (!"stand".equals(animationChannel.getAnimationName())) { animationChannel.setAnim("stand"); } } else if (!"Walk".equals(animationChannel.getAnimationName())) { animationChannel.setAnim("Walk", 0.7f); // 0.7f controls rate of animation } } playerControl.setWalkDirection(walkDirection); // THIS IS WHERE THE WALKING HAPPENS if (triggerExplosion1 == true) { this.triggerExplosion1 = this.explosion.triggerEffect(tpf, speed, triggerExplosion1); // We must turn off the explosion trigger after the explosion to ensure it doesn't repeat in a loop. } // This method is where we update score, health, check for collisions, make enemies calculate next move, play sounds, roll dice for traps, etc. //ninja.rotate(0, 2*tpf, 0); /* * * Use the loop to poll the game state and then initiate actions. Use the loop to trigger reactions and update the game state. Use the loop wisely, because having too many calls in the loop also slows down the game. * To prevent the size from becoming unmanagable: * Move code blocks from the simpleInitApp() method to AppStates. Move code blocks from the simpleUpdate() method to Custom Controls. * */ //Can you make a rolling cube? (rotate around the x axis, and translate along the z axis) } /** Custom Keybinding: Map named actions to inputs. */ private void initKeys() { // configure mappings, e.g. the WASD keys inputManager.addMapping("CharLeft", new KeyTrigger(KeyInput.KEY_J)); inputManager.addMapping("CharRight", new KeyTrigger(KeyInput.KEY_L)); inputManager.addMapping("CharForward", new KeyTrigger(KeyInput.KEY_I)); inputManager.addMapping("CharBackward", new KeyTrigger(KeyInput.KEY_K)); inputManager.addMapping("CharJump", new KeyTrigger(KeyInput.KEY_RETURN)); inputManager.addMapping("CharAttack", new KeyTrigger(KeyInput.KEY_O)); // setup mapping that uses our override (via ActionListener interface): inputManager.addListener(this, "CharLeft", "CharRight"); inputManager.addListener(this, "CharForward", "CharBackward"); inputManager.addListener(this, "CharJump", "CharAttack"); // You can map one or several inputs to one named action inputManager.addMapping("Pause", new KeyTrigger(KeyInput.KEY_P)); // inputManager.addMapping("Left", new KeyTrigger(KeyInput.KEY_J)); // inputManager.addMapping("Right", new KeyTrigger(KeyInput.KEY_K)); // inputManager.addMapping("RotateLeft", new MouseButtonTrigger(MouseInput.BUTTON_LEFT)); // inputManager.addMapping("RotateRight", new MouseButtonTrigger(MouseInput.BUTTON_RIGHT)); inputManager.addMapping("Run", new KeyTrigger(KeyInput.KEY_SPACE)); inputManager.addMapping("Walk", new KeyTrigger(KeyInput.KEY_G)); inputManager.addMapping("Shoot", new KeyTrigger(KeyInput.KEY_B)); inputManager.addListener(this, "Shoot"); inputManager.addMapping("Lefts", new KeyTrigger(KeyInput.KEY_0)); inputManager.addMapping("Rights", new KeyTrigger(KeyInput.KEY_1)); inputManager.addMapping("Ups", new KeyTrigger(KeyInput.KEY_2)); inputManager.addMapping("Downs", new KeyTrigger(KeyInput.KEY_3)); inputManager.addMapping("Space", new KeyTrigger(KeyInput.KEY_4)); inputManager.addMapping("Reset", new KeyTrigger(KeyInput.KEY_5)); inputManager.addListener(this, "Lefts"); inputManager.addListener(this, "Rights"); inputManager.addListener(this, "Ups"); inputManager.addListener(this, "Downs"); inputManager.addListener(this, "Space"); inputManager.addListener(this, "Reset"); // inputManager.addListener(actionListener, "Walk", "Shoot", "Left", "Right", "Run","RotateLeft", "RotateRight"); // // Add the names to the action listener. // inputManager.addListener(actionListener,"Pause"); // You register the pause action to the ActionListener, because it is an "on/off" action. //inputManager.addListener(analogListener, "RotateLeft", "RotateRight"); // You register the movement actions to the AnalogListener, because they are gradual actions. /* TO make character pickup an object, here are the steps: * 1. button is pressed * 2. We use ray casting to detect/target the object in front of the character. * Aim ray in front of character * detect collisions * check for collisions less than particular distance * 3. If true, we use an actionListener to elevate the object and set isHoldingObject = true. * 4. If isHoldingObject == true, when character moves, the object also moves. * 5. We wire an actionListener to put down the object and set isHoldingObject = false. * */ } // public void onAction(String name, boolean isPressed, float tpf) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. @Override public void onAction(String binding, boolean value, float tpf) { if (binding.equals("CharLeft")) { if (value) left = true; else left = false; } else if (binding.equals("CharRight")) { if (value) right = true; else right = false; } else if (binding.equals("CharForward")) { if (value) up = true; else up = false; } else if (binding.equals("CharBackward")) { if (value) down = true; else down = false; } else if (binding.equals("CharJump")) playerControl.jump(); if (binding.equals("CharAttack")){ attack(); this.triggerExplosion1 = true; } if (binding.equals("Lefts")) { if (value) { steeringValue += .5f; } else { steeringValue += -.5f; } vehicle.steer(steeringValue); } else if (binding.equals("Rights")) { if (value) { steeringValue += -.5f; } else { steeringValue += .5f; } vehicle.steer(steeringValue); } else if (binding.equals("Ups")) { if (value) {//note that our fancy car actually goes backwards.. accelerationValue -= accelerationForce; } else { accelerationValue += accelerationForce; } vehicle.accelerate(accelerationValue); vehicle.setCollisionShape(CollisionShapeFactory.createDynamicMeshShape(findGeom(carNode, "Car"))); } else if (binding.equals("Downs")) { if (value) { vehicle.brake(brakeForce); } else { vehicle.brake(0f); } } else if (binding.equals("Space")) { if (value) { vehicle.applyImpulse(jumpForce, Vector3f.ZERO); } } else if (binding.equals("Reset")) { if (value) { System.out.println("Reset"); vehicle.setPhysicsLocation(Vector3f.ZERO); vehicle.setPhysicsRotation(new Matrix3f()); vehicle.setLinearVelocity(Vector3f.ZERO); vehicle.setAngularVelocity(Vector3f.ZERO); vehicle.resetSuspension(); } else { } } if (binding.equals("Shoot")) { // Should we have something like [binding.equals("Shoot") && !keyPressed] here? // // 1. Reset results list // CollisionResults results = new CollisionResults(); // // 2. Aim the ray from character location to character direction. //// Vector3f forward = new Vector3f(0,0,1.05f); // set the magnitude in front of char. //// Vector3f actualForward = new Vector3f(); //// player.localToWorld(forward, actualForward); //// Ray ray = new Ray(player.getLocalTranslation(), actualForward); // Ray ray = new Ray(cam.getLocation(), cam.getDirection()); // // 3. Collect intersections between Ray and grabbables in results list. // shootables.collideWith(ray, results); // for (int i = 0; i < results.size(); i++) { // // For each hit, we know distance, impact point, name of geometry. // float dist = results.getCollision(i).getDistance(); // Vector3f pt = results.getCollision(i).getContactPoint(); // String hit = results.getCollision(i).getGeometry().getName(); // System.out.println("* Collision // System.out.println(" You shot " + hit + " at " + pt + ", " + dist + " wu away."); // // Next, we want to calculate and print the distance between our player's vector and // // the colliding object's vector. // Vector3f playerLocation = player.getLocalTranslation(); // float distanceBetweenPlayerAndCollision = playerLocation.distance(pt); // System.out.println("The distance between your player and the collision is: " + distanceBetweenPlayerAndCollision + // " world units (wu)."); // if (distanceBetweenPlayerAndCollision < 20 && !"level-geom-5".equals(hit)) { // (ensure we don't try to pick up the entire town) // // i.e. If object is near player, then lift object (if object is not too heavy) // Geometry collidingObject = results.getCollision(i).getGeometry(); // // i.e. Grab actual object from the collision. // Vector3f objectLocation = collidingObject.getLocalTranslation(); // Vector3f moveUp = new Vector3f(0,1f,0); // Vector3f actualMovement = new Vector3f(); // collidingObject.localToWorld(moveUp, actualMovement); // collidingObject.setLocalTranslation(actualMovement); // // we need to move the mark on the object // // we need to check if the object is approximately in front of character. // // we need to be able to put the object down // // we need the picked-up object to move with the character makeCannonBall(); // THE IMPORTED CODE IS BELOW if (!inventory.getChildren().isEmpty()) { Spatial s1 = inventory.getChild(0); // scale back s1.scale(.02f); s1.setLocalTranslation(oldPosition); inventory.detachAllChildren(); shootables.attachChild(s1); } else { CollisionResults results = new CollisionResults(); Ray ray = new Ray(cam.getLocation(), cam.getDirection()); shootables.collideWith(ray, results); if (results.size() > 0) { CollisionResult closest = results.getClosestCollision(); Spatial s = closest.getGeometry(); // we cheat Model differently with simple Geometry // s.parent is Oto-ogremesh when s is Oto_geom-1 and that is what we need if (s.getName().equals("Oto-geom-1")) { s = s.getParent(); } // It's important to get a clone or otherwise it will behave weird oldPosition = s.getLocalTranslation().clone(); // We also need to ensure that the object can be actually picked up. // To do this, we will need to check its mass and any other relevant properties. // We also need a way to get the object to persist (in inventory) after the button is no longer being // pressed. We also need a way to take the item out of inventory and put it in front of the // character. // We must check if the pickedUp boolean is true. If true, then remove the item from // inventory and place it in front of the character (where cursor is placed). // Then, we need to add the animation in Blender. shootables.detachChild(s); inventory.attachChild(s); // make it bigger to see on the HUD s.scale(50f); int width = settings.getWidth() - 100; int height = settings.getHeight() - 100; // make it on the HUD center s.setLocalTranslation(width, 100, 0); // s.setLocalTranslation(settings.getWidth() / 2, settings.getHeight() / 2, 0); } } } } private void attack() { // The player can attack and walk at the same time. attack() is a custom method that triggers an attack animation in the arms. Here you should also add custom code to play an effect and sound, and to determine whether the hit was successful. attackChannel.setAnim("Dodge", 0.1f); attackChannel.setLoopMode(LoopMode.DontLoop); // this can be an attackChannel instead. } // private ActionListener actionListener = new ActionListener(){ // public void onAction(String name, boolean keyPressed, float tpf){ // if (name.equals("Run")) { // Vector3f forward = playerControl.getViewDirection(); // //Vector3f v = player.getLocalTranslation(); // //Vector3f forward = new Vector3f(0,0,.05f); // Vector3f actualForward = new Vector3f(); // player.localToWorld(forward, actualForward); // if (!channel.getAnimationName().equals("Walk")) { // channel.setAnim("Walk", 0.50f); // channel.setLoopMode(LoopMode.Loop); // //player.setLocalTranslation(actualForward); // playerControl.setWalkDirection(keyPressed ? actualForward : Vector3f.ZERO); // if (name.equals("RotateLeft")) { // Vector3f forward = playerControl.getViewDirection(); // // right direction = cross product between forward and up (forward cross up) // Vector3f downVector = new Vector3f(0,-1,0); // Vector3f leftVector = forward.cross(downVector).normalize(); // playerControl.setViewDirection(keyPressed ? leftVector : Vector3f.ZERO); // if (name.equals("RotateRight")) { // Vector3f forward = playerControl.getViewDirection(); // // right direction = cross product between forward and up (forward cross up) // Vector3f upVector = new Vector3f(0,1,0); // Vector3f rightVector = forward.cross(upVector).normalize(); // playerControl.setViewDirection(keyPressed ? rightVector : Vector3f.ZERO); // if (name.equals("Left")) { // Vector3f forward = player.getLocalTranslation(); // // right direction = cross product between forward and up (forward cross up) // Vector3f downVector = new Vector3f(0,-1,0); // Vector3f leftVector = forward.cross(downVector).normalize(); // playerControl.setWalkDirection(keyPressed ? leftVector : Vector3f.ZERO); // //playerControl.setWalkDirection(leftVector); // //Vector3f v = player.getLocalTranslation(); // //player.setLocalTranslation(v.x - value*speed, v.y, v.z); // if (name.equals("Right")) { // Vector3f forward = player.getLocalTranslation(); // // right direction = cross product between forward and up (forward cross up) // Vector3f upVector = new Vector3f(0,1,0); // Vector3f rightVector = forward.cross(upVector).normalize(); // playerControl.setWalkDirection(keyPressed ? rightVector : Vector3f.ZERO); // //playerControl.setWalkDirection(rightVector); // //player.setLocalTranslation(v.x + value*speed, v.y, v.z); // if (name.equals("Pause") && !keyPressed) { // isRunning = !isRunning; // if (name.equals("Walk") && !keyPressed) { // if (!channel.getAnimationName().equals("Walk")) { // channel.setAnim("Walk", 0.50f); // // How do we activate the analogListener for walk when this occurs? // channel.setLoopMode(LoopMode.Loop); // if (name.equals("Shoot") && !keyPressed) { // // 1. Reset results list // CollisionResults results = new CollisionResults(); // // 2. Aim the ray from character location to character direction. //// Vector3f forward = new Vector3f(0,0,1.05f); // set the magnitude in front of char. //// Vector3f actualForward = new Vector3f(); //// player.localToWorld(forward, actualForward); //// Ray ray = new Ray(player.getLocalTranslation(), actualForward); // Ray ray = new Ray(cam.getLocation(), cam.getDirection()); // // 3. Collect intersections between Ray and grabbables in results list. // shootables.collideWith(ray, results); // for (int i = 0; i < results.size(); i++) { // // For each hit, we know distance, impact point, name of geometry. // float dist = results.getCollision(i).getDistance(); // Vector3f pt = results.getCollision(i).getContactPoint(); // String hit = results.getCollision(i).getGeometry().getName(); // System.out.println("* Collision // System.out.println(" You shot " + hit + " at " + pt + ", " + dist + " wu away."); // // Next, we want to calculate and print the distance between our player's vector and // // the colliding object's vector. // Vector3f playerLocation = player.getLocalTranslation(); // float distanceBetweenPlayerAndCollision = playerLocation.distance(pt); // System.out.println("The distance between your player and the collision is: " + distanceBetweenPlayerAndCollision + // " world units (wu)."); // if (distanceBetweenPlayerAndCollision < 20 && !"level-geom-5".equals(hit)) { // (ensure we don't try to pick up the entire town) // // i.e. If object is near player, then lift object (if object is not too heavy) // Geometry collidingObject = results.getCollision(i).getGeometry(); // // i.e. Grab actual object from the collision. // Vector3f objectLocation = collidingObject.getLocalTranslation(); // Vector3f moveUp = new Vector3f(0,1f,0); // Vector3f actualMovement = new Vector3f(); // collidingObject.localToWorld(moveUp, actualMovement); // collidingObject.setLocalTranslation(actualMovement); // // we need to move the mark on the object // // we need to check if the object is approximately in front of character. // // we need to be able to put the object down // // we need the picked-up object to move with the character // // 5. Use the results (we mark the hit object) // if (results.size() > 0) { // // The closest collision ponit is what was truly hit: // CollisionResult closest = results.getClosestCollision(); // // Let's interact - we mark the hit object with a red dot // mark.setLocalTranslation(closest.getContactPoint()); // rootNode.attachChild(mark); // we need to attach to a container instead of the object // // then, we can move the container when the object is picked up by the character // }else{ // // No hits? Then remove the red mark. // rootNode.detachChild(mark); private AnalogListener analogListener = new AnalogListener(){ public void onAnalog(String name, float value, float tpf){ if (isRunning) { // if (name.equals("Right")) { // Vector3f forward = player.getLocalTranslation(); // // right direction = cross product between forward and up (forward cross up) // Vector3f upVector = new Vector3f(0,1,0); // Vector3f rightVector = forward.cross(upVector).normalize(); // playerControl.setWalkDirection(isPressed ? rightVector : Vector3f.zero); // //playerControl.setWalkDirection(rightVector); // //player.setLocalTranslation(v.x + value*speed, v.y, v.z); // if (name.equals("Left")) { // Vector3f forward = player.getLocalTranslation(); // // right direction = cross product between forward and up (forward cross up) // Vector3f downVector = new Vector3f(0,-1,0); // Vector3f leftVector = forward.cross(downVector).normalize(); // playerControl.setWalkDirection(isPressed ? leftVector : Vector3f.zero); // //playerControl.setWalkDirection(leftVector); // //Vector3f v = player.getLocalTranslation(); // //player.setLocalTranslation(v.x - value*speed, v.y, v.z); if (name.equals("RotateLeft")) { player.rotate(0, value*speed, 0); } if (name.equals("RotateRight")) { player.rotate(0, -value*speed, 0); } if (name.equals("Run")) { Vector3f v = player.getLocalTranslation(); // I can set the local translation to a vector instead. // I would need to calculate the walk vector as a function of their direction? // i.e. It's a function of x and z where x and z can sometimes be negative, // depending on their direction. Thus, it has something to do with radial numbers. Vector3f forward = new Vector3f(0,0,.05f); Vector3f actualForward = new Vector3f(); player.localToWorld(forward, actualForward); // actualForward corresponds to the actual forward direction, but how do we scale this up? // use lookAt to create a quaternion from an up vector and a look direction. // use this resulting quaternion to rotate my vector. Vector3f upVector = new Vector3f(0,1,0); Quaternion quat = new Quaternion(); //quat.lookAt(direction, upVector); quat.lookAt(v, upVector); // the resulting quaternion should rotate a vector that is perpendicular (around x) to the upVector. // we take the vector of our applied values and use the quaternion to rotate it. // The lookAt method available on SPATIALS generates a the direction vector // based on the world location of the spatial and the supplied // location vector. // This allows us to quickly rotate the spatial towards a certain location. if (!channel.getAnimationName().equals("Walk")) { channel.setAnim("Walk", 0.50f); // How do we activate the analogListener for walk when this occurs? channel.setLoopMode(LoopMode.Loop); } //player.setLocalTranslation(actualForward); playerControl.setWalkDirection(actualForward); } else { System.out.println("Press P to unpause."); } } } }; public void onAnimCycleDone(AnimControl control, AnimChannel channel, String animName) { //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. // reset the character to a standing position after a Walk cycle is done. if (channel == attackChannel) channel.setAnim("stand"); if (animName.equals("Walk") || animName.equals("Run") || animName.equals("Right") || animName.equals("Left")) { channel.setAnim("stand", 0.50f); channel.setLoopMode(LoopMode.DontLoop); channel.setSpeed(1f); } } public void onAnimChange(AnimControl control, AnimChannel channel, String animName) { //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. // unused } /** A cube object for target practice */ protected Geometry makeCube(String name, float x, float y, float z) { Box box = new Box(1, 1, 1); Geometry cube = new Geometry(name, box); cube.setLocalTranslation(x, y, z); Material mat1 = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); mat1.setColor("Color", ColorRGBA.randomColor()); cube.setMaterial(mat1); return cube; } /** A red ball that marks the last spot that was "hit" by the "shot". */ protected void initMark() { Sphere sphere = new Sphere(30, 30, 0.2f); mark = new Geometry("BOOM!", sphere); Material mark_mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); mark_mat.setColor("Color", ColorRGBA.Red); mark.setMaterial(mark_mat); } /** A centred plus sign to help the player aim. */ protected void initCrossHairs() { setDisplayStatView(false); guiFont = assetManager.loadFont("Interface/Fonts/Default.fnt"); BitmapText ch = new BitmapText(guiFont, false); ch.setSize(guiFont.getCharSet().getRenderedSize() * 2); ch.setText("+"); // crosshairs ch.setLocalTranslation( // center settings.getWidth() / 2 - ch.getLineWidth()/2, settings.getHeight() / 2 + ch.getLineHeight()/2, 0); guiNode.attachChild(ch); } /** Initialize the materials used in this scene. */ public void initMaterials() { wall_mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); TextureKey key = new TextureKey("Textures/Terrain/BrickWall/BrickWall.jpg"); key.setGenerateMips(true); Texture tex = assetManager.loadTexture(key); wall_mat.setTexture("ColorMap", tex); stone_mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); TextureKey key2 = new TextureKey("Textures/Terrain/Rock/Rock.PNG"); key2.setGenerateMips(true); Texture tex2 = assetManager.loadTexture(key2); stone_mat.setTexture("ColorMap", tex2); floor_mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); TextureKey key3 = new TextureKey("Textures/Terrain/Pond/Pond.jpg"); key3.setGenerateMips(true); Texture tex3 = assetManager.loadTexture(key3); tex3.setWrap(WrapMode.Repeat); floor_mat.setTexture("ColorMap", tex3); } /** Make a solid floor and add it to the scene. */ public void initFloor() { Geometry floor_geo = new Geometry("Floor", floor); floor_geo.setMaterial(floor_mat); floor_geo.setLocalTranslation(0, -5.1f, 0); this.rootNode.attachChild(floor_geo); /* Make the floor physical with mass 0.0f! */ floor_phy = new RigidBodyControl(0.0f); floor_geo.addControl(floor_phy); bulletAppState.getPhysicsSpace().add(floor_phy); } /** This loop builds a wall out of individual bricks. */ public void initWall() { float startpt = brickLength / 4; float height = 0; for (int j = 0; j < 15; j++) { for (int i = 0; i < 6; i++) { Vector3f vt = new Vector3f(i * brickLength * 2 + startpt, brickHeight + height, 0); makeBrick(vt); } startpt = -startpt; height += 2 * brickHeight; } } /** This method creates one individual physical brick. */ public void makeBrick(Vector3f loc) { /** Create a brick geometry and attach to scene graph. */ Geometry brick_geo = new Geometry("brick", box); brick_geo.setMaterial(wall_mat); rootNode.attachChild(brick_geo); /** Position the brick geometry */ brick_geo.setLocalTranslation(loc); /** Make brick physical with a mass > 0.0f. */ brick_phy = new RigidBodyControl(2f); /** Add physical brick to physics space. */ brick_geo.addControl(brick_phy); bulletAppState.getPhysicsSpace().add(brick_phy); } /** This method creates one individual physical cannon ball. * By defaul, the ball is accelerated and flies * from the camera position in the camera direction.*/ public void makeCannonBall() { /** Create a cannon ball geometry and attach to scene graph. */ Geometry ball_geo = new Geometry("cannon ball", sphere); ball_geo.setMaterial(stone_mat); rootNode.attachChild(ball_geo); /** Position the cannon ball */ Vector3f cannonBallOrigin = carNode.getLocalTranslation(); ball_geo.setLocalTranslation(cannonBallOrigin); // ball_geo.setLocalTranslation(cam.getLocation()); /** Make the ball physcial with a mass > 0.0f */ ball_phy = new RigidBodyControl(1f); /** Add physical ball to physics space. */ ball_geo.addControl(ball_phy); bulletAppState.getPhysicsSpace().add(ball_phy); /** Accelerate the physcial ball to shoot it. */ ball_phy.setLinearVelocity(cam.getDirection().mult(25)); } }
package com.horcrux.svg; import android.graphics.PointF; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.WritableMap; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.annotation.Nonnull; import javax.annotation.Nullable; class GlyphContext { private ArrayList<ArrayList<String>> mXPositionsContext; private ArrayList<ArrayList<String>> mYPositionsContext; private ArrayList<ArrayList<Float>> mRotationsContext; private ArrayList<ArrayList<Float>> mDeltaXsContext; private ArrayList<ArrayList<Float>> mDeltaYsContext; private ArrayList<ReadableMap> mFontContext; private ArrayList<Float> mRotationContext; private ArrayList<Float> mRotations; private ArrayList<Float> mDeltaXs; private ArrayList<Float> mDeltaYs; private ArrayList<String> mXs; private ArrayList<String> mYs; private @Nonnull PointF mCurrentLocation; private @Nonnull PointF mCurrentDelta; private int top = -1; private float mScale; private float mWidth; private float mHeight; private float mRotation; private int mContextLength; private static final float DEFAULT_KERNING = 0f; private static final float DEFAULT_FONT_SIZE = 12f; private static final float DEFAULT_LETTER_SPACING = 0f; GlyphContext(float scale, float width, float height) { mXPositionsContext = new ArrayList<>(); mYPositionsContext = new ArrayList<>(); mRotationsContext = new ArrayList<>(); mRotationContext = new ArrayList<>(); mDeltaXsContext = new ArrayList<>(); mDeltaYsContext = new ArrayList<>(); mFontContext = new ArrayList<>(); mRotations = new ArrayList<>(); mDeltaXs = new ArrayList<>(); mDeltaYs = new ArrayList<>(); mXs = new ArrayList<>(); mYs = new ArrayList<>(); mCurrentLocation = new PointF(); mCurrentDelta = new PointF(); mHeight = height; mWidth = width; mScale = scale; } void pushContext(@Nullable ReadableMap font) { mRotationsContext.add(mRotations); mRotationContext.add(mRotation); mDeltaXsContext.add(mDeltaXs); mDeltaYsContext.add(mDeltaYs); mXPositionsContext.add(mXs); mYPositionsContext.add(mYs); mFontContext.add(font); mContextLength++; top++; } void pushContext(@Nullable ReadableMap font, @Nullable ReadableArray rotate, @Nullable ReadableArray deltaX, @Nullable ReadableArray deltaY, @Nullable String positionX, @Nullable String positionY) { if (positionX != null) { mXs = new ArrayList<>(Arrays.asList(positionX.trim().split("\\s+"))); } if (positionY != null) { mYs = new ArrayList<>(Arrays.asList(positionY.trim().split("\\s+"))); } ArrayList<Float> rotations = getFloatArrayListFromReadableArray(rotate); if (rotations.size() != 0) { mRotation = rotations.get(0); mRotations = rotations; } ArrayList<Float> deltaXs = getFloatArrayListFromReadableArray(deltaX); if (deltaXs.size() != 0) { mDeltaXs = deltaXs; } ArrayList<Float> deltaYs = getFloatArrayListFromReadableArray(deltaY); if (deltaYs.size() != 0) { mDeltaYs = deltaYs; } mRotationsContext.add(mRotations); mRotationContext.add(mRotation); mDeltaXsContext.add(mDeltaXs); mDeltaYsContext.add(mDeltaYs); mXPositionsContext.add(mXs); mYPositionsContext.add(mYs); mFontContext.add(font); mContextLength++; top++; } void popContext() { mContextLength top mXPositionsContext.remove(mContextLength); mYPositionsContext.remove(mContextLength); mRotationsContext.remove(mContextLength); mRotationContext.remove(mContextLength); mDeltaXsContext.remove(mContextLength); mDeltaYsContext.remove(mContextLength); mFontContext.remove(mContextLength); if (mContextLength != 0) { mRotations = mRotationsContext.get(top); mRotation = mRotationContext.get(top); mDeltaXs = mDeltaXsContext.get(top); mDeltaYs = mDeltaYsContext.get(top); mXs = mXPositionsContext.get(top); mYs = mYPositionsContext.get(top); } else { mCurrentDelta.x = mCurrentDelta.y = mRotation = 0; mCurrentLocation.x = mCurrentLocation.y = 0; } } PointF getNextGlyphPoint(float glyphWidth) { mCurrentLocation.x = getGlyphPosition(true); mCurrentLocation.y = getGlyphPosition(false); mCurrentLocation.x += glyphWidth; return mCurrentLocation; } PointF getNextGlyphDelta() { mCurrentDelta.x = getNextDelta(true); mCurrentDelta.y = getNextDelta(false); return mCurrentDelta; } float getNextGlyphRotation() { List<Float> prev = null; int index = top; for (; index >= 0; index List<Float> rotations = mRotationsContext.get(index); if (prev != rotations && rotations.size() != 0) { float val = rotations.remove(0); mRotationContext.set(index, val); if (index == top) { mRotation = val; } } prev = rotations; } return mRotation; } private float getNextDelta(boolean isX) { ArrayList<ArrayList<Float>> lists = isX ? mDeltaXsContext : mDeltaYsContext; float delta = isX ? mCurrentDelta.x : mCurrentDelta.y; List<Float> prev = null; for (int index = top; index >= 0; index List<Float> deltas = lists.get(index); if (prev != deltas && deltas.size() != 0) { float val = deltas.remove(0); if (top == index) { delta += val * mScale; } } prev = deltas; } return delta; } private float getGlyphPosition(boolean isX) { ArrayList<ArrayList<String>> lists = isX ? mXPositionsContext : mYPositionsContext; float value = isX ? mCurrentLocation.x : mCurrentLocation.y; List<String> prev = null; for (int index = top; index >= 0; index List<String> list = lists.get(index); if (prev != list && list.size() != 0) { String val = list.remove(0); if (top == index) { float relative = isX ? mWidth : mHeight; value = PropHelper.fromPercentageToFloat(val, relative, 0, mScale); if (isX) { mCurrentDelta.x = 0; } else { mCurrentDelta.y = 0; } } } prev = list; } return value; } ReadableMap getGlyphFont() { float letterSpacing = DEFAULT_LETTER_SPACING; float fontSize = DEFAULT_FONT_SIZE; float kerning = DEFAULT_KERNING; boolean letterSpacingSet = false; boolean fontSizeSet = false; boolean kerningSet = false; String fontFamily = null; String fontWeight = null; String fontStyle = null; // TODO: add support for other length units for (int index = top; index >= 0; index ReadableMap font = mFontContext.get(index); if (fontFamily == null && font.hasKey("fontFamily")) { fontFamily = font.getString("fontFamily"); } if (!fontSizeSet && font.hasKey("fontSize")) { fontSize = (float) font.getDouble("fontSize"); fontSizeSet = true; } if (!kerningSet && font.hasKey("kerning")) { kerning = Float.valueOf(font.getString("kerning")); kerningSet = true; } if (!letterSpacingSet && font.hasKey("letterSpacing")) { letterSpacing = Float.valueOf(font.getString("letterSpacing")); letterSpacingSet = true; } if (fontWeight == null && font.hasKey("fontWeight")) { fontWeight = font.getString("fontWeight"); } if (fontStyle == null && font.hasKey("fontStyle")) { fontStyle = font.getString("fontStyle"); } if (fontFamily != null && fontSizeSet && kerningSet && letterSpacingSet && fontWeight != null && fontStyle != null) { break; } } WritableMap map = Arguments.createMap(); map.putBoolean("isKerningValueSet", kerningSet); map.putDouble("letterSpacing", letterSpacing); map.putString("fontFamily", fontFamily); map.putString("fontWeight", fontWeight); map.putString("fontStyle", fontStyle); map.putDouble("fontSize", fontSize); map.putDouble("kerning", kerning); return map; } private ArrayList<Float> getFloatArrayListFromReadableArray(ReadableArray readableArray) { float fontSize = (float) getGlyphFont().getDouble("fontSize"); ArrayList<Float> arrayList = new ArrayList<>(); if (readableArray != null) { for (int i = 0; i < readableArray.size(); i++) { switch (readableArray.getType(i)) { case String: String val = readableArray.getString(i); arrayList.add(Float.valueOf(val.substring(0, val.length() - 2)) * fontSize); break; case Number: arrayList.add((float) readableArray.getDouble(i)); break; } } } return arrayList; } }
package org.swellrt.android.service; import java.util.ArrayList; import java.util.Collections; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import org.swellrt.android.service.scheduler.OptimalGroupingScheduler; import org.swellrt.android.service.scheduler.SchedulerInstance; import org.swellrt.android.service.wave.WaveDocuments; import org.swellrt.android.service.wave.client.common.util.ClientPercentEncoderDecoder; import org.swellrt.android.service.wave.client.concurrencycontrol.LiveChannelBinder; import org.swellrt.android.service.wave.client.concurrencycontrol.MuxConnector; import org.swellrt.android.service.wave.client.concurrencycontrol.MuxConnector.Command; import org.swellrt.android.service.wave.client.concurrencycontrol.WaveletOperationalizer; import org.swellrt.model.generic.Model; import org.waveprotocol.wave.common.logging.LoggerBundle; import org.waveprotocol.wave.concurrencycontrol.channel.OperationChannelMultiplexer; import org.waveprotocol.wave.concurrencycontrol.channel.OperationChannelMultiplexerImpl; import org.waveprotocol.wave.concurrencycontrol.channel.OperationChannelMultiplexerImpl.LoggerContext; import org.waveprotocol.wave.concurrencycontrol.channel.ViewChannelFactory; import org.waveprotocol.wave.concurrencycontrol.channel.ViewChannelImpl; import org.waveprotocol.wave.concurrencycontrol.channel.WaveViewService; import org.waveprotocol.wave.concurrencycontrol.common.UnsavedDataListener; import org.waveprotocol.wave.concurrencycontrol.common.UnsavedDataListenerFactory; import org.waveprotocol.wave.concurrencycontrol.wave.CcDataDocumentImpl; import org.waveprotocol.wave.model.conversation.ObservableConversationView; import org.waveprotocol.wave.model.conversation.WaveBasedConversationView; import org.waveprotocol.wave.model.document.WaveContext; import org.waveprotocol.wave.model.document.indexed.IndexedDocumentImpl; import org.waveprotocol.wave.model.document.operation.DocInitialization; import org.waveprotocol.wave.model.document.operation.automaton.DocumentSchema; import org.waveprotocol.wave.model.id.IdConstants; import org.waveprotocol.wave.model.id.IdFilter; import org.waveprotocol.wave.model.id.IdGenerator; import org.waveprotocol.wave.model.id.IdURIEncoderDecoder; import org.waveprotocol.wave.model.id.WaveId; import org.waveprotocol.wave.model.id.WaveletId; import org.waveprotocol.wave.model.schema.SchemaProvider; import org.waveprotocol.wave.model.schema.conversation.ConversationSchemas; import org.waveprotocol.wave.model.supplement.ObservableSupplementedWave; import org.waveprotocol.wave.model.util.FuzzingBackOffScheduler; import org.waveprotocol.wave.model.util.FuzzingBackOffScheduler.Cancellable; import org.waveprotocol.wave.model.util.FuzzingBackOffScheduler.CollectiveScheduler; import org.waveprotocol.wave.model.util.Scheduler; import org.waveprotocol.wave.model.version.HashedVersion; import org.waveprotocol.wave.model.version.HashedVersionFactory; import org.waveprotocol.wave.model.version.HashedVersionZeroFactoryImpl; import org.waveprotocol.wave.model.wave.ParticipantId; import org.waveprotocol.wave.model.wave.data.DocumentFactory; import org.waveprotocol.wave.model.wave.data.ObservableWaveletData; import org.waveprotocol.wave.model.wave.data.WaveViewData; import org.waveprotocol.wave.model.wave.data.impl.ObservablePluggableMutableDocument; import org.waveprotocol.wave.model.wave.data.impl.WaveViewDataImpl; import org.waveprotocol.wave.model.wave.data.impl.WaveletDataImpl; import org.waveprotocol.wave.model.wave.opbased.OpBasedWavelet; import org.waveprotocol.wave.model.wave.opbased.WaveViewImpl; import org.waveprotocol.wave.model.wave.opbased.WaveViewImpl.WaveletConfigurator; import org.waveprotocol.wave.model.wave.opbased.WaveViewImpl.WaveletFactory; import org.waveprotocol.wave.model.waveref.WaveRef; import com.google.common.base.Preconditions; public class WaveLoader { public class WaveLoaderTask extends TimerTask { private org.waveprotocol.wave.model.util.Scheduler.Command command; public WaveLoaderTask(org.waveprotocol.wave.model.util.Scheduler.Command command) { this.command = command; } @Override public void run() { command.execute(); } public Cancellable getCancellable() { return new Cancellable() { @Override public void cancel() { WaveLoaderTask.this.cancel(); } }; } }; private boolean isClosed = true; // Provided objects private final WaveRef waveRef; private final boolean isNewWave; private final Set<ParticipantId> otherParticipants; private IdGenerator idGenerator; private ParticipantId signedInuser; private final RemoteViewServiceMultiplexer channel; private final UnsavedDataListener unsavedDataListener; private WaveContext waveContext; private Timer timer; private CollectiveScheduler rpcScheduler; // Wave stack. private WaveViewData waveData; private WaveDocuments<CcDataDocumentImpl> documentRegistry; private WaveletOperationalizer wavelets; private WaveViewImpl<OpBasedWavelet> wave; private MuxConnector connector; // Model objects private ObservableConversationView conversations; // private ObservableSupplementedWave supplement; public static WaveLoader create(boolean isNewWave, WaveRef waveRef, RemoteViewServiceMultiplexer channel, ParticipantId participant, Set<ParticipantId> otherParticipants, IdGenerator idGenerator, UnsavedDataListener unsavedDataListener, Timer timer) { WaveLoader loader = new WaveLoader(isNewWave, waveRef, channel, participant, otherParticipants, idGenerator, unsavedDataListener, timer); return loader; } protected WaveLoader(boolean isNewWave, WaveRef waveRef, RemoteViewServiceMultiplexer channel, ParticipantId participant, Set<ParticipantId> otherParticipants, IdGenerator idGenerator, UnsavedDataListener unsavedDataListener, Timer timer) { this.signedInuser = participant; this.waveRef = waveRef; this.isNewWave = isNewWave; this.idGenerator = idGenerator; this.channel = channel; this.otherParticipants = otherParticipants; this.unsavedDataListener = unsavedDataListener; this.timer = timer; } protected void init(Command command) { waveData = WaveViewDataImpl.create(waveRef.getWaveId()); if (isNewWave) { // Code taken from StageTwoProvider // For a new wave, initial state comes from local initialization. // getConversations().createRoot().getRootThread().appendBlip(); // Adding any initial participant to the new wave // getConversations().getRoot().addParticipantIds(otherParticipants); // getConversations().createRoot().addParticipantIds(otherParticipants); // Install diff control before rendering, because logical diff state may // need to be adjusted due to arbitrary UI policies. getConversations().createRoot().addParticipantIds(otherParticipants); getConnector().connect(command); } else { // For an existing wave, while we're still using the old protocol, // rendering must be delayed until the channel is opened, because the // initial state snapshots come from the channel. // Install diff control before rendering, because logical diff state may // need to be adjusted due to arbitrary UI policies. getConnector().connect(command); } isClosed = false; } public WaveContext getWaveContext() { if (isClosed) return null; if (waveContext == null) waveContext = new WaveContext(getWave(), getConversations(), getSupplement(), null); return waveContext; } public void close() { if (!isClosed) { getConnector().close(); isClosed = true; } } // Level 1 protected WaveViewData getWaveData() { Preconditions.checkState(waveData != null, "wave not ready"); return waveData; } protected ObservableConversationView getConversations() { return conversations == null ? conversations = createConversations() : conversations; } protected ObservableConversationView createConversations() { return WaveBasedConversationView.create(getWave(), getIdGenerator()); } protected MuxConnector getConnector() { return connector == null ? connector = createConnector() : connector; } protected MuxConnector createConnector() { // LoggerBundle logger = LoggerBundle.NOP_IMPL; LoggerBundle loggerOps = new AndroidLoggerBundle("WaveProtocol::ops"); LoggerBundle loggerDeltas = new AndroidLoggerBundle("WaveProtocol::deltas"); LoggerBundle loggerCc = new AndroidLoggerBundle("WaveProtocol::CC"); LoggerBundle loggerView = new AndroidLoggerBundle("WaveProtocol::view"); LoggerContext loggers = new LoggerContext(loggerOps, loggerDeltas, loggerCc, loggerView); IdURIEncoderDecoder uriCodec = new IdURIEncoderDecoder(new ClientPercentEncoderDecoder()); HashedVersionFactory hashFactory = new HashedVersionZeroFactoryImpl(uriCodec); Scheduler scheduler = new FuzzingBackOffScheduler.Builder(getRpcScheduler()) .setInitialBackOffMs(1000).setMaxBackOffMs(60000).setRandomisationFactor(0.5).build(); ViewChannelFactory viewFactory = ViewChannelImpl.factory(createWaveViewService(), loggerView); UnsavedDataListenerFactory unsyncedListeners = new UnsavedDataListenerFactory() { private final UnsavedDataListener listener = unsavedDataListener; @Override public UnsavedDataListener create(WaveletId waveletId) { return listener; } @Override public void destroy(WaveletId waveletId) { } }; WaveletId udwId = getIdGenerator().newUserDataWaveletId(getSignedInUser().getAddress()); ArrayList<String> prefixes = new ArrayList<String>(); prefixes.add(IdConstants.CONVERSATION_WAVELET_PREFIX); prefixes.add(Model.WAVELET_ID_PREFIX); final IdFilter filter = IdFilter.of(Collections.singleton(udwId), prefixes); WaveletDataImpl.Factory snapshotFactory = WaveletDataImpl.Factory.create(getDocumentRegistry()); final OperationChannelMultiplexer mux = new OperationChannelMultiplexerImpl(getWave() .getWaveId(), viewFactory, snapshotFactory, loggers, unsyncedListeners, scheduler, hashFactory); final WaveViewImpl<OpBasedWavelet> wave = getWave(); return new MuxConnector() { @Override public void connect(Command onOpened) { LiveChannelBinder.openAndBind(getWavelets(), wave, getDocumentRegistry(), mux, filter, onOpened); } @Override public void close() { mux.close(); } }; } // Level 2 protected ParticipantId getSignedInUser() { return signedInuser; } protected IdGenerator getIdGenerator() { return idGenerator; // TODO assess whether create the id generator here } protected WaveViewImpl<OpBasedWavelet> getWave() { return wave == null ? wave = createWave() : wave; } protected WaveViewImpl<OpBasedWavelet> createWave() { WaveViewData snapshot = getWaveData(); // The operationalizer makes the wavelets function via operation control. // The hookup with concurrency-control and remote operation streams occurs // later in createUpgrader(). final WaveletOperationalizer operationalizer = getWavelets(); WaveletFactory<OpBasedWavelet> waveletFactory = new WaveletFactory<OpBasedWavelet>() { @Override public OpBasedWavelet create(WaveId waveId, WaveletId id, ParticipantId creator) { long now = System.currentTimeMillis(); ObservableWaveletData data = new WaveletDataImpl(id, creator, now, 0L, HashedVersion.unsigned(0), now, waveId, getDocumentRegistry()); return operationalizer.operationalize(data); } }; WaveViewImpl<OpBasedWavelet> wave = WaveViewImpl.create(waveletFactory, snapshot.getWaveId(), getIdGenerator(), getSignedInUser(), WaveletConfigurator.ADD_CREATOR); // Populate the initial state. for (ObservableWaveletData waveletData : snapshot.getWavelets()) { wave.addWavelet(operationalizer.operationalize(waveletData)); } return wave; } protected CollectiveScheduler getRpcScheduler() { return rpcScheduler == null ? rpcScheduler = createRpcScheduler() : rpcScheduler; } protected CollectiveScheduler createRpcScheduler() { // Use a scheduler that runs closely-timed tasks at the same time. // Adapted Android version from orignal GWT-based return new OptimalGroupingScheduler(SchedulerInstance.getLowPriorityTimer()); } protected WaveViewService createWaveViewService() { return new RemoteWaveViewService(waveRef.getWaveId(), channel, getDocumentRegistry()); } protected WaveDocuments<CcDataDocumentImpl> getDocumentRegistry() { return documentRegistry == null ? documentRegistry = createDocumentRegistry() : documentRegistry; } /** * This Document registry separates the pure Wave protocol client code from * the former GWT/HTML user interface. * * In this Android version, there are no referenfes to ContentDocument and * LazyContentDocument, actual classes for blip rendering in GWT/HTML. * * Now all Wave documents are handle as Data Documents. * * @return WaveDocuments<CcDataDocumentImpl> */ protected WaveDocuments<CcDataDocumentImpl> createDocumentRegistry() { IndexedDocumentImpl.performValidation = false; // TODO createSchemas() is needed? DocumentFactory<?> dataDocFactory = ObservablePluggableMutableDocument.createFactory(createSchemas()); /** * Replacement of * * <pre> * DocumentFactory<LazyContentDocument> * </pre> * * By now, no special content documents are managed. No schema constrains * are attached to new docs. * */ DocumentFactory<CcDataDocumentImpl> fakeBlipDocFactory = new DocumentFactory<CcDataDocumentImpl>() { @Override public CcDataDocumentImpl create(WaveletId waveletId, String docId, DocInitialization content) { return new CcDataDocumentImpl(DocumentSchema.NO_SCHEMA_CONSTRAINTS, content); } }; return WaveDocuments.create(fakeBlipDocFactory, dataDocFactory); } protected WaveletOperationalizer getWavelets() { return wavelets == null ? wavelets = createWavelets() : wavelets; } protected WaveletOperationalizer createWavelets() { return WaveletOperationalizer.create(getWaveData().getWaveId(), getSignedInUser()); } // Level 3 protected SchemaProvider createSchemas() { return new ConversationSchemas(); } public final ObservableSupplementedWave getSupplement() { return null; // Supplement relies on GWT scheduler, so we ignore it // anyway // return supplement == null ? supplement = createSupplement() : supplement; } protected ObservableSupplementedWave createSupplement() { /* * Wavelet udw = getWave().getUserData(); if (udw == null) { udw = * getWave().createUserData(); } ObservablePrimitiveSupplement state = * WaveletBasedSupplement.create(udw); ObservableSupplementedWave live = new * LiveSupplementedWaveImpl(state, getWave(), getSignedInUser(), * DefaultFollow.ALWAYS, getConversations()); return * LocalSupplementedWaveImpl.create(getWave(), live); */ return null; } }
package edu.wustl.query.domain; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Stack; import org.apache.commons.lang.math.NumberUtils; import edu.wustl.common.actionForm.IValueObject; import edu.wustl.common.domain.AbstractDomainObject; import edu.wustl.common.exception.AssignDataException; import edu.wustl.common.querysuite.queryobject.IAbstractQuery; import edu.wustl.common.querysuite.queryobject.IOperation; import edu.wustl.common.querysuite.queryobject.impl.CompositeQuery; import edu.wustl.common.querysuite.queryobject.impl.Intersection; import edu.wustl.common.querysuite.queryobject.impl.Minus; import edu.wustl.common.querysuite.queryobject.impl.Operation; import edu.wustl.common.querysuite.queryobject.impl.ParameterizedQuery; import edu.wustl.common.querysuite.queryobject.impl.Union; import edu.wustl.query.actionForm.WorkflowForm; import edu.wustl.query.util.global.CompositeQueryOperations; /** * @author vijay_pande * Class for Workflow domain object */ public class Workflow extends AbstractDomainObject { /** * Default serial version id */ private static final long serialVersionUID = 1L; /** * List of items in workflow */ private List<WorkflowItem> workflowItemList; /** * identifier for workflow */ private Long id; /** * Name of workflow */ private String name; /** * Workflow creation date */ private Date createdOn; // private User createdBy; private final Map<String,IAbstractQuery> queryIdMap = new HashMap<String, IAbstractQuery>(); /** * Default constructor for workflow */ public Workflow() { super(); } /** * Constructor for workflow * @param object object of type IValueObject (formbean) * @throws AssignDataException */ public Workflow(final IValueObject object) throws AssignDataException { this(); setAllValues(object); } /** * Method to get name of the workflow * @return name of type String */ public String getName() { return name; } /** * Method to set name of the workflow * @param name of type String */ public void setName(String name) { this.name = name; } /** * Method to set id of the workflow * * @param id of type Long */ @Override public void setId(Long id) { this.id = id; } /** * Method to set id of the workflow * @return id of type Long */ @Override public Long getId() { return this.id; } /** * Method to set workflowItemList of the workflow * @param workflowItemList List of object of type WorkflowItem */ public void setWorkflowItemList(List<WorkflowItem> workflowItemList) { this.workflowItemList = workflowItemList; } /** * Method to get workflowItemList of the workflow * @return workflowItemList List of object of type WorkflowItem */ public List<WorkflowItem> getWorkflowItemList() { return this.workflowItemList; } /** * Method to get workflow creation date * @return createdOn of type Date */ public Date getCreatedOn() { return createdOn; } /** * Method to set workflow creation date * @param createdOn of type Date */ public void setCreatedOn(Date createdOn) { this.createdOn = createdOn; } // public User getCreatedBy() // return createdBy; // public void setCreatedBy(User createdBy) // this.createdBy = createdBy; /** * @param workflow form * @throws AssignDataException * Method to populate domain object from formBean */ @Override public void setAllValues(IValueObject form) throws AssignDataException { WorkflowForm workFlowForm = (WorkflowForm) form; String[] displayQueryTitle =workFlowForm.getDisplayQueryTitle(); this.workflowItemList = new ArrayList<WorkflowItem>(); this.setName(workFlowForm.getName()); this.setCreatedOn(new Date()); String[] operators = workFlowForm.getOperators(); String[] operands = workFlowForm.getOperands(); String[] identifier=workFlowForm.getQueryIdForRow(); String[] expressions = workFlowForm.getExpression(); // String[] expressions = new String[] {""}; int numberOfRows = 0; if (operators != null) { numberOfRows = operators.length; } for (int i = 0; i < numberOfRows; i++) { // IAbstractQuery query = getQuery(operators[i], operands[i],displayQueryTitle[i]); IAbstractQuery query = getQuery(expressions[i]); query.setName(displayQueryTitle[i]); WorkflowItem workflowItem = new WorkflowItem(); if(!identifier[i].contains("_")) { query.setId(Long.parseLong(identifier[i])); } workflowItem.setQuery(query); workflowItem.setPosition(i); this.workflowItemList.add(workflowItem); } this.setWorkflowItemList(workflowItemList); } /** * Method to get label for the domain object * @return label of domain object */ @Override public String getMessageLabel() { return this.getClass().toString(); } /** * @param operators * @param operands * @param queryTitle * @param expression * @return */ public IAbstractQuery getQuery(String operators, String operands,String queryTitle) { IAbstractQuery query = null; if (operators.equals(CompositeQueryOperations.NONE.getOperation())) { query = new ParameterizedQuery(); //query.setId(Long.parseLong(operands)); ((ParameterizedQuery)query).setName(queryTitle); } else { query = getCompositeQuery(operators, operands); ((CompositeQuery)query).setName(queryTitle); } return query; } public IAbstractQuery getCompositeQuery(String operators, String operands) { String[] operand = operands.split("_"); IAbstractQuery compositeQuery = new CompositeQuery(); if (operand.length > 2) { IAbstractQuery operandTwo = new ParameterizedQuery(); operandTwo.setId(Long.parseLong(operands.substring(operands.lastIndexOf('_') + 1))); String tempOperation = operators.substring(operators.lastIndexOf('_') + 1); IAbstractQuery tempCompositeQuery = getCompositeQuery(operators.substring(0, operators .lastIndexOf('_')), operands.substring(0, operands.lastIndexOf('_'))); ((CompositeQuery) compositeQuery).setOperation(getOperationForCompositeQuery( tempOperation, tempCompositeQuery, operandTwo)); } else { String[] ids = operands.split("_"); String[] operator = operators.split("_"); IAbstractQuery operandOne = new ParameterizedQuery(); operandOne.setId(Long.parseLong(ids[0])); IAbstractQuery operandTwo = new ParameterizedQuery(); operandTwo.setId(Long.parseLong(ids[1])); compositeQuery = new CompositeQuery(); ((CompositeQuery) compositeQuery).setOperation(getOperationForCompositeQuery( operator[0], operandOne, operandTwo)); String name = "CompositeQuery_"+ new Date().getTime(); ((CompositeQuery)compositeQuery).setName(name); ((CompositeQuery)compositeQuery).setType("operation"); } return compositeQuery; } public IOperation getOperationForCompositeQuery(String operation, IAbstractQuery operandOne, IAbstractQuery operandTwo) { Operation operationObj = null; if (operation.equals(CompositeQueryOperations.UNION.getOperation())) { operationObj = new Union(); } else if (operation.equals(CompositeQueryOperations.MINUS.getOperation())) { operationObj = new Minus(); } else if (operation.equals(CompositeQueryOperations.INTERSECTION.getOperation())) { operationObj = new Intersection(); } operationObj.setOperandOne(operandOne); operationObj.setOperandTwo(operandTwo); return operationObj; } /** * Forms the IAbstract Query object based on the post fix expression. * @param expression The post fix expression * @return The correspondign IAbstractQuery object. */ public IAbstractQuery getQuery(String expression) { Stack<IAbstractQuery> stack = new Stack<IAbstractQuery>(); String[] exprStack = expression.split("_"); for (String var : exprStack) { var = var.trim(); if (NumberUtils.isNumber(var)) { // Its a queryId, so skip IAbstractQuery queryVar = null; if (queryIdMap.containsKey(var)) { queryVar = queryIdMap.get(var); } else { queryVar = new ParameterizedQuery(); queryIdMap.put(var, queryVar); } stack.push(queryVar); } else { // Its an operator, so pop last 2 from stack, create a new CQ // with current operator and the popped operands and then push // the new node. IAbstractQuery op1 = stack.pop(); IAbstractQuery op2 = stack.pop(); IAbstractQuery op3 = null; String key = op2.getId() + "_" + op1.getId() + "_" + var; if (queryIdMap.containsKey(key)) { op3 = queryIdMap.get(key); } else { op3 = new CompositeQuery(); Operation operationObj = null; CompositeQueryOperations opr = CompositeQueryOperations.get(var); if (opr.equals(CompositeQueryOperations.UNION)) { operationObj = new Union(); } else if (opr.equals(CompositeQueryOperations.MINUS)) { operationObj = new Minus(); } else if (opr.equals(CompositeQueryOperations.INTERSECTION)) { operationObj = new Intersection(); } operationObj.setOperandOne(op1); operationObj.setOperandTwo(op2); ((CompositeQuery) op3).setOperation(operationObj); queryIdMap.put(key, op3); } stack.push(op3); } } return stack.pop(); } }
package org.workcraft.gui; import java.awt.Dimension; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JToggleButton; import javax.swing.JToolBar; import javax.swing.SwingConstants; import org.workcraft.Framework; import org.workcraft.annotations.Annotations; import org.workcraft.dom.visual.SizeHelper; import org.workcraft.dom.visual.VisualModel; import org.workcraft.gui.events.GraphEditorKeyEvent; import org.workcraft.gui.graph.GraphEditorPanel; import org.workcraft.gui.graph.generators.DefaultNodeGenerator; import org.workcraft.gui.graph.tools.CustomToolsProvider; import org.workcraft.gui.graph.tools.GraphEditorKeyListener; import org.workcraft.gui.graph.tools.GraphEditorTool; import org.workcraft.gui.graph.tools.NodeGeneratorTool; import org.workcraft.gui.graph.tools.ToolProvider; public class Toolbox implements ToolProvider, GraphEditorKeyListener { class ToolTracker { ArrayList<GraphEditorTool> tools = new ArrayList<>(); int nextIndex = 0; public void addTool(GraphEditorTool tool) { tools.add(tool); nextIndex = 0; } public void reset() { nextIndex = 0; } public GraphEditorTool getNextTool() { GraphEditorTool ret = tools.get(nextIndex); setNext(nextIndex + 1); return ret; } private void setNext(int next) { if (next >= tools.size()) { next %= tools.size(); } nextIndex = next; } public void track(GraphEditorTool tool) { setNext(tools.indexOf(tool) + 1); } } private final GraphEditorPanel editor; private final HashSet<GraphEditorTool> tools = new HashSet<>(); private final LinkedHashMap<GraphEditorTool, JToggleButton> buttons = new LinkedHashMap<>(); private final HashMap<Integer, ToolTracker> hotkeyMap = new HashMap<>(); private GraphEditorTool defaultTool = null; private GraphEditorTool selectedTool = null; public Toolbox(GraphEditorPanel editor) { this.editor = editor; VisualModel model = editor.getModel(); Class<? extends CustomToolsProvider> customTools = Annotations.getCustomToolsProvider(model.getClass()); if (customTools != null) { boolean isDefault = true; CustomToolsProvider provider = null; try { provider = customTools.getConstructor().newInstance(); } catch (Exception e) { e.printStackTrace(); } if (provider != null) { for (GraphEditorTool tool : provider.getTools()) { addTool(tool, isDefault); isDefault = false; } } } for (Class<?> cls : Annotations.getDefaultCreateButtons(model.getClass())) { NodeGeneratorTool tool = new NodeGeneratorTool(new DefaultNodeGenerator(cls)); addTool(tool, false); } for (Class<? extends GraphEditorTool> tool : Annotations.getCustomTools(model.getClass())) { try { addTool(tool.newInstance(), false); } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException(e); } } selectedTool = defaultTool; setToolButtonSelection(selectedTool, true); } private void addTool(final GraphEditorTool tool, boolean isDefault) { tools.add(tool); if (tool.requiresButton()) { JToggleButton button = createToolButton(tool); buttons.put(tool, button); } assignToolHotKey(tool, tool.getHotKeyCode()); if (isDefault) { defaultTool = tool; } } private void assignToolHotKey(final GraphEditorTool tool, int hotKeyCode) { if (hotKeyCode != -1) { ToolTracker tracker = hotkeyMap.get(hotKeyCode); if (tracker == null) { tracker = new ToolTracker(); hotkeyMap.put(hotKeyCode, tracker); } tracker.addTool(tool); } } private JToggleButton createToolButton(final GraphEditorTool tool) { JToggleButton button = new JToggleButton(); button.setFocusable(false); button.setHorizontalAlignment(SwingConstants.LEFT); button.setMargin(new Insets(0, 0, 0, 0)); int iconSize = SizeHelper.getToolIconSize(); Insets insets = button.getInsets(); int minSize = iconSize + Math.max(insets.left + insets.right, insets.top + insets.bottom); Icon icon = tool.getIcon(); if (icon == null) { button.setText(tool.getLabel()); button.setPreferredSize(new Dimension(120, minSize)); } else { BufferedImage crop = new BufferedImage(iconSize, iconSize, BufferedImage.TYPE_INT_ARGB); int x = (iconSize - icon.getIconWidth()) / 2; int y = (iconSize - icon.getIconHeight()) / 2; icon.paintIcon(button, crop.getGraphics(), x, y); button.setIcon(new ImageIcon(crop)); button.setPreferredSize(new Dimension(minSize, minSize)); } int hotKeyCode = tool.getHotKeyCode(); if (hotKeyCode != -1) { button.setToolTipText(tool.getLabel() + " (" + Character.toString((char) hotKeyCode) + ")"); } else { button.setToolTipText(tool.getLabel()); } button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { selectTool(tool); } }); return button; } @SuppressWarnings("unchecked") public <T extends GraphEditorTool> T getToolInstance(Class<T> cls) { for (GraphEditorTool tool : tools) { if (cls == tool.getClass()) { return (T) tool; } } for (GraphEditorTool tool : tools) { if (cls.isInstance(tool)) { return (T) tool; } } return null; } public <T extends GraphEditorTool> T selectToolInstance(Class<T> cls) { final T tool = getToolInstance(cls); if (tool != null) { selectTool(tool); return (T) tool; } return null; } public void selectTool(GraphEditorTool tool) { if (selectedTool != null) { ToolTracker oldTracker = hotkeyMap.get(selectedTool.getHotKeyCode()); if (oldTracker != null) { oldTracker.reset(); } selectedTool.deactivated(editor); setToolButtonSelection(selectedTool, false); } ToolTracker tracker = hotkeyMap.get(tool.getHotKeyCode()); if (tracker != null) { tracker.track(tool); } // Setup and activate the selected tool (before updating Property editor and Tool controls). selectedTool = tool; setToolButtonSelection(selectedTool, true); selectedTool.setup(editor); selectedTool.activated(editor); // Update the content of Property editor (first) and Tool controls (second). editor.updatePropertyView(); editor.updateToolsView(); // Update visibility of Property editor and Tool controls. final Framework framework = Framework.getInstance(); final MainWindow mainWindow = framework.getMainWindow(); mainWindow.updateDockableWindowVisibility(); } public void setToolsForModel(JToolBar toolbar) { for (JToggleButton button: buttons.values()) { toolbar.add(button); } // FIXME: Add separator to force the same toolbar height as the tool controls and global toolbars. toolbar.addSeparator(); } @Override public GraphEditorTool getDefaultTool() { return defaultTool; } @Override public GraphEditorTool getSelectedTool() { return selectedTool; } @Override public boolean keyPressed(GraphEditorKeyEvent event) { if (selectedTool.keyPressed(event)) { return true; } int keyCode = event.getKeyCode(); if (keyCode == KeyEvent.VK_ESCAPE) { selectTool(defaultTool); return true; } if (!event.isAltKeyDown() && !event.isMenuKeyDown() && !event.isShiftKeyDown()) { ToolTracker tracker = hotkeyMap.get(keyCode); if (tracker != null) { GraphEditorTool tool = tracker.getNextTool(); selectTool(tool); return true; } } return false; } @Override public boolean keyReleased(GraphEditorKeyEvent event) { return selectedTool.keyReleased(event); } @Override public boolean keyTyped(GraphEditorKeyEvent event) { return selectedTool.keyTyped(event); } public void setToolButtonEnableness(GraphEditorTool tool, boolean state) { JToggleButton button = buttons.get(tool); if (button != null) { button.setEnabled(state); } } public void setToolButtonSelection(GraphEditorTool tool, boolean state) { JToggleButton button = buttons.get(tool); if (button != null) { button.setSelected(state); } } }
package traffic; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import org.apache.log4j.Logger; import org.apache.log4j.BasicConfigurator; import org.jdom.JDOMException; import traffic.model.ConfigurationException; import traffic.model.SimulationXMLReader; import traffic.model.TrafficSimulator; /** * This is the main class for running the simulator * It takes in a commandline argument and attempts to run the simulation with it * * @author Jonathan Ramaswamy - ramaswamyj12@gmail.com */ public class TrafficMain { private static Logger logger = Logger.getLogger(TrafficMain.class); //Logger that outputs simulation information private static TrafficSimulator tsim; //The instance of the traffic simulator /** * * @param args * @throws JDOMException * @throws IOException * @throws ConfigurationException */ public static void main(String[] args) { BasicConfigurator.configure(); ConfigurationOptions opts = null; logger.info( Version.versionString() ); try { opts = ConfigurationOptions.parse(args); } catch (Exception e) { //Catches invalid commandline statement logger.error( "Parsing commandline arguments: " + e.getMessage() ); System.exit(1); } assert opts != null; logger.info("Loading Simulation"); try{ tsim = SimulationXMLReader.buildSimulator( new File(opts.getInputFile() ) ); logger.info("Starting Simulation"); tsim.run(); logger.info("Stopping simulation"); } catch (ConfigurationException e) { //Catches configuration error in XML file logger.info("Exiting due to configuration error " + e.getMessage()); } catch (FileNotFoundException e) { logger.info("Exiting because file cannot be found " + e.getMessage()); } //NO CODE BEYOND THIS LINE } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; /** * This class is a barebones example of how to use the BukkitDev ServerMods API to check for file updates. * <br> * See the README file for further information of use. */ public class Update { // The project's unique ID private final int projectID; // An optional API key to use, will be null if not submitted private final String apiKey; // Keys for extracting file information from JSON response private static final String API_NAME_VALUE = "name"; private static final String API_LINK_VALUE = "downloadUrl"; private static final String API_RELEASE_TYPE_VALUE = "releaseType"; private static final String API_FILE_NAME_VALUE = "fileName"; private static final String API_GAME_VERSION_VALUE = "gameVersion"; // Static information for querying the API private static final String API_QUERY = "/servermods/files?projectIds="; private static final String API_HOST = "https://api.curseforge.com"; /** * Check for updates anonymously (keyless) * * @param projectID The BukkitDev Project ID, found in the "Facts" panel on the right-side of your project page. */ public Update(int projectID) { this(projectID, null); } public Update(int projectID, String apiKey) { this.projectID = projectID; this.apiKey = apiKey; query(); } /** * Query the API to find the latest approved file's details. */ public void query() { URL url = null; try { // Create the URL to query using the project's ID url = new URL(API_HOST + API_QUERY + projectID); } catch (MalformedURLException e) { // There was an error creating the URL e.printStackTrace(); return; } try { // Open a connection and query the project URLConnection conn = url.openConnection(); if (apiKey != null) { // Add the API key to the request if present conn.addRequestProperty("X-API-Key", apiKey); } // Add the user-agent to identify the program conn.addRequestProperty("User-Agent", "ServerModsAPI-Example (by Gravity)"); // Read the response of the query // The response will be in a JSON format, so only reading one line is necessary. final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String response = reader.readLine(); // Parse the array of files from the query's response JSONArray array = (JSONArray) JSONValue.parse(response); if (array.size() > 0) { // Get the newest file's details JSONObject latest = (JSONObject) array.get(array.size() - 1); // Get the version's title String versionName = (String) latest.get(API_NAME_VALUE); // Get the version's link String versionLink = (String) latest.get(API_LINK_VALUE); // Get the version's release type String versionType = (String) latest.get(API_RELEASE_TYPE_VALUE); // Get the version's file name String versionFileName = (String) latest.get(API_FILE_NAME_VALUE); // Get the version's game version String versionGameVersion = (String) latest.get(API_GAME_VERSION_VALUE); System.out.println( "The latest version of " + versionFileName + " is " + versionName + ", a " + versionType.toUpperCase() + " for " + versionGameVersion + ", available at: " + versionLink ); } else { System.out.println("There are no files for this project"); } } catch (IOException e) { // There was an error reading the query e.printStackTrace(); return; } } }
package ublu.command; import ublu.util.ArgArray; import ublu.util.DataSink; import ublu.util.Generics.StringArrayList; import ublu.util.Tuple; import com.ibm.as400.access.AS400; import com.ibm.as400.access.AS400SecurityException; import com.ibm.as400.access.AS400Text; import com.ibm.as400.access.ErrorCompletingRequestException; import com.ibm.as400.access.IFSFile; import com.ibm.as400.access.IFSFileInputStream; import com.ibm.as400.access.IFSFileOutputStream; import com.ibm.as400.access.IFSFileWriter; import com.ibm.as400.access.ObjectDoesNotExistException; import com.ibm.as400.access.RequestNotSupportedException; import java.beans.PropertyVetoException; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.sql.SQLException; import java.util.logging.Level; import ublu.util.Generics.ByteArrayList; /** * Command to access Integrated File System stream files * * @author jwoehr */ public class CmdIFS extends Command { { setNameAndDescription("ifs", "/4? [-ifs,-- @ifsfile] [-as400 @as400] [-length ~@{length}] [-offset ~@{offset}] [-create | -delete | -exists | -file | -list | -mkdirs | -read ~@{offset} ~@{chars} | -write [~@{string }] | -writebin ] [-to datasink] [-from datasink] ~@{/fully/qualified/pathname} ~@{system} ~@{user} ~@{password} : integrated file system access"); } /** * The functions performed by the ifs command */ protected static enum FUNCTIONS { /** * Create an IFS file */ CREATE, /** * Delete an IFS file */ DELETE, /** * Test existence of an IFS file */ EXISTS, /** * Instance object representing file */ FILE, /** * List directory of IFS files */ LIST, /** * Create a dir or dir hierarchy */ MKDIRS, /** * Nada */ NOOP, /** * Read an IFS file */ READ, /** * Write an IFS text file */ WRITE, /** * Write an IFS binary file */ WRITEBIN } /** * Create instance */ public CmdIFS() { } private Tuple ifsFileTuple = null; private Integer binOffset = null; private Integer binLength = null; /** * Parse arguments and perform IFS operations * * @param argArray passed-in arg array * @return rest of arg array */ public ArgArray ifs(ArgArray argArray) { FUNCTIONS function = FUNCTIONS.FILE; String writeableString = null; int offset = 0; int numToRead = 0; while (argArray.hasDashCommand()) { String dashCommand = argArray.parseDashCommand(); switch (dashCommand) { case "-ifs": case " ifsFileTuple = argArray.nextTupleOrPop(); break; case "-as400": setAs400(getAS400Tuple(argArray.next())); break; case "-to": setDataDest(DataSink.fromSinkName(argArray.next())); break; case "-from": setDataSrc(DataSink.fromSinkName(argArray.next())); break; case "-create": function = FUNCTIONS.CREATE; break; case "-delete": function = FUNCTIONS.DELETE; break; case "-exists": function = FUNCTIONS.EXISTS; break; case "-file": function = FUNCTIONS.FILE; break; case "-list": function = FUNCTIONS.LIST; break; case "-mkdirs": function = FUNCTIONS.MKDIRS; break; case "-noop": break; case "-read": function = FUNCTIONS.READ; offset = argArray.nextIntMaybeQuotationTuplePopString(); numToRead = argArray.nextIntMaybeQuotationTuplePopString(); break; case "-write": function = FUNCTIONS.WRITE; if (getDataSrc().getType() == DataSink.SINKTYPE.STD) { writeableString = argArray.nextMaybeQuotationTuplePopString(); } break; case "-writebin": function = FUNCTIONS.WRITEBIN; break; case "-offset": binOffset = argArray.nextIntMaybeQuotationTuplePopString(); break; case "-length": binLength = argArray.nextIntMaybeQuotationTuplePopString(); break; default: unknownDashCommand(dashCommand); } } if (havingUnknownDashCommand()) { setCommandResult(COMMANDRESULT.FAILURE); } else { switch (function) { case CREATE: ifsCreate(argArray); break; case DELETE: ifsDelete(argArray); break; case EXISTS: ifsExists(argArray); break; case FILE: ifsFile(argArray); break; case LIST: ifsList(argArray); break; case MKDIRS: ifsMkdirs(argArray); break; case NOOP: ifsNoop(); break; case READ: ifsRead(argArray, offset, numToRead); break; case WRITE: ifsWrite(argArray, writeableString); break; case WRITEBIN: ifsWriteBin(argArray); break; } } return argArray; } private IFSFile getIFSFileFromDataSink(DataSink datasink) { IFSFile ifsFile = null; if (datasink.getType() == DataSink.SINKTYPE.TUPLE) { Tuple t = getTuple(datasink.getName()); Object o = t.getValue(); ifsFile = o instanceof IFSFile ? IFSFile.class.cast(o) : null; } return ifsFile; } private IFSFile getIFSFileFromEponymous() { IFSFile ifsFile = null; if (ifsFileTuple != null) { Object o = ifsFileTuple.getValue(); ifsFile = o instanceof IFSFile ? IFSFile.class.cast(o) : null; } return ifsFile; } private IFSFile getIFSFileFromDataSource() { IFSFile ifsFile; ifsFile = getIFSFileFromEponymous(); if (ifsFile == null) { ifsFile = getIFSFileFromDataSink(getDataSrc()); } return ifsFile; } private IFSFile getIFSFileFromDataDest() { IFSFile ifsFile; ifsFile = getIFSFileFromEponymous(); if (ifsFile == null) { ifsFile = getIFSFileFromDataSink(getDataDest()); } return ifsFile; } private IFSFile getIFSFileFromArgArray(ArgArray argArray) { IFSFile ifsFile = null; if (getAs400() == null && argArray.size() < 3) { // if no passed-in AS400 instance and not enough args to generate one logArgArrayTooShortError(argArray); setCommandResult(COMMANDRESULT.FAILURE); } else { String fqpn = argArray.nextMaybeQuotationTuplePopString(); if (getAs400() == null) { try { setAs400FromArgs(argArray); } catch (PropertyVetoException ex) { getLogger().log(Level.SEVERE, "The ifs commmand encountered an exception getting an IFS file from the supplied command arguments.", ex); setCommandResult(COMMANDRESULT.FAILURE); } } if (getAs400() != null) { ifsFile = new IFSFile(getAs400(), fqpn); } } return ifsFile; } private String getTextToWrite(AS400 as400, String writeableString) throws FileNotFoundException, IOException { String text = null; DataSink dsrc = getDataSrc(); switch (dsrc.getType()) { case STD: text = writeableString; break; case FILE: File f = new File(dsrc.getName()); FileReader fr = new FileReader(f); int length = new Long(f.length()).intValue(); char[] in = new char[length]; fr.read(in); text = new String(in); break; case TUPLE: text = getTuple(dsrc.getName()).getValue().toString(); break; } return text; } private void ifsCreate(ArgArray argArray) { IFSFile ifsFile = getIFSFileFromDataSource(); if (ifsFile == null) { ifsFile = getIFSFileFromArgArray(argArray); } if (ifsFile != null) { try { put(ifsFile.createNewFile()); } catch (IOException | RequestNotSupportedException | SQLException | AS400SecurityException | InterruptedException | ObjectDoesNotExistException | ErrorCompletingRequestException ex) { getLogger().log(Level.SEVERE, "The ifs commmand encountered an exception in the -create operation", ex); setCommandResult(COMMANDRESULT.FAILURE); } } } private void ifsDelete(ArgArray argArray) { IFSFile ifsFile = getIFSFileFromDataSource(); if (ifsFile == null) { ifsFile = getIFSFileFromArgArray(argArray); } if (ifsFile != null) { try { put(ifsFile.delete()); } catch (IOException | RequestNotSupportedException | SQLException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException ex) { getLogger().log(Level.SEVERE, "The ifs commmand encountered an exception in the -create operation", ex); setCommandResult(COMMANDRESULT.FAILURE); } } } private void ifsExists(ArgArray argArray) { IFSFile ifsFile = getIFSFileFromDataSource(); if (ifsFile == null) { ifsFile = getIFSFileFromArgArray(argArray); } if (ifsFile != null) { try { put(ifsFile.exists()); } catch (IOException | RequestNotSupportedException | SQLException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException ex) { getLogger().log(Level.SEVERE, "The ifs commmand encountered an exception putting the result to the destination datasink.", ex); setCommandResult(COMMANDRESULT.FAILURE); } } } private void ifsFile(ArgArray argArray) { IFSFile ifsFile = getIFSFileFromDataSource(); if (ifsFile == null) { ifsFile = getIFSFileFromArgArray(argArray); } try { put(ifsFile); } catch (SQLException | RequestNotSupportedException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException ex) { getLogger().log(Level.SEVERE, "The ifs commmand encountered an exception in the -file operation.", ex); setCommandResult(COMMANDRESULT.FAILURE); } } private void ifsList(ArgArray argArray) { IFSFile ifsFile = getIFSFileFromDataSource(); if (ifsFile == null) { ifsFile = getIFSFileFromArgArray(argArray); } if (ifsFile != null) { try { StringArrayList sal = new StringArrayList(ifsFile.list()); put(sal); } catch (SQLException | RequestNotSupportedException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException ex) { getLogger().log(Level.SEVERE, "The ifs commmand encountered an exception in the -list operation.", ex); setCommandResult(COMMANDRESULT.FAILURE); } } } private void ifsMkdirs(ArgArray argArray) { IFSFile ifsFile = getIFSFileFromDataSource(); if (ifsFile == null) { ifsFile = getIFSFileFromArgArray(argArray); } if (ifsFile != null) { try { put(ifsFile.mkdirs()); } catch (SQLException | RequestNotSupportedException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException ex) { getLogger().log(Level.SEVERE, "The ifs commmand encountered an exception in the -mkdirs operation.", ex); setCommandResult(COMMANDRESULT.FAILURE); } } } private void ifsNoop() { try { put(FUNCTIONS.NOOP.name()); } catch (SQLException | RequestNotSupportedException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException ex) { getLogger().log(Level.SEVERE, "The ifs commmand encountered an exception in the -noop operation.", ex); setCommandResult(COMMANDRESULT.FAILURE); } } private void ifsRead(ArgArray argArray, int offset, int length) { IFSFile ifsFile = getIFSFileFromDataSource(); if (ifsFile == null) { ifsFile = getIFSFileFromArgArray(argArray); } if (ifsFile != null) { try { IFSFileInputStream ifsIn = new IFSFileInputStream(ifsFile); byte[] data = new byte[length]; int numRead = ifsIn.read(data, offset, length); String s = new AS400Text(numRead, ifsFile.getSystem()).toObject(data).toString(); put(s); } catch (IOException | RequestNotSupportedException | SQLException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException ex) { getLogger().log(Level.SEVERE, "The ifs commmand encountered an exception in putting from the -read operation.", ex); setCommandResult(COMMANDRESULT.FAILURE); } } } private void ifsWrite(ArgArray argArray, String writeableString) { IFSFile ifsFile = getIFSFileFromDataDest(); if (ifsFile == null) { ifsFile = getIFSFileFromArgArray(argArray); } if (ifsFile != null) { try { String text = getTextToWrite(ifsFile.getSystem(), writeableString); try (PrintWriter writer = new PrintWriter(new BufferedWriter(new IFSFileWriter(ifsFile)))) { writer.print(text); } } catch (AS400SecurityException | IOException ex) { getLogger().log(Level.SEVERE, "The ifs commmand encountered an exception in the -write operation.", ex); setCommandResult(COMMANDRESULT.FAILURE); } } } private byte[] getBytesToWrite() throws FileNotFoundException, IOException { byte[] result = null; DataSink ds = getDataSrc(); switch (ds.getType()) { case STD: getLogger().log(Level.SEVERE, "Cannot write a binary file from STD: in {0}", getNameAndDescription()); setCommandResult(COMMANDRESULT.FAILURE); break; case FILE: File f = new File(ds.getName()); Long length = f.length(); result = new byte[length.intValue()]; FileInputStream fis = new FileInputStream(ds.getName()); int numread = fis.read(result); if (numread != length) { getLogger().log(Level.WARNING, "File is {0} bytes long but {1} bytes were read in {2}", new Object[]{length, numread, getNameAndDescription()}); } break; case TUPLE: Object o = getTuple(getDataSrc().getName()).getValue(); if (o instanceof ByteArrayList) { result = ByteArrayList.class.cast(o).byteArray(); } else if (o instanceof byte[]) { result = (byte[]) o; } else { getLogger().log(Level.SEVERE, "Tuple {0} is not a byte array in {1}", new Object[]{getDataSrc().getName(), getNameAndDescription()}); setCommandResult(COMMANDRESULT.FAILURE); } break; } return result; } private void ifsWriteBin(ArgArray argArray) { IFSFile ifsFile; ifsFile = getIFSFileFromDataDest(); if (ifsFile == null) { ifsFile = getIFSFileFromArgArray(argArray); } if (ifsFile != null) { byte[] bytes = null; try { bytes = getBytesToWrite(); } catch (IOException ex) { getLogger().log(Level.SEVERE, "Exception reading file in -writebin in " + getNameAndDescription(), ex); setCommandResult(COMMANDRESULT.FAILURE); } if (bytes != null) { try (IFSFileOutputStream ifsout = new IFSFileOutputStream(ifsFile)) { ifsout.write(bytes, binOffset == null ? 0 : binOffset, binLength == null ? bytes.length : binLength); } catch (AS400SecurityException | IOException ex) { getLogger().log(Level.SEVERE, "Exception encountered in the -writebin operation of " + getNameAndDescription(), ex); setCommandResult(COMMANDRESULT.FAILURE); } } else { getLogger().log(Level.SEVERE, "No bytes provided in the -write operation of {0}", getNameAndDescription()); setCommandResult(COMMANDRESULT.FAILURE); } } else { getLogger().log(Level.SEVERE, "No ifs file object provided to the -writebin operation in {0}", getNameAndDescription()); setCommandResult(COMMANDRESULT.FAILURE); } } @Override public ArgArray cmd(ArgArray args ) { reinit(); return ifs(args); } @Override public COMMANDRESULT getResult() { return getCommandResult(); } }
package ublu.command; import ublu.util.ArgArray; import ublu.util.DataSink; import ublu.util.Generics.StringArrayList; import ublu.util.Tuple; import com.ibm.as400.access.AS400; import com.ibm.as400.access.AS400SecurityException; import com.ibm.as400.access.ErrorCompletingRequestException; import com.ibm.as400.access.IFSFile; import com.ibm.as400.access.IFSFileInputStream; import com.ibm.as400.access.IFSFileOutputStream; import com.ibm.as400.access.IFSFileWriter; import com.ibm.as400.access.ObjectDoesNotExistException; import com.ibm.as400.access.RequestNotSupportedException; import java.beans.PropertyVetoException; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.sql.SQLException; import java.util.logging.Level; import ublu.util.Generics.ByteArrayList; /** * Command to access Integrated File System stream files * * @author jwoehr */ public class CmdIFS extends Command { { setNameAndDescription("ifs", "/4? [-ifs,-- @ifsfile] [-as400 @as400] [-create | -delete | -exists | -file | -list | -mkdirs | -read ~@${offset}$ ~@${chars}$ | -write [${ string }$] | -writebin ] [-to datasink] [-from datasink] ~@${/fully/qualified/pathname}$ ~@${system}$ ~@${user}$ ~@${password}$ : integrated file system access"); } /** * The functions performed by the ifs command */ protected static enum FUNCTIONS { /** * Create an IFS file */ CREATE, /** * Delete an IFS file */ DELETE, /** * Test existence of an IFS file */ EXISTS, /** * Instance object representing file */ FILE, /** * List directory of IFS files */ LIST, /** * Create a dir or dir hierarchy */ MKDIRS, /** * Nada */ NOOP, /** * Read an IFS file */ READ, /** * Write an IFS text file */ WRITE, /** * Write an IFS binary file */ WRITEBIN } /** * Create instance */ public CmdIFS() { } private Tuple ifsFileTuple = null; /** * Parse arguments and perform IFS operations * * @param argArray passed-in arg array * @return rest of arg array */ public ArgArray ifs(ArgArray argArray) { FUNCTIONS function = FUNCTIONS.NOOP; String writeableString = null; int offset = 0; int numToRead = 0; while (argArray.hasDashCommand()) { String dashCommand = argArray.parseDashCommand(); switch (dashCommand) { case "-ifs": case " ifsFileTuple = argArray.nextTupleOrPop(); break; case "-as400": setAs400(getAS400Tuple(argArray.next())); break; case "-to": setDataDest(DataSink.fromSinkName(argArray.next())); break; case "-from": setDataSrc(DataSink.fromSinkName(argArray.next())); break; case "-create": function = FUNCTIONS.CREATE; break; case "-delete": function = FUNCTIONS.DELETE; break; case "-exists": function = FUNCTIONS.EXISTS; break; case "-file": function = FUNCTIONS.FILE; break; case "-list": function = FUNCTIONS.LIST; break; case "-mkdirs": function = FUNCTIONS.MKDIRS; break; case "-noop": break; case "-read": function = FUNCTIONS.READ; offset = argArray.nextIntMaybeQuotationTuplePopString(); numToRead = argArray.nextIntMaybeQuotationTuplePopString(); break; case "-write": function = FUNCTIONS.WRITE; if (getDataSrc().getType() == DataSink.SINKTYPE.STD) { writeableString = argArray.nextUnlessNotQuotation(); } break; case "-writebin": function = FUNCTIONS.WRITEBIN; break; default: unknownDashCommand(dashCommand); } } if (havingUnknownDashCommand()) { setCommandResult(COMMANDRESULT.FAILURE); } else { switch (function) { case CREATE: ifsCreate(argArray); break; case DELETE: ifsDelete(argArray); break; case EXISTS: ifsExists(argArray); break; case FILE: ifsFile(argArray); break; case LIST: ifsList(argArray); break; case MKDIRS: ifsMkdirs(argArray); break; case NOOP: ifsNoop(); break; case READ: ifsRead(argArray, offset, numToRead); break; case WRITE: ifsWrite(argArray, writeableString); break; case WRITEBIN: ifsWriteBin(argArray); break; } } return argArray; } private IFSFile getIFSFileFromDataSink(DataSink datasink) { IFSFile ifsFile = null; if (datasink.getType() == DataSink.SINKTYPE.TUPLE) { Tuple t = getTuple(datasink.getName()); Object o = t.getValue(); ifsFile = o instanceof IFSFile ? IFSFile.class.cast(o) : null; } return ifsFile; } private IFSFile getIFSFileFromDataSource() { return getIFSFileFromDataSink(getDataSrc()); } private IFSFile getIFSFileFromDataDest() { return getIFSFileFromDataSink(getDataDest()); } private IFSFile getIFSFileFromArgArray(ArgArray argArray) { IFSFile ifsFile = null; if (getAs400() == null && argArray.size() < 3) { // if no passed-in AS400 instance and not enough args to generate one logArgArrayTooShortError(argArray); setCommandResult(COMMANDRESULT.FAILURE); } else { String fqpn = argArray.nextMaybeQuotationTuplePopString(); if (getAs400() == null) { try { setAs400FromArgs(argArray); } catch (PropertyVetoException ex) { getLogger().log(Level.SEVERE, "The ifs commmand encountered an exception getting an IFS file from the supplied command arguments.", ex); setCommandResult(COMMANDRESULT.FAILURE); } } if (getAs400() != null) { ifsFile = new IFSFile(getAs400(), fqpn); } } return ifsFile; } private String getTextToWrite(AS400 as400, String writeableString) throws FileNotFoundException, IOException { String text = null; DataSink dsrc = getDataSrc(); switch (dsrc.getType()) { case STD: text = writeableString; break; case FILE: File f = new File(dsrc.getName()); FileReader fr = new FileReader(f); int length = new Long(f.length()).intValue(); char[] in = new char[length]; fr.read(in); text = new String(in); break; case TUPLE: text = getTuple(dsrc.getName()).getValue().toString(); break; } return text; } private void ifsCreate(ArgArray argArray) { IFSFile ifsFile = getIFSFileFromDataSource(); if (ifsFile == null) { ifsFile = getIFSFileFromArgArray(argArray); } if (ifsFile != null) { try { put(ifsFile.createNewFile()); } catch (IOException | RequestNotSupportedException | SQLException | AS400SecurityException | InterruptedException | ObjectDoesNotExistException | ErrorCompletingRequestException ex) { getLogger().log(Level.SEVERE, "The ifs commmand encountered an exception in the -create operation", ex); setCommandResult(COMMANDRESULT.FAILURE); } } } private void ifsDelete(ArgArray argArray) { IFSFile ifsFile = getIFSFileFromDataSource(); if (ifsFile == null) { ifsFile = getIFSFileFromArgArray(argArray); } if (ifsFile != null) { try { put(ifsFile.delete()); } catch (IOException | RequestNotSupportedException | SQLException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException ex) { getLogger().log(Level.SEVERE, "The ifs commmand encountered an exception in the -create operation", ex); setCommandResult(COMMANDRESULT.FAILURE); } } } private void ifsExists(ArgArray argArray) { IFSFile ifsFile = getIFSFileFromDataSource(); if (ifsFile == null) { ifsFile = getIFSFileFromArgArray(argArray); } if (ifsFile != null) { try { put(ifsFile.exists()); } catch (IOException | RequestNotSupportedException | SQLException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException ex) { getLogger().log(Level.SEVERE, "The ifs commmand encountered an exception putting the result to the destination datasink.", ex); setCommandResult(COMMANDRESULT.FAILURE); } } } private void ifsFile(ArgArray argArray) { IFSFile ifsFile = getIFSFileFromDataSource(); if (ifsFile == null) { ifsFile = getIFSFileFromArgArray(argArray); } try { put(ifsFile); } catch (SQLException | RequestNotSupportedException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException ex) { getLogger().log(Level.SEVERE, "The ifs commmand encountered an exception in the -file operation.", ex); setCommandResult(COMMANDRESULT.FAILURE); } } private void ifsList(ArgArray argArray) { IFSFile ifsFile = getIFSFileFromDataSource(); if (ifsFile == null) { ifsFile = getIFSFileFromArgArray(argArray); } if (ifsFile != null) { try { StringArrayList sal = new StringArrayList(ifsFile.list()); put(sal); } catch (SQLException | RequestNotSupportedException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException ex) { getLogger().log(Level.SEVERE, "The ifs commmand encountered an exception in the -list operation.", ex); setCommandResult(COMMANDRESULT.FAILURE); } } } private void ifsMkdirs(ArgArray argArray) { IFSFile ifsFile = getIFSFileFromDataSource(); if (ifsFile == null) { ifsFile = getIFSFileFromArgArray(argArray); } if (ifsFile != null) { try { put(ifsFile.mkdirs()); } catch (SQLException | RequestNotSupportedException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException ex) { getLogger().log(Level.SEVERE, "The ifs commmand encountered an exception in the -mkdirs operation.", ex); setCommandResult(COMMANDRESULT.FAILURE); } } } private void ifsNoop() { try { put(FUNCTIONS.NOOP.name()); } catch (SQLException | RequestNotSupportedException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException ex) { getLogger().log(Level.SEVERE, "The ifs commmand encountered an exception in the -noop operation.", ex); setCommandResult(COMMANDRESULT.FAILURE); } } private void ifsRead(ArgArray argArray, int offset, int length) { IFSFile ifsFile = getIFSFileFromDataSource(); if (ifsFile == null) { ifsFile = getIFSFileFromArgArray(argArray); } if (ifsFile != null) { try { IFSFileInputStream ifsIn = new IFSFileInputStream(ifsFile); byte[] data = new byte[length]; int numRead = ifsIn.read(data, offset, length); String s = new String(data, 0, numRead); put(s); } catch (IOException | RequestNotSupportedException | SQLException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException ex) { getLogger().log(Level.SEVERE, "The ifs commmand encountered an exception in putting from the -read operation.", ex); setCommandResult(COMMANDRESULT.FAILURE); } } } private void ifsWrite(ArgArray argArray, String writeableString) { IFSFile ifsFile = getIFSFileFromDataDest(); if (ifsFile == null) { ifsFile = getIFSFileFromArgArray(argArray); } if (ifsFile != null) { try { String text = getTextToWrite(ifsFile.getSystem(), writeableString); try (PrintWriter writer = new PrintWriter(new BufferedWriter(new IFSFileWriter(ifsFile)))) { // writer.print(aS400Text); writer.print(text); } } catch (AS400SecurityException | IOException ex) { getLogger().log(Level.SEVERE, "The ifs commmand encountered an exception in the -write operation.", ex); setCommandResult(COMMANDRESULT.FAILURE); } } } private byte[] getBytesToWrite() throws FileNotFoundException, IOException { byte[] result = null; DataSink ds = getDataSrc(); switch (ds.getType()) { case STD: getLogger().log(Level.SEVERE, "Cannot write a binary file from STD: in {0}", getNameAndDescription()); setCommandResult(COMMANDRESULT.FAILURE); break; case FILE: File f = new File(ds.getName()); Long length = f.length(); result = new byte[length.intValue()]; FileInputStream fis = new FileInputStream(ds.getName()); int numread = fis.read(result); if (numread != length) { getLogger().log(Level.WARNING, "File is {0} bytes long but {1} bytes were read in {2}", new Object[]{length, numread, getNameAndDescription()}); } break; case TUPLE: Object o = getTuple(getDataSrc().getName()).getValue(); if (o instanceof ByteArrayList) { result = ByteArrayList.class.cast(o).byteArray(); } else if (o instanceof byte[]) { result = (byte[]) o; } else { getLogger().log(Level.SEVERE, "Tuple {0} is not a byte array in {1}", new Object[]{getDataSrc().getName(), getNameAndDescription()}); setCommandResult(COMMANDRESULT.FAILURE); } break; } return result; } private void ifsWriteBin(ArgArray argArray) { IFSFile ifsFile = null; if (ifsFileTuple == null) { ifsFile = getIFSFileFromDataDest(); if (ifsFile == null) { ifsFile = getIFSFileFromArgArray(argArray); } } else { Object o = ifsFileTuple.getValue(); if (o instanceof IFSFile) { ifsFile = IFSFile.class.cast(o); } else { getLogger().log(Level.SEVERE, "Tuple provided to -writebin operation of {0} is not an IFSFile in ", getNameAndDescription()); setCommandResult(COMMANDRESULT.FAILURE); } } if (ifsFile != null) { byte[] bytes = null; try { bytes = getBytesToWrite(); } catch (IOException ex) { getLogger().log(Level.SEVERE, "Exception reading file in -writebin in " + getNameAndDescription(), ex); setCommandResult(COMMANDRESULT.FAILURE); } if (bytes != null) { try (IFSFileOutputStream ifsout = new IFSFileOutputStream(ifsFile)) { // writer.print(aS400Text); ifsout.write(bytes); } catch (AS400SecurityException | IOException ex) { getLogger().log(Level.SEVERE, "Exception encountered in the -writebin operation of " + getNameAndDescription(), ex); setCommandResult(COMMANDRESULT.FAILURE); } } else { getLogger().log(Level.SEVERE, "No bytes provided in the -write operation of {0}", getNameAndDescription()); setCommandResult(COMMANDRESULT.FAILURE); } } else { getLogger().log(Level.SEVERE, "No ifs file object provided to the -writebin operation in {0}", getNameAndDescription()); setCommandResult(COMMANDRESULT.FAILURE); } } @Override public ArgArray cmd(ArgArray args ) { reinit(); return ifs(args); } @Override public COMMANDRESULT getResult() { return getCommandResult(); } }
package util.genome.pwm; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Serializable; import java.util.*; public class PWM implements Serializable{ private static final long serialVersionUID = 1L; private static final int NUM_BASES = 4; private static final int A = 0; private static final int C = 1; private static final int G = 2; private static final int T = 3; private static final String A_LINE = "A:"; private static final String C_LINE = "C:"; private static final String G_LINE = "G:"; private static final String T_LINE = "T:"; private int getBaseIndex(char base){ if(base == 'a' || base == 'A'){ return A; } if(base == 'c' || base == 'C'){ return C; } if(base == 'g' || base == 'G'){ return G; } if(base == 't' || base == 'T'){ return T; } throw new RuntimeException("No encoding for base: "+base); } public static final PWM readPWM(InputStream in){ List<Double> a = new ArrayList<Double>(); List<Double> c = new ArrayList<Double>(); List<Double> g = new ArrayList<Double>(); List<Double> t = new ArrayList<Double>(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line; try { while((line = reader.readLine()) != null){ if(line.startsWith(A_LINE)){ a = parse(line); } if(line.startsWith(C_LINE)){ c = parse(line); } if(line.startsWith(G_LINE)){ g = parse(line); } if(line.startsWith(T_LINE)){ t = parse(line); } //check if all bases have been read if(!a.isEmpty() && !c.isEmpty() && !g.isEmpty() && !t.isEmpty()){ break; } } reader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return new PWM(toArray(a), toArray(c), toArray(g), toArray(t)); } private static final double[] toArray(Collection<Double> col){ double[] array = new double[col.size()]; int i = 0; for(double d : col){ array[i] = d; i++; } return array; } private static final List<Double> parse(String line){ String[] tokens = line.split("\\s"); List<Double> scores = new ArrayList<Double>(); for(int i=1; i<tokens.length; i++){ scores.add(Double.parseDouble(tokens[i])); } return scores; } private final double[][] m_Scores; public PWM(double[] aScores, double[] cScores, double[] gScores, double[] tScores){ if(aScores.length != cScores.length || aScores.length != gScores.length || aScores.length != tScores.length){ throw new RuntimeException("Cannot create a PWM from score arrays of different lengths: A "+aScores.length+ ", C "+cScores.length+", G "+gScores.length+", T "+tScores.length+"."); } m_Scores = new double[NUM_BASES][aScores.length]; for(int i=0; i<aScores.length; i++){ m_Scores[A][i] = aScores[i]; m_Scores[C][i] = cScores[i]; m_Scores[G][i] = gScores[i]; m_Scores[T][i] = tScores[i]; } } /** * Returns the score of the given word according to this PWM. The word score is the sum of the (char,position) scores. * @param word - sequence to be scored by this PWM * @return the summed position scores */ public double score(String word){ if(word.length() == this.length()){ double score = 0; for(int i=0; i<word.length(); i++){ char base = word.charAt(i); score += m_Scores[getBaseIndex(base)][i]; } return score; } throw new RuntimeException("Cannot score word: "+word+". Word length is not the same as PWM length: "+this.length()+"."); } /** * Scores a sequence according to this PWM. Returns an array containing the scores of each word of contained * by the given sequence. * @param seq - the sequence to be scored * @return an array of size (seq.length() - PWM.length() + 1) containing the scores of each word of size PWM.length() contained by the sequence */ public double[] scoreSeq(String seq){ if(seq.length() < this.length()){ throw new RuntimeException("Cannot score sequence: "+seq+". Sequence length is less than this PWMs length: "+this.length()+"."); } double[] scores = new double[seq.length() - this.length() + 1]; for(int i=0; i<scores.length; i++){ String word = seq.substring(i, i+this.length()); scores[i] = this.score(word); } return scores; } public int length(){ return m_Scores[A].length; } }
package org.jscep.message; import org.jscep.asn1.IssuerAndSubject; import org.jscep.transaction.MessageType; import org.jscep.transaction.Nonce; import org.jscep.transaction.TransactionId; public class GetCertInitial extends PkiRequest<IssuerAndSubject> { public GetCertInitial(TransactionId transId, Nonce senderNonce, IssuerAndSubject messageData) { super(transId, MessageType.GetCertInitial, senderNonce, messageData); } }
package edu.isep.sixcolors.model; import java.io.Serializable; public class Config implements Serializable { public static final String newLine = System.getProperty("line.separator"); public static final String GAME_TITLE = "Six Colors Game"; public static final String GRID_PROMPT_MESSAGE = "Size of the board : "; public static final int GRID_MIN = 5; public static final int GRID_MAX = 50; public static final String GAME_PARAMETERS_ZONE_TITLE = "Game parameters"; public static final String PLAYER_NB_PROMPT_MESSAGE = "Number of players : "; public static final int PLAYER_NB_MIN = 2; public static final int PLAYER_NB_MAX = 4; public static final String INVALID_ENTRY_TITLE = "Invalid Entry"; public static final String OUT_OF_BOUNDS_GRID_CONFIG_MESSAGE = "The grid must be between " + GRID_MIN + " and " + GRID_MAX + " tiles wide"; public static final String OUT_OF_BOUNDS_PLAYER_NB_CONFIG_MESSAGE = "There can be from " + PLAYER_NB_MIN + " to " + PLAYER_NB_MAX + " players"; public static final String NUMBER_FORMAT_CONFIG_MESSAGE = "Please input valid numbers"; public static final String PLAYERS_NAMES_ZONE_TITLE = "Players names"; public static String PLAYER_NAME_PROMPT_MESSAGE(int number){ return "Player " + (number+1) + "'s Name : "; } public static final String EMPTY_PLAYER_NAME_MESSAGE = "Please input a name for each player"; public static String WINNER_SPLASH(String winner){return "Game is over, winner is " + winner + " !"; } public static final String RANDOM_BOARD_BUTTON_TEXT = "Random Board"; public static final String CUSTOM_BOARD_BUTTON_TEXT = "Custom Board"; public static final String LOAD_GAME_BUTTON_TEXT = "Load Game"; public static final String PLAY_BUTTON_TEXT = "Play"; public static final String LOAD_SAVE_ACTION_NAME = "Select"; public static final String EXIT_MESSAGE = "Would you like to exit ?"; public static final String EXIT_AFTER_SAVE_MESSAGE = "Your game has been saved" + newLine + EXIT_MESSAGE; public static final String EXIT_TITLE = "Exit Six Colors"; public static final long GAME_VERSION_UNIQUE_ID = 1337L + 42L; }
import java.util.*; public class MovementLogic { public static final int ROUTINE_A = 0; public static final int ROUTINE_B = 1; public static final int ROUTINE_C = 2; public static final int ROUTINE_D = 3; public MovementLogic (Map theMap, boolean debug) { _theMap = theMap; _robotTrack = new Trail(_theMap); _path = new Stack<String>(); _robotFacing = CellId.ROBOT_FACING_UP; _currentMoveDirection = ""; _currentPosition = new Coordinate(_theMap.findStartingPoint()); _debug = debug; } public void createMovementFunctions () { createPath(); String pathElement = _path.pop(); System.out.println("Path:"); while (pathElement != null) { System.out.println(pathElement); try { _path.pop(); } catch (Exception ex) { pathElement = null; } } } public void createMovementRoutine () { } /* * Create path using only L and R. */ private boolean createPath () { System.out.println("createPath from: "+_currentPosition); if (_currentPosition != null) { /* * Try L then R. * * Robot always starts facing up. Change facing when we * start to move but remember initial facing so we can * refer movement directions as L or R. */ if (!tryToMove(CellId.MOVE_LEFT, leftCoordinate(_currentPosition))) { return tryToMove(CellId.MOVE_RIGHT, rightCoordinate(_currentPosition)); } else return true; } else { System.out.println("Robot not found!"); return false; } } private boolean tryToMove (String direction, Coordinate coord) { System.out.println("tryMove: "+coord+" with direction: "+direction); if (_robotTrack.path(coord)) System.out.println("CROSSING PATH!!"); if (_robotTrack.visited(coord)) { System.out.println("Robot already visited this location."); return false; } System.out.println("Location not visited ... yet."); if (_theMap.isScaffold(coord)) { System.out.println("Is scaffolding!"); _currentMoveDirection = direction; _path.push(_currentMoveDirection); _robotTrack.changeElement(coord, _currentMoveDirection); _currentPosition = coord; System.out.println("\n"+_robotTrack); return createPath(); } else { System.out.println("Not scaffolding!"); System.out.println("Robot was facing "+_robotFacing+" and moving "+direction); changeFacing(); System.out.println("Robot now facing "+_robotFacing); String nextDirection = getNextDirection(); System.out.println("Next direction to try with new facing: "+nextDirection); if (CellId.MOVE_LEFT.equals(nextDirection)) coord = leftCoordinate(_currentPosition); else coord = rightCoordinate(_currentPosition); return tryToMove(nextDirection, coord); } } private String getNextDirection () { System.out.println("Getting next direction to move from: "+_currentPosition); Coordinate coord = leftCoordinate(_currentPosition); System.out.println("Left coordinate would be: "+coord); if (_robotTrack.visited(coord) || !_robotTrack.isScaffold(coord)) { System.out.println("Visited so try right ..."); coord = rightCoordinate(_currentPosition); System.out.println("Right coordinate would be: "+coord); if (_robotTrack.visited(coord)) return null; else return CellId.MOVE_RIGHT; } else { System.out.println("Not visited."); return CellId.MOVE_LEFT; } } private void changeFacing () { switch (_robotFacing) { case CellId.ROBOT_FACING_UP: { if (_currentMoveDirection.equals(CellId.MOVE_LEFT)) _robotFacing = CellId.ROBOT_FACING_LEFT; else _robotFacing = CellId.ROBOT_FACING_RIGHT; } break; case CellId.ROBOT_FACING_DOWN: { if (_currentMoveDirection.equals(CellId.MOVE_LEFT)) _robotFacing = CellId.ROBOT_FACING_RIGHT; else _robotFacing = CellId.ROBOT_FACING_LEFT; } break; case CellId.ROBOT_FACING_LEFT: { if (_currentMoveDirection.equals(CellId.MOVE_LEFT)) _robotFacing = CellId.ROBOT_FACING_DOWN; else _robotFacing = CellId.ROBOT_FACING_UP; } break; case CellId.ROBOT_FACING_RIGHT: default: { if (_currentMoveDirection.equals(CellId.MOVE_LEFT)) _robotFacing = CellId.ROBOT_FACING_UP; else _robotFacing = CellId.ROBOT_FACING_DOWN; } break; } } private final Coordinate rightCoordinate (Coordinate coord) { int x = coord.getX(); int y = coord.getY(); System.out.println("rightCoordinate facing: "+_robotFacing+" and position: "+coord); switch (_robotFacing) { case CellId.ROBOT_FACING_DOWN: { x } break; case CellId.ROBOT_FACING_UP: { x++; } break; case CellId.ROBOT_FACING_LEFT: { y } break; case CellId.ROBOT_FACING_RIGHT: default: { y++; } break; } return new Coordinate(x, y); } private final Coordinate leftCoordinate (Coordinate coord) { int x = coord.getX(); int y = coord.getY(); System.out.println("leftCoordinate facing: "+_robotFacing+" and position: "+coord); switch (_robotFacing) { case CellId.ROBOT_FACING_DOWN: { x++; } break; case CellId.ROBOT_FACING_UP: { x } break; case CellId.ROBOT_FACING_LEFT: { y++; } break; case CellId.ROBOT_FACING_RIGHT: default: { y } break; } return new Coordinate(x, y); } private Map _theMap; private Trail _robotTrack; private Stack<String> _path; private String _robotFacing; private String _currentMoveDirection; private Coordinate _currentPosition; private boolean _debug; }
package com.rogoapp; import java.util.ArrayList; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class SendRequestActivity extends Activity implements LocationListener { Button sendRequestButton; String userID; String trait; String location; String lat; String lon; LocationManager loc; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.send_request); postLocation(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.send_request, menu); return true; } public void onRequest(View v){ //Intent intent = getIntent(); //TODO: FOR THIS TO WORK, VALUES MUST BE PASSED IN FROM OPENING ACTIVITY USING THE FOLLOWING CODE AS A GUIDELINE: /* Intent i=new Intent(context,SendMessage.class); //Create the Intent i.putExtra("id", user.getUserAccountId()+""); //Use "putExtra" to include bonus info into new activity i.putExtra("name", user.getUserFullName()); context.startActivity(i); //Start Activity */ //String TargetUserID = intent.getStringExtra("TargetUserID"); // or should we be using username? //TODO: How do we know our current user's username? //String RequestingUserID = intent.getStringExtra("RequestingUserID"); //temp String userID = "1234"; //temp String targetID = (String) getIntent().getSerializableExtra("user"); EditText trait = (EditText) findViewById(R.id.request_trait); EditText location = (EditText) findViewById(R.id.request_location); System.out.println(trait.getText().toString()); System.out.println(location.getText().toString()); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); //nameValuePairs.add(new BasicNameValuePair("RequestingUser", userID)); nameValuePairs.add(new BasicNameValuePair("person_id", targetID)); nameValuePairs.add(new BasicNameValuePair("characteristic", trait.getText().toString())); nameValuePairs.add(new BasicNameValuePair("location_label", location.getText().toString())); JSONObject jObj = ServerClient.genericPostRequest("meetrequest", nameValuePairs, this.getApplicationContext()); String status = null; try{ status = jObj.getString("status"); }catch(JSONException e){ System.err.print(e); } //TODO: Remove this! System.out.println("status = " + status); final Context context = this; if(status.equals("success")){ final Intent start = new Intent(context, MainScreenActivity.class); start.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(start); } } public String getLocation(){ List<Address> user = null; double lat; double lng; Geocoder geocoder; String out = ""; String provider = ""; Location location = null; loc = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if ( !loc.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) { buildAlertMessageNoGps(); loc.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,0,this); provider = "Network"; location = loc.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); } else{ loc.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,this); provider = "GPS"; location = loc.getLastKnownLocation(LocationManager.GPS_PROVIDER); } if (location == null){ Toast.makeText(this,"Current Location Not found",Toast.LENGTH_LONG).show(); }else{ geocoder = new Geocoder(this); try { user = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1); lat=(double)user.get(0).getLatitude(); lng=(double)user.get(0).getLongitude(); Toast.makeText(this,provider + " lat: " +lat+", longitude: "+lng, Toast.LENGTH_LONG).show(); System.out.println(provider + " lat: " +lat+", longitude: "+lng); out = lat+ "," + lng; }catch (Exception e) { e.printStackTrace(); } } return out; } private void buildAlertMessageNoGps() { final AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Your GPS seems to be disabled, do you want to enable it?") .setCancelable(false) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, final int id) { startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, final int id) { dialog.cancel(); } }); final AlertDialog alert = builder.create(); alert.show(); } public void postLocation(){ location = getLocation(); String[] latLon = location.split(","); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); if(latLon.length == 2){ lat = latLon[0]; lon = latLon[1]; nameValuePairs.add(new BasicNameValuePair("location_lat",lat)); nameValuePairs.add(new BasicNameValuePair("location_lon",lon)); System.out.println("Latitude: " + latLon[1]); System.out.println("Longitude: " + latLon[2]); } else{ nameValuePairs.add(new BasicNameValuePair("location_lat","0.000000")); //Maybe I'm a bad person, but nameValuePairs.add(new BasicNameValuePair("location_lon","0.000000")); //But the server requires a minimum of 5 decimal places System.out.println("Location not available"); } //TODO NEED TO PULL USER INFO nameValuePairs.add(new BasicNameValuePair("availability","available")); nameValuePairs.add(new BasicNameValuePair("radius","1")); //1 mile ServerClient.genericPostRequest("availability", nameValuePairs, this.getApplicationContext()); } /* @SuppressWarnings("deprecation") public void openRequestPopup(View v){ AlertDialog alertDialog = new AlertDialog.Builder(this).create(); alertDialog.setTitle("Send Request"); alertDialog.setMessage("Send Request to User?"); alertDialog.setButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { //TODO NEED TO UPDATE FOR MEETUP REQUEST List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("user_id1", "")); nameValuePairs.add(new BasicNameValuePair("user1_trait", "")); nameValuePairs.add(new BasicNameValuePair("location", "")); ServerClient sc = new ServerClient(); //TODO create server request for this post JSONObject jObj = sc.genericPostRequest("meetup_request", nameValuePairs); String uid = null; String status = null; try{ //uid = sc.getLastResponse().getString("uid"); status = jObj.getString("status"); }catch(JSONException e){ System.err.print(e); } System.out.println("status = " + status + ", uid = " + uid); } }); alertDialog.show(); } */ @Override public void onLocationChanged(Location location) { // TODO Auto-generated method stub } @Override public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } @Override public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } }
// Exporter.java package loci.plugins; import ij.*; import ij.gui.GenericDialog; import ij.io.SaveDialog; import ij.process.*; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.*; import loci.formats.*; public class Exporter { // -- Fields -- /** Current stack. */ private ImagePlus imp; private LociExporter plugin; // -- Constructor -- public Exporter(LociExporter plugin, ImagePlus imp) { this.plugin = plugin; this.imp = imp; } // -- Exporter API methods -- /** Executes the plugin. */ public void run(ImageProcessor ip) { String outfile = null; if (plugin.arg != null && plugin.arg.startsWith("outfile=")) { outfile = Macro.getValue(plugin.arg, "outfile", null); plugin.arg = null; } if (outfile == null) { String options = Macro.getOptions(); if (options != null) { String save = Macro.getValue(options, "save", null); if (save != null) outfile = save; } } if (outfile == null || outfile.length() == 0) { // open a dialog prompting for the filename to save SaveDialog sd = new SaveDialog("LOCI Bio-Formats Exporter", "", ""); String dir = sd.getDirectory(); String name = sd.getFileName(); if (dir == null || name == null) return; outfile = new File(dir, name).getAbsolutePath(); if (outfile == null) return; } try { IFormatWriter w = new ImageWriter().getWriter(outfile); w.setId(outfile); // prompt for options String[] codecs = w.getCompressionTypes(); ImageProcessor proc = imp.getStack().getProcessor(1); Image firstImage = proc.createImage(); firstImage = ImageTools.makeBuffered(firstImage, proc.getColorModel()); int thisType = ImageTools.getPixelType((BufferedImage) firstImage); boolean forceType = false; boolean notSupportedType = !w.isSupportedType(thisType); if ((codecs != null && codecs.length > 1) || notSupportedType) { GenericDialog gd = new GenericDialog("LOCI Bio-Formats Exporter Options"); if (codecs != null) { gd.addChoice("Compression type: ", codecs, codecs[0]); } if (notSupportedType) { gd.addCheckbox("Force compatible pixel type", true); } gd.showDialog(); if (gd.wasCanceled()) return; if (codecs != null) w.setCompression(gd.getNextChoice()); if (notSupportedType) forceType = gd.getNextBoolean(); } // convert and save slices ImageStack is = imp.getStack(); int size = is.getSize(); boolean doStack = w.canDoStacks() && size > 1; int start = doStack ? 0 : imp.getCurrentSlice() - 1; int end = doStack ? size : start + 1; for (int i=start; i<end; i++) { if (doStack) { IJ.showStatus("Saving plane " + (i + 1) + "/" + size); IJ.showProgress((double) (i + 1) / size); } else IJ.showStatus("Saving image"); proc = is.getProcessor(i + 1); BufferedImage img = null; int x = proc.getWidth(); int y = proc.getHeight(); if (proc instanceof ByteProcessor) { byte[] b = (byte[]) proc.getPixels(); img = ImageTools.makeImage(b, x, y); } else if (proc instanceof ShortProcessor) { short[] s = (short[]) proc.getPixels(); img = ImageTools.makeImage(s, x, y); } else if (proc instanceof FloatProcessor) { float[] b = (float[]) proc.getPixels(); img = ImageTools.makeImage(b, x, y); } else if (proc instanceof ColorProcessor) { byte[][] pix = new byte[3][x*y]; ((ColorProcessor) proc).getRGB(pix[0], pix[1], pix[2]); img = ImageTools.makeImage(pix, x, y); } if (forceType) { if (notSupportedType) { int[] types = w.getPixelTypes(); img = ImageTools.makeType(img, types[types.length - 1]); } w.saveImage(img, i == end - 1); } else w.saveImage(img, i == end - 1); } } catch (FormatException e) { e.printStackTrace(); ByteArrayOutputStream buf = new ByteArrayOutputStream(); e.printStackTrace(new PrintStream(buf)); IJ.error(e.getMessage() + ":\n" + buf.toString()); } catch (IOException e) { e.printStackTrace(); ByteArrayOutputStream buf = new ByteArrayOutputStream(); e.printStackTrace(new PrintStream(buf)); IJ.error(e.getMessage() + ":\n" + buf.toString()); } } }
package com.jme.scene; import java.io.IOException; import java.io.Serializable; import java.nio.FloatBuffer; import java.util.ArrayList; import java.util.Stack; import com.jme.bounding.BoundingVolume; import com.jme.intersection.PickResults; import com.jme.math.FastMath; import com.jme.math.Ray; import com.jme.math.Vector3f; import com.jme.renderer.CloneCreator; import com.jme.renderer.ColorRGBA; import com.jme.renderer.Renderer; import com.jme.scene.state.RenderState; import com.jme.util.geom.BufferUtils; /** * <code>Geometry</code> defines a leaf node of the scene graph. The leaf node * contains the geometric data for rendering objects. It manages all rendering * information such as a collection of states and the data for a model. * Subclasses define what the model data is. * * @author Mark Powell * @author Joshua Slack * @version $Id: Geometry.java,v 1.89 2005-12-10 17:06:02 Mojomonkey Exp $ */ public abstract class Geometry extends Spatial implements Serializable { /** The local bounds of this Geometry object. */ protected BoundingVolume bound; /** The number of vertexes in this geometry. */ protected int vertQuantity = 0; /** The geometry's per vertex color information. */ protected transient FloatBuffer colorBuf; /** The geometry's per vertex normal information. */ protected transient FloatBuffer normBuf; /** The geometry's vertex information. */ protected transient FloatBuffer vertBuf; /** The geometry's per Texture per vertex texture coordinate information. */ protected transient ArrayList texBuf; /** The geometry's VBO information. */ protected VBOInfo vboInfo; /** * The compiled list of renderstates for this geometry, taking into account * ancestors' states - updated with updateRenderStates() */ public RenderState[] states = new RenderState[RenderState.RS_MAX_STATE]; /** Non -1 values signal this geometry is a clone of grouping "cloneID". */ private int cloneID = -1; private ColorRGBA defaultColor = ColorRGBA.white; /** Static computation field */ protected static Vector3f compVect = new Vector3f(); /** * Empty Constructor to be used internally only. */ public Geometry() { texBuf = new ArrayList(1); } /** * Constructor instantiates a new <code>Geometry</code> object. This is * the default object which has an empty vertex array. All other data is * null. * * @param name * the name of the scene element. This is required for * identification and comparision purposes. * */ public Geometry(String name) { super(name); reconstruct(null, null, null, null); } /** * Constructor creates a new <code>Geometry</code> object. During * instantiation the geometry is set including vertex, normal, color and * texture information. * * @param name * the name of the scene element. This is required for * identification and comparision purposes. * @param vertex * the points that make up the geometry. * @param normal * the normals of the geometry. * @param color * the color of each point of the geometry. * @param texture * the texture coordinates of the geometry (position 0.) */ public Geometry(String name, FloatBuffer vertex, FloatBuffer normal, FloatBuffer color, FloatBuffer texture) { super(name); reconstruct(vertex, normal, color, texture); } /** * <code>reconstruct</code> reinitializes the geometry with new data. This * will reuse the geometry object. * * @param vertices * the new vertices to use. * @param normals * the new normals to use. * @param colors * the new colors to use. * @param textureCoords * the new texture coordinates to use (position 0). */ public void reconstruct(FloatBuffer vertices, FloatBuffer normals, FloatBuffer colors, FloatBuffer textureCoords) { if (vertices == null) vertQuantity = 0; else vertQuantity = vertices.capacity() / 3; vertBuf = vertices; normBuf = normals; colorBuf = colors; if(texBuf == null) { texBuf = new ArrayList(1); } texBuf.clear(); texBuf.add(textureCoords); if(vboInfo != null) { vboInfo.resizeTextureIds(texBuf.size()); } } public void setVBOInfo(VBOInfo info) { vboInfo = info; if(vboInfo != null) { vboInfo.resizeTextureIds(texBuf.size()); } } public VBOInfo getVBOInfo() { return vboInfo; } /** * * <code>setSolidColor</code> sets the color array of this geometry to a * single color. For greater efficiency, try setting the the ColorBuffer * to null and using DefaultColor instead. * * @param color * the color to set. */ public void setSolidColor(ColorRGBA color) { if (colorBuf == null) colorBuf = BufferUtils.createColorBuffer(vertQuantity); colorBuf.rewind(); for (int x = 0, cLength = colorBuf.remaining(); x < cLength; x+=4) { colorBuf.put(color.r); colorBuf.put(color.g); colorBuf.put(color.b); colorBuf.put(color.a); } colorBuf.flip(); } /** * Sets every color of this geometry's color array to a random color. */ public void setRandomColors() { if (colorBuf == null) colorBuf = BufferUtils.createColorBuffer(vertQuantity); for (int x = 0, cLength = colorBuf.capacity(); x < cLength; x+=4) { colorBuf.put(FastMath.nextRandomFloat()); colorBuf.put(FastMath.nextRandomFloat()); colorBuf.put(FastMath.nextRandomFloat()); colorBuf.put(1); } colorBuf.flip(); } /** * <code>getVertexBuffer</code> returns the float buffer that * contains this geometry's vertex information. * * @return the float buffer that contains this geometry's vertex * information. */ public FloatBuffer getVertexBuffer() { return vertBuf; } /** * <code>setVertexBuffer</code> sets this geometry's vertices via a * float buffer consisting of groups of three floats: x,y and z. * * @param buff * the new vertex buffer. */ public void setVertexBuffer(FloatBuffer buff) { this.vertBuf = buff; if (vertBuf != null) vertQuantity = vertBuf.capacity() / 3; else vertQuantity = 0; } /** * Returns the number of vertices defined in this Geometry object. * * @return The number of vertices in this Geometry object. */ public int getVertQuantity() { return vertQuantity; } /** * * @param quantity * the value to override the quantity with. This is overridden by * setVertexBuffer(). */ public void setVertQuantity(int quantity) { vertQuantity = quantity; } /** * <code>getNormalBuffer</code> retrieves this geometry's normal * information as a float buffer. * * @return the float buffer containing the geometry information. */ public FloatBuffer getNormalBuffer() { return normBuf; } /** * <code>setNormalBuffer</code> sets this geometry's normals via a * float buffer consisting of groups of three floats: x,y and z. * * @param buff * the new normal buffer. */ public void setNormalBuffer(FloatBuffer buff) { this.normBuf = buff; } /** * <code>getColorBuffer</code> retrieves the float buffer that * contains this geometry's color information. * * @return the buffer that contains this geometry's color information. */ public FloatBuffer getColorBuffer() { return colorBuf; } /** * <code>setColorBuffer</code> sets this geometry's colors via a * float buffer consisting of groups of four floats: r,g,b and a. * * @param buff * the new color buffer. */ public void setColorBuffer(FloatBuffer buff) { this.colorBuf = buff; } /** * * <code>copyTextureCoords</code> copys the texture coordinates of a given * texture unit to another location. If the texture unit is not valid, then * the coordinates are ignored. * * @param fromIndex * the coordinates to copy. * @param toIndex * the texture unit to set them to. */ public void copyTextureCoords(int fromIndex, int toIndex) { copyTextureCoords(fromIndex, toIndex, 1.0f); } /** * * <code>copyTextureCoords</code> copys the texture coordinates of a given * texture unit to another location. If the texture unit is not valid, then * the coordinates are ignored. Coords are multiplied by the given factor. * * @param fromIndex * the coordinates to copy. * @param toIndex * the texture unit to set them to. * @param factor * a multiple to apply when copying */ public void copyTextureCoords(int fromIndex, int toIndex, float factor) { if (texBuf == null) return; if (fromIndex < 0 || fromIndex >= texBuf.size() || texBuf.get(fromIndex) == null) { return; } if (toIndex < 0 || toIndex == fromIndex) { return; } if(toIndex >= texBuf.size() ) { while(toIndex >= texBuf.size()) { texBuf.add(null); } } FloatBuffer buf = (FloatBuffer)texBuf.get(toIndex); FloatBuffer src = (FloatBuffer)texBuf.get(fromIndex); if (buf == null || buf.capacity() != src.capacity()) { buf = BufferUtils.createFloatBuffer(src.capacity()); texBuf.set(toIndex, buf); } buf.clear(); int oldLimit = src.limit(); src.clear(); for (int i = 0, len = buf.capacity(); i < len; i++) { buf.put(factor * src.get()); } src.limit(oldLimit); buf.limit(oldLimit); if(vboInfo != null) { vboInfo.resizeTextureIds(this.texBuf.size()); } } /** * <code>getTextureBuffer</code> retrieves this geometry's texture * information contained within a float buffer. * * @return the float buffer that contains this geometry's texture * information. */ public FloatBuffer getTextureBuffer() { if (texBuf.size() > 0) { return (FloatBuffer)texBuf.get(0); } return null; } /** * <code>getTextureBuffers</code> retrieves this geometry's texture * information contained within a float buffer array. * * @return the float buffers that contain this geometry's texture * information. */ public FloatBuffer[] getTextureBuffers() { return (FloatBuffer[])texBuf.toArray(new FloatBuffer[texBuf.size()]); } /** * * <code>getTextureAsFloatBuffer</code> retrieves the texture buffer of a * given texture unit. * * @param textureUnit * the texture unit to check. * @return the texture coordinates at the given texture unit. */ public FloatBuffer getTextureBuffer(int textureUnit) { if (texBuf == null) return null; if (textureUnit >= texBuf.size()) return null; return (FloatBuffer)texBuf.get(textureUnit); } /** * <code>setTextureBuffer</code> sets this geometry's textures (position * 0) via a float buffer consisting of groups of two floats: x and y. * * @param buff * the new vertex buffer. */ public void setTextureBuffer(FloatBuffer buff) { setTextureBuffer(buff, 0); } /** * <code>setTextureBuffer</code> sets this geometry's textures st the * position given via a float buffer consisting of groups of two floats: x * and y. * * @param buff * the new vertex buffer. */ public void setTextureBuffer(FloatBuffer buff, int position) { if (position >= texBuf.size()) { while (position >= texBuf.size()) { texBuf.add(null); } } texBuf.set(position, buff); if (vboInfo != null) { vboInfo.resizeTextureIds(texBuf.size()); } } /** * * <code>getNumberOfUnits</code> returns the number of texture units this * geometry supports. * * @return the number of texture units supported by the geometry. */ public int getNumberOfUnits() { if (texBuf == null) return 0; return texBuf.size(); } public int getType() { return Spatial.GEOMETRY; } /** * Clears all vertex, normal, texture, and color buffers by setting them to * null. */ public void clearBuffers() { reconstruct(null, null, null, null); } /** * <code>updateBound</code> recalculates the bounding object assigned to * the geometry. This resets it parameters to adjust for any changes to the * vertex information. * */ public void updateModelBound() { if (bound != null) { bound.computeFromPoints(vertBuf); updateWorldBound(); } } /** * * <code>getModelBound</code> retrieves the bounding object that contains * the geometry node's vertices. * * @return the bounding object for this geometry. */ public BoundingVolume getModelBound() { return bound; } /** * * <code>setModelBound</code> sets the bounding object for this geometry. * * @param modelBound * the bounding object for this geometry. */ public void setModelBound(BoundingVolume modelBound) { this.worldBound = null; this.bound = modelBound; } /** * * <code>setStates</code> applies all the render states for this * particular geometry. * */ public void applyStates() { RenderState tempState = null; for (int i = 0; i < states.length; i++) { tempState = enforcedStateList[i] != null ? enforcedStateList[i] : states[i]; if (tempState != null) { if (tempState != currentStates[i]) { tempState.apply(); currentStates[i] = tempState; } } else { currentStates[i] = null; } } } /** * <code>draw</code> prepares the geometry for rendering to the display. * The renderstate is set and the subclass is responsible for rendering the * actual data. * * @see com.jme.scene.Spatial#draw(com.jme.renderer.Renderer) * @param r * the renderer that displays to the context. */ public void draw(Renderer r) { applyStates(); } /** * <code>updateWorldBound</code> updates the bounding volume that contains * this geometry. The location of the geometry is based on the location of * all this node's parents. * * @see com.jme.scene.Spatial#updateWorldBound() */ public void updateWorldBound() { if (bound != null) { worldBound = bound.transform(worldRotation, worldTranslation, worldScale, worldBound); } } /** * <code>applyRenderState</code> determines if a particular render state * is set for this Geometry. If not, the default state will be used. */ protected void applyRenderState(Stack[] states) { for (int x = 0; x < states.length; x++) { if (states[x].size() > 0) { this.states[x] = ((RenderState) states[x].peek()).extract( states[x], this); } else { this.states[x] = (RenderState) defaultStateList[x]; } } } /** * <code>randomVertice</code> returns a random vertex from the list of * vertices set to this geometry. If there are no vertices set, null is * returned. * * @param fill * a Vector3f to fill with the results. If null, one is created. * It is more efficient to pass in a nonnull vector. * @return Vector3f a random vertex from the vertex list. Null is returned * if the vertex list is not set. */ public Vector3f randomVertice(Vector3f fill) { if (vertBuf == null) return null; int i = (int) (FastMath.nextRandomFloat() * vertQuantity); if (fill == null) fill = new Vector3f(); BufferUtils.populateFromBuffer(fill, vertBuf, i); worldRotation.multLocal(fill).addLocal(worldTranslation); return fill; } public void findPick(Ray ray, PickResults results) { if (getWorldBound() == null || !isCollidable) { return; } if (getWorldBound().intersects(ray)) { //find the triangle that is being hit. //add this node and the triangle to the PickResults list. results.addPick(ray, this); } } public Spatial putClone(Spatial store, CloneCreator properties) { if (store == null) return null; super.putClone(store, properties); Geometry toStore = (Geometry) store; // This should never throw a class // cast exception if // the clone is written correctly. // Create a CloneID if none exist for this mesh. if (!properties.CloneIDExist(this)) properties.createCloneID(this); toStore.cloneID = properties.getCloneID(this); if (properties.isSet("vertices")) { toStore.setVertexBuffer(vertBuf); } else { if (vertBuf != null) { toStore.setVertexBuffer(BufferUtils.createFloatBuffer(vertBuf.capacity())); vertBuf.rewind(); toStore.vertBuf.put(vertBuf); toStore.setVertexBuffer(toStore.vertBuf); // pick up vertQuantity } else toStore.setVertexBuffer(null); } if (properties.isSet("colors")) { // if I should shallow copy colors toStore.setColorBuffer(colorBuf); } else if (colorBuf != null) { // If I should deep copy colors if (colorBuf != null) { toStore.colorBuf = BufferUtils.createFloatBuffer(colorBuf.capacity()); colorBuf.rewind(); toStore.colorBuf.put(colorBuf); } else toStore.setColorBuffer(null); } if (properties.isSet("normals")) { toStore.setNormalBuffer(normBuf); } else if (normBuf != null) { if (normBuf != null) { toStore.normBuf = BufferUtils.createFloatBuffer(normBuf.capacity()); normBuf.rewind(); toStore.normBuf.put(normBuf); } else toStore.setNormalBuffer(null); } if (properties.isSet("texcoords")) { toStore.texBuf = this.texBuf; // pick up all array positions } else { if (texBuf != null) { for (int i = 0; i < texBuf.size(); i++) { FloatBuffer src = (FloatBuffer)texBuf.get(i); if (src != null) { toStore.texBuf.set(i,BufferUtils.createFloatBuffer(src.capacity())); src.rewind(); ((FloatBuffer)toStore.texBuf.get(i)).put(src); } else toStore.texBuf.set(i,null); } } else toStore.texBuf = null; } if (bound != null) toStore.setModelBound((BoundingVolume) bound.clone(null)); if (properties.isSet("vboinfo")) { toStore.vboInfo = this.vboInfo; } else { if (toStore.vboInfo != null) { toStore.setVBOInfo((VBOInfo)vboInfo.copy()); } else toStore.vboInfo = null; } return toStore; } /** * Returns the ID number that identifies this Geometry's clone ID. * * @return The assigned clone ID of this geometry. Non clones are -1. */ public int getCloneID() { return cloneID; } /** * Used with Serialization. Do not call this directly. * * @param s * @throws IOException * @see java.io.Serializable */ private void writeObject(java.io.ObjectOutputStream s) throws IOException { s.defaultWriteObject(); // vert buffer if (vertBuf == null) s.writeInt(0); else { s.writeInt(vertBuf.capacity()); vertBuf.rewind(); for (int x = 0, len = vertBuf.capacity(); x < len; x++) s.writeFloat(vertBuf.get()); } // norm buffer if (normBuf == null) s.writeInt(0); else { s.writeInt(normBuf.capacity()); normBuf.rewind(); for (int x = 0, len = normBuf.capacity(); x < len; x++) s.writeFloat(normBuf.get()); } // color buffer if (colorBuf == null) s.writeInt(0); else { s.writeInt(colorBuf.capacity()); colorBuf.rewind(); for (int x = 0, len = colorBuf.capacity(); x < len; x++) s.writeFloat(colorBuf.get()); } // tex buffer if (texBuf == null || texBuf.size() == 0) s.writeInt(0); else { s.writeInt(texBuf.size()); for (int i = 0; i < texBuf.size(); i++) { if (texBuf.get(i) == null) s.writeInt(0); else { FloatBuffer src = (FloatBuffer)texBuf.get(i); s.writeInt(src.capacity()); src.rewind(); for (int x = 0, len = src.capacity(); x < len; x++) s.writeFloat(src.get()); } } } } /** * Used with Serialization. Do not call this directly. * * @param s * @throws IOException * @throws ClassNotFoundException * @see java.io.Serializable */ private void readObject(java.io.ObjectInputStream s) throws IOException, ClassNotFoundException { s.defaultReadObject(); // vert buffer int len = s.readInt(); if (len == 0) { setVertexBuffer(null); } else { FloatBuffer buf = BufferUtils.createFloatBuffer(len); for (int x = 0; x < len; x++) buf.put(s.readFloat()); setVertexBuffer(buf); } // norm buffer len = s.readInt(); if (len == 0) { setNormalBuffer(null); } else { FloatBuffer buf = BufferUtils.createFloatBuffer(len); for (int x = 0; x < len; x++) buf.put(s.readFloat()); setNormalBuffer(buf); } // color buffer len = s.readInt(); if (len == 0) { setColorBuffer(null); } else { FloatBuffer buf = BufferUtils.createFloatBuffer(len); for (int x = 0; x < len; x++) buf.put(s.readFloat()); setColorBuffer(buf); } // tex buffers len = s.readInt(); if (len == 0) { texBuf = null; } else { texBuf.clear(); for (int i = 0; i < len; i++) { len = s.readInt(); if (len == 0) { setTextureBuffer(null, i); } else { FloatBuffer buf = BufferUtils.createFloatBuffer(len); for (int x = 0; x < len; x++) buf.put(s.readFloat()); setTextureBuffer(buf, i); } } } } /** * <code>getDefaultColor</code> returns the color used if no * per vertex colors are specified. * * @return default color */ public ColorRGBA getDefaultColor() { return defaultColor; } /** * <code>setDefaultColor</code> sets the color to be used * if no per vertex color buffer is set. * * @param color */ public void setDefaultColor(ColorRGBA color) { defaultColor = color; } /** * <code>getWorldCoords</code> translates/rotates and scales the * coordinates of this Geometry to world coordinates based on its world * settings. The results are stored in the given FloatBuffer. If given * FloatBuffer is null, one is created. * * @param store * the FloatBuffer to store the results in, or null if you want one created. * @return store or new FloatBuffer if store == null. */ public FloatBuffer getWorldCoords(FloatBuffer store) { if (store == null || store.capacity() != vertBuf.capacity()) store = BufferUtils.clone(vertBuf); for (int v = 0, vSize = store.capacity() / 3; v < vSize; v++) { BufferUtils.populateFromBuffer(compVect, store, v); worldRotation.multLocal(compVect).multLocal(worldScale).addLocal(worldTranslation); BufferUtils.setInBuffer(compVect, store, v); } return store; } }
package com.pty4j.util; import com.google.common.base.Function; import com.google.common.collect.Lists; import com.pty4j.windows.WinPty; import com.sun.jna.Platform; import java.io.File; import java.net.URLDecoder; import java.security.CodeSource; import java.util.List; import java.util.Map; /** * @author traff */ public class PtyUtil { private final static String PTY_LIB_FOLDER = System.getenv("PTY_LIB_FOLDER"); public static String[] toStringArray(Map<String, String> environment) { List<String> list = Lists.transform(Lists.newArrayList(environment.entrySet()), new Function<Map.Entry<String, String>, String>() { public String apply(Map.Entry<String, String> entry) { return entry.getKey() + "=" + entry.getValue(); } }); return list.toArray(new String[list.size()]); } /** * Returns the folder that contains a jar that contains the class * * @param aclass a class to find a jar * @return */ public static String getJarContainingFolderPath(Class aclass) throws Exception { CodeSource codeSource = aclass.getProtectionDomain().getCodeSource(); File jarFile; if (codeSource.getLocation() != null) { jarFile = new File(codeSource.getLocation().toURI()); } else { String path = aclass.getResource(aclass.getSimpleName() + ".class").getPath(); int startIndex = path.indexOf(":") + 1; int endIndex = path.indexOf("!"); if (startIndex == -1 || endIndex == -1) { throw new IllegalStateException("Class " + aclass.getSimpleName() + " is located not within a jar: " + path); } String jarFilePath = path.substring(startIndex, endIndex); jarFilePath = URLDecoder.decode(jarFilePath, "UTF-8"); jarFile = new File(jarFilePath); } return jarFile.getParentFile().getAbsolutePath(); } public static String getPtyLibFolderPath() throws Exception { if (PTY_LIB_FOLDER != null) { return PTY_LIB_FOLDER; } //Class aclass = WinPty.class.getClassLoader().loadClass("com.jediterm.pty.PtyMain"); Class aclass = WinPty.class; return getJarContainingFolderPath(aclass); } public static File resolveNativeLibrary() throws Exception { String libFolderPath = getPtyLibFolderPath(); if (libFolderPath != null) { File libFolder = new File(libFolderPath); File lib = resolveNativeLibrary(libFolder); lib = lib.exists() ? lib : resolveNativeLibrary(new File(libFolder, "libpty")); if (!lib.exists()) { throw new IllegalStateException(String.format("Couldn't find %s, jar folder %s", lib.getName(), libFolder.getAbsolutePath())); } return lib; } else { throw new IllegalStateException("Couldn't detect lib folder"); } } public static File resolveNativeLibrary(File parent) { File path = new File(parent, getPlatformFolder()); path = Platform.is64Bit() ? new File(path, "x86_64") : new File(path, "x86"); return new File(path, getNativeLibraryName()); } private static String getPlatformFolder() { String result; if (Platform.isMac()) { result = "macosx"; } else if (Platform.isWindows()) { result = "win"; } else if (Platform.isLinux()) { result = "linux"; } else { throw new IllegalStateException("Platform " + Platform.getOSType() + " is not supported"); } return result; } private static String getNativeLibraryName() { String result; if (Platform.isMac()) { result = "libpty.dylib"; } else if (Platform.isWindows()) { result = "libwinpty.dll"; } else if (Platform.isLinux()) { result = "libpty.so"; } else { throw new IllegalStateException("Platform " + Platform.getOSType() + " is not supported"); } return result; } }
package com.soofw.trk; import android.util.Log; // FIXME import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.regex.Matcher; import java.util.regex.Pattern; public class TaskList { final private static Pattern re_tag = Pattern.compile("(^|\\s)([\\@\\ final private static Pattern re_at = Pattern.compile("(^|\\s)(\\@([\\w\\/]+))"); final private static Pattern re_hash = Pattern.compile("(^|\\s)(\\ final private static Pattern re_plus = Pattern.compile("(^|\\s)(\\+([\\w\\/]+))"); private File file= null; private ArrayList<Task> mainList = new ArrayList<Task>(); private ArrayList<Task> filterList = new ArrayList<Task>(); private ArrayList<String> tagList = new ArrayList<String>(); private ArrayList<String> tagFilters = new ArrayList<String>(); public TaskList(File file) { this.file = file; } public void read() { try { String line = null; BufferedReader reader = new BufferedReader(new FileReader(this.file)); while(true) { line = reader.readLine(); if(line == null) break; this.mainList.add(new Task(line)); } this.filterList.addAll(this.mainList); this.generateTagList(); reader.close(); } catch(FileNotFoundException e) { // FIXME Log.e("TRK", e.getMessage()); } catch(IOException e) { // FIXME Log.e("TRK", e.getMessage()); } } public void write() { try { BufferedWriter writer = new BufferedWriter(new FileWriter(this.file)); // FIXME sort for(int i = 0; i < this.mainList.size(); i++) { writer.write(this.mainList.get(i).source + "\n"); } writer.flush(); writer.close(); } catch(IOException e) { // FIXME Log.e("TRK", e.getMessage()); } } public void add(String source) { this.mainList.add(new Task(source)); this.generateTagList(); } public void add(Task source) { this.mainList.add(source); this.generateTagList(); } public void remove(int id) { this.mainList.remove(this.filterList.get(id)); this.generateTagList(); } public void generateTagList() { this.tagList.clear(); for(int i = 0; i < this.mainList.size(); i++) { Matcher m = null; m = re_tag.matcher(this.mainList.get(i).source); while(m.find()) { char type = m.group(2).charAt(0); String[] subtags = m.group(2).substring(1).split("/"); for(int j = 0; j < subtags.length; j++) { if(this.tagList.contains(type + subtags[j])) continue; this.tagList.add(type + subtags[j]); } } } Collections.sort(this.tagList); } public void addTagFilter(String tag) { this.tagFilters.add(tag); } public void removeTagFilter(String tag) { if(this.tagFilters.contains(tag)) { this.tagFilters.remove(tag); } } public void setTagFilter(String tag) { this.tagFilters.clear(); this.tagFilters.add(tag); } public void clearTagFilter() { this.tagFilters.clear(); } public void filter(String search) { this.filterList.clear(); for(int i = 0; i < this.mainList.size(); i++) { if(!this.mainList.get(i).contains(search)) continue; if(this.tagFilters.size() > 0) { boolean add = false; for(int j = 0; j < this.tagFilters.size(); j++) { if(this.mainList.get(i).matches(this.tagFilters.get(j))) { add = true; break; } } if(!add) continue; } this.filterList.add(this.mainList.get(i)); } } public ArrayList<Task> getMainList() { return this.mainList; } public ArrayList<Task> getFilterList() { return this.filterList; } public ArrayList<String> getTagList() { return this.tagList; } }
package com.xnx3.j2ee.util; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import com.xnx3.DateUtil; import com.xnx3.Lang; /** * sql * @author * */ public class Sql { private String tableName = ""; final static String[] COLUMN_GROUP = {">=","<=","=","<>",">","<"}; /** * SQL */ final static String[] INJECT_KEYWORD = {"AND","EXEC","INSERT","SELECT","DELETE","UPDATE","COUNT","MASTER","TRUNCATE","CHAR","DECLARE","OR"}; private String where = ""; //SQL WHERE private String orderBy = ""; private String selectFrom = ""; // SELECT * FROM user SELECT FROM private Page page; private HttpServletRequest request; private String groupBy = ""; //GROUP BY public Sql(HttpServletRequest request) { this.request = request; String ob = request.getParameter("orderBy"); if(ob != null && ob.length()>0){ if(ob.indexOf("_ASC")>0){ orderBy = " ORDER BY "+ob.replace("_ASC", "")+" ASC"; }else if (ob.indexOf("_DESC")>0) { orderBy = " ORDER BY "+ob.replace("_DESC", "")+" DESC"; } } } public String setSearchColumn(String[] column){ if(column != null){ //list // List<SqlColumn> columnList = new ArrayList<SqlColumn>(); Map<String, SqlColumn> columnMap = new HashMap<String, SqlColumn>(); //sql > SqlColumn String columns = ","; for (int i = 0; i < column.length; i++) { SqlColumn sqlColumn = new SqlColumn(column[i]); columnMap.put(sqlColumn.getColumnName(), sqlColumn); columns = columns +sqlColumn.getColumnName() + ","; } //where Enumeration<String> p = request.getParameterNames(); while(p.hasMoreElements()){ String name = p.nextElement(); String sqltable_column_name = name.replace("_start", "").replace("_end", ""); if(columns.indexOf(","+sqltable_column_name+",") > -1){ SqlColumn sc = columnMap.get(sqltable_column_name); if(sc.getOperators() != null && sc.getOperators().equals("<>")){ if(name.indexOf("_start") > -1){ String start = request.getParameter(name); if(start != null && start.length() > 0){ start = inject(start); if(start.length() > 0){ if(sc.getDateFormat()!=null){ //value10 start = ""+DateUtil.StringToInt(start, sc.getDateFormat()); } if(where.equals("")){ where=" WHERE "; }else{ where = where + " AND "; } where = where +getSearchColumnTableName()+sc.getColumnName()+" >= "+start.replaceAll(" ", ""); } } }else if(name.indexOf("_end") > -1){ String end = request.getParameter(name); if(end != null && end.length() > 0){ end = inject(end); if(end.length() > 0){ if(sc.getDateFormat()!=null){ //value10 end = ""+DateUtil.StringToInt(end, sc.getDateFormat()); } if(where.equals("")){ where=" WHERE "; }else{ where = where + " AND "; } where = where +getSearchColumnTableName()+sc.getColumnName()+" <= "+end.replaceAll(" ", ""); } } } }else if(sc.getColumnName().equals(name)){ String value = inject(request.getParameter(name)); if(value.length()>0){ if(sc.getDateFormat()!=null){ //value10 value = ""+DateUtil.StringToInt(value, sc.getDateFormat()); } if(where.equals("")){ where=" WHERE "; }else{ where = where + " AND "; } String valueArray[] = {""}; if(value.indexOf(",") > -1){ valueArray = value.split(","); }else{ valueArray[0] = value; } int va = 0; StringBuffer appendWhere = new StringBuffer(); //wherewhere,OR while (valueArray.length > va) { String val = valueArray[va]; if(val == null || val.length() == 0){ va++; continue; } appendWhere.append((va == 0 ? "":" OR ") + getSearchColumnTableName()+sc.getColumnName()); if(sc.getOperators() == null ){ appendWhere.append(" LIKE '%"+val+"%'"); }else{ appendWhere.append(" "+sc.getOperators()+" '"+val+"' "); } va++; } String appendW = valueArray.length > 1 ? "( "+appendWhere.toString()+" )":appendWhere.toString(); where = where + appendW; } } } } } // if(column!=null){ // Enumeration<String> p = request.getParameterNames(); // while(p.hasMoreElements()){ // String name = p.nextElement(); // for (int i = 0; i < column.length; i++) { // SqlColumn sqlColumn = new SqlColumn(column[i]); // if(sqlColumn.getOperators() != null && sqlColumn.getOperators().equals("<>")){ // String start = request.getParameter(name+"_start"); // String end = request.getParameter(name+"_end"); // if(start != null && start.length() > 0){ // start = inject(start); // if(start.length() > 0){ // if(sqlColumn.getDateFormat()!=null){ // //value10 // start = ""+DateUtil.StringToInt(start, sqlColumn.getDateFormat()); // if(where.equals("")){ // where=" WHERE "; // }else{ // where = where + " AND "; // where = where +getSearchColumnTableName()+sqlColumn.getColumnName()+" >= "+start.replaceAll(" ", ""); // if(end != null && end.length() > 0){ // end = inject(end); // if(end.length() > 0){ // if(sqlColumn.getDateFormat()!=null){ // //value10 // end = ""+DateUtil.StringToInt(end, sqlColumn.getDateFormat()); // if(where.equals("")){ // where=" WHERE "; // }else{ // where = where + " AND "; // where = where +getSearchColumnTableName()+sqlColumn.getColumnName()+" <= "+end.replaceAll(" ", ""); // if(sqlColumn.getColumnName().equals(name)){ // String value = inject(request.getParameter(name)); // if(value.length()>0){ // if(sqlColumn.getDateFormat()!=null){ // //value10 // value = ""+DateUtil.StringToInt(value, sqlColumn.getDateFormat()); // if(where.equals("")){ // where=" WHERE "; // }else{ // where = where + " AND "; // if(sqlColumn.getOperators() == null ){ // where = where +getSearchColumnTableName()+sqlColumn.getColumnName()+" LIKE '%"+value+"%'"; // }else{ // where = where + getSearchColumnTableName()+sqlColumn.getColumnName()+" "+sqlColumn.getOperators()+" '"+value+"' "; return where; } private String getSearchColumnTableName(){ if(this.tableName.length()>0){ return tableName+"."; }else{ return ""; } } /** * SQL * @param selectFrom SELECT * FROM user * @param page {@link Page} LIMIT * @return SQL */ public String setSelectFromAndPage(String selectFrom, Page page){ this.selectFrom = selectFrom; this.page = page; return selectFrom+where+groupBy+orderBy+" LIMIT "+page.getLimitStart()+","+page.getEveryNumber(); }
package bayesGame.bayesbayes; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; import org.apache.commons.math3.fraction.Fraction; import org.apache.commons.math3.util.Pair; import bayesGame.bayesbayes.nodeCPD.DeterministicOR; import bayesGame.bayesbayes.nodeCPD.NodeCPD; import edu.uci.ics.jung.graph.DirectedSparseGraph; public class BayesNet { private int edgeCounter = 0; private Map<Object,BayesNode> nodes; private NetGraph graph; private HashSet<BayesNode> visitedDownstreamNodes; private Stack<Pair<BayesNode, BayesNode>> downstreamMessagePaths; public BayesNet() { graph = new NetGraph(this); nodes = new HashMap<Object,BayesNode>(); } public boolean addNode(BayesNode node){ boolean added = graph.addVertex(node); if (added){ nodes.put(node.type, node); } return added; } public boolean addNode(Object object){ BayesNode node = new BayesNode(object); return addNode(node); } public boolean addNode(Object object, Object[] scope){ BayesNode node = getNode(object, scope); return addNode(node); } public boolean addNode(Object object, NodeCPD cpd, Object... parents){ return addNodeWithParents(object, cpd, parents); } public void addNodes(Object... nodes){ for (Object o : nodes){ addNode(o); } } private BayesNode getNode(Object o){ BayesNode newNode = getNodeIffPresent(o); if (newNode == null){ newNode = new BayesNode(o); } return newNode; } private BayesNode getNode(Object o, Object[] scope){ BayesNode newNode = getNodeIffPresent(o); if (newNode == null){ newNode = new BayesNode(o, scope); } return newNode; } public DirectedSparseGraph<BayesNode, Pair<Integer,Integer>> getGraph(){ return graph; } public boolean isPresent(Object o){ return nodes.containsKey(o); } public boolean isFullyAssumed(){ boolean fullyAssumed = true; Collection<BayesNode> nodeValues = nodes.values(); for (BayesNode existingNode : nodeValues){ if (!existingNode.isObserved() && !existingNode.isAssumed()){ fullyAssumed = false; break; } } return fullyAssumed; } private BayesNode getNodeIffPresent(Object o){ return nodes.get(o); } public boolean removeBayesNode(Object object){ BayesNode node = new BayesNode(object); nodes.remove(node); return graph.removeVertex(node); } private boolean connectNodes(BayesNode node1, BayesNode node2){ boolean result = graph.addEdge(new Pair<Integer,Integer>(edgeCounter,0), node1, node2); if (result){ edgeCounter++; } return result; } public boolean connectNodes(Object rawNode1, Object rawNode2){ BayesNode node1 = getNode(rawNode1); BayesNode node2 = getNode(rawNode2); if (!scopesCompatible(node1, node2)){ return false; } return this.connectNodes(node1, node2); } /** * Connects two existing nodes, adding the parent to the child's scope if neither has the * other in its scope. Note that this will rewrite the child's conditional probability table. * To avoid this, use the regular connectNodes function which takes no action for incompatible * scopes, or use the changeNodeCPD function to make the child conform to the desired probability * distribution. * * @param rawNode1 * @param rawNode2 * @return */ public boolean forceConnectNodes(Object rawNode1, Object rawNode2){ BayesNode node1 = getNode(rawNode1); BayesNode node2 = getNode(rawNode2); if (!scopesCompatible(node1, node2)){ node2.addItemToScope(node1.type); } return this.connectNodes(node1, node2); } /** * Adds a node to the network which evaluates to true (with P = 1) iff at least one * of its parents is true (with P = 1). The parents of the node must already exist * in the network, whereas the node itself must not exist: if these criteria are not * met, or if no parents are provided, the function will return false and do nothing. * * @param orNode The identifier of the deterministic OR node to be added * @param parents The parents of the OR node * @return true if the node was added, false otherwise */ public boolean addDeterministicOr(Object orNode, Object... parents){ return addNodeWithParents(orNode, new DeterministicOR(), parents); } public boolean addNodeWithParents(Object object, NodeCPD cpd, Object... parents){ BayesNode orBayesNode = new BayesNode(object, parents); if (parents.length == 0){ return false; } for (Object o : parents){ if (!isPresent(o)){ return false; } } this.setNodeTo(orBayesNode, parents, cpd); boolean added = addNode(orBayesNode); if (!added){ return false; } for (Object o : parents){ boolean sanityCheck = connectNodes(o, object); if (!sanityCheck){ throw new IllegalStateException("Failed to connect nodes that should be connected fine ??? Shouldn't be possible"); } } return true; } private BayesNode setNodeTo(BayesNode node, Object[] parents, NodeCPD cpd){ return node = cpd.getNode(node, parents); } /** * Turns an existing node with at least one parent into a deterministic OR node. * * @param orNode The node to be made into a deterministic OR node * @return false if the node doesn't exist or has no parents, true otherwise. */ public boolean makeDeterministicOr(Object orObject){ return changeNodeCPD(orObject, new DeterministicOR()); } /** * Gives an existing node with at least one parent the kind of probability distribution specified in the parameter. * * @param object The node to be changed * @param cpd The desired probability distribution * @return false if the node doesn't exist or has no parents, true otherwise. */ public boolean changeNodeCPD(Object object, NodeCPD cpd){ BayesNode node = getNodeIffPresent(object); // the node has to already exist for us to do anything if (node == null){ return false; } ArrayList<BayesNode> parentNodes = new ArrayList<BayesNode>(graph.getPredecessors(node)); // and it should have parents if (parentNodes.size() == 0){ return false; } Object[] parents = new Object[parentNodes.size()]; // the graph object returns the parents as a list of BayesNodes, so let's extract their // types into a separate array for (int i = 0; i < parentNodes.size(); i++){ parents[i] = parentNodes.get(i).type; } // as the node relies on the values of its parents, it should have its parents in its scope Set<Object> scopeSet = new HashSet<Object>(Arrays.asList(node.scope)); for (Object p : parents){ if (!scopeSet.contains(p)){ node.addItemToScope(p); } } this.setNodeTo(node, parents, cpd); return true; } private boolean scopesCompatible(BayesNode node1, BayesNode node2){ ArrayList<Object> difference = getScopeDifference(node1, node2); if (difference.isEmpty()){ return false; } return true; } private ArrayList<Object> getScopeDifference(BayesNode node1, BayesNode node2){ ArrayList<Object> list1 = new ArrayList<Object>(Arrays.asList(node1.scope)); ArrayList<Object> list2 = new ArrayList<Object>(Arrays.asList(node2.scope)); list1.retainAll(list2); return list1; } public boolean containsNode(Object rawNode){ return isPresent(rawNode); } public Fraction getProbability(Object object){ BayesNode node = getNodeIffPresent(object); if (node == null){ throw new IllegalArgumentException("Requested object not found in the graph"); } return node.getProbability(); } public ArrayList<Map<Object,Boolean>> getNonZeroProbabilities(Object object){ BayesNode node = getNodeIffPresent(object); if (node == null){ throw new IllegalArgumentException("Requested object not found in the graph"); } return node.getNonZeroProbabilities(); } public Map<Object,Boolean> getCurrentAssignments(){ Map<Object,Boolean> assignments = new HashMap<Object,Boolean>(nodes.size()); Collection<BayesNode> nodeValues = nodes.values(); for (BayesNode node : nodeValues){ if (node.isObserved() || node.isAssumed()){ boolean truthValue = node.getProbability().equals(Fraction.ONE); assignments.put(node.type, truthValue); } } return assignments; } public boolean observe(Object object){ BayesNode node = getNode(object); node.observe(); Fraction probability = node.getProbability(); return (probability.intValue() == 1); } public void observe(Object object, boolean value){ BayesNode node = getNode(object); node.observe(value); } public boolean isObserved(Object object){ BayesNode node = getNodeIffPresent(object); return node.isObserved(); } public void assume(Object object, boolean value){ BayesNode node = getNodeIffPresent(object); if (node == null){ throw new IllegalArgumentException("Requested object not found in the graph"); } node.assumeValue(value); } public void assume(Object object){ BayesNode node = getNodeIffPresent(object); if (node == null){ throw new IllegalArgumentException("Requested object not found in the graph"); } node.clearAssumedValue(); } public void addProperty(Object object, String property){ BayesNode node = getNodeIffPresent(object); if (node == null){ throw new IllegalArgumentException("Requested object not found in the graph"); } node.addProperty(property); } public void removeProperty(Object object, String property){ BayesNode node = getNodeIffPresent(object); node.removeProperty(property); } public boolean setProbabilityOfUntrue(Object object, Fraction probability, Object... variables){ BayesNode node = getNode(object); return node.setProbabilityOfUntrueVariables(probability, variables); } public boolean setTrueValue(Object object, boolean value){ BayesNode node = getNodeIffPresent(object); if (node == null){ return false; } node.setTrueValue(value); return true; } public void clearAssumptions(){ Collection<BayesNode> nodeValues = nodes.values(); for (BayesNode node : nodeValues){ node.clearAssumedValue(); } } public void resetNetworkBeliefs(){ Collection<BayesNode> nodeValues = nodes.values(); for (BayesNode node : nodeValues){ node.resetPotential(); } } public void resetNetworkBeliefsObservations(){ Collection<BayesNode> nodeValues = nodes.values(); for (BayesNode node : nodeValues){ node.resetNode(); } } // TODO: currently assumes that all the nodes are connected, this should be checked // TODO: only works on polytrees, doesn't check that the network is one public void updateBeliefs(){ if (nodes.size() > 1){ HashMap<BayesNode,Fraction> calculatedProbabilities = new HashMap<BayesNode,Fraction>(); Collection<BayesNode> nodeValues = nodes.values(); for (BayesNode root : nodeValues){ resetNetworkBeliefs(); visitedDownstreamNodes = new HashSet<BayesNode>(); downstreamMessagePaths = new Stack<Pair<BayesNode,BayesNode>>(); sendDownstreamMessages(root); visitedDownstreamNodes.clear(); sendUpstreamMessages(); root.multiplyPotentialWithMessages(); Fraction rootProbability = root.getProbability(); calculatedProbabilities.put(root, rootProbability); System.out.println("Probability of " + root.toString() + " calculated as " + rootProbability.toString()); } for (BayesNode node : nodeValues){ Fraction calculatedProbability = calculatedProbabilities.get(node); node.setProbability(calculatedProbability); } } } private void sendDownstreamMessages(BayesNode source){ visitedDownstreamNodes.add(source); ArrayList<BayesNode> sourceNeighbors = new ArrayList<BayesNode>(graph.getNeighbors(source)); for (BayesNode neighbor : sourceNeighbors){ if (!visitedDownstreamNodes.contains(neighbor)){ Object[] sharedScope = getScopeDifference(source, neighbor).toArray(); //b Object[] sharedScope = new Object[]{source.type}; Message message = source.generateDownstreamMessage(sharedScope); neighbor.receiveDownstreamMessage(message); downstreamMessagePaths.push(new Pair<BayesNode,BayesNode>(source, neighbor)); sendDownstreamMessages(neighbor); } } } private void sendUpstreamMessages(){ while (!downstreamMessagePaths.isEmpty()){ Pair<BayesNode,BayesNode> path = downstreamMessagePaths.pop(); BayesNode source = path.getSecond(); BayesNode receiver = path.getFirst(); Object[] sharedScope = getScopeDifference(source, receiver).toArray(); // Object[] sharedScope = new Object[]{source.type}; Message message = source.generateUpstreamMessage(sharedScope); receiver.receiveUpstreamMessage(message); source.multiplyPotentialWithMessages(); } } }
// -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import java.awt.*; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import java.util.Optional; import javax.imageio.ImageIO; import javax.swing.*; public final class MainPanel extends JPanel { private final transient TexturePaint texture; private MainPanel() { super(new BorderLayout()); String path = "example/16x16.png"; ClassLoader cl = Thread.currentThread().getContextClassLoader(); BufferedImage bi = Optional.ofNullable(cl.getResource(path)).map(url -> { try (InputStream s = url.openStream()) { return ImageIO.read(s); } catch (IOException ex) { ex.printStackTrace(); return makeMissingImage(); } }).orElseGet(MainPanel::makeMissingImage); texture = new TexturePaint(bi, new Rectangle(bi.getWidth(), bi.getHeight())); add(new JLabel("@title@")); setOpaque(false); setPreferredSize(new Dimension(320, 240)); } @Override protected void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g.create(); g2.setPaint(texture); g2.fillRect(0, 0, getWidth(), getHeight()); g2.dispose(); super.paintComponent(g); } private static BufferedImage makeMissingImage() { Icon missingIcon = UIManager.getIcon("OptionPane.errorIcon"); int w = missingIcon.getIconWidth(); int h = missingIcon.getIconHeight(); BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = bi.createGraphics(); missingIcon.paintIcon(null, g2, 0, 0); g2.dispose(); return bi; } public static void main(String[] args) { EventQueue.invokeLater(MainPanel::createAndShowGui); } private static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); Toolkit.getDefaultToolkit().beep(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }
package com.kuxhausen.huemore.timing; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Calendar; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPut; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.preference.PreferenceManager; import android.text.format.DateUtils; import android.util.Log; import android.widget.Toast; import com.google.gson.Gson; import com.kuxhausen.huemore.R; import com.kuxhausen.huemore.network.TransmitGroupMood; import com.kuxhausen.huemore.persistence.DatabaseDefinitions; import com.kuxhausen.huemore.persistence.DatabaseDefinitions.GroupColumns; import com.kuxhausen.huemore.persistence.DatabaseDefinitions.MoodColumns; import com.kuxhausen.huemore.persistence.DatabaseDefinitions.PreferencesKeys; import com.kuxhausen.huemore.state.BulbState; public class AlarmReciever extends BroadcastReceiver { private final static String ALARM_DETAILS = "alarmDetailsBundle"; public static AlarmState createAlarms(Context context, String group, String mood, int transitiontime, int brightness, Boolean[] repeats, int currentHour, int currentMin) { Gson gson = new Gson(); AlarmState as = new AlarmState(); as.group = group; as.mood = mood; as.transitiontime = transitiontime; as.brightness = brightness; as.repeats = repeats; as.scheduledForFuture = true; Calendar projectedTime = Calendar.getInstance(); projectedTime.setLenient(true); projectedTime.set(Calendar.HOUR_OF_DAY, currentHour); projectedTime.set(Calendar.MINUTE, currentMin); projectedTime.set(Calendar.SECOND, 0); // ensure transition starts ahead of time to culminate at the specified // time projectedTime.add(Calendar.SECOND, -transitiontime / 10); return createAlarms(context, as, projectedTime); } public static AlarmState createAlarms(Context context, AlarmState as, Calendar timeAdjustedCal) { boolean none = false; for (boolean bool : as.repeats) { none |= bool; } none = !none; if (none) { while (timeAdjustedCal.before(Calendar.getInstance())) // make sure this hour & minute is in the future timeAdjustedCal.set(Calendar.DATE, timeAdjustedCal.get(Calendar.DATE) + 1); as.scheduledTimes = new Long[1]; as.scheduledTimes[0] = timeAdjustedCal.getTimeInMillis(); } else { as.scheduledTimes = new Long[7]; for (int i = 0; i < 7; i++) { if (as.repeats[i]) { Calendar copyForDayOfWeek = Calendar.getInstance(); copyForDayOfWeek.setLenient(true); copyForDayOfWeek.setTimeInMillis(timeAdjustedCal .getTimeInMillis()); switch (i) { case 0: copyForDayOfWeek.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); break; case 1: copyForDayOfWeek.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); break; case 2: copyForDayOfWeek.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY); break; case 3: copyForDayOfWeek.set(Calendar.DAY_OF_WEEK, Calendar.WEDNESDAY); break; case 4: copyForDayOfWeek.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY); break; case 5: copyForDayOfWeek.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY); break; case 6: copyForDayOfWeek.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY); break; } if (copyForDayOfWeek.before(Calendar.getInstance()))// if in // past, // choose // that // day // next // week copyForDayOfWeek.set(Calendar.DATE, copyForDayOfWeek.get(Calendar.DATE) + 7); as.scheduledTimes[i] = copyForDayOfWeek.getTimeInMillis(); } } } Calendar soonestTime = null; for (Long t : as.scheduledTimes) { if (t != null) { Calendar setTime = Calendar.getInstance(); setTime.setTimeInMillis(t); if (as.scheduledTimes.length == 7) {// repeating weekly alarm Log.e("asdf", "repeatingAlarm"); AlarmReciever.createRepeatingAlarm(context, as, setTime.getTimeInMillis()); } else { Log.e("asdf", "oneOffAlarm"); AlarmReciever.createAlarm(context, as, setTime.getTimeInMillis()); } if (soonestTime == null || setTime.before(soonestTime)) soonestTime = setTime; } } Toast.makeText( context, context.getString(R.string.next_scheduled_intro) + " " + DateUtils.getRelativeTimeSpanString(soonestTime .getTimeInMillis()), Toast.LENGTH_SHORT).show(); return as; } public static void createAlarm(Context context, AlarmState alarmState, Long timeInMillis) { Gson gson = new Gson(); String aState = gson.toJson(alarmState); AlarmManager alarmMgr = (AlarmManager) context .getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(context, AlarmReciever.class); intent.putExtra(ALARM_DETAILS, aState); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, generateRequestCode(aState), intent, PendingIntent.FLAG_UPDATE_CURRENT); alarmMgr.set(AlarmManager.RTC_WAKEUP, timeInMillis, pendingIntent); } public static void createRepeatingAlarm(Context context, AlarmState alarmState, Long timeInMillis) { Gson gson = new Gson(); String aState = gson.toJson(alarmState); AlarmManager alarmMgr = (AlarmManager) context .getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(context, AlarmReciever.class); intent.putExtra(ALARM_DETAILS, aState); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, generateRequestCode(aState), intent, PendingIntent.FLAG_UPDATE_CURRENT); alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, timeInMillis, AlarmManager.INTERVAL_DAY * 7, pendingIntent); } public static void cancelAlarm(Context context, AlarmState alarmState) { Gson gson = new Gson(); String aState = gson.toJson(alarmState); AlarmManager alarmMgr = (AlarmManager) context .getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(context, AlarmReciever.class); intent.putExtra(ALARM_DETAILS, aState); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, generateRequestCode(aState), intent, PendingIntent.FLAG_UPDATE_CURRENT); alarmMgr.cancel(pendingIntent); } public static int generateRequestCode(String aState) { Gson gson = new Gson(); AlarmState as = gson.fromJson(aState, AlarmState.class); int code = 0; int bit = 1; for (boolean b : as.repeats) { if (b) code += bit; bit *= 2; } return code; } @Override public void onReceive(Context context, Intent intent) { Gson gson = new Gson(); AlarmState as = gson.fromJson( intent.getExtras().getString(ALARM_DETAILS), AlarmState.class); // Look up bulbs for that mood from database String[] groupColumns = { GroupColumns.BULB }; String[] gWhereClause = { as.group }; Cursor groupCursor = context.getContentResolver().query( DatabaseDefinitions.GroupColumns.GROUPBULBS_URI, // Use the // default // content // URI // for the // provider. groupColumns, // Return the note ID and title for each note. GroupColumns.GROUP + "=?", // selection clause gWhereClause, // selection clause args null // Use the default sort order. ); ArrayList<Integer> groupStates = new ArrayList<Integer>(); while (groupCursor.moveToNext()) { groupStates.add(groupCursor.getInt(0)); } Integer[] bulbS = groupStates.toArray(new Integer[groupStates.size()]); String[] moodColumns = { MoodColumns.STATE }; String[] mWereClause = { as.mood }; Cursor moodCursor = context.getContentResolver().query( DatabaseDefinitions.MoodColumns.MOODSTATES_URI, // Use the // default // content URI // for the // provider. moodColumns, // Return the note ID and title for each note. MoodColumns.MOOD + "=?", // selection clause mWereClause, // election clause args null // Use the default sort order. ); ArrayList<String> moodStates = new ArrayList<String>(); while (moodCursor.moveToNext()) { moodStates.add(moodCursor.getString(0)); } String[] moodS = moodStates.toArray(new String[moodStates.size()]); int brightness = as.brightness; int transitiontime = as.transitiontime; for (int i = 0; i < moodS.length; i++) { BulbState bs = gson.fromJson(moodS[i], BulbState.class); bs.bri = brightness; bs.transitiontime = transitiontime; moodS[i] = gson.toJson(bs);// put back into json string for Transmit // Group Mood } this.execute(context, bulbS, moodS); Toast.makeText(context, "HueMore Alarm " + as.group + " " + as.mood + " went off", Toast.LENGTH_SHORT).show(); } /** * synchronous version of TransmitGroupMood * @param cont * @param bulbs * @param moods * @return */ private Integer execute(Context cont, Integer[] bulbs, String[] moods){ if (cont == null || bulbs == null || moods == null) return -1; // Get username and IP from preferences cache SharedPreferences settings = PreferenceManager .getDefaultSharedPreferences(cont); String bridge = settings.getString(PreferencesKeys.BRIDGE_IP_ADDRESS, null); String hash = settings.getString(PreferencesKeys.HASHED_USERNAME, ""); if (bridge == null) return -1; for (int i = 0; i < bulbs.length; i++) { StringBuilder builder = new StringBuilder(); HttpClient client = new DefaultHttpClient(); HttpPut httpPut = new HttpPut("http://" + bridge + "/api/" + hash + "/lights/" + bulbs[i] + "/state"); try { StringEntity se = new StringEntity(moods[i % moods.length]); // sets the post request as the resulting string httpPut.setEntity(se); HttpResponse response = client.execute(httpPut); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader( new InputStreamReader(content)); String line; String debugOutput = ""; while ((line = reader.readLine()) != null) { builder.append(line); debugOutput += line; } } else { } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return 1; } }
package com.digiwiz.geofence; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.IBinder; import android.preference.PreferenceManager; import com.digiwiz.geofence.log.Log; import com.digiwiz.geofence.settings.SimpleGeofenceStore; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.Geofence; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import java.util.ArrayList; public class AutoStartUp extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, SharedPreferences.OnSharedPreferenceChangeListener { private GoogleApiClient mApiClient; private ArrayList<Geofence> geofenceList; private SharedPreferences mPrefs; // Stores the PendingIntent used to request geofence monitoring. private PendingIntent mGeofenceRequestIntent; // Stores the PendingIntent used to request location monitoring. private PendingIntent mLocationRequestIntent; private SimpleGeofenceStore geoStore; @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); this.geofenceList = new ArrayList<>(); this.geoStore = new SimpleGeofenceStore(this); if (!isGooglePlayServicesAvailable()) { return; } mApiClient = new GoogleApiClient.Builder(this) .addApi(LocationServices.API) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build(); mApiClient.connect(); // To use the preferences when the activity starts and when the user navigates back from the settings activity. mPrefs = PreferenceManager.getDefaultSharedPreferences(this); mPrefs.registerOnSharedPreferenceChangeListener(this); //Log.i(Constants.LOG_TAG, "Start Service"); } /** * Checks if Google Play services is available. * * @return true if it is. */ private boolean isGooglePlayServicesAvailable() { int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); if (ConnectionResult.SUCCESS == resultCode) { return true; } else { Log.e(Constants.LOG_TAG, "Google Play services is unavailable."); return false; } } @Override public void onConnected(Bundle bundle) { //Log.e(Constants.LOG_TAG, "Google Play onConnected."); mGeofenceRequestIntent = getGeofencePendingIntent(); mLocationRequestIntent = getLocationPendingIntent(); if (mApiClient.isConnected()) { enableCoordinates(); addGeoFence(); } else { Log.i(Constants.LOG_TAG, "Googgle Play services not connected"); } } @Override public void onConnectionSuspended(int i) { if (null != mGeofenceRequestIntent) { //Log.i(Constants.LOG_TAG, "Removing geofence"); LocationServices.GeofencingApi.removeGeofences(mApiClient, mGeofenceRequestIntent); } } public void reloadGeoFence() { //Log.i(Constants.LOG_TAG, "Reload geofence"); //remove the fences from the API LocationServices.GeofencingApi.removeGeofences(mApiClient, mGeofenceRequestIntent); //clear the array geofenceList.clear(); //re-add the fences addGeoFence(); } public void addGeoFence() { Geofence geofence = geoStore.getGeofence(); if (geofence == null) { Log.w(Constants.LOG_TAG, "No configuration found. Please configure the geofence first..."); } else { geofenceList.add(geofence); /** Add a geofence ay current location for debug purposes * */ /* double lat = 52.103368; double lng = 4.313771; float radius = 1000; // Build a new Geofence object. Geofence debugFence = new Geofence.Builder() .setRequestId("Debug") .setCircularRegion(lat, lng, radius) .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT) .setExpirationDuration(Geofence.NEVER_EXPIRE) .build(); geofenceList.add(debugFence); */ LocationServices.GeofencingApi.addGeofences(mApiClient, geofenceList, mGeofenceRequestIntent); } } /** * Create a PendingIntent that triggers GeofenceIntentService when a geofence * transition occurs. */ private PendingIntent getGeofencePendingIntent() { Intent intent = new Intent(this, GeofenceIntentService.class); return PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); } private PendingIntent getLocationPendingIntent() { Intent intent = new Intent(this, LocationIntentService.class); return PendingIntent.getService(this, 1, intent, 0); } @Override public void onConnectionFailed(ConnectionResult connectionResult) { int errorCode = connectionResult.getErrorCode(); Log.e(Constants.LOG_TAG, "Connection to Google Play services failed with error code " + errorCode); } public void enableCoordinates() { if (geoStore.getTracking()) { Log.i(Constants.LOG_TAG, "Location tracking is enabled"); LocationRequest locationRequest = com.google.android.gms.location.LocationRequest.create(); //Set the update interval after which a new location request will be issued locationRequest.setInterval(geoStore.getUpdateInterval()); //Set the interval for receiving location updates triggered by other applications locationRequest.setFastestInterval(60 * 1000); //1 minute (specified in milliseconds) locationRequest.setPriority(geoStore.getPowerMode()); LocationServices.FusedLocationApi.requestLocationUpdates(mApiClient, locationRequest, mLocationRequestIntent); } else { Log.i(Constants.LOG_TAG, "Location tracking is disabled"); LocationServices.FusedLocationApi.removeLocationUpdates(mApiClient, mLocationRequestIntent); } } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { enableCoordinates(); reloadGeoFence(); } }
package com.example.pac.pacman; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PointF; import android.graphics.Rect; import android.graphics.RectF; import android.util.Log; public abstract class Character { private String _name; private String _nickName; private final Paint _debugPaint; protected float _moveDelta; protected Paint _foreground; protected float _x, _y; protected float _size; // NOTE: Test-induces design damage public PointF getPosition() { return new PointF(_x, _y); } private Rect _invalidateRect; public Rect getInvalidateRect() { return _invalidateRect; } protected final Labyrinth _labyrinth; private Direction _newDirection = Direction.Stopped; private Direction _direction = Direction.Stopped; public Character(String name, String nickName, Labyrinth labyrinth) { _labyrinth = labyrinth; _name = name; _nickName = nickName; _foreground = new Paint(Paint.ANTI_ALIAS_FLAG); _foreground.setStyle(Paint.Style.FILL); _debugPaint = new Paint(Paint.ANTI_ALIAS_FLAG); _debugPaint.setStyle(Paint.Style.STROKE); _debugPaint.setColor(Color.RED); } public void init() { _size = _labyrinth.getCellSize() - 2; _moveDelta = _size / 6; Log.i("Character", "MOVE DELTA = " + _moveDelta); newInvalidateRect(_x, _y); } protected void newInvalidateRect(float newX, float newY) { float l = Math.min(_x, newX) - _size; float t = Math.min(_y, newY) - _size; float r = Math.max(_x, newX) + _size + 1; float b = Math.max(_y, newY) + _size + 1; _invalidateRect = new Rect((int) l, (int) t, (int) r + 1, (int) b + 1); } public void draw(Canvas canvas) { //int cell = _labyrinth.cellAt(_x, _y); //RectF bounds = _labyrinth.getCellBounds(cell); //canvas.drawRect(bounds, _debugPaint); //canvas.drawCircle(_x, _y, 1, _debugPaint); } public abstract void move(); protected Direction move(Direction direction) { int cell = _labyrinth.cellAt(_x, _y); RectF bounds = _labyrinth.getCellBounds(cell); float centerX = bounds.centerX(); float centerY = bounds.centerY(); float delta = _moveDelta; boolean canMove = true; if (_newDirection.isPerpendicular(_direction)) { delta = getDelta(centerX, centerY, _moveDelta); _direction = getDirectionInTheSameCell(centerX, centerY); } else { _newDirection = direction; if (!_newDirection.isPerpendicular(_direction)) { _direction = _newDirection; } canMove = _labyrinth.canMove(cell, _direction); if (!canMove) { delta = getDelta(centerX, centerY, _moveDelta); _direction = getDirectionInTheSameCell(centerX, centerY); canMove = delta != 0; } } float newX = _x; float newY = _y; switch (_direction) { case Stopped: break; case Left: newX = _x - delta; break; case Right: newX = _x + delta; break; case Up: newY = _y - delta; break; case Down: newY = _y + delta; break; } if (_direction != Direction.Stopped && canMove) { // use teleportation to get on the other side ;) if (newX > _labyrinth.getBounds().right) { newX = _labyrinth.getBounds().left; } if (newX < _labyrinth.getBounds().left) { newX = _labyrinth.getBounds().right; } newInvalidateRect(newX, newY); _x = newX; _y = newY; } return _direction; } private float getDelta(float centerX, float centerY, float delta) { if (_x == centerX && _y == centerY) { delta = 0; } else if (_x != centerX) { delta = centerX - _x; } else if (_y != centerY) { delta = centerY - _y; } delta = Math.abs(delta); delta = delta > _moveDelta ? _moveDelta : delta; return delta; } private Direction getDirectionInTheSameCell(float centerX, float centerY) { if (_x == centerX && _y == centerY) { return _newDirection; } else if (_x != centerX) { return centerX - _x > 0 ? Direction.Right : Direction.Left; } else if (_y != centerY) { return centerY - _y > 0 ? Direction.Down : Direction.Up; } return _direction; } }
package com.felix.zhiban.bean.book; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.io.Serializable; import java.util.List; public class Books implements Serializable{ @SerializedName("id") @Expose private String id; @SerializedName("isbn10") @Expose private String isbn10; @SerializedName("isbn13") @Expose private String isbn13; @SerializedName("title") @Expose private String title; @SerializedName("origin_title") @Expose private String originTitle; @SerializedName("alt_title") @Expose private String altTitle; @SerializedName("subtitle") @Expose private String subtitle; @SerializedName("url") @Expose private String url; @SerializedName("alt") @Expose private String alt; @SerializedName("image") @Expose private String image; @SerializedName("images") @Expose private Images images; @SerializedName("author") @Expose private List<String> author = null; @SerializedName("translator") @Expose private List<String> translator = null; @SerializedName("publisher") @Expose private String publisher; @SerializedName("pubdate") @Expose private String pubdate; @SerializedName("rating") @Expose private Rating rating; @SerializedName("tags") @Expose private List<Tag> tags = null; @SerializedName("binding") @Expose private String binding; @SerializedName("price") @Expose private String price; @SerializedName("series") @Expose private Series series; @SerializedName("pages") @Expose private String pages; @SerializedName("author_intro") @Expose private String authorIntro; @SerializedName("summary") @Expose private String summary; @SerializedName("catalog") @Expose private String catalog; @SerializedName("ebook_url") @Expose private String ebookUrl; @SerializedName("ebook_price") @Expose private String ebookPrice; // protected Book(Parcel in) { // id = in.readString(); // isbn10 = in.readString(); // isbn13 = in.readString(); // title = in.readString(); // originTitle = in.readString(); // altTitle = in.readString(); // subtitle = in.readString(); // url = in.readString(); // alt = in.readString(); // image = in.readString(); // author = in.createStringArrayList(); // translator = in.createStringArrayList(); // publisher = in.readString(); // pubdate = in.readString(); // rating=in.readParcelable(Rating.class.getClassLoader()); // binding = in.readString(); // price = in.readString(); // pages = in.readString(); // authorIntro = in.readString(); // summary = in.readString(); // catalog = in.readString(); // ebookUrl = in.readString(); // ebookPrice = in.readString(); // public static final Creator<Book> CREATOR = new Creator<Book>() { // @Override // public Book createFromParcel(Parcel in) { // return new Book(in); // @Override // public Book[] newArray(int size) { // return new Book[size]; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getIsbn10() { return isbn10; } public void setIsbn10(String isbn10) { this.isbn10 = isbn10; } public String getIsbn13() { return isbn13; } public void setIsbn13(String isbn13) { this.isbn13 = isbn13; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getOriginTitle() { return originTitle; } public void setOriginTitle(String originTitle) { this.originTitle = originTitle; } public String getAltTitle() { return altTitle; } public void setAltTitle(String altTitle) { this.altTitle = altTitle; } public String getSubtitle() { return subtitle; } public void setSubtitle(String subtitle) { this.subtitle = subtitle; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getAlt() { return alt; } public void setAlt(String alt) { this.alt = alt; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public Images getImages() { return images; } public void setImages(Images images) { this.images = images; } public List<String> getAuthor() { return author; } public void setAuthor(List<String> author) { this.author = author; } public List<String> getTranslator() { return translator; } public void setTranslator(List<String> translator) { this.translator = translator; } public String getPublisher() { return publisher; } public void setPublisher(String publisher) { this.publisher = publisher; } public String getPubdate() { return pubdate; } public void setPubdate(String pubdate) { this.pubdate = pubdate; } public Rating getRating() { return rating; } public void setRating(Rating rating) { this.rating = rating; } public List<Tag> getTags() { return tags; } public void setTags(List<Tag> tags) { this.tags = tags; } public String getBinding() { return binding; } public void setBinding(String binding) { this.binding = binding; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public Series getSeries() { return series; } public void setSeries(Series series) { this.series = series; } public String getPages() { return pages; } public void setPages(String pages) { this.pages = pages; } public String getAuthorIntro() { return authorIntro; } public void setAuthorIntro(String authorIntro) { this.authorIntro = authorIntro; } public String getSummary() { return summary; } public void setSummary(String summary) { this.summary = summary; } public String getCatalog() { return catalog; } public void setCatalog(String catalog) { this.catalog = catalog; } public String getEbookUrl() { return ebookUrl; } public void setEbookUrl(String ebookUrl) { this.ebookUrl = ebookUrl; } public String getEbookPrice() { return ebookPrice; } public void setEbookPrice(String ebookPrice) { this.ebookPrice = ebookPrice; } // @Override // public int describeContents() { // return 0; // @Override // public void writeToParcel(Parcel parcel, int i) { // parcel.writeString(id); // parcel.writeString(isbn10); // parcel.writeString(isbn13); // parcel.writeString(title); // parcel.writeString(originTitle); // parcel.writeString(altTitle); // parcel.writeString(subtitle); // parcel.writeString(url); // parcel.writeString(alt); // parcel.writeString(image); // parcel.writeStringList(author); // parcel.writeStringList(translator); // parcel.writeString(publisher); // parcel.writeString(pubdate); // parcel.writeParcelable(this.Rating,0); // parcel.writeString(binding); // parcel.writeString(price); // parcel.writeString(pages); // parcel.writeString(authorIntro); // parcel.writeString(summary); // parcel.writeString(catalog); // parcel.writeString(ebookUrl); // parcel.writeString(ebookPrice); }
package com.samourai.wallet; import android.app.ActionBar; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ActivityInfo; import android.graphics.Bitmap; import android.graphics.Point; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.os.Bundle; import android.os.Looper; import android.support.v4.content.LocalBroadcastManager; import android.text.InputFilter; import android.text.Spanned; import android.view.Display; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.ArrayAdapter; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.Switch; import android.widget.TextView; import android.text.Editable; import android.text.TextWatcher; import android.widget.Button; import android.widget.Toast; //import android.util.Log; import org.apache.commons.lang3.tuple.Pair; import org.bitcoinj.core.Address; import org.bitcoinj.core.Transaction; import org.bitcoinj.core.TransactionInput; import org.bitcoinj.core.TransactionOutput; import org.bitcoinj.crypto.MnemonicException; import com.dm.zbar.android.scanner.ZBarConstants; import com.dm.zbar.android.scanner.ZBarScannerActivity; import com.google.zxing.BarcodeFormat; import com.google.zxing.WriterException; import com.google.zxing.client.android.Contents; import com.google.zxing.client.android.encode.QRCodeEncoder; import com.samourai.wallet.JSONRPC.TrustedNodeUtil; import com.samourai.wallet.access.AccessFactory; import com.samourai.wallet.api.APIFactory; import com.samourai.wallet.bip47.BIP47Activity; import com.samourai.wallet.bip47.BIP47Meta; import com.samourai.wallet.bip47.BIP47Util; import com.samourai.wallet.bip47.rpc.PaymentAddress; import com.samourai.wallet.bip47.rpc.PaymentCode; import com.samourai.wallet.hd.HD_WalletFactory; import com.samourai.wallet.payload.PayloadUtil; import com.samourai.wallet.ricochet.RicochetActivity; import com.samourai.wallet.ricochet.RicochetMeta; import com.samourai.wallet.segwit.BIP49Util; import com.samourai.wallet.send.FeeUtil; import com.samourai.wallet.send.MyTransactionOutPoint; import com.samourai.wallet.send.RBFSpend; import com.samourai.wallet.send.SendFactory; import com.samourai.wallet.send.SuggestedFee; import com.samourai.wallet.send.UTXO; import com.samourai.wallet.util.AddressFactory; import com.samourai.wallet.util.AppUtil; import com.samourai.wallet.util.CharSequenceX; import com.samourai.wallet.util.ExchangeRateFactory; import com.samourai.wallet.util.FormatsUtil; import com.samourai.wallet.util.MonetaryUtil; import com.samourai.wallet.util.PrefsUtil; import com.samourai.wallet.send.PushTx; import com.samourai.wallet.send.RBFUtil; import com.samourai.wallet.util.SendAddressUtil; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.math.BigInteger; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.text.DecimalFormatSymbols; import net.sourceforge.zbar.Symbol; import org.bitcoinj.core.Coin; import org.bitcoinj.params.MainNetParams; import org.bitcoinj.script.Script; import org.json.JSONException; import org.json.JSONObject; import org.bouncycastle.util.encoders.Base64; import org.bouncycastle.util.encoders.DecoderException; import org.bouncycastle.util.encoders.Hex; import static java.lang.System.currentTimeMillis; public class SendActivity extends Activity { private final static int SCAN_QR = 2012; private final static int RICOCHET = 2013; private TextView tvMaxPrompt = null; private TextView tvMax = null; private TextView tvCurrentFeePrompt = null; private long balance = 0L; private EditText edAddress = null; private String strDestinationBTCAddress = null; private TextWatcher textWatcherAddress = null; private EditText edAmountBTC = null; private EditText edAmountFiat = null; private TextWatcher textWatcherBTC = null; private TextWatcher textWatcherFiat = null; private String defaultSeparator = null; private Button btFee = null; private final static int FEE_LOW = 0; private final static int FEE_NORMAL = 1; private final static int FEE_PRIORITY = 2; private final static int FEE_CUSTOM = 3; private int FEE_TYPE = 0; public final static int SPEND_SIMPLE = 0; public final static int SPEND_BIP126 = 1; public final static int SPEND_RICOCHET = 2; private int SPEND_TYPE = SPEND_BIP126; // private CheckBox cbSpendType = null; private Switch swRicochet = null; private String strFiat = null; private double btc_fx = 286.0; private TextView tvFiatSymbol = null; private Button btSend = null; private int selectedAccount = 0; private String strPCode = null; private boolean bViaMenu = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_send); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); SendActivity.this.getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); if(SamouraiWallet.getInstance().getShowTotalBalance()) { if(SamouraiWallet.getInstance().getCurrentSelectedAccount() == 2) { selectedAccount = 1; } else { selectedAccount = 0; } } else { selectedAccount = 0; } tvMaxPrompt = (TextView)findViewById(R.id.max_prompt); tvMax = (TextView)findViewById(R.id.max); try { balance = APIFactory.getInstance(SendActivity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(selectedAccount).xpubstr()); } catch(IOException ioe) { balance = 0L; } catch(MnemonicException.MnemonicLengthException mle) { balance = 0L; } catch(java.lang.NullPointerException npe) { balance = 0L; } final String strAmount; NumberFormat nf = NumberFormat.getInstance(Locale.getDefault()); nf.setMaximumFractionDigits(8); nf.setMinimumFractionDigits(1); nf.setMinimumIntegerDigits(1); int unit = PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.BTC_UNITS, MonetaryUtil.UNIT_BTC); switch(unit) { case MonetaryUtil.MICRO_BTC: strAmount = nf.format(((double)(balance * 1000000L)) / 1e8); break; case MonetaryUtil.MILLI_BTC: strAmount = nf.format(((double)(balance * 1000L)) / 1e8); break; default: strAmount = nf.format(balance / 1e8); break; } tvMax.setText(strAmount + " " + getDisplayUnits()); tvMaxPrompt.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { edAmountBTC.setText(strAmount); return false; } }); tvMax.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { edAmountBTC.setText(strAmount); return false; } }); tvCurrentFeePrompt = (TextView)findViewById(R.id.current_fee_prompt); tvCurrentFeePrompt.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { doCustomFee(); return false; } }); DecimalFormat format = (DecimalFormat)DecimalFormat.getInstance(Locale.getDefault()); DecimalFormatSymbols symbols = format.getDecimalFormatSymbols(); defaultSeparator = Character.toString(symbols.getDecimalSeparator()); strFiat = PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.CURRENT_FIAT, "USD"); btc_fx = ExchangeRateFactory.getInstance(SendActivity.this).getAvgPrice(strFiat); tvFiatSymbol = (TextView)findViewById(R.id.fiatSymbol); tvFiatSymbol.setText(getDisplayUnits() + "-" + strFiat); edAddress = (EditText)findViewById(R.id.destination); textWatcherAddress = new TextWatcher() { public void afterTextChanged(Editable s) { validateSpend(); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { ; } public void onTextChanged(CharSequence s, int start, int before, int count) { ; } }; edAddress.addTextChangedListener(textWatcherAddress); edAddress.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { //final int DRAWABLE_LEFT = 0; //final int DRAWABLE_TOP = 1; final int DRAWABLE_RIGHT = 2; //final int DRAWABLE_BOTTOM = 3; if(event.getAction() == MotionEvent.ACTION_UP && event.getRawX() >= (edAddress.getRight() - edAddress.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) { final List<String> entries = new ArrayList<String>(); entries.addAll(BIP47Meta.getInstance().getSortedByLabels(false)); final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(SendActivity.this, android.R.layout.select_dialog_singlechoice); for(int i = 0; i < entries.size(); i++) { arrayAdapter.add(BIP47Meta.getInstance().getDisplayLabel(entries.get(i))); } AlertDialog.Builder dlg = new AlertDialog.Builder(SendActivity.this); dlg.setIcon(R.drawable.ic_launcher); dlg.setTitle(R.string.app_name); dlg.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Toast.makeText(SendActivity.this, BIP47Meta.getInstance().getDisplayLabel(entries.get(which)), Toast.LENGTH_SHORT).show(); // Toast.makeText(SendActivity.this, entries.get(which), Toast.LENGTH_SHORT).show(); processPCode(entries.get(which), null); } }); dlg.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); dlg.show(); return true; } return false; } }); edAmountBTC = (EditText)findViewById(R.id.amountBTC); edAmountFiat = (EditText)findViewById(R.id.amountFiat); textWatcherBTC = new TextWatcher() { public void afterTextChanged(Editable s) { edAmountBTC.removeTextChangedListener(this); edAmountFiat.removeTextChangedListener(textWatcherFiat); int unit = PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.BTC_UNITS, MonetaryUtil.UNIT_BTC); int max_len = 8; NumberFormat btcFormat = NumberFormat.getInstance(Locale.US); switch (unit) { case MonetaryUtil.MICRO_BTC: max_len = 2; break; case MonetaryUtil.MILLI_BTC: max_len = 4; break; default: max_len = 8; break; } btcFormat.setMaximumFractionDigits(max_len + 1); btcFormat.setMinimumFractionDigits(0); double d = 0.0; try { d = NumberFormat.getInstance(Locale.US).parse(s.toString()).doubleValue(); String s1 = btcFormat.format(d); if (s1.indexOf(defaultSeparator) != -1) { String dec = s1.substring(s1.indexOf(defaultSeparator)); if (dec.length() > 0) { dec = dec.substring(1); if (dec.length() > max_len) { edAmountBTC.setText(s1.substring(0, s1.length() - 1)); edAmountBTC.setSelection(edAmountBTC.getText().length()); s = edAmountBTC.getEditableText(); } } } } catch (NumberFormatException nfe) { ; } catch (ParseException pe) { ; } switch (unit) { case MonetaryUtil.MICRO_BTC: d = d / 1000000.0; break; case MonetaryUtil.MILLI_BTC: d = d / 1000.0; break; default: break; } if(d > 21000000.0) { edAmountFiat.setText("0.00"); edAmountFiat.setSelection(edAmountFiat.getText().length()); edAmountBTC.setText("0"); edAmountBTC.setSelection(edAmountBTC.getText().length()); Toast.makeText(SendActivity.this, R.string.invalid_amount, Toast.LENGTH_SHORT).show(); } else { edAmountFiat.setText(MonetaryUtil.getInstance().getFiatFormat(strFiat).format(d * btc_fx)); edAmountFiat.setSelection(edAmountFiat.getText().length()); } edAmountFiat.addTextChangedListener(textWatcherFiat); edAmountBTC.addTextChangedListener(this); validateSpend(); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { ; } public void onTextChanged(CharSequence s, int start, int before, int count) { ; } }; edAmountBTC.addTextChangedListener(textWatcherBTC); textWatcherFiat = new TextWatcher() { public void afterTextChanged(Editable s) { edAmountFiat.removeTextChangedListener(this); edAmountBTC.removeTextChangedListener(textWatcherBTC); int max_len = 2; NumberFormat fiatFormat = NumberFormat.getInstance(Locale.US); fiatFormat.setMaximumFractionDigits(max_len + 1); fiatFormat.setMinimumFractionDigits(0); double d = 0.0; try { d = NumberFormat.getInstance(Locale.US).parse(s.toString()).doubleValue(); String s1 = fiatFormat.format(d); if(s1.indexOf(defaultSeparator) != -1) { String dec = s1.substring(s1.indexOf(defaultSeparator)); if(dec.length() > 0) { dec = dec.substring(1); if(dec.length() > max_len) { edAmountFiat.setText(s1.substring(0, s1.length() - 1)); edAmountFiat.setSelection(edAmountFiat.getText().length()); } } } } catch(NumberFormatException nfe) { ; } catch(ParseException pe) { ; } int unit = PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.BTC_UNITS, MonetaryUtil.UNIT_BTC); switch (unit) { case MonetaryUtil.MICRO_BTC: d = d * 1000000.0; break; case MonetaryUtil.MILLI_BTC: d = d * 1000.0; break; default: break; } if((d / btc_fx) > 21000000.0) { edAmountFiat.setText("0.00"); edAmountFiat.setSelection(edAmountFiat.getText().length()); edAmountBTC.setText("0"); edAmountBTC.setSelection(edAmountBTC.getText().length()); Toast.makeText(SendActivity.this, R.string.invalid_amount, Toast.LENGTH_SHORT).show(); } else { edAmountBTC.setText(MonetaryUtil.getInstance().getBTCFormat().format(d / btc_fx)); edAmountBTC.setSelection(edAmountBTC.getText().length()); } edAmountBTC.addTextChangedListener(textWatcherBTC); edAmountFiat.addTextChangedListener(this); validateSpend(); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { ; } public void onTextChanged(CharSequence s, int start, int before, int count) { ; } }; edAmountFiat.addTextChangedListener(textWatcherFiat); /* cbSpendType = (CheckBox)findViewById(R.id.simple); cbSpendType.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CheckBox cb = (CheckBox)v; if(swRicochet.isChecked()) { SPEND_TYPE = SPEND_RICOCHET; } else { SPEND_TYPE = cb.isChecked() ? SPEND_SIMPLE : SPEND_BIP126; } } }); */ SPEND_TYPE = PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.SPEND_TYPE, SPEND_BIP126); if(SPEND_TYPE > SPEND_BIP126) { SPEND_TYPE = SPEND_BIP126; PrefsUtil.getInstance(SendActivity.this).setValue(PrefsUtil.SPEND_TYPE, SPEND_BIP126); } swRicochet = (Switch)findViewById(R.id.ricochet); swRicochet.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked) { SPEND_TYPE = SPEND_RICOCHET; if (BIP47Meta.getInstance().getOutgoingStatus(BIP47Meta.strSamouraiDonationPCode) != BIP47Meta.STATUS_SENT_CFM) { AlertDialog.Builder dlg = new AlertDialog.Builder(SendActivity.this) .setTitle(R.string.app_name) .setMessage(R.string.ricochet_fee_via_bip47) .setCancelable(false) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); // Intent intent = new Intent(SendActivity.this, BIP47Activity.class); // startActivity(intent); Intent intent = new Intent(SendActivity.this, BIP47Activity.class); intent.putExtra("pcode", BIP47Meta.strSamouraiDonationPCode); intent.putExtra("meta", BIP47Meta.strSamouraiDonationMeta); startActivity(intent); } }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); if(!isFinishing()) { dlg.show(); } } } else { SPEND_TYPE = PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.SPEND_TYPE, SPEND_BIP126); } } }); btFee = (Button)findViewById(R.id.fee); FEE_TYPE = PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.CURRENT_FEE_TYPE, FEE_NORMAL); switch(FEE_TYPE) { case FEE_NORMAL: btFee.setText(getString(R.string.auto_fee)); FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getNormalFee()); break; case FEE_LOW: btFee.setText(getString(R.string.low_fee)); FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getLowFee()); break; case FEE_PRIORITY: btFee.setText(getString(R.string.priority_fee)); FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getHighFee()); break; default: btFee.setText(getString(R.string.auto_fee)); FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getNormalFee()); break; } tvCurrentFeePrompt.setText(getCurrentFeeSetting()); btFee.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { switch(FEE_TYPE) { case FEE_NORMAL: FEE_TYPE = FEE_LOW; btFee.setText(getString(R.string.low_fee)); FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getLowFee()); break; case FEE_LOW: FEE_TYPE = FEE_PRIORITY; btFee.setText(getString(R.string.priority_fee)); FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getHighFee()); break; case FEE_PRIORITY: FEE_TYPE = FEE_NORMAL; btFee.setText(getString(R.string.auto_fee)); FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getNormalFee()); break; case FEE_CUSTOM: default: FEE_TYPE = FEE_NORMAL; btFee.setText(getString(R.string.auto_fee)); FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getNormalFee()); break; } PrefsUtil.getInstance(SendActivity.this).setValue(PrefsUtil.CURRENT_FEE_TYPE, FEE_TYPE == FEE_CUSTOM ? FEE_NORMAL : FEE_TYPE); tvCurrentFeePrompt.setText(getCurrentFeeSetting()); } }); btSend = (Button)findViewById(R.id.send); btSend.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { btSend.setClickable(false); btSend.setActivated(false); double btc_amount = 0.0; try { btc_amount = NumberFormat.getInstance(Locale.US).parse(edAmountBTC.getText().toString().trim()).doubleValue(); // Log.i("SendFragment", "amount entered:" + btc_amount); } catch (NumberFormatException nfe) { btc_amount = 0.0; } catch (ParseException pe) { btc_amount = 0.0; } double dAmount; int unit = PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.BTC_UNITS, MonetaryUtil.UNIT_BTC); switch (unit) { case MonetaryUtil.MICRO_BTC: dAmount = btc_amount / 1000000.0; break; case MonetaryUtil.MILLI_BTC: dAmount = btc_amount / 1000.0; break; default: dAmount = btc_amount; break; } long amount = (long)(Math.round(dAmount * 1e8));; // Log.i("SendActivity", "amount:" + amount); final String address = strDestinationBTCAddress == null ? edAddress.getText().toString() : strDestinationBTCAddress; final int accountIdx = selectedAccount; final boolean isBIP49 = Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), address).isP2SHAddress(); final HashMap<String, BigInteger> receivers = new HashMap<String, BigInteger>(); receivers.put(address, BigInteger.valueOf(amount)); // store current change index to restore value in case of sending fail int change_index = 0; if(isBIP49) { change_index = BIP49Util.getInstance(SendActivity.this).getWallet().getAccount(0).getChange().getAddrIdx(); } else { try { change_index = HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(0).getChange().getAddrIdx(); // Log.d("SendActivity", "storing change index:" + change_index); } catch(IOException ioe) { ; } catch(MnemonicException.MnemonicLengthException mle) { ; } } // get all UTXO List<UTXO> utxos = APIFactory.getInstance(SendActivity.this).getUtxos(); final List<UTXO> selectedUTXO = new ArrayList<UTXO>(); long totalValueSelected = 0L; long change = 0L; BigInteger fee = null; // Log.d("SendActivity", "amount:" + amount); // Log.d("SendActivity", "balance:" + balance); // insufficient funds if(amount > balance) { Toast.makeText(SendActivity.this, R.string.insufficient_funds, Toast.LENGTH_SHORT).show(); } // entire balance (can only be simple spend) else if(amount == balance) { // make sure we are using simple spend SPEND_TYPE = SPEND_SIMPLE; // Log.d("SendActivity", "amount == balance"); // take all utxos, deduct fee selectedUTXO.addAll(utxos); for(UTXO u : selectedUTXO) { totalValueSelected += u.getValue(); } // Log.d("SendActivity", "balance:" + balance); // Log.d("SendActivity", "total value selected:" + totalValueSelected); } else { ; } org.apache.commons.lang3.tuple.Pair<ArrayList<MyTransactionOutPoint>, ArrayList<TransactionOutput>> pair = null; if(SPEND_TYPE == SPEND_RICOCHET) { boolean samouraiFeeViaBIP47 = false; if(BIP47Meta.getInstance().getOutgoingStatus(BIP47Meta.strSamouraiDonationPCode) == BIP47Meta.STATUS_SENT_CFM) { samouraiFeeViaBIP47 = true; } final JSONObject jObj = RicochetMeta.getInstance(SendActivity.this).script(amount, FeeUtil.getInstance().getSuggestedFee().getDefaultPerKB().longValue(), address, 4, strPCode, samouraiFeeViaBIP47); if(jObj != null) { try { long totalAmount = jObj.getLong("total_spend"); if(totalAmount > balance) { Toast.makeText(SendActivity.this, R.string.insufficient_funds, Toast.LENGTH_SHORT).show(); return; } String msg = getText(R.string.ricochet_spend1) + " " + address + " " + getText(R.string.ricochet_spend2) + " " + Coin.valueOf(totalAmount).toPlainString() + " " + getText(R.string.ricochet_spend3); AlertDialog.Builder dlg = new AlertDialog.Builder(SendActivity.this) .setTitle(R.string.app_name) .setMessage(msg) .setCancelable(false) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { RicochetMeta.getInstance(SendActivity.this).add(jObj); dialog.dismiss(); Intent intent = new Intent(SendActivity.this, RicochetActivity.class); startActivityForResult(intent, RICOCHET); } }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); if(!isFinishing()) { dlg.show(); } return; } catch(JSONException je) { return; } } return; } // if BIP126 try both hetero/alt, if fails change type to SPEND_SIMPLE else if(SPEND_TYPE == SPEND_BIP126) { List<UTXO> _utxos = utxos; //Collections.shuffle(_utxos); // sort in descending order by value Collections.sort(_utxos, new UTXO.UTXOComparator()); // hetero pair = SendFactory.getInstance(SendActivity.this).heterogeneous(_utxos, BigInteger.valueOf(amount), address); if(pair == null) { //Collections.sort(_utxos, new UTXO.UTXOComparator()); // alt pair = SendFactory.getInstance(SendActivity.this).altHeterogeneous(_utxos, BigInteger.valueOf(amount), address); } if(pair == null) { // can't do BIP126, revert to SPEND_SIMPLE SPEND_TYPE = SPEND_SIMPLE; } } else { ; } // simple spend (less than balance) if(SPEND_TYPE == SPEND_SIMPLE) { List<UTXO> _utxos = utxos; // sort in ascending order by value Collections.sort(_utxos, new UTXO.UTXOComparator()); Collections.reverse(_utxos); // get smallest 1 UTXO > than spend + fee + dust for(UTXO u : _utxos) { Pair<Integer,Integer> outpointTypes = FeeUtil.getInstance().getOutpointCount(u.getOutpoints()); if(u.getValue() >= (amount + SamouraiWallet.bDust.longValue() + FeeUtil.getInstance().estimatedFeeSegwit(outpointTypes.getLeft(), outpointTypes.getRight(), 2).longValue())) { selectedUTXO.add(u); totalValueSelected += u.getValue(); // Log.d("SendActivity", "spend type:" + SPEND_TYPE); // Log.d("SendActivity", "single output"); // Log.d("SendActivity", "amount:" + amount); // Log.d("SendActivity", "value selected:" + u.getValue()); // Log.d("SendActivity", "total value selected:" + totalValueSelected); // Log.d("SendActivity", "nb inputs:" + u.getOutpoints().size()); break; } } if(selectedUTXO.size() == 0) { // sort in descending order by value Collections.sort(_utxos, new UTXO.UTXOComparator()); int selected = 0; int p2pkh = 0; int p2wpkh = 0; // get largest UTXOs > than spend + fee + dust for(UTXO u : _utxos) { selectedUTXO.add(u); totalValueSelected += u.getValue(); selected += u.getOutpoints().size(); // Log.d("SendActivity", "value selected:" + u.getValue()); // Log.d("SendActivity", "total value selected/threshold:" + totalValueSelected + "/" + (amount + SamouraiWallet.bDust.longValue() + FeeUtil.getInstance().estimatedFee(selected, 2).longValue())); Pair<Integer,Integer> outpointTypes = FeeUtil.getInstance().getOutpointCount(u.getOutpoints()); p2pkh += outpointTypes.getLeft(); p2wpkh += outpointTypes.getRight(); if(totalValueSelected >= (amount + SamouraiWallet.bDust.longValue() + FeeUtil.getInstance().estimatedFeeSegwit(p2pkh, p2wpkh, 2).longValue())) { // Log.d("SendActivity", "spend type:" + SPEND_TYPE); // Log.d("SendActivity", "multiple outputs"); // Log.d("SendActivity", "amount:" + amount); // Log.d("SendActivity", "total value selected:" + totalValueSelected); // Log.d("SendActivity", "nb inputs:" + selected); break; } } } } else if(pair != null) { selectedUTXO.clear(); receivers.clear(); long inputAmount = 0L; long outputAmount = 0L; for(MyTransactionOutPoint outpoint : pair.getLeft()) { UTXO u = new UTXO(); List<MyTransactionOutPoint> outs = new ArrayList<MyTransactionOutPoint>(); outs.add(outpoint); u.setOutpoints(outs); totalValueSelected += u.getValue(); selectedUTXO.add(u); inputAmount += u.getValue(); } for(TransactionOutput output : pair.getRight()) { try { Script script = new Script(output.getScriptBytes()); receivers.put(script.getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(), BigInteger.valueOf(output.getValue().longValue())); outputAmount += output.getValue().longValue(); } catch(Exception e) { Toast.makeText(SendActivity.this, R.string.error_bip126_output, Toast.LENGTH_SHORT).show(); return; } } change = outputAmount - amount; fee = BigInteger.valueOf(inputAmount - outputAmount); } else { Toast.makeText(SendActivity.this, R.string.cannot_select_utxo, Toast.LENGTH_SHORT).show(); return; } // do spend here if(selectedUTXO.size() > 0) { // estimate fee for simple spend, already done if BIP126 if(SPEND_TYPE == SPEND_SIMPLE) { List<MyTransactionOutPoint> outpoints = new ArrayList<MyTransactionOutPoint>(); for(UTXO utxo : selectedUTXO) { outpoints.addAll(utxo.getOutpoints()); } Pair<Integer,Integer> outpointTypes = FeeUtil.getInstance().getOutpointCount(outpoints); fee = FeeUtil.getInstance().estimatedFeeSegwit(outpointTypes.getLeft(), outpointTypes.getRight(), 2); } // Log.d("SendActivity", "spend type:" + SPEND_TYPE); // Log.d("SendActivity", "amount:" + amount); // Log.d("SendActivity", "total value selected:" + totalValueSelected); // Log.d("SendActivity", "fee:" + fee.longValue()); // Log.d("SendActivity", "nb inputs:" + selectedUTXO.size()); change = totalValueSelected - (amount + fee.longValue()); // Log.d("SendActivity", "change:" + change); boolean changeIsDust = false; if(change < SamouraiWallet.bDust.longValue() && SPEND_TYPE == SPEND_SIMPLE) { change = 0L; fee = fee.add(BigInteger.valueOf(change)); amount = totalValueSelected - fee.longValue(); // Log.d("SendActivity", "fee:" + fee.longValue()); // Log.d("SendActivity", "change:" + change); // Log.d("SendActivity", "amount:" + amount); receivers.put(address, BigInteger.valueOf(amount)); changeIsDust = true; } final long _change = change; final BigInteger _fee = fee; final int _change_index = change_index; String dest = null; if(strPCode != null && strPCode.length() > 0) { dest = BIP47Meta.getInstance().getDisplayLabel(strPCode); } else { dest = address; } String strPrivacyWarning = null; if(SendAddressUtil.getInstance().get(address) == 1) { strPrivacyWarning = getString(R.string.send_privacy_warning) + "\n\n"; } else { strPrivacyWarning = ""; } String strChangeIsDust = null; if(changeIsDust) { strChangeIsDust = getString(R.string.change_is_dust) + "\n\n"; } else { strChangeIsDust = ""; } String message = strChangeIsDust + strPrivacyWarning + "Send " + Coin.valueOf(amount).toPlainString() + " to " + dest + " (fee:" + Coin.valueOf(_fee.longValue()).toPlainString() + ")?"; final long _amount = amount; AlertDialog.Builder builder = new AlertDialog.Builder(SendActivity.this); builder.setTitle(R.string.app_name); builder.setMessage(message); builder.setCancelable(false); builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int whichButton) { final ProgressDialog progress = new ProgressDialog(SendActivity.this); progress.setCancelable(false); progress.setTitle(R.string.app_name); progress.setMessage(getString(R.string.please_wait_sending)); progress.show(); final List<MyTransactionOutPoint> outPoints = new ArrayList<MyTransactionOutPoint>(); for(UTXO u : selectedUTXO) { outPoints.addAll(u.getOutpoints()); } // add change if(_change > 0L) { if(SPEND_TYPE == SPEND_SIMPLE) { if(isBIP49) { String change_address = BIP49Util.getInstance(SendActivity.this).getAddressAt(AddressFactory.CHANGE_CHAIN, BIP49Util.getInstance(SendActivity.this).getWallet().getAccount(0).getChange().getAddrIdx()).getAddressAsString(); receivers.put(change_address, BigInteger.valueOf(_change)); } else { try { String change_address = HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(0).getChange().getAddressAt(HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(0).getChange().getAddrIdx()).getAddressString(); receivers.put(change_address, BigInteger.valueOf(_change)); } catch(IOException ioe) { ; } catch(MnemonicException.MnemonicLengthException mle) { ; } } } else if (SPEND_TYPE == SPEND_BIP126) { // do nothing, change addresses included } else { ; } } // make tx Transaction tx = SendFactory.getInstance(SendActivity.this).makeTransaction(0, outPoints, receivers); final RBFSpend rbf; if(PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.RBF_OPT_IN, false) == true) { rbf = new RBFSpend(); for(TransactionInput input : tx.getInputs()) { boolean _isBIP49 = false; String _addr = null; Address _address = input.getConnectedOutput().getAddressFromP2PKHScript(SamouraiWallet.getInstance().getCurrentNetworkParams()); if(_address != null) { _addr = _address.toString(); } if(_addr == null) { _addr = input.getConnectedOutput().getAddressFromP2SH(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(); _isBIP49 = true; } String path = APIFactory.getInstance(SendActivity.this).getUnspentPaths().get(_addr); if(path != null) { if(_isBIP49) { rbf.addKey(input.getOutpoint().toString(), path + "/49"); } else { rbf.addKey(input.getOutpoint().toString(), path); } } else { String pcode = BIP47Meta.getInstance().getPCode4Addr(_addr); int idx = BIP47Meta.getInstance().getIdx4Addr(_addr); rbf.addKey(input.getOutpoint().toString(), pcode + "/" + idx); } } } else { rbf = null; } if(tx != null) { tx = SendFactory.getInstance(SendActivity.this).signTransaction(tx); final Transaction _tx = tx; final String hexTx = new String(Hex.encode(tx.bitcoinSerialize())); // Log.d("SendActivity", hexTx); final String strTxHash = tx.getHashAsString(); if(PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.BROADCAST_TX, true) == false) { if(progress != null && progress.isShowing()) { progress.dismiss(); } doShowTx(hexTx, strTxHash); return; } new Thread(new Runnable() { @Override public void run() { Looper.prepare(); boolean isOK = false; String response = null; try { if(PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.USE_TRUSTED_NODE, false) == true) { if(TrustedNodeUtil.getInstance().isSet()) { response = PushTx.getInstance(SendActivity.this).trustedNode(hexTx); JSONObject jsonObject = new org.json.JSONObject(response); if(jsonObject.has("result")) { if(jsonObject.getString("result").matches("^[A-Za-z0-9]{64}$")) { isOK = true; } else { Toast.makeText(SendActivity.this, R.string.trusted_node_tx_error, Toast.LENGTH_SHORT).show(); } } } else { Toast.makeText(SendActivity.this, R.string.trusted_node_not_valid, Toast.LENGTH_SHORT).show(); } } else { response = PushTx.getInstance(SendActivity.this).samourai(hexTx); if(response != null) { JSONObject jsonObject = new org.json.JSONObject(response); if(jsonObject.has("status")) { if(jsonObject.getString("status").equals("ok")) { isOK = true; } } } else { Toast.makeText(SendActivity.this, R.string.pushtx_returns_null, Toast.LENGTH_SHORT).show(); } } if(isOK) { if(PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.USE_TRUSTED_NODE, false) == false) { Toast.makeText(SendActivity.this, R.string.tx_sent, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(SendActivity.this, R.string.trusted_node_tx_sent, Toast.LENGTH_SHORT).show(); } if(_change > 0L && SPEND_TYPE == SPEND_SIMPLE) { try { HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(0).getChange().incAddrIdx(); } catch(IOException ioe) { ; } catch(MnemonicException.MnemonicLengthException mle) { ; } } if(PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.RBF_OPT_IN, false) == true) { for(TransactionOutput out : _tx.getOutputs()) { if(!isBIP49 && !address.equals(out.getAddressFromP2PKHScript(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString())) { rbf.addChangeAddr(out.getAddressFromP2PKHScript(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString()); } else if(isBIP49 && !address.equals(out.getAddressFromP2SH(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString())) { rbf.addChangeAddr(out.getAddressFromP2SH(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString()); } else { ; } } rbf.setHash(strTxHash); rbf.setSerializedTx(hexTx); RBFUtil.getInstance().add(rbf); } // increment counter if BIP47 spend if(strPCode != null && strPCode.length() > 0) { BIP47Meta.getInstance().getPCode4AddrLookup().put(address, strPCode); BIP47Meta.getInstance().inc(strPCode); SimpleDateFormat sd = new SimpleDateFormat("dd MMM"); String strTS = sd.format(currentTimeMillis()); String event = strTS + " " + SendActivity.this.getString(R.string.sent) + " " + MonetaryUtil.getInstance().getBTCFormat().format((double) _amount / 1e8) + " BTC"; BIP47Meta.getInstance().setLatestEvent(strPCode, event); strPCode = null; } SendAddressUtil.getInstance().add(address, true); Intent intent = new Intent("com.samourai.wallet.BalanceFragment.REFRESH"); intent.putExtra("notifTx", false); intent.putExtra("fetch", true); LocalBroadcastManager.getInstance(SendActivity.this).sendBroadcast(intent); View view = SendActivity.this.getCurrentFocus(); if (view != null) { InputMethodManager imm = (InputMethodManager)SendActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0); } if(bViaMenu) { SendActivity.this.finish(); } else { Intent _intent = new Intent(SendActivity.this, BalanceActivity.class); _intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); startActivity(_intent); } } else { Toast.makeText(SendActivity.this, R.string.tx_failed, Toast.LENGTH_SHORT).show(); // reset change index upon tx fail if(isBIP49) { BIP49Util.getInstance(SendActivity.this).getWallet().getAccount(0).getChange().setAddrIdx(_change_index); } else { HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(0).getChange().setAddrIdx(_change_index); } } } catch(JSONException je) { Toast.makeText(SendActivity.this, "pushTx:" + je.getMessage(), Toast.LENGTH_SHORT).show(); } catch(MnemonicException.MnemonicLengthException mle) { Toast.makeText(SendActivity.this, "pushTx:" + mle.getMessage(), Toast.LENGTH_SHORT).show(); } catch(DecoderException de) { Toast.makeText(SendActivity.this, "pushTx:" + de.getMessage(), Toast.LENGTH_SHORT).show(); } catch(IOException ioe) { Toast.makeText(SendActivity.this, "pushTx:" + ioe.getMessage(), Toast.LENGTH_SHORT).show(); } finally { SendActivity.this.runOnUiThread(new Runnable() { @Override public void run() { btSend.setActivated(true); btSend.setClickable(true); progress.dismiss(); dialog.dismiss(); } }); } Looper.loop(); } }).start(); } else { // Log.d("SendActivity", "tx error"); Toast.makeText(SendActivity.this, "tx error", Toast.LENGTH_SHORT).show(); } } }); builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int whichButton) { try { // reset change index upon 'NO' if(isBIP49) { BIP49Util.getInstance(SendActivity.this).getWallet().getAccount(0).getChange().setAddrIdx(_change_index); } else { HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(0).getChange().setAddrIdx(_change_index); } } catch(Exception e) { // Log.d("SendActivity", e.getMessage()); Toast.makeText(SendActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } finally { SendActivity.this.runOnUiThread(new Runnable() { @Override public void run() { btSend.setActivated(true); btSend.setClickable(true); dialog.dismiss(); } }); } } }); AlertDialog alert = builder.create(); alert.show(); } } }); Bundle extras = getIntent().getExtras(); if(extras != null) { bViaMenu = extras.getBoolean("via_menu", false); String strUri = extras.getString("uri"); strPCode = extras.getString("pcode"); if(strUri != null && strUri.length() > 0) { processScan(strUri); } if(strPCode != null && strPCode.length() > 0) { processPCode(strPCode, null); } } validateSpend(); } @Override public void onResume() { super.onResume(); AppUtil.getInstance(SendActivity.this).checkTimeOut(); } @Override public void onPause() { super.onPause(); } @Override public void onDestroy() { SendActivity.this.getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); super.onDestroy(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); menu.findItem(R.id.action_settings).setVisible(false); menu.findItem(R.id.action_sweep).setVisible(false); menu.findItem(R.id.action_backup).setVisible(false); menu.findItem(R.id.action_refresh).setVisible(false); menu.findItem(R.id.action_share_receive).setVisible(false); menu.findItem(R.id.action_tor).setVisible(false); menu.findItem(R.id.action_sign).setVisible(false); return super.onCreateOptionsMenu(menu); } @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(); // noinspection SimplifiableIfStatement if (id == R.id.action_scan_qr) { doScan(); } else if (id == R.id.action_ricochet) { Intent intent = new Intent(SendActivity.this, RicochetActivity.class); startActivity(intent); } else if (id == R.id.action_empty_ricochet) { emptyRicochetQueue(); } else if (id == R.id.action_utxo) { doUTXO(); } else if (id == R.id.action_fees) { doFees(); } else { ; } return super.onOptionsItemSelected(item); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if(resultCode == Activity.RESULT_OK && requestCode == SCAN_QR) { if(data != null && data.getStringExtra(ZBarConstants.SCAN_RESULT) != null) { final String strResult = data.getStringExtra(ZBarConstants.SCAN_RESULT); processScan(strResult); } } else if(resultCode == Activity.RESULT_CANCELED && requestCode == SCAN_QR) { ; } else if(resultCode == Activity.RESULT_OK && requestCode == RICOCHET) { ; } else if(resultCode == Activity.RESULT_CANCELED && requestCode == RICOCHET) { ; } else { ; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK) { if(bViaMenu) { SendActivity.this.finish(); } else { Intent _intent = new Intent(SendActivity.this, BalanceActivity.class); _intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); startActivity(_intent); } return true; } else { ; } return false; } private void doScan() { Intent intent = new Intent(SendActivity.this, ZBarScannerActivity.class); intent.putExtra(ZBarConstants.SCAN_MODES, new int[]{ Symbol.QRCODE } ); startActivityForResult(intent, SCAN_QR); } private void processScan(String data) { if(FormatsUtil.getInstance().isValidPaymentCode(data)) { processPCode(data, null); return; } if(FormatsUtil.getInstance().isBitcoinUri(data)) { String address = FormatsUtil.getInstance().getBitcoinAddress(data); String amount = FormatsUtil.getInstance().getBitcoinAmount(data); edAddress.setText(address); if(amount != null) { try { NumberFormat btcFormat = NumberFormat.getInstance(Locale.US); btcFormat.setMaximumFractionDigits(8); btcFormat.setMinimumFractionDigits(1); edAmountBTC.setText(btcFormat.format(Double.parseDouble(amount) / 1e8)); } catch (NumberFormatException nfe) { edAmountBTC.setText("0.0"); } } PrefsUtil.getInstance(SendActivity.this).setValue(PrefsUtil.BTC_UNITS, MonetaryUtil.UNIT_BTC); tvFiatSymbol.setText(getDisplayUnits() + "-" + strFiat); final String strAmount; NumberFormat nf = NumberFormat.getInstance(Locale.US); nf.setMinimumIntegerDigits(1); nf.setMinimumFractionDigits(1); nf.setMaximumFractionDigits(8); strAmount = nf.format(balance / 1e8); tvMax.setText(strAmount + " " + getDisplayUnits()); try { if(amount != null && Double.parseDouble(amount) != 0.0) { edAddress.setEnabled(false); edAmountBTC.setEnabled(false); edAmountFiat.setEnabled(false); // Toast.makeText(SendActivity.this, R.string.no_edit_BIP21_scan, Toast.LENGTH_SHORT).show(); } } catch (NumberFormatException nfe) { edAmountBTC.setText("0.0"); } } else if(FormatsUtil.getInstance().isValidBitcoinAddress(data)) { edAddress.setText(data); } else if(data.indexOf("?") != -1) { String pcode = data.substring(0, data.indexOf("?")); // not valid BIP21 but seen often enough if(pcode.startsWith("bitcoin: pcode = pcode.substring(10); } if(pcode.startsWith("bitcoin:")) { pcode = pcode.substring(8); } if(FormatsUtil.getInstance().isValidPaymentCode(pcode)) { processPCode(pcode, data.substring(data.indexOf("?"))); } } else { Toast.makeText(SendActivity.this, R.string.scan_error, Toast.LENGTH_SHORT).show(); } validateSpend(); } private void processPCode(String pcode, String meta) { if(FormatsUtil.getInstance().isValidPaymentCode(pcode)) { if(BIP47Meta.getInstance().getOutgoingStatus(pcode) == BIP47Meta.STATUS_SENT_CFM) { try { PaymentCode _pcode = new PaymentCode(pcode); PaymentAddress paymentAddress = BIP47Util.getInstance(SendActivity.this).getSendAddress(_pcode, BIP47Meta.getInstance().getOutgoingIdx(pcode)); strDestinationBTCAddress = paymentAddress.getSendECKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(); strPCode = _pcode.toString(); edAddress.setText(BIP47Meta.getInstance().getDisplayLabel(strPCode)); edAddress.setEnabled(false); } catch(Exception e) { Toast.makeText(SendActivity.this, R.string.error_payment_code, Toast.LENGTH_SHORT).show(); } } else { // Toast.makeText(SendActivity.this, "Payment must be added and notification tx sent", Toast.LENGTH_SHORT).show(); if(meta != null && meta.startsWith("?") && meta.length() > 1) { meta = meta.substring(1); } Intent intent = new Intent(SendActivity.this, BIP47Activity.class); intent.putExtra("pcode", pcode); if(meta != null && meta.length() > 0) { intent.putExtra("meta", meta); } startActivity(intent); } } else { Toast.makeText(SendActivity.this, R.string.invalid_payment_code, Toast.LENGTH_SHORT).show(); } } private void validateSpend() { boolean isValid = false; boolean insufficientFunds = false; double btc_amount = 0.0; String strBTCAddress = edAddress.getText().toString().trim(); if(strBTCAddress.startsWith("bitcoin:")) { edAddress.setText(strBTCAddress.substring(8)); } try { btc_amount = NumberFormat.getInstance(Locale.US).parse(edAmountBTC.getText().toString().trim()).doubleValue(); // Log.i("SendFragment", "amount entered:" + btc_amount); } catch (NumberFormatException nfe) { btc_amount = 0.0; } catch (ParseException pe) { btc_amount = 0.0; } final double dAmount; int unit = PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.BTC_UNITS, MonetaryUtil.UNIT_BTC); switch (unit) { case MonetaryUtil.MICRO_BTC: dAmount = btc_amount / 1000000.0; break; case MonetaryUtil.MILLI_BTC: dAmount = btc_amount / 1000.0; break; default: dAmount = btc_amount; break; } // Log.i("SendFragment", "amount entered (converted):" + dAmount); final long amount = (long)(Math.round(dAmount * 1e8)); // Log.i("SendFragment", "amount entered (converted to long):" + amount); // Log.i("SendFragment", "balance:" + balance); if(amount > balance) { insufficientFunds = true; } // Log.i("SendFragment", "insufficient funds:" + insufficientFunds); if(btc_amount > 0.00 && FormatsUtil.getInstance().isValidBitcoinAddress(edAddress.getText().toString())) { isValid = true; } else if(btc_amount > 0.00 && strDestinationBTCAddress != null && FormatsUtil.getInstance().isValidBitcoinAddress(strDestinationBTCAddress)) { isValid = true; } else { isValid = false; } if(!isValid || insufficientFunds) { btSend.setVisibility(View.INVISIBLE); } else { btSend.setVisibility(View.VISIBLE); } } public String getDisplayUnits() { return (String) MonetaryUtil.getInstance().getBTCUnits()[PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.BTC_UNITS, MonetaryUtil.UNIT_BTC)]; } private boolean hasBIP47UTXO(List<MyTransactionOutPoint> outPoints) { List<String> addrs = BIP47Meta.getInstance().getUnspentAddresses(SendActivity.this, BIP47Util.getInstance(SendActivity.this).getWallet().getAccount(0).getPaymentCode()); for(MyTransactionOutPoint o : outPoints) { if(addrs.contains(o.getAddress())) { return true; } } return false; } private String getCurrentFeeSetting() { return getText(R.string.current_fee_selection) + "\n" + (FeeUtil.getInstance().getSuggestedFee().getDefaultPerKB().longValue() / 1000L) + " " + getText(R.string.slash_sat); } private void doCustomFee() { long sanitySat = FeeUtil.getInstance().getHighFee().getDefaultPerKB().longValue() / 1000L; final long sanityValue = (long)(sanitySat * 1.25); final EditText etCustomFee = new EditText(SendActivity.this); // etCustomFee.setInputType(InputType.TYPE_CLASS_NUMBER); etCustomFee.setText(Long.toString((FeeUtil.getInstance().getSuggestedFee().getDefaultPerKB().longValue() / 1000L))); InputFilter filter = new InputFilter() { String strCharset = "0123456789nollNOLL"; public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { for(int i = start; i < end; i++) { if(strCharset.indexOf(source.charAt(i)) == -1) { return ""; } } return null; } }; etCustomFee.setFilters(new InputFilter[] { filter } ); AlertDialog.Builder dlg = new AlertDialog.Builder(SendActivity.this) .setTitle(R.string.app_name) .setMessage(R.string.set_sat) .setView(etCustomFee) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String strCustomFee = etCustomFee.getText().toString(); long customValue = 0L; if(strCustomFee.equalsIgnoreCase("noll") && PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.USE_TRUSTED_NODE, false) == true) { customValue = 0L; } else { try { customValue = Long.valueOf(strCustomFee); } catch (Exception e) { Toast.makeText(SendActivity.this, R.string.custom_fee_too_low, Toast.LENGTH_SHORT).show(); return; } } if(customValue < 3 && !strCustomFee.equalsIgnoreCase("noll")) { Toast.makeText(SendActivity.this, R.string.custom_fee_too_low, Toast.LENGTH_SHORT).show(); } else if(customValue > sanityValue) { Toast.makeText(SendActivity.this, R.string.custom_fee_too_high, Toast.LENGTH_SHORT).show(); } else { SuggestedFee suggestedFee = new SuggestedFee(); suggestedFee.setStressed(false); suggestedFee.setOK(true); suggestedFee.setDefaultPerKB(BigInteger.valueOf(customValue * 1000L)); FeeUtil.getInstance().setSuggestedFee(suggestedFee); tvCurrentFeePrompt.setText(getCurrentFeeSetting()); btFee.setText(" "); } dialog.dismiss(); } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); if(!isFinishing()) { dlg.show(); } } private void doUTXO() { Intent intent = new Intent(SendActivity.this, UTXOActivity.class); startActivity(intent); } private void doFees() { SuggestedFee highFee = FeeUtil.getInstance().getHighFee(); SuggestedFee normalFee = FeeUtil.getInstance().getNormalFee(); SuggestedFee lowFee = FeeUtil.getInstance().getLowFee(); String message = getText(R.string.current_fee_selection) + " " + (FeeUtil.getInstance().getSuggestedFee().getDefaultPerKB().longValue() / 1000L) + " " + getText(R.string.slash_sat); message += "\n"; message += getText(R.string.current_hi_fee_value) + " " + (highFee.getDefaultPerKB().longValue() / 1000L) + " " + getText(R.string.slash_sat); message += "\n"; message += getText(R.string.current_mid_fee_value) + " " + (normalFee.getDefaultPerKB().longValue() / 1000L) + " " + getText(R.string.slash_sat); message += "\n"; message += getText(R.string.current_lo_fee_value) + " " + (lowFee.getDefaultPerKB().longValue() / 1000L) + " " + getText(R.string.slash_sat); AlertDialog.Builder dlg = new AlertDialog.Builder(SendActivity.this) .setTitle(R.string.app_name) .setMessage(message) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); if(!isFinishing()) { dlg.show(); } } private void emptyRicochetQueue() { RicochetMeta.getInstance(SendActivity.this).setLastRicochet(null); RicochetMeta.getInstance(SendActivity.this).empty(); new Thread(new Runnable() { @Override public void run() { try { PayloadUtil.getInstance(SendActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(SendActivity.this).getGUID() + AccessFactory.getInstance(SendActivity.this).getPIN())); } catch(Exception e) { ; } } }).start(); } private void doShowTx(final String hexTx, final String txHash) { final int QR_ALPHANUM_CHAR_LIMIT = 4296; // tx max size in bytes == 2148 TextView showTx = new TextView(SendActivity.this); showTx.setText(hexTx); showTx.setTextIsSelectable(true); showTx.setPadding(40, 10, 40, 10); showTx.setTextSize(18.0f); LinearLayout hexLayout = new LinearLayout(SendActivity.this); hexLayout.setOrientation(LinearLayout.VERTICAL); hexLayout.addView(showTx); new AlertDialog.Builder(SendActivity.this) .setTitle(txHash) .setView(hexLayout) .setCancelable(false) .setPositiveButton(R.string.close, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); SendActivity.this.finish(); } }) .setNegativeButton(R.string.show_qr, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if(hexTx.length() <= QR_ALPHANUM_CHAR_LIMIT) { final ImageView ivQR = new ImageView(SendActivity.this); Display display = (SendActivity.this).getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); int imgWidth = size.x - 240; Bitmap bitmap = null; QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(hexTx, null, Contents.Type.TEXT, BarcodeFormat.QR_CODE.toString(), imgWidth); try { bitmap = qrCodeEncoder.encodeAsBitmap(); } catch (WriterException e) { e.printStackTrace(); } ivQR.setImageBitmap(bitmap); LinearLayout qrLayout = new LinearLayout(SendActivity.this); qrLayout.setOrientation(LinearLayout.VERTICAL); qrLayout.addView(ivQR); new AlertDialog.Builder(SendActivity.this) .setTitle(txHash) .setView(qrLayout) .setCancelable(false) .setPositiveButton(R.string.close, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); SendActivity.this.finish(); } }) .setNegativeButton(R.string.share_qr, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String strFileName = AppUtil.getInstance(SendActivity.this).getReceiveQRFilename(); File file = new File(strFileName); if(!file.exists()) { try { file.createNewFile(); } catch(Exception e) { Toast.makeText(SendActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } } file.setReadable(true, false); FileOutputStream fos = null; try { fos = new FileOutputStream(file); } catch(FileNotFoundException fnfe) { ; } if(file != null && fos != null) { Bitmap bitmap = ((BitmapDrawable)ivQR.getDrawable()).getBitmap(); bitmap.compress(Bitmap.CompressFormat.PNG, 0, fos); try { fos.close(); } catch(IOException ioe) { ; } Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.setType("image/png"); intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file)); startActivity(Intent.createChooser(intent, SendActivity.this.getText(R.string.send_tx))); } } }).show(); } else { Toast.makeText(SendActivity.this, R.string.tx_too_large_qr, Toast.LENGTH_SHORT).show(); } } }).show(); } }
package trajectories; import jaci.pathfinder.Pathfinder; import jaci.pathfinder.Trajectory; import jaci.pathfinder.Waypoint; public class Waypoints { // aw - alliance wall public static Waypoint RED_AW_1, RED_AW_2, BLUE_AW_1, BLUE_AW_2; // as - airshop public static Waypoint RED_AS_1, RED_AS_2, RED_AS_3, BLUE_AS_1, BLUE_AS_2, BLUE_AS_3; // o - overflow, r - return, ls - loading station public static Waypoint RED_OLS, RED_RLS, BLUE_OLS, BLUE_RLS; static { RED_AW_1 = new Waypoint(15, 53.3, Math.toRadians(-90)); RED_AW_2 = new Waypoint(15, 268.8, Math.toRadians(-90)); RED_AS_1 = new Waypoint(107.4, 86.71, Math.toRadians(-120)); } public static void main(String[] args) { Waypoint[] points = new Waypoint[] { RED_AW_1, RED_AS_2 }; Trajectory.Config config = new Trajectory.Config(Trajectory.FitMethod.HERMITE_CUBIC, Trajectory.Config.SAMPLES_HIGH, 0.02, 1.7, 2.0, 60); Trajectory traj = Pathfinder.generate(points, config); for (int i = 0; i < traj.length(); i++) { Trajectory.Segment seg = traj.get(i); System.out.printf("%f,%f,%f,%f,%f,%f,%f,%f\n", seg.dt, seg.x, seg.y, seg.position, seg.velocity, seg.acceleration, seg.jerk, seg.heading); } } }
package com.sgwares.android; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.util.Log; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.ChildEventListener; 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.ValueEventListener; import com.google.firebase.messaging.FirebaseMessaging; import com.google.firebase.messaging.RemoteMessage; import com.sgwares.android.models.Game; import com.sgwares.android.models.Move; import com.sgwares.android.models.User; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.UUID; public class GameActivity extends Activity { private static final String TAG = GameActivity.class.getSimpleName(); private FirebaseDatabase mDatabase; private DatabaseReference mGameRef; private DatabaseReference mMovesRef; private DatabaseReference mUsersRef; private DatabaseReference mParticipantsRef; private List<User> mPossibleParticipants = new ArrayList<>();; private Map<User, TextView> mParticipants = new LinkedHashMap<>(); private ArrayAdapter mAdapter; private ChildEventListener mMovesListener; private ChildEventListener mPossibleParticipantListener; private ChildEventListener mParticipantsListener; private Game mGame; private GameSurface mGameSurface; private LinearLayout mScoreboard; private User mUser; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // TODO Check bundle to see if a game key is present setContentView(R.layout.activity_game_setup); // Get user and create game final FirebaseAuth auth = FirebaseAuth.getInstance(); mDatabase = FirebaseDatabase.getInstance(); mUsersRef = mDatabase.getReference("users"); mUsersRef.child(auth.getCurrentUser().getUid()).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { mUser = dataSnapshot.getValue(User.class); createGame(); } @Override public void onCancelled(DatabaseError databaseError) { Log.d(TAG, "onCancelled: " + databaseError.getMessage()); } }); mAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, mPossibleParticipants); final ListView listView = (ListView) findViewById(R.id.possible_participants); listView.setAdapter(mAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //TODO invite user to game inviteParticipant(mPossibleParticipants.get(position)); } }); mPossibleParticipantListener = new ChildEventListener() { @Override public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) { Log.d(TAG, "onChildAdded: " + dataSnapshot.getKey()); User user = dataSnapshot.getValue(User.class); user.setKey(dataSnapshot.getKey()); if (!user.getKey().equals(auth.getCurrentUser().getUid())) { Log.d(TAG, "New possible participant: " + user); mPossibleParticipants.add(user); mAdapter.notifyDataSetChanged(); } } @Override public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) { Log.d(TAG, "onChildChanged:" + dataSnapshot.getKey()); User user = dataSnapshot.getValue(User.class); user.setKey(dataSnapshot.getKey()); //TODO update participant picker } @Override public void onChildRemoved(DataSnapshot dataSnapshot) { Log.d(TAG, "onChildRemoved:" + dataSnapshot.getKey()); //TODO remove from participant picker } @Override public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) { Log.d(TAG, "onChildMoved:" + dataSnapshot.getKey()); } @Override public void onCancelled(DatabaseError databaseError) { Log.w(TAG, "onCancelled", databaseError.toException()); } }; mUsersRef.addChildEventListener(mPossibleParticipantListener); } /** * Create a new game and add current user as participant */ private void createGame() { mGameRef = mDatabase.getReference("games").push(); Log.d(TAG, "Created game key: " + mGameRef.getKey()); mGame = new Game(); List<User> initialParticipants = new ArrayList<>(); initialParticipants.add(mUser); mGame.setParticipants(initialParticipants); mGame.setBackground("#bbbbbb"); mGame.setKey(mGameRef.getKey()); mGameRef.setValue(mGame); final Button startGame = (Button) findViewById(R.id.start); startGame.setVisibility(View.VISIBLE); startGame.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mUsersRef.removeEventListener(mPossibleParticipantListener); startGame(); } }); } // TODO chnage to invite partipant private void inviteParticipant(User user) { Log.d(TAG, "inviteParticipant: " + user); RemoteMessage message = new RemoteMessage.Builder("/topics/" + user.getKey()) .setMessageId(UUID.randomUUID().toString()) .addData("message", "Hello") .build(); FirebaseMessaging.getInstance().send(message); mPossibleParticipants.remove(user); mAdapter.notifyDataSetChanged(); Snackbar.make(findViewById(R.id.content_main), user.getName() + " invited", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } /** * Start the game, show game surface and setup handlers */ private void startGame() { mGameSurface = new GameSurface(getApplicationContext(), mGame, mUser); setContentView(R.layout.activity_game); mScoreboard = (LinearLayout) findViewById(R.id.scoreboard); RelativeLayout view = (RelativeLayout) findViewById(R.id.content_main); view.addView(mGameSurface, 0); setupMoveHandler(); setupParticipantHandler(); } /** * Listen for new moves and trigger redraw of the canvas */ private void setupMoveHandler() { mMovesRef = mDatabase.getReference("moves").child(mGameRef.getKey()); mMovesListener = new ChildEventListener() { @Override public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) { Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey()); Move move = dataSnapshot.getValue(Move.class); mGame.getMoves().add(move); mGameSurface.invalidate(); } @Override public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) { Log.d(TAG, "onChildChanged:" + dataSnapshot.getKey()); } @Override public void onChildRemoved(DataSnapshot dataSnapshot) { Log.d(TAG, "onChildRemoved:" + dataSnapshot.getKey()); } @Override public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) { Log.d(TAG, "onChildMoved:" + dataSnapshot.getKey()); } @Override public void onCancelled(DatabaseError databaseError) { Log.w(TAG, "onCancelled", databaseError.toException()); } }; mMovesRef.addChildEventListener(mMovesListener); } /** * Add new participants to game and add score */ private void setupParticipantHandler() { mParticipantsRef = mGameRef.child("participants"); mParticipantsListener = new ChildEventListener() { @Override public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) { Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey()); User user = dataSnapshot.getValue(User.class); TextView tv = new TextView(getApplicationContext()); tv.setText(user.toString()); tv.setTextColor(Color.parseColor(user.getColour())); tv.setLayoutParams(new FrameLayout.LayoutParams( FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT)); mParticipants.put(user, tv); mScoreboard.addView(tv); } @Override public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) { Log.d(TAG, "onChildChanged:" + dataSnapshot.getKey()); User user = dataSnapshot.getValue(User.class); TextView tv = mParticipants.get(user); tv.setText(user.toString()); tv.setTextColor(Color.parseColor(user.getColour())); } @Override public void onChildRemoved(DataSnapshot dataSnapshot) { Log.d(TAG, "onChildRemoved:" + dataSnapshot.getKey()); User user = dataSnapshot.getValue(User.class); mScoreboard.removeView(mParticipants.remove(user)); } @Override public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) { Log.d(TAG, "onChildMoved:" + dataSnapshot.getKey()); } @Override public void onCancelled(DatabaseError databaseError) { Log.w(TAG, "onCancelled", databaseError.toException()); } }; mParticipantsRef.addChildEventListener(mParticipantsListener); } @Override public void onBackPressed() { Log.d(TAG, "onBackPressed: end game"); // TODO confirmation box, option to end game, show final score finish(); } @Override public void onDestroy() { Log.d(TAG, "onDestroy: ended game"); if ((mMovesRef != null) && (mMovesListener != null)) { mMovesRef.removeEventListener(mMovesListener); } if ((mUsersRef != null) && (mPossibleParticipantListener != null)) { mUsersRef.removeEventListener(mPossibleParticipantListener); } if ((mParticipantsRef != null) && (mParticipantsListener != null)) { mParticipantsRef.removeEventListener(mParticipantsListener); } super.onDestroy(); } }
package com.spit.matrix15; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.ProgressBar; import com.spit.matrix15.R; import org.apache.http.NameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class SplashActivity extends AppCompatActivity { private ProgressBar pDialog; ArrayList<Event> eventsList; JSONParser jParser = new JSONParser(); // SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("DBVer", 0); //url to get all events private static String url_all_events = "http://matrixthefest.org/get_all_events.php"; // JSON Node names private static final String TAG_SUCCESS = "success"; private static final String TAG_PRODUCTS = "event"; private static final String TAG_ID = "event_id"; private static final String TAG_NAME = "event_name"; private static final String TAG_DESC = "event_desciption"; private static final String TAG_CATEGORY = "category"; private static final String TAG_EMAIL = "email"; private static final String TAG_CONTACT1 = "contact1"; private static final String TAG_CONTACT2 = "contact2"; private static final String TAG_FEE = "fee"; private static final String TAG_VENUE = "venue"; private static final String TAG_EVENTHIGHLIGHT1 = "eventhighlight1"; private static final String TAG_EVENTHIGHLIGHT2 = "eventhighlight2"; private static final String TAG_EVENTHIGHLIGHT3 = "eventhighlight3"; private static final String TAG_POSTERNAME = "eventposter"; JSONArray events = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); SharedPreferences preferences = getSharedPreferences("app_start", 0); boolean isFirstStart = preferences.getBoolean("isFirstStart", true); if (isFirstStart) { if (!isNetworkAvailable()) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Can't proceed!") .setMessage("You don't have a data connection. We need a data connection the first time this app is started.") .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { System.exit(0); } }) .create() .show(); } else { new LoadAllEventsTask().execute(); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("isFirstStart", false); editor.commit(); } } if(isNetworkAvailable() && !isFirstStart) new LoadAllEventsTask().execute(); else if (!isFirstStart) new WaitTask().execute(); } private boolean isNetworkAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } class WaitTask extends AsyncTask<String, String, String> { protected void onPreExecute() { super.onPreExecute(); } protected String doInBackground(String ... strings) { try { Thread.sleep(3000); } catch (Exception e) { e.printStackTrace(); } return null; } protected void onPostExecute(String file_url) { runOnUiThread(new Runnable() { @Override public void run() { Intent i = new Intent(getApplicationContext(), CategoriesActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(i); finish(); } }); } } class LoadAllEventsTask extends AsyncTask<String, String, String> { private EventsDataSource eventsDataSource; @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected String doInBackground(String... strings) { eventsList = new ArrayList<Event>(); List<NameValuePair> params = new ArrayList<NameValuePair>(); JSONObject json = jParser.makeHttpRequest(url_all_events, "GET", params); if(json == null) { System.exit(0); } Log.d("All Products: ", json.toString()); try { int success = json.getInt(TAG_SUCCESS); if (success == 1) { // Getting Array of Products events = json.getJSONArray(TAG_PRODUCTS); // looping through All Events for (int i = 0; i < events.length(); i++) { JSONObject c = events.getJSONObject(i); Event newEvent = new Event(); // Storing each json item in variable newEvent.eventId = c.getString(TAG_ID); newEvent.eventName = c.getString(TAG_NAME); newEvent.eventDescription = c.getString(TAG_DESC); newEvent.email = c.getString(TAG_EMAIL); newEvent.contact1 = c.getString(TAG_CONTACT1); newEvent.contact2 = c.getString(TAG_CONTACT2); newEvent.fee = c.getString(TAG_FEE); newEvent.venue = c.getString(TAG_VENUE); newEvent.eventHighlight1 = c.getString(TAG_EVENTHIGHLIGHT1); newEvent.eventHighlight2 = c.getString(TAG_EVENTHIGHLIGHT2); newEvent.eventHighlight3 = c.getString(TAG_EVENTHIGHLIGHT3); newEvent.eventCategory = c.getString(TAG_CATEGORY); newEvent.eventPoster = c.getString(TAG_POSTERNAME); eventsList.add(newEvent); } } } catch (JSONException e) { e.printStackTrace(); } for (Event event : eventsList) { boolean nameInDb = false; for (Event event1 : Event.listAll(Event.class)) { if (event1.eventName.equals(event.eventName)) { nameInDb = true; break; } } if (!nameInDb) event.save(); } return null; } protected void onPostExecute(String file_url) { runOnUiThread(new Runnable() { public void run() { /* SET LIST ADAPTER HERE USE eventsList list in the adapter */ // SharedPreferences.Editor editor = sharedPreferences.edit(); // editor.putInt("ver", sharedPreferences.getInt("ver", 1) + 1); // Do this when refreshing // int version = sharedPreferences.getInt("ver", 1); Intent i = new Intent(getApplicationContext(), CategoriesActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(i); finish(); } }); } } }